blob: 76836f93074cd2b6c56aaf7d02610d6d13647b6a [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;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002123 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002124 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002125 if (p.finishing) {
2126 continue;
2127 }
2128 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
2129 + " out to target's task " + target.task);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002130 p.setTask(target.task, curThumbHolder, false);
2131 curThumbHolder = p.thumbHolder;
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002132 canMoveOptions = false;
2133 if (!gotOptions && topOptions == null) {
2134 topOptions = p.takeOptionsLocked();
2135 if (topOptions != null) {
2136 gotOptions = true;
2137 }
2138 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002139 if (DEBUG_ADD_REMOVE) {
2140 RuntimeException here = new RuntimeException("here");
2141 here.fillInStackTrace();
2142 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2143 + dstPos, here);
2144 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002145 mHistory.remove(srcPos);
2146 mHistory.add(dstPos, p);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002147 mService.mWindowManager.moveAppToken(dstPos, p.appToken);
2148 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002149 dstPos++;
2150 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002151 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002152 }
2153 i++;
2154 }
Craig Mautner05d6272ba2013-02-11 09:39:27 -08002155 mService.mWindowManager.moveTaskToBottom(target.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002156 if (taskTop == p) {
2157 taskTop = below;
2158 }
2159 if (taskTopI == replyChainEnd) {
2160 taskTopI = -1;
2161 }
2162 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002163 } else if (forceReset || finishOnTaskLaunch
2164 || clearWhenTaskReset) {
2165 // If the activity should just be removed -- either
2166 // because it asks for it, or the task should be
2167 // cleared -- then finish it and anything that is
2168 // part of its reply chain.
2169 if (clearWhenTaskReset) {
2170 // In this case, we want to finish this activity
2171 // and everything above it, so be sneaky and pretend
2172 // like these are all in the reply chain.
2173 replyChainEnd = targetI+1;
2174 while (replyChainEnd < mHistory.size() &&
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002175 (mHistory.get(
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002176 replyChainEnd)).task == task) {
2177 replyChainEnd++;
2178 }
2179 replyChainEnd--;
2180 } else if (replyChainEnd < 0) {
2181 replyChainEnd = targetI;
2182 }
2183 ActivityRecord p = null;
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002184 boolean gotOptions = !canMoveOptions;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002185 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002186 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002187 if (p.finishing) {
2188 continue;
2189 }
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002190 canMoveOptions = false;
2191 if (!gotOptions && topOptions == null) {
2192 topOptions = p.takeOptionsLocked();
2193 if (topOptions != null) {
2194 gotOptions = true;
2195 }
2196 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002197 if (finishActivityLocked(p, srcPos,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002198 Activity.RESULT_CANCELED, null, "reset", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002199 replyChainEnd--;
2200 srcPos--;
2201 }
2202 }
2203 if (taskTop == p) {
2204 taskTop = below;
2205 }
2206 if (taskTopI == replyChainEnd) {
2207 taskTopI = -1;
2208 }
2209 replyChainEnd = -1;
2210 } else {
2211 // If we were in the middle of a chain, well the
2212 // activity that started it all doesn't want anything
2213 // special, so leave it all as-is.
2214 replyChainEnd = -1;
2215 }
2216 } else {
2217 // Reached the bottom of the task -- any reply chain
2218 // should be left as-is.
2219 replyChainEnd = -1;
2220 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002221
2222 } else if (target.resultTo != null && (below == null
2223 || below.task == target.task)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002224 // If this activity is sending a reply to a previous
2225 // activity, we can't do anything with it now until
2226 // we reach the start of the reply chain.
2227 // XXX note that we are assuming the result is always
2228 // to the previous activity, which is almost always
2229 // the case but we really shouldn't count on.
2230 if (replyChainEnd < 0) {
2231 replyChainEnd = targetI;
2232 }
2233
2234 } else if (taskTopI >= 0 && allowTaskReparenting
2235 && task.affinity != null
2236 && task.affinity.equals(target.taskAffinity)) {
2237 // We are inside of another task... if this activity has
2238 // an affinity for our task, then either remove it if we are
2239 // clearing or move it over to our task. Note that
2240 // we currently punt on the case where we are resetting a
2241 // task that is not at the top but who has activities above
2242 // with an affinity to it... this is really not a normal
2243 // case, and we will need to later pull that task to the front
2244 // and usually at that point we will do the reset and pick
2245 // up those remaining activities. (This only happens if
2246 // someone starts an activity in a new task from an activity
2247 // in a task that is not currently on top.)
2248 if (forceReset || finishOnTaskLaunch) {
2249 if (replyChainEnd < 0) {
2250 replyChainEnd = targetI;
2251 }
2252 ActivityRecord p = null;
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002253 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index "
2254 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002255 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002256 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002257 if (p.finishing) {
2258 continue;
2259 }
2260 if (finishActivityLocked(p, srcPos,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002261 Activity.RESULT_CANCELED, null, "reset", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002262 taskTopI--;
2263 lastReparentPos--;
2264 replyChainEnd--;
2265 srcPos--;
2266 }
2267 }
2268 replyChainEnd = -1;
2269 } else {
2270 if (replyChainEnd < 0) {
2271 replyChainEnd = targetI;
2272 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002273 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting task at index "
2274 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002275 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002276 ActivityRecord p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002277 if (p.finishing) {
2278 continue;
2279 }
2280 if (lastReparentPos < 0) {
2281 lastReparentPos = taskTopI;
2282 taskTop = p;
2283 } else {
2284 lastReparentPos--;
2285 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002286 if (DEBUG_ADD_REMOVE) {
2287 RuntimeException here = new RuntimeException("here");
2288 here.fillInStackTrace();
2289 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2290 + lastReparentPos, here);
2291 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002292 mHistory.remove(srcPos);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002293 p.setTask(task, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002294 mHistory.add(lastReparentPos, p);
2295 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002296 + " from " + srcPos + " to " + lastReparentPos
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002297 + " in to resetting task " + task);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002298 mService.mWindowManager.moveAppToken(lastReparentPos, p.appToken);
2299 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002300 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002301 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002302 }
2303 }
Craig Mautner05d6272ba2013-02-11 09:39:27 -08002304 // TODO: This is wrong because it doesn't take lastReparentPos into account.
2305 mService.mWindowManager.moveTaskToTop(task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002306 replyChainEnd = -1;
2307
2308 // Now we've moved it in to place... but what if this is
2309 // a singleTop activity and we have put it on top of another
2310 // instance of the same activity? Then we drop the instance
2311 // below so it remains singleTop.
2312 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2313 for (int j=lastReparentPos-1; j>=0; j--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002314 ActivityRecord p = mHistory.get(j);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002315 if (p.finishing) {
2316 continue;
2317 }
2318 if (p.intent.getComponent().equals(target.intent.getComponent())) {
2319 if (finishActivityLocked(p, j,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002320 Activity.RESULT_CANCELED, null, "replace", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002321 taskTopI--;
2322 lastReparentPos--;
2323 }
2324 }
2325 }
2326 }
2327 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002328
2329 } else if (below != null && below.task != target.task) {
2330 // We hit the botton of a task; the reply chain can't
2331 // pass through it.
2332 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002333 }
2334
2335 target = below;
2336 targetI = i;
2337 }
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002338
2339 if (topOptions != null) {
2340 // If we got some ActivityOptions from an activity on top that
2341 // was removed from the task, propagate them to the new real top.
2342 if (taskTop != null) {
2343 taskTop.updateOptionsLocked(topOptions);
2344 } else {
2345 topOptions.abort();
2346 }
2347 }
2348
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002349 return taskTop;
2350 }
2351
2352 /**
2353 * Perform clear operation as requested by
2354 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2355 * stack to the given task, then look for
2356 * an instance of that activity in the stack and, if found, finish all
2357 * activities on top of it and return the instance.
2358 *
2359 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002360 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002361 * or null if none was found.
2362 */
2363 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002364 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002365 int i = mHistory.size();
2366
2367 // First find the requested task.
2368 while (i > 0) {
2369 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002370 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002371 if (r.task.taskId == taskId) {
2372 i++;
2373 break;
2374 }
2375 }
2376
2377 // Now clear it.
2378 while (i > 0) {
2379 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002380 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002381 if (r.finishing) {
2382 continue;
2383 }
2384 if (r.task.taskId != taskId) {
2385 return null;
2386 }
2387 if (r.realActivity.equals(newR.realActivity)) {
2388 // Here it is! Now finish everything in front...
2389 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002390 while (i < (mHistory.size()-1)) {
2391 i++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002392 r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002393 if (r.task.taskId != taskId) {
2394 break;
2395 }
2396 if (r.finishing) {
2397 continue;
2398 }
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002399 ActivityOptions opts = r.takeOptionsLocked();
2400 if (opts != null) {
2401 ret.updateOptionsLocked(opts);
2402 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002403 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002404 null, "clear", false)) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002405 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002406 }
2407 }
2408
2409 // Finally, if this is a normal launch mode (that is, not
2410 // expecting onNewIntent()), then we will finish the current
2411 // instance of the activity so a new fresh one can be started.
2412 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2413 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
2414 if (!ret.finishing) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08002415 int index = mHistory.indexOf(ret);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002416 if (index >= 0) {
2417 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002418 null, "clear", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002419 }
2420 return null;
2421 }
2422 }
2423
2424 return ret;
2425 }
2426 }
2427
2428 return null;
2429 }
2430
2431 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002432 * Completely remove all activities associated with an existing
2433 * task starting at a specified index.
2434 */
2435 private final void performClearTaskAtIndexLocked(int taskId, int i) {
Dianne Hackborneabd3282011-10-13 16:26:49 -07002436 while (i < mHistory.size()) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002437 ActivityRecord r = mHistory.get(i);
2438 if (r.task.taskId != taskId) {
2439 // Whoops hit the end.
2440 return;
2441 }
2442 if (r.finishing) {
2443 i++;
2444 continue;
2445 }
2446 if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002447 null, "clear", false)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002448 i++;
2449 }
2450 }
2451 }
2452
2453 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002454 * Completely remove all activities associated with an existing task.
2455 */
2456 private final void performClearTaskLocked(int taskId) {
2457 int i = mHistory.size();
2458
2459 // First find the requested task.
2460 while (i > 0) {
2461 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002462 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002463 if (r.task.taskId == taskId) {
2464 i++;
2465 break;
2466 }
2467 }
2468
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002469 // Now find the start and clear it.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002470 while (i > 0) {
2471 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002472 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002473 if (r.finishing) {
2474 continue;
2475 }
2476 if (r.task.taskId != taskId) {
2477 // We hit the bottom. Now finish it all...
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002478 performClearTaskAtIndexLocked(taskId, i+1);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002479 return;
2480 }
2481 }
2482 }
2483
2484 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002485 * Find the activity in the history stack within the given task. Returns
2486 * the index within the history at which it's found, or < 0 if not found.
2487 */
2488 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2489 int i = mHistory.size();
2490 while (i > 0) {
2491 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002492 ActivityRecord candidate = mHistory.get(i);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07002493 if (candidate.finishing) {
2494 continue;
2495 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002496 if (candidate.task.taskId != task) {
2497 break;
2498 }
2499 if (candidate.realActivity.equals(r.realActivity)) {
2500 return i;
2501 }
2502 }
2503
2504 return -1;
2505 }
2506
2507 /**
2508 * Reorder the history stack so that the activity at the given index is
2509 * brought to the front.
2510 */
2511 private final ActivityRecord moveActivityToFrontLocked(int where) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002512 ActivityRecord newTop = mHistory.remove(where);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002513 int top = mHistory.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002514 ActivityRecord oldTop = mHistory.get(top-1);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002515 if (DEBUG_ADD_REMOVE) {
2516 RuntimeException here = new RuntimeException("here");
2517 here.fillInStackTrace();
2518 Slog.i(TAG, "Removing and adding activity " + newTop + " to stack at "
2519 + top, here);
2520 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002521 mHistory.add(top, newTop);
2522 oldTop.frontOfTask = false;
2523 newTop.frontOfTask = true;
2524 return newTop;
2525 }
2526
2527 final int startActivityLocked(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002528 Intent intent, String resolvedType, ActivityInfo aInfo, IBinder resultTo,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002529 String resultWho, int requestCode,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002530 int callingPid, int callingUid, String callingPackage, int startFlags, Bundle options,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002531 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002532
Dianne Hackborna4972e92012-03-14 10:38:05 -07002533 int err = ActivityManager.START_SUCCESS;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002534
2535 ProcessRecord callerApp = null;
2536 if (caller != null) {
2537 callerApp = mService.getRecordForAppLocked(caller);
2538 if (callerApp != null) {
2539 callingPid = callerApp.pid;
2540 callingUid = callerApp.info.uid;
2541 } else {
2542 Slog.w(TAG, "Unable to find app for caller " + caller
2543 + " (pid=" + callingPid + ") when starting: "
2544 + intent.toString());
Dianne Hackborna4972e92012-03-14 10:38:05 -07002545 err = ActivityManager.START_PERMISSION_DENIED;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002546 }
2547 }
2548
Dianne Hackborna4972e92012-03-14 10:38:05 -07002549 if (err == ActivityManager.START_SUCCESS) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002550 final int userId = aInfo != null ? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0;
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07002551 Slog.i(TAG, "START u" + userId + " {" + intent.toShortString(true, true, true, false)
2552 + "} from pid " + (callerApp != null ? callerApp.pid : callingPid));
Dianne Hackbornefb58102010-10-14 16:47:34 -07002553 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002554
2555 ActivityRecord sourceRecord = null;
2556 ActivityRecord resultRecord = null;
2557 if (resultTo != null) {
2558 int index = indexOfTokenLocked(resultTo);
2559 if (DEBUG_RESULTS) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002560 TAG, "Will send result to " + resultTo + " (index " + index + ")");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002561 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002562 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002563 if (requestCode >= 0 && !sourceRecord.finishing) {
2564 resultRecord = sourceRecord;
2565 }
2566 }
2567 }
2568
2569 int launchFlags = intent.getFlags();
2570
2571 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2572 && sourceRecord != null) {
2573 // Transfer the result target from the source activity to the new
2574 // one being started, including any failures.
2575 if (requestCode >= 0) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002576 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002577 return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002578 }
2579 resultRecord = sourceRecord.resultTo;
2580 resultWho = sourceRecord.resultWho;
2581 requestCode = sourceRecord.requestCode;
2582 sourceRecord.resultTo = null;
2583 if (resultRecord != null) {
2584 resultRecord.removeResultsLocked(
2585 sourceRecord, resultWho, requestCode);
2586 }
2587 }
2588
Dianne Hackborna4972e92012-03-14 10:38:05 -07002589 if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002590 // We couldn't find a class that can handle the given Intent.
2591 // That's the end of that!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002592 err = ActivityManager.START_INTENT_NOT_RESOLVED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002593 }
2594
Dianne Hackborna4972e92012-03-14 10:38:05 -07002595 if (err == ActivityManager.START_SUCCESS && aInfo == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002596 // We couldn't find the specific class specified in the Intent.
2597 // Also the end of the line.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002598 err = ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002599 }
2600
Dianne Hackborna4972e92012-03-14 10:38:05 -07002601 if (err != ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002602 if (resultRecord != null) {
2603 sendActivityResultLocked(-1,
2604 resultRecord, resultWho, requestCode,
2605 Activity.RESULT_CANCELED, null);
2606 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002607 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002608 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002609 return err;
2610 }
2611
Jeff Sharkey35be7562012-04-18 19:16:15 -07002612 final int startAnyPerm = mService.checkPermission(
2613 START_ANY_ACTIVITY, callingPid, callingUid);
2614 final int componentPerm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002615 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Jeff Sharkey35be7562012-04-18 19:16:15 -07002616 if (startAnyPerm != PERMISSION_GRANTED && componentPerm != PERMISSION_GRANTED) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002617 if (resultRecord != null) {
2618 sendActivityResultLocked(-1,
2619 resultRecord, resultWho, requestCode,
2620 Activity.RESULT_CANCELED, null);
2621 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002622 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002623 String msg;
2624 if (!aInfo.exported) {
2625 msg = "Permission Denial: starting " + intent.toString()
2626 + " from " + callerApp + " (pid=" + callingPid
2627 + ", uid=" + callingUid + ")"
2628 + " not exported from uid " + aInfo.applicationInfo.uid;
2629 } else {
2630 msg = "Permission Denial: starting " + intent.toString()
2631 + " from " + callerApp + " (pid=" + callingPid
2632 + ", uid=" + callingUid + ")"
2633 + " requires " + aInfo.permission;
2634 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002635 Slog.w(TAG, msg);
2636 throw new SecurityException(msg);
2637 }
2638
2639 if (mMainStack) {
2640 if (mService.mController != null) {
2641 boolean abort = false;
2642 try {
2643 // The Intent we give to the watcher has the extra data
2644 // stripped off, since it can contain private information.
2645 Intent watchIntent = intent.cloneFilter();
2646 abort = !mService.mController.activityStarting(watchIntent,
2647 aInfo.applicationInfo.packageName);
2648 } catch (RemoteException e) {
2649 mService.mController = null;
2650 }
2651
2652 if (abort) {
2653 if (resultRecord != null) {
2654 sendActivityResultLocked(-1,
2655 resultRecord, resultWho, requestCode,
2656 Activity.RESULT_CANCELED, null);
2657 }
2658 // We pretend to the caller that it was really started, but
2659 // they will just get a cancel result.
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002660 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002661 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002662 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002663 }
2664 }
2665 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002666
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002667 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid, callingPackage,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002668 intent, resolvedType, aInfo, mService.mConfiguration,
2669 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002670 if (outActivity != null) {
2671 outActivity[0] = r;
2672 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002673
2674 if (mMainStack) {
2675 if (mResumedActivity == null
2676 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2677 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2678 PendingActivityLaunch pal = new PendingActivityLaunch();
2679 pal.r = r;
2680 pal.sourceRecord = sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002681 pal.startFlags = startFlags;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002682 mService.mPendingActivityLaunches.add(pal);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002683 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002684 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002685 return ActivityManager.START_SWITCHES_CANCELED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002686 }
2687 }
2688
2689 if (mService.mDidAppSwitch) {
2690 // This is the second allowed switch since we stopped switches,
2691 // so now just generally allow switches. Use case: user presses
2692 // home (switches disabled, switch to home, mDidAppSwitch now true);
2693 // user taps a home icon (coming from home so allowed, we hit here
2694 // and now allow anyone to switch again).
2695 mService.mAppSwitchesAllowedTime = 0;
2696 } else {
2697 mService.mDidAppSwitch = true;
2698 }
2699
2700 mService.doPendingActivityLaunchesLocked(false);
2701 }
2702
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002703 err = startActivityUncheckedLocked(r, sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002704 startFlags, true, options);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002705 if (mDismissKeyguardOnNextActivity && mPausingActivity == null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002706 // Someone asked to have the keyguard dismissed on the next
2707 // activity start, but we are not actually doing an activity
2708 // switch... just dismiss the keyguard now, because we
2709 // probably want to see whatever is behind it.
2710 mDismissKeyguardOnNextActivity = false;
2711 mService.mWindowManager.dismissKeyguard();
2712 }
2713 return err;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002714 }
2715
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002716 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2717 if ((launchFlags &
2718 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2719 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2720 // Caller wants to appear on home activity, so before starting
2721 // their own activity we will bring home to the front.
2722 moveHomeToFrontLocked();
2723 }
2724 }
2725
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002726 final int startActivityUncheckedLocked(ActivityRecord r,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002727 ActivityRecord sourceRecord, int startFlags, boolean doResume,
2728 Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002729 final Intent intent = r.intent;
2730 final int callingUid = r.launchedFromUid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002731
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002732 int launchFlags = intent.getFlags();
2733
2734 // We'll invoke onUserLeaving before onPause only if the launching
2735 // activity did not explicitly state that this is an automated launch.
2736 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2737 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2738 "startActivity() => mUserLeaving=" + mUserLeaving);
2739
2740 // If the caller has asked not to resume at this point, we make note
2741 // of this in the record so that we can skip it when trying to find
2742 // the top running activity.
2743 if (!doResume) {
2744 r.delayedResume = true;
2745 }
2746
2747 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2748 != 0 ? r : null;
2749
2750 // If the onlyIfNeeded flag is set, then we can do this if the activity
2751 // being launched is the same as the one making the call... or, as
2752 // a special case, if we do not know the caller then we count the
2753 // current top activity as the caller.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002754 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002755 ActivityRecord checkedCaller = sourceRecord;
2756 if (checkedCaller == null) {
2757 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2758 }
2759 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2760 // Caller is not the same as launcher, so always needed.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002761 startFlags &= ~ActivityManager.START_FLAG_ONLY_IF_NEEDED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002762 }
2763 }
2764
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002765 if (sourceRecord == null) {
2766 // This activity is not being started from another... in this
2767 // case we -always- start a new task.
2768 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2769 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2770 + intent);
2771 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2772 }
2773 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2774 // The original activity who is starting us is running as a single
2775 // instance... this new activity it is starting must go on its
2776 // own task.
2777 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2778 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2779 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2780 // The activity being started is a single instance... it always
2781 // gets launched into its own task.
2782 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2783 }
2784
2785 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2786 // For whatever reason this activity is being launched into a new
2787 // task... yet the caller has requested a result back. Well, that
2788 // is pretty messed up, so instead immediately send back a cancel
2789 // and let the new task continue launched as normal without a
2790 // dependency on its originator.
2791 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2792 sendActivityResultLocked(-1,
2793 r.resultTo, r.resultWho, r.requestCode,
2794 Activity.RESULT_CANCELED, null);
2795 r.resultTo = null;
2796 }
2797
2798 boolean addingToTask = false;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002799 boolean movedHome = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002800 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002801 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2802 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2803 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2804 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2805 // If bring to front is requested, and no result is requested, and
2806 // we can find a task that was started with this same
2807 // component, then instead of launching bring that one to the front.
2808 if (r.resultTo == null) {
2809 // See if there is a task to bring to the front. If this is
2810 // a SINGLE_INSTANCE activity, there can be one and only one
2811 // instance of it in the history, and it is always in its own
2812 // unique task, so we do a special search.
2813 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2814 ? findTaskLocked(intent, r.info)
2815 : findActivityLocked(intent, r.info);
2816 if (taskTop != null) {
2817 if (taskTop.task.intent == null) {
2818 // This task was started because of movement of
2819 // the activity based on affinity... now that we
2820 // are actually launching it, we can assign the
2821 // base intent.
2822 taskTop.task.setIntent(intent, r.info);
2823 }
2824 // If the target task is not in the front, then we need
2825 // to bring it to the front... except... well, with
2826 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2827 // to have the same behavior as if a new instance was
2828 // being started, which means not bringing it to the front
2829 // if the caller is not itself in the front.
2830 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002831 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002832 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2833 boolean callerAtFront = sourceRecord == null
2834 || curTop.task == sourceRecord.task;
2835 if (callerAtFront) {
2836 // We really do want to push this one into the
2837 // user's face, right now.
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002838 movedHome = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002839 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002840 moveTaskToFrontLocked(taskTop.task, r, options);
Dianne Hackborn84375872012-06-01 19:03:50 -07002841 options = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002842 }
2843 }
2844 // If the caller has requested that the target task be
2845 // reset, then do so.
2846 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2847 taskTop = resetTaskIfNeededLocked(taskTop, r);
2848 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002849 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002850 // We don't need to start a new activity, and
2851 // the client said not to do anything if that
2852 // is the case, so this is it! And for paranoia, make
2853 // sure we have correctly resumed the top activity.
2854 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07002855 resumeTopActivityLocked(null, options);
2856 } else {
2857 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002858 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002859 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002860 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002861 if ((launchFlags &
2862 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2863 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2864 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002865 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002866 // not be too hard...
2867 reuseTask = taskTop.task;
2868 performClearTaskLocked(taskTop.task.taskId);
2869 reuseTask.setIntent(r.intent, r.info);
2870 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002871 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2872 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2873 // In this situation we want to remove all activities
2874 // from the task up to the one being started. In most
2875 // cases this means we are resetting the task to its
2876 // initial state.
2877 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002878 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002879 if (top != null) {
2880 if (top.frontOfTask) {
2881 // Activity aliases may mean we use different
2882 // intents for the top activity, so make sure
2883 // the task now has the identity of the new
2884 // intent.
2885 top.task.setIntent(r.intent, r.info);
2886 }
2887 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002888 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002889 } else {
2890 // A special case: we need to
2891 // start the activity because it is not currently
2892 // running, and the caller has asked to clear the
2893 // current task to have this activity at the top.
2894 addingToTask = true;
2895 // Now pretend like this activity is being started
2896 // by the top of its task, so it is put in the
2897 // right place.
2898 sourceRecord = taskTop;
2899 }
2900 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2901 // In this case the top activity on the task is the
2902 // same as the one being launched, so we take that
2903 // as a request to bring the task to the foreground.
2904 // If the top activity in the task is the root
2905 // activity, deliver this new intent to it if it
2906 // desires.
Johan Viktorssonf363dfd2012-02-16 17:05:16 +01002907 if (((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2908 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP)
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002909 && taskTop.realActivity.equals(r.realActivity)) {
2910 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2911 if (taskTop.frontOfTask) {
2912 taskTop.task.setIntent(r.intent, r.info);
2913 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002914 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002915 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2916 // In this case we are launching the root activity
2917 // of the task, but with a different intent. We
2918 // should start a new instance on top.
2919 addingToTask = true;
2920 sourceRecord = taskTop;
2921 }
2922 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2923 // In this case an activity is being launched in to an
2924 // existing task, without resetting that task. This
2925 // is typically the situation of launching an activity
2926 // from a notification or shortcut. We want to place
2927 // the new activity on top of the current task.
2928 addingToTask = true;
2929 sourceRecord = taskTop;
2930 } else if (!taskTop.task.rootWasReset) {
2931 // In this case we are launching in to an existing task
2932 // that has not yet been started from its front door.
2933 // The current task has been brought to the front.
2934 // Ideally, we'd probably like to place this new task
2935 // at the bottom of its stack, but that's a little hard
2936 // to do with the current organization of the code so
2937 // for now we'll just drop it.
2938 taskTop.task.setIntent(r.intent, r.info);
2939 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002940 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002941 // We didn't do anything... but it was needed (a.k.a., client
2942 // don't use that intent!) And for paranoia, make
2943 // sure we have correctly resumed the top activity.
2944 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07002945 resumeTopActivityLocked(null, options);
2946 } else {
2947 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002948 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002949 return ActivityManager.START_TASK_TO_FRONT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002950 }
2951 }
2952 }
2953 }
2954
2955 //String uri = r.intent.toURI();
2956 //Intent intent2 = new Intent(uri);
2957 //Slog.i(TAG, "Given intent: " + r.intent);
2958 //Slog.i(TAG, "URI is: " + uri);
2959 //Slog.i(TAG, "To intent: " + intent2);
2960
2961 if (r.packageName != null) {
2962 // If the activity being launched is the same as the one currently
2963 // at the top, then we need to check if it should only be launched
2964 // once.
2965 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2966 if (top != null && r.resultTo == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002967 if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002968 if (top.app != null && top.app.thread != null) {
2969 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2970 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2971 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2972 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2973 // For paranoia, make sure we have correctly
2974 // resumed the top activity.
2975 if (doResume) {
2976 resumeTopActivityLocked(null);
2977 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002978 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002979 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002980 // We don't need to start a new activity, and
2981 // the client said not to do anything if that
2982 // is the case, so this is it!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002983 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002984 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002985 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002986 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002987 }
2988 }
2989 }
2990 }
2991
2992 } else {
2993 if (r.resultTo != null) {
2994 sendActivityResultLocked(-1,
2995 r.resultTo, r.resultWho, r.requestCode,
2996 Activity.RESULT_CANCELED, null);
2997 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002998 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002999 return ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003000 }
3001
3002 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003003 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003004
3005 // Should this be considered a new task?
3006 if (r.resultTo == null && !addingToTask
3007 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003008 if (reuseTask == null) {
3009 // todo: should do better management of integers.
3010 mService.mCurTask++;
3011 if (mService.mCurTask <= 0) {
3012 mService.mCurTask = 1;
3013 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003014 r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003015 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
3016 + " in new task " + r.task);
3017 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003018 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003019 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003020 newTask = true;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07003021 if (!movedHome) {
3022 moveHomeToFrontFromLaunchLocked(launchFlags);
3023 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003024
3025 } else if (sourceRecord != null) {
3026 if (!addingToTask &&
3027 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
3028 // In this case, we are adding the activity to an existing
3029 // task, but the caller has asked to clear that task if the
3030 // activity is already running.
3031 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003032 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003033 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003034 if (top != null) {
3035 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07003036 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003037 // For paranoia, make sure we have correctly
3038 // resumed the top activity.
3039 if (doResume) {
3040 resumeTopActivityLocked(null);
3041 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003042 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003043 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003044 }
3045 } else if (!addingToTask &&
3046 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
3047 // In this case, we are launching an activity in our own task
3048 // that may already be running somewhere in the history, and
3049 // we want to shuffle it to the front of the stack if so.
3050 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
3051 if (where >= 0) {
3052 ActivityRecord top = moveActivityToFrontLocked(where);
3053 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003054 top.updateOptionsLocked(options);
Dianne Hackborn39792d22010-08-19 18:01:52 -07003055 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003056 if (doResume) {
3057 resumeTopActivityLocked(null);
3058 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07003059 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003060 }
3061 }
3062 // An existing activity is starting this new activity, so we want
3063 // to keep the new one in the same task as the one that is starting
3064 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003065 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003066 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
3067 + " in existing task " + r.task);
3068
3069 } else {
3070 // This not being started from an existing activity, and not part
3071 // of a new task... just put it in the top task, though these days
3072 // this case should never happen.
3073 final int N = mHistory.size();
3074 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003075 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003076 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003077 ? prev.task
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003078 : new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003079 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
3080 + " in new guessed " + r.task);
3081 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07003082
Dianne Hackborn39792d22010-08-19 18:01:52 -07003083 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003084 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07003085
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003086 if (newTask) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003087 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.userId, r.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003088 }
3089 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003090 startActivityLocked(r, newTask, doResume, keepCurTransition, options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003091 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003092 }
3093
Dianne Hackborna4972e92012-03-14 10:38:05 -07003094 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003095 String profileFile, ParcelFileDescriptor profileFd, int userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003096 // Collect information about the target of the Intent.
3097 ActivityInfo aInfo;
3098 try {
3099 ResolveInfo rInfo =
3100 AppGlobals.getPackageManager().resolveIntent(
3101 intent, resolvedType,
3102 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07003103 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003104 aInfo = rInfo != null ? rInfo.activityInfo : null;
3105 } catch (RemoteException e) {
3106 aInfo = null;
3107 }
3108
3109 if (aInfo != null) {
3110 // Store the found target back into the intent, because now that
3111 // we have it we never want to do this again. For example, if the
3112 // user navigates back to this point in the history, we should
3113 // always restart the exact same activity.
3114 intent.setComponent(new ComponentName(
3115 aInfo.applicationInfo.packageName, aInfo.name));
3116
3117 // Don't debug things in the system process
Dianne Hackborna4972e92012-03-14 10:38:05 -07003118 if ((startFlags&ActivityManager.START_FLAG_DEBUG) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003119 if (!aInfo.processName.equals("system")) {
3120 mService.setDebugApp(aInfo.processName, true, false);
3121 }
3122 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003123
Dianne Hackborna4972e92012-03-14 10:38:05 -07003124 if ((startFlags&ActivityManager.START_FLAG_OPENGL_TRACES) != 0) {
Siva Velusamy92a8b222012-03-09 16:24:04 -08003125 if (!aInfo.processName.equals("system")) {
3126 mService.setOpenGlTraceApp(aInfo.applicationInfo, aInfo.processName);
3127 }
3128 }
3129
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003130 if (profileFile != null) {
3131 if (!aInfo.processName.equals("system")) {
3132 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003133 profileFile, profileFd,
3134 (startFlags&ActivityManager.START_FLAG_AUTO_STOP_PROFILER) != 0);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003135 }
3136 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003137 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003138 return aInfo;
3139 }
3140
3141 final int startActivityMayWait(IApplicationThread caller, int callingUid,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003142 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003143 String resultWho, int requestCode, int startFlags, String profileFile,
3144 ParcelFileDescriptor profileFd, WaitResult outResult, Configuration config,
3145 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003146 // Refuse possible leaked file descriptors
3147 if (intent != null && intent.hasFileDescriptors()) {
3148 throw new IllegalArgumentException("File descriptors passed in Intent");
3149 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003150 boolean componentSpecified = intent.getComponent() != null;
3151
3152 // Don't modify the client's object!
3153 intent = new Intent(intent);
3154
3155 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003156 ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003157 profileFile, profileFd, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003158
3159 synchronized (mService) {
3160 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003161 if (callingUid >= 0) {
3162 callingPid = -1;
3163 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003164 callingPid = Binder.getCallingPid();
3165 callingUid = Binder.getCallingUid();
3166 } else {
3167 callingPid = callingUid = -1;
3168 }
3169
3170 mConfigWillChange = config != null
3171 && mService.mConfiguration.diff(config) != 0;
3172 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3173 "Starting activity when config will change = " + mConfigWillChange);
3174
3175 final long origId = Binder.clearCallingIdentity();
3176
3177 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07003178 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003179 // This may be a heavy-weight process! Check to see if we already
3180 // have another, different heavy-weight process running.
3181 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
3182 if (mService.mHeavyWeightProcess != null &&
3183 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
3184 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
3185 int realCallingPid = callingPid;
3186 int realCallingUid = callingUid;
3187 if (caller != null) {
3188 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
3189 if (callerApp != null) {
3190 realCallingPid = callerApp.pid;
3191 realCallingUid = callerApp.info.uid;
3192 } else {
3193 Slog.w(TAG, "Unable to find app for caller " + caller
3194 + " (pid=" + realCallingPid + ") when starting: "
3195 + intent.toString());
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003196 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003197 return ActivityManager.START_PERMISSION_DENIED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003198 }
3199 }
3200
3201 IIntentSender target = mService.getIntentSenderLocked(
Dianne Hackborna4972e92012-03-14 10:38:05 -07003202 ActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn41203752012-08-31 14:05:51 -07003203 realCallingUid, userId, null, null, 0, new Intent[] { intent },
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003204 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003205 | PendingIntent.FLAG_ONE_SHOT, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003206
3207 Intent newIntent = new Intent();
3208 if (requestCode >= 0) {
3209 // Caller is requesting a result.
3210 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
3211 }
3212 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
3213 new IntentSender(target));
3214 if (mService.mHeavyWeightProcess.activities.size() > 0) {
3215 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
3216 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
3217 hist.packageName);
3218 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
3219 hist.task.taskId);
3220 }
3221 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
3222 aInfo.packageName);
3223 newIntent.setFlags(intent.getFlags());
3224 newIntent.setClassName("android",
3225 HeavyWeightSwitcherActivity.class.getName());
3226 intent = newIntent;
3227 resolvedType = null;
3228 caller = null;
3229 callingUid = Binder.getCallingUid();
3230 callingPid = Binder.getCallingPid();
3231 componentSpecified = true;
3232 try {
3233 ResolveInfo rInfo =
3234 AppGlobals.getPackageManager().resolveIntent(
3235 intent, null,
3236 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07003237 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003238 aInfo = rInfo != null ? rInfo.activityInfo : null;
Amith Yamasani742a6712011-05-04 14:49:28 -07003239 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003240 } catch (RemoteException e) {
3241 aInfo = null;
3242 }
3243 }
3244 }
3245 }
3246
3247 int res = startActivityLocked(caller, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003248 aInfo, resultTo, resultWho, requestCode, callingPid, callingUid,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003249 callingPackage, startFlags, options, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003250
3251 if (mConfigWillChange && mMainStack) {
3252 // If the caller also wants to switch to a new configuration,
3253 // do so now. This allows a clean switch, as we are waiting
3254 // for the current activity to pause (so we will not destroy
3255 // it), and have not yet started the next activity.
3256 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
3257 "updateConfiguration()");
3258 mConfigWillChange = false;
3259 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3260 "Updating to new configuration after starting activity.");
Dianne Hackborn813075a62011-11-14 17:45:19 -08003261 mService.updateConfigurationLocked(config, null, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003262 }
3263
3264 Binder.restoreCallingIdentity(origId);
3265
3266 if (outResult != null) {
3267 outResult.result = res;
Dianne Hackborna4972e92012-03-14 10:38:05 -07003268 if (res == ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003269 mWaitingActivityLaunched.add(outResult);
3270 do {
3271 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003272 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003273 } catch (InterruptedException e) {
3274 }
3275 } while (!outResult.timeout && outResult.who == null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003276 } else if (res == ActivityManager.START_TASK_TO_FRONT) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003277 ActivityRecord r = this.topRunningActivityLocked(null);
3278 if (r.nowVisible) {
3279 outResult.timeout = false;
3280 outResult.who = new ComponentName(r.info.packageName, r.info.name);
3281 outResult.totalTime = 0;
3282 outResult.thisTime = 0;
3283 } else {
3284 outResult.thisTime = SystemClock.uptimeMillis();
3285 mWaitingActivityVisible.add(outResult);
3286 do {
3287 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003288 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003289 } catch (InterruptedException e) {
3290 }
3291 } while (!outResult.timeout && outResult.who == null);
3292 }
3293 }
3294 }
3295
3296 return res;
3297 }
3298 }
3299
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003300 final int startActivities(IApplicationThread caller, int callingUid, String callingPackage,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003301 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
3302 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003303 if (intents == null) {
3304 throw new NullPointerException("intents is null");
3305 }
3306 if (resolvedTypes == null) {
3307 throw new NullPointerException("resolvedTypes is null");
3308 }
3309 if (intents.length != resolvedTypes.length) {
3310 throw new IllegalArgumentException("intents are length different than resolvedTypes");
3311 }
3312
3313 ActivityRecord[] outActivity = new ActivityRecord[1];
3314
3315 int callingPid;
3316 if (callingUid >= 0) {
3317 callingPid = -1;
3318 } else if (caller == null) {
3319 callingPid = Binder.getCallingPid();
3320 callingUid = Binder.getCallingUid();
3321 } else {
3322 callingPid = callingUid = -1;
3323 }
3324 final long origId = Binder.clearCallingIdentity();
3325 try {
3326 synchronized (mService) {
3327
3328 for (int i=0; i<intents.length; i++) {
3329 Intent intent = intents[i];
3330 if (intent == null) {
3331 continue;
3332 }
3333
3334 // Refuse possible leaked file descriptors
3335 if (intent != null && intent.hasFileDescriptors()) {
3336 throw new IllegalArgumentException("File descriptors passed in Intent");
3337 }
3338
3339 boolean componentSpecified = intent.getComponent() != null;
3340
3341 // Don't modify the client's object!
3342 intent = new Intent(intent);
3343
3344 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003345 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i],
Amith Yamasani483f3b02012-03-13 16:08:00 -07003346 0, null, null, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07003347 // TODO: New, check if this is correct
3348 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003349
3350 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
3351 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
3352 throw new IllegalArgumentException(
3353 "FLAG_CANT_SAVE_STATE not supported here");
3354 }
3355
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003356 Bundle theseOptions;
3357 if (options != null && i == intents.length-1) {
3358 theseOptions = options;
3359 } else {
3360 theseOptions = null;
3361 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003362 int res = startActivityLocked(caller, intent, resolvedTypes[i],
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003363 aInfo, resultTo, null, -1, callingPid, callingUid, callingPackage,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003364 0, theseOptions, componentSpecified, outActivity);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003365 if (res < 0) {
3366 return res;
3367 }
3368
Dianne Hackbornbe707852011-11-11 14:32:10 -08003369 resultTo = outActivity[0] != null ? outActivity[0].appToken : null;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003370 }
3371 }
3372 } finally {
3373 Binder.restoreCallingIdentity(origId);
3374 }
3375
Dianne Hackborna4972e92012-03-14 10:38:05 -07003376 return ActivityManager.START_SUCCESS;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003377 }
3378
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003379 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
3380 long thisTime, long totalTime) {
3381 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
3382 WaitResult w = mWaitingActivityLaunched.get(i);
3383 w.timeout = timeout;
3384 if (r != null) {
3385 w.who = new ComponentName(r.info.packageName, r.info.name);
3386 }
3387 w.thisTime = thisTime;
3388 w.totalTime = totalTime;
3389 }
3390 mService.notifyAll();
3391 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003392
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003393 void reportActivityVisibleLocked(ActivityRecord r) {
3394 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
3395 WaitResult w = mWaitingActivityVisible.get(i);
3396 w.timeout = false;
3397 if (r != null) {
3398 w.who = new ComponentName(r.info.packageName, r.info.name);
3399 }
3400 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
3401 w.thisTime = w.totalTime;
3402 }
3403 mService.notifyAll();
Dianne Hackborn90c52de2011-09-23 12:57:44 -07003404
3405 if (mDismissKeyguardOnNextActivity) {
3406 mDismissKeyguardOnNextActivity = false;
3407 mService.mWindowManager.dismissKeyguard();
3408 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003409 }
3410
3411 void sendActivityResultLocked(int callingUid, ActivityRecord r,
3412 String resultWho, int requestCode, int resultCode, Intent data) {
3413
3414 if (callingUid > 0) {
3415 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003416 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003417 }
3418
3419 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3420 + " : who=" + resultWho + " req=" + requestCode
3421 + " res=" + resultCode + " data=" + data);
3422 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3423 try {
3424 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3425 list.add(new ResultInfo(resultWho, requestCode,
3426 resultCode, data));
Dianne Hackbornbe707852011-11-11 14:32:10 -08003427 r.app.thread.scheduleSendResult(r.appToken, list);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003428 return;
3429 } catch (Exception e) {
3430 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3431 }
3432 }
3433
3434 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3435 }
3436
3437 private final void stopActivityLocked(ActivityRecord r) {
3438 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3439 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3440 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3441 if (!r.finishing) {
Christopher Tated3f175c2012-06-14 14:16:54 -07003442 if (!mService.mSleeping) {
3443 if (DEBUG_STATES) {
3444 Slog.d(TAG, "no-history finish of " + r);
3445 }
3446 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003447 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07003448 } else {
3449 if (DEBUG_STATES) Slog.d(TAG, "Not finishing noHistory " + r
3450 + " on stop because we're just sleeping");
3451 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003452 }
Christopher Tate5007ddd2012-06-12 13:08:18 -07003453 }
3454
3455 if (r.app != null && r.app.thread != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003456 if (mMainStack) {
3457 if (mService.mFocusedActivity == r) {
3458 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3459 }
3460 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003461 r.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003462 try {
3463 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003464 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3465 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003466 r.state = ActivityState.STOPPING;
3467 if (DEBUG_VISBILITY) Slog.v(
3468 TAG, "Stopping visible=" + r.visible + " for " + r);
3469 if (!r.visible) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003470 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003471 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003472 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003473 if (mService.isSleeping()) {
3474 r.setSleeping(true);
3475 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003476 Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG);
3477 msg.obj = r;
3478 mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003479 } catch (Exception e) {
3480 // Maybe just ignore exceptions here... if the process
3481 // has crashed, our death notification will clean things
3482 // up.
3483 Slog.w(TAG, "Exception thrown during pause", e);
3484 // Just in case, assume it to be stopped.
3485 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003486 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003487 r.state = ActivityState.STOPPED;
3488 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003489 destroyActivityLocked(r, true, false, "stop-except");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003490 }
3491 }
3492 }
3493 }
3494
3495 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3496 boolean remove) {
3497 int N = mStoppingActivities.size();
3498 if (N <= 0) return null;
3499
3500 ArrayList<ActivityRecord> stops = null;
3501
3502 final boolean nowVisible = mResumedActivity != null
3503 && mResumedActivity.nowVisible
3504 && !mResumedActivity.waitingVisible;
3505 for (int i=0; i<N; i++) {
3506 ActivityRecord s = mStoppingActivities.get(i);
3507 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3508 + nowVisible + " waitingVisible=" + s.waitingVisible
3509 + " finishing=" + s.finishing);
3510 if (s.waitingVisible && nowVisible) {
3511 mWaitingVisibleActivities.remove(s);
3512 s.waitingVisible = false;
3513 if (s.finishing) {
3514 // If this activity is finishing, it is sitting on top of
3515 // everyone else but we now know it is no longer needed...
3516 // so get rid of it. Otherwise, we need to go through the
3517 // normal flow and hide it once we determine that it is
3518 // hidden by the activities in front of it.
3519 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003520 mService.mWindowManager.setAppVisibility(s.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003521 }
3522 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003523 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003524 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3525 if (stops == null) {
3526 stops = new ArrayList<ActivityRecord>();
3527 }
3528 stops.add(s);
3529 mStoppingActivities.remove(i);
3530 N--;
3531 i--;
3532 }
3533 }
3534
3535 return stops;
3536 }
3537
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003538 final void scheduleIdleLocked() {
3539 Message msg = Message.obtain();
3540 msg.what = IDLE_NOW_MSG;
3541 mHandler.sendMessage(msg);
3542 }
3543
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003544 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003545 Configuration config) {
3546 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3547
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003548 ActivityRecord res = null;
3549
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003550 ArrayList<ActivityRecord> stops = null;
3551 ArrayList<ActivityRecord> finishes = null;
3552 ArrayList<ActivityRecord> thumbnails = null;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003553 ArrayList<UserStartedState> startingUsers = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003554 int NS = 0;
3555 int NF = 0;
3556 int NT = 0;
3557 IApplicationThread sendThumbnail = null;
3558 boolean booting = false;
3559 boolean enableScreen = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003560 boolean activityRemoved = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003561
3562 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003563 ActivityRecord r = ActivityRecord.forToken(token);
3564 if (r != null) {
3565 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003566 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003567 }
3568
3569 // Get the activity record.
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003570 int index = mHistory.indexOf(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003571 if (index >= 0) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003572 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003573
3574 if (fromTimeout) {
3575 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3576 }
3577
3578 // This is a hack to semi-deal with a race condition
3579 // in the client where it can be constructed with a
3580 // newer configuration from when we asked it to launch.
3581 // We'll update with whatever configuration it now says
3582 // it used to launch.
3583 if (config != null) {
3584 r.configuration = config;
3585 }
3586
3587 // No longer need to keep the device awake.
3588 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3589 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3590 mLaunchingActivity.release();
3591 }
3592
3593 // We are now idle. If someone is waiting for a thumbnail from
3594 // us, we can now deliver.
3595 r.idle = true;
3596 mService.scheduleAppGcsLocked();
3597 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3598 sendThumbnail = r.app.thread;
3599 r.thumbnailNeeded = false;
3600 }
3601
3602 // If this activity is fullscreen, set up to hide those under it.
3603
3604 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3605 ensureActivitiesVisibleLocked(null, 0);
3606
3607 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3608 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003609 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003610 mService.mBooted = true;
3611 enableScreen = true;
3612 }
3613 }
3614
3615 } else if (fromTimeout) {
3616 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3617 }
3618
3619 // Atomically retrieve all of the other things to do.
3620 stops = processStoppingActivitiesLocked(true);
3621 NS = stops != null ? stops.size() : 0;
3622 if ((NF=mFinishingActivities.size()) > 0) {
3623 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3624 mFinishingActivities.clear();
3625 }
Craig Mautnercae015f2013-02-08 14:31:27 -08003626 if ((NT=mCancelledThumbnails.size()) > 0) {
3627 thumbnails = new ArrayList<ActivityRecord>(mCancelledThumbnails);
3628 mCancelledThumbnails.clear();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003629 }
3630
3631 if (mMainStack) {
3632 booting = mService.mBooting;
3633 mService.mBooting = false;
3634 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003635 if (mStartingUsers.size() > 0) {
3636 startingUsers = new ArrayList<UserStartedState>(mStartingUsers);
3637 mStartingUsers.clear();
3638 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003639 }
3640
3641 int i;
3642
3643 // Send thumbnail if requested.
3644 if (sendThumbnail != null) {
3645 try {
3646 sendThumbnail.requestThumbnail(token);
3647 } catch (Exception e) {
3648 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3649 mService.sendPendingThumbnail(null, token, null, null, true);
3650 }
3651 }
3652
3653 // Stop any activities that are scheduled to do so but have been
3654 // waiting for the next one to start.
3655 for (i=0; i<NS; i++) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003656 ActivityRecord r = stops.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003657 synchronized (mService) {
3658 if (r.finishing) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003659 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003660 } else {
3661 stopActivityLocked(r);
3662 }
3663 }
3664 }
3665
3666 // Finish any activities that are scheduled to do so but have been
3667 // waiting for the next one to start.
3668 for (i=0; i<NF; i++) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003669 ActivityRecord r = finishes.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003670 synchronized (mService) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003671 activityRemoved = destroyActivityLocked(r, true, false, "finish-idle");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003672 }
3673 }
3674
3675 // Report back to any thumbnail receivers.
3676 for (i=0; i<NT; i++) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003677 ActivityRecord r = thumbnails.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003678 mService.sendPendingThumbnail(r, null, null, null, true);
3679 }
3680
3681 if (booting) {
3682 mService.finishBooting();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003683 } else if (startingUsers != null) {
3684 for (i=0; i<startingUsers.size(); i++) {
3685 mService.finishUserSwitch(startingUsers.get(i));
3686 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003687 }
3688
3689 mService.trimApplications();
3690 //dump();
3691 //mWindowManager.dump();
3692
3693 if (enableScreen) {
3694 mService.enableScreenAfterBoot();
3695 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003696
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003697 if (activityRemoved) {
3698 resumeTopActivityLocked(null);
3699 }
3700
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003701 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003702 }
3703
3704 /**
3705 * @return Returns true if the activity is being finished, false if for
3706 * some reason it is being left as-is.
3707 */
3708 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003709 Intent resultData, String reason, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003710 int index = indexOfTokenLocked(token);
Christopher Tated3f175c2012-06-14 14:16:54 -07003711 if (DEBUG_RESULTS || DEBUG_STATES) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003712 TAG, "Finishing activity @" + index + ": token=" + token
Christopher Tated3f175c2012-06-14 14:16:54 -07003713 + ", result=" + resultCode + ", data=" + resultData
3714 + ", reason=" + reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003715 if (index < 0) {
3716 return false;
3717 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003718 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003719
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003720 finishActivityLocked(r, index, resultCode, resultData, reason, oomAdj);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003721 return true;
3722 }
3723
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003724 final void finishSubActivityLocked(IBinder token, String resultWho, int requestCode) {
3725 ActivityRecord self = isInStackLocked(token);
3726 if (self == null) {
3727 return;
3728 }
3729
3730 int i;
3731 for (i=mHistory.size()-1; i>=0; i--) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003732 ActivityRecord r = mHistory.get(i);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003733 if (r.resultTo == self && r.requestCode == requestCode) {
3734 if ((r.resultWho == null && resultWho == null) ||
3735 (r.resultWho != null && r.resultWho.equals(resultWho))) {
3736 finishActivityLocked(r, i,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003737 Activity.RESULT_CANCELED, null, "request-sub", false);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003738 }
3739 }
3740 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003741 mService.updateOomAdjLocked();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003742 }
3743
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003744 final void finishTopRunningActivityLocked(ProcessRecord app) {
3745 ActivityRecord r = topRunningActivityLocked(null);
3746 if (r != null && r.app == app) {
3747 // If the top running activity is from this crashing
3748 // process, then terminate it to avoid getting in a loop.
3749 Slog.w(TAG, " Force finishing activity "
3750 + r.intent.getComponent().flattenToShortString());
3751 int index = mHistory.indexOf(r);
3752 r.stack.finishActivityLocked(r, index,
3753 Activity.RESULT_CANCELED, null, "crashed", false);
3754 // Also terminate any activities below it that aren't yet
3755 // stopped, to avoid a situation where one will get
3756 // re-start our crashing activity once it gets resumed again.
3757 index--;
3758 if (index >= 0) {
3759 r = mHistory.get(index);
3760 if (r.state == ActivityState.RESUMED
3761 || r.state == ActivityState.PAUSING
3762 || r.state == ActivityState.PAUSED) {
3763 if (!r.isHomeActivity || mService.mHomeProcess != r.app) {
3764 Slog.w(TAG, " Force finishing activity "
3765 + r.intent.getComponent().flattenToShortString());
3766 r.stack.finishActivityLocked(r, index,
3767 Activity.RESULT_CANCELED, null, "crashed", false);
3768 }
3769 }
3770 }
3771 }
3772 }
3773
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003774 final boolean finishActivityAffinityLocked(IBinder token) {
3775 int index = indexOfTokenLocked(token);
3776 if (DEBUG_RESULTS) Slog.v(
3777 TAG, "Finishing activity affinity @" + index + ": token=" + token);
3778 if (index < 0) {
3779 return false;
3780 }
3781 ActivityRecord r = mHistory.get(index);
3782
Amith Yamasanibfc1be12012-05-15 11:12:17 -07003783 while (index >= 0) {
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003784 ActivityRecord cur = mHistory.get(index);
3785 if (cur.task != r.task) {
3786 break;
3787 }
3788 if (cur.taskAffinity == null && r.taskAffinity != null) {
3789 break;
3790 }
3791 if (cur.taskAffinity != null && !cur.taskAffinity.equals(r.taskAffinity)) {
3792 break;
3793 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003794 finishActivityLocked(cur, index, Activity.RESULT_CANCELED, null,
3795 "request-affinity", true);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003796 index--;
3797 }
3798 return true;
3799 }
3800
Dianne Hackborn5c607432012-02-28 14:44:19 -08003801 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
3802 // send the result
3803 ActivityRecord resultTo = r.resultTo;
3804 if (resultTo != null) {
3805 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3806 + " who=" + r.resultWho + " req=" + r.requestCode
3807 + " res=" + resultCode + " data=" + resultData);
3808 if (r.info.applicationInfo.uid > 0) {
3809 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3810 resultTo.packageName, resultData,
3811 resultTo.getUriPermissionsLocked());
3812 }
3813 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3814 resultData);
3815 r.resultTo = null;
3816 }
3817 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3818
3819 // Make sure this HistoryRecord is not holding on to other resources,
3820 // because clients have remote IPC references to this object so we
3821 // can't assume that will go away and want to avoid circular IPC refs.
3822 r.results = null;
3823 r.pendingResults = null;
3824 r.newIntents = null;
3825 r.icicle = null;
3826 }
3827
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003828 /**
3829 * @return Returns true if this activity has been removed from the history
3830 * list, or false if it is still in the list and will be removed later.
3831 */
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003832 final boolean finishActivityLocked(ActivityRecord r,
3833 int resultCode, Intent resultData, String reason, boolean oomAdj) {
3834 int index = mHistory.indexOf(r);
3835 if (index >= 0) {
3836 return finishActivityLocked(r, index, resultCode, resultData, reason, false, oomAdj);
3837 }
3838 return false;
3839 }
3840
3841 /**
3842 * @return Returns true if this activity has been removed from the history
3843 * list, or false if it is still in the list and will be removed later.
3844 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003845 final boolean finishActivityLocked(ActivityRecord r, int index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003846 int resultCode, Intent resultData, String reason, boolean oomAdj) {
3847 return finishActivityLocked(r, index, resultCode, resultData, reason, false, oomAdj);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003848 }
3849
3850 /**
3851 * @return Returns true if this activity has been removed from the history
3852 * list, or false if it is still in the list and will be removed later.
3853 */
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003854 final boolean finishActivityLocked(ActivityRecord r, int index, int resultCode,
3855 Intent resultData, String reason, boolean immediate, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003856 if (r.finishing) {
3857 Slog.w(TAG, "Duplicate finish request for " + r);
3858 return false;
3859 }
3860
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003861 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003862 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003863 r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003864 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003865 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003866 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003867 if (next.task == r.task) {
3868 if (r.frontOfTask) {
3869 // The next activity is now the front of the task.
3870 next.frontOfTask = true;
3871 }
3872 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3873 // If the caller asked that this activity (and all above it)
3874 // be cleared when the task is reset, don't lose that information,
3875 // but propagate it up to the next activity.
3876 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3877 }
3878 }
3879 }
3880
3881 r.pauseKeyDispatchingLocked();
3882 if (mMainStack) {
3883 if (mService.mFocusedActivity == r) {
3884 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3885 }
3886 }
3887
Dianne Hackborn5c607432012-02-28 14:44:19 -08003888 finishActivityResultsLocked(r, resultCode, resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003889
3890 if (mService.mPendingThumbnails.size() > 0) {
3891 // There are clients waiting to receive thumbnails so, in case
3892 // this is an activity that someone is waiting for, add it
3893 // to the pending list so we can correctly update the clients.
Craig Mautnercae015f2013-02-08 14:31:27 -08003894 mCancelledThumbnails.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003895 }
3896
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003897 if (immediate) {
3898 return finishCurrentActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003899 FINISH_IMMEDIATELY, oomAdj) == null;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003900 } else if (mResumedActivity == r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003901 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003902 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003903 if (DEBUG_TRANSITION) Slog.v(TAG,
3904 "Prepare close transition: finishing " + r);
3905 mService.mWindowManager.prepareAppTransition(endTask
Craig Mautner4b71aa12012-12-27 17:20:01 -08003906 ? AppTransition.TRANSIT_TASK_CLOSE
3907 : AppTransition.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003908
3909 // Tell window manager to prepare for this one to be removed.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003910 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003911
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003912 if (mPausingActivity == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003913 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3914 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3915 startPausingLocked(false, false);
3916 }
3917
3918 } else if (r.state != ActivityState.PAUSING) {
3919 // If the activity is PAUSING, we will complete the finish once
3920 // it is done pausing; else we can just directly finish it here.
3921 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3922 return finishCurrentActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003923 FINISH_AFTER_PAUSE, oomAdj) == null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003924 } else {
3925 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3926 }
3927
3928 return false;
3929 }
3930
3931 private static final int FINISH_IMMEDIATELY = 0;
3932 private static final int FINISH_AFTER_PAUSE = 1;
3933 private static final int FINISH_AFTER_VISIBLE = 2;
3934
3935 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003936 int mode, boolean oomAdj) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003937 final int index = mHistory.indexOf(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003938 if (index < 0) {
3939 return null;
3940 }
3941
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003942 return finishCurrentActivityLocked(r, index, mode, oomAdj);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003943 }
3944
3945 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003946 int index, int mode, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003947 // First things first: if this activity is currently visible,
3948 // and the resumed activity is not yet visible, then hold off on
3949 // finishing until the resumed one becomes visible.
3950 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3951 if (!mStoppingActivities.contains(r)) {
3952 mStoppingActivities.add(r);
3953 if (mStoppingActivities.size() > 3) {
3954 // If we already have a few activities waiting to stop,
3955 // then give up on things going idle and start clearing
3956 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003957 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003958 } else {
3959 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003960 }
3961 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003962 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3963 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003964 r.state = ActivityState.STOPPING;
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003965 if (oomAdj) {
3966 mService.updateOomAdjLocked();
3967 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003968 return r;
3969 }
3970
3971 // make sure the record is cleaned out of other places.
3972 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003973 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003974 mWaitingVisibleActivities.remove(r);
3975 if (mResumedActivity == r) {
3976 mResumedActivity = null;
3977 }
3978 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003979 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003980 r.state = ActivityState.FINISHING;
3981
3982 if (mode == FINISH_IMMEDIATELY
3983 || prevState == ActivityState.STOPPED
3984 || prevState == ActivityState.INITIALIZING) {
3985 // If this activity is already stopped, we can just finish
3986 // it right now.
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003987 boolean activityRemoved = destroyActivityLocked(r, true,
3988 oomAdj, "finish-imm");
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003989 if (activityRemoved) {
3990 resumeTopActivityLocked(null);
3991 }
3992 return activityRemoved ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003993 }
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003994
3995 // Need to go through the full pause cycle to get this
3996 // activity into the stopped state and then finish it.
3997 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3998 mFinishingActivities.add(r);
3999 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004000 return r;
4001 }
4002
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004003 final boolean navigateUpToLocked(ActivityRecord srec, Intent destIntent, int resultCode,
4004 Intent resultData) {
4005 final int start = mHistory.indexOf(srec);
4006 if (start < 0) {
4007 // Current activity is not in history stack; do nothing.
4008 return false;
4009 }
4010 int finishTo = start - 1;
4011 ActivityRecord parent = null;
4012 boolean foundParentInTask = false;
4013 ComponentName dest = destIntent.getComponent();
4014 if (dest != null) {
4015 TaskRecord tr = srec.task;
4016 for (int i = start - 1; i >= 0; i--) {
4017 ActivityRecord r = mHistory.get(i);
4018 if (tr != r.task) {
4019 // Couldn't find parent in the same task; stop at the one above this.
4020 // (Root of current task; in-app "home" behavior)
4021 // Always at least finish the current activity.
4022 finishTo = Math.min(start - 1, i + 1);
4023 parent = mHistory.get(finishTo);
4024 break;
4025 } else if (r.info.packageName.equals(dest.getPackageName()) &&
4026 r.info.name.equals(dest.getClassName())) {
4027 finishTo = i;
4028 parent = r;
4029 foundParentInTask = true;
4030 break;
4031 }
4032 }
4033 }
4034
4035 IActivityController controller = mService.mController;
4036 if (controller != null) {
4037 ActivityRecord next = topRunningActivityLocked(srec.appToken, 0);
4038 if (next != null) {
4039 // ask watcher if this is allowed
4040 boolean resumeOK = true;
4041 try {
4042 resumeOK = controller.activityResuming(next.packageName);
4043 } catch (RemoteException e) {
4044 mService.mController = null;
4045 }
4046
4047 if (!resumeOK) {
4048 return false;
4049 }
4050 }
4051 }
4052 final long origId = Binder.clearCallingIdentity();
4053 for (int i = start; i > finishTo; i--) {
4054 ActivityRecord r = mHistory.get(i);
4055 requestFinishActivityLocked(r.appToken, resultCode, resultData,
4056 "navigate-up", true);
4057 // Only return the supplied result for the first activity finished
4058 resultCode = Activity.RESULT_CANCELED;
4059 resultData = null;
4060 }
4061
4062 if (parent != null && foundParentInTask) {
4063 final int parentLaunchMode = parent.info.launchMode;
4064 final int destIntentFlags = destIntent.getFlags();
4065 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
4066 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
4067 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
4068 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
4069 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
4070 } else {
4071 try {
4072 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
4073 destIntent.getComponent(), 0, srec.userId);
4074 int res = startActivityLocked(srec.app.thread, destIntent,
4075 null, aInfo, parent.appToken, null,
4076 0, -1, parent.launchedFromUid, parent.launchedFromPackage,
4077 0, null, true, null);
4078 foundParentInTask = res == ActivityManager.START_SUCCESS;
4079 } catch (RemoteException e) {
4080 foundParentInTask = false;
4081 }
4082 requestFinishActivityLocked(parent.appToken, resultCode,
4083 resultData, "navigate-up", true);
4084 }
4085 }
4086 Binder.restoreCallingIdentity(origId);
4087 return foundParentInTask;
4088 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004089 /**
4090 * Perform the common clean-up of an activity record. This is called both
4091 * as part of destroyActivityLocked() (when destroying the client-side
4092 * representation) and cleaning things up as a result of its hosting
4093 * processing going away, in which case there is no remaining client-side
4094 * state to destroy so only the cleanup here is needed.
4095 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004096 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
4097 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004098 if (mResumedActivity == r) {
4099 mResumedActivity = null;
4100 }
4101 if (mService.mFocusedActivity == r) {
4102 mService.mFocusedActivity = null;
4103 }
4104
4105 r.configDestroy = false;
4106 r.frozenBeforeDestroy = false;
4107
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004108 if (setState) {
4109 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
4110 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08004111 if (DEBUG_APP) Slog.v(TAG, "Clearing app during cleanUp for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004112 r.app = null;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004113 }
4114
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004115 // Make sure this record is no longer in the pending finishes list.
4116 // This could happen, for example, if we are trimming activities
4117 // down to the max limit while they are still waiting to finish.
4118 mFinishingActivities.remove(r);
4119 mWaitingVisibleActivities.remove(r);
4120
4121 // Remove any pending results.
4122 if (r.finishing && r.pendingResults != null) {
4123 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
4124 PendingIntentRecord rec = apr.get();
4125 if (rec != null) {
4126 mService.cancelIntentSenderLocked(rec, false);
4127 }
4128 }
4129 r.pendingResults = null;
4130 }
4131
4132 if (cleanServices) {
4133 cleanUpActivityServicesLocked(r);
4134 }
4135
4136 if (mService.mPendingThumbnails.size() > 0) {
4137 // There are clients waiting to receive thumbnails so, in case
4138 // this is an activity that someone is waiting for, add it
4139 // to the pending list so we can correctly update the clients.
Craig Mautnercae015f2013-02-08 14:31:27 -08004140 mCancelledThumbnails.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004141 }
4142
4143 // Get rid of any pending idle timeouts.
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004144 removeTimeoutsForActivityLocked(r);
4145 }
4146
4147 private void removeTimeoutsForActivityLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004148 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07004149 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004150 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004151 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07004152 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004153 }
4154
Dianne Hackborn5c607432012-02-28 14:44:19 -08004155 final void removeActivityFromHistoryLocked(ActivityRecord r) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004156 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
4157 r.makeFinishing();
4158 if (DEBUG_ADD_REMOVE) {
4159 RuntimeException here = new RuntimeException("here");
4160 here.fillInStackTrace();
4161 Slog.i(TAG, "Removing activity " + r + " from stack");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004162 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004163 mHistory.remove(r);
4164 r.takeFromHistory();
4165 removeTimeoutsForActivityLocked(r);
4166 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4167 + " (removed from history)");
4168 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08004169 if (DEBUG_APP) Slog.v(TAG, "Clearing app during remove for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004170 r.app = null;
4171 mService.mWindowManager.removeAppToken(r.appToken);
4172 if (VALIDATE_TOKENS) {
4173 validateAppTokensLocked();
4174 }
4175 cleanUpActivityServicesLocked(r);
4176 r.removeUriPermissionsLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004177 }
4178
4179 /**
4180 * Perform clean-up of service connections in an activity record.
4181 */
4182 final void cleanUpActivityServicesLocked(ActivityRecord r) {
4183 // Throw away any services that have been bound by this activity.
4184 if (r.connections != null) {
4185 Iterator<ConnectionRecord> it = r.connections.iterator();
4186 while (it.hasNext()) {
4187 ConnectionRecord c = it.next();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004188 mService.mServices.removeConnectionLocked(c, null, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004189 }
4190 r.connections = null;
4191 }
4192 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004193
4194 final void scheduleDestroyActivities(ProcessRecord owner, boolean oomAdj, String reason) {
4195 Message msg = mHandler.obtainMessage(DESTROY_ACTIVITIES_MSG);
4196 msg.obj = new ScheduleDestroyArgs(owner, oomAdj, reason);
4197 mHandler.sendMessage(msg);
4198 }
4199
Dianne Hackborn28695e02011-11-02 21:59:51 -07004200 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004201 boolean lastIsOpaque = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004202 boolean activityRemoved = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004203 for (int i=mHistory.size()-1; i>=0; i--) {
4204 ActivityRecord r = mHistory.get(i);
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004205 if (r.finishing) {
4206 continue;
4207 }
4208 if (r.fullscreen) {
4209 lastIsOpaque = true;
4210 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004211 if (owner != null && r.app != owner) {
4212 continue;
4213 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004214 if (!lastIsOpaque) {
4215 continue;
4216 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004217 // We can destroy this one if we have its icicle saved and
4218 // it is not in the process of pausing/stopping/finishing.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004219 if (r.app != null && r != mResumedActivity && r != mPausingActivity
4220 && r.haveState && !r.visible && r.stopped
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004221 && r.state != ActivityState.DESTROYING
4222 && r.state != ActivityState.DESTROYED) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004223 if (DEBUG_SWITCH) Slog.v(TAG, "Destroying " + r + " in state " + r.state
4224 + " resumed=" + mResumedActivity
4225 + " pausing=" + mPausingActivity);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004226 if (destroyActivityLocked(r, true, oomAdj, reason)) {
4227 activityRemoved = true;
4228 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004229 }
4230 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004231 if (activityRemoved) {
4232 resumeTopActivityLocked(null);
4233 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004234 }
4235
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004236 /**
4237 * Destroy the current CLIENT SIDE instance of an activity. This may be
4238 * called both when actually finishing an activity, or when performing
4239 * a configuration switch where we destroy the current client-side object
4240 * but then create a new client-side object for this same HistoryRecord.
4241 */
4242 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackborn28695e02011-11-02 21:59:51 -07004243 boolean removeFromApp, boolean oomAdj, String reason) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004244 if (DEBUG_SWITCH || DEBUG_CLEANUP) Slog.v(
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004245 TAG, "Removing activity from " + reason + ": token=" + r
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004246 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
4247 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004248 r.userId, System.identityHashCode(r),
Dianne Hackborn28695e02011-11-02 21:59:51 -07004249 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004250
4251 boolean removedFromHistory = false;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004252
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004253 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004254
4255 final boolean hadApp = r.app != null;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004256
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004257 if (hadApp) {
4258 if (removeFromApp) {
4259 int idx = r.app.activities.indexOf(r);
4260 if (idx >= 0) {
4261 r.app.activities.remove(idx);
4262 }
4263 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
4264 mService.mHeavyWeightProcess = null;
4265 mService.mHandler.sendEmptyMessage(
4266 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
4267 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004268 if (r.app.activities.size() == 0) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07004269 // No longer have activities, so update oom adj.
4270 mService.updateOomAdjLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004271 }
4272 }
4273
4274 boolean skipDestroy = false;
4275
4276 try {
4277 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004278 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004279 r.configChangeFlags);
4280 } catch (Exception e) {
4281 // We can just ignore exceptions here... if the process
4282 // has crashed, our death notification will clean things
4283 // up.
4284 //Slog.w(TAG, "Exception thrown during finish", e);
4285 if (r.finishing) {
4286 removeActivityFromHistoryLocked(r);
4287 removedFromHistory = true;
4288 skipDestroy = true;
4289 }
4290 }
4291
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004292 r.nowVisible = false;
4293
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004294 // If the activity is finishing, we need to wait on removing it
4295 // from the list to give it a chance to do its cleanup. During
4296 // that time it may make calls back with its token so we need to
4297 // be able to find it on the list and so we don't want to remove
4298 // it from the list yet. Otherwise, we can just immediately put
4299 // it in the destroyed state since we are not removing it from the
4300 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004301 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004302 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
4303 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004304 r.state = ActivityState.DESTROYING;
4305 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
4306 msg.obj = r;
4307 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
4308 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004309 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4310 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004311 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08004312 if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004313 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004314 }
4315 } else {
4316 // remove this record from the history.
4317 if (r.finishing) {
4318 removeActivityFromHistoryLocked(r);
4319 removedFromHistory = true;
4320 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004321 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4322 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004323 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08004324 if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004325 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004326 }
4327 }
4328
4329 r.configChangeFlags = 0;
4330
4331 if (!mLRUActivities.remove(r) && hadApp) {
4332 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
4333 }
4334
4335 return removedFromHistory;
4336 }
4337
4338 final void activityDestroyed(IBinder token) {
4339 synchronized (mService) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004340 final long origId = Binder.clearCallingIdentity();
4341 try {
4342 ActivityRecord r = ActivityRecord.forToken(token);
4343 if (r != null) {
4344 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004345 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004346
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004347 int index = mHistory.indexOf(r);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004348 if (index >= 0) {
4349 if (r.state == ActivityState.DESTROYING) {
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07004350 cleanUpActivityLocked(r, true, false);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004351 removeActivityFromHistoryLocked(r);
4352 }
4353 }
4354 resumeTopActivityLocked(null);
4355 } finally {
4356 Binder.restoreCallingIdentity(origId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004357 }
4358 }
4359 }
4360
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004361 private void removeHistoryRecordsForAppLocked(ArrayList<ActivityRecord> list,
4362 ProcessRecord app, String listName) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004363 int i = list.size();
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004364 if (DEBUG_CLEANUP) Slog.v(
4365 TAG, "Removing app " + app + " from list " + listName
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004366 + " with " + i + " entries");
4367 while (i > 0) {
4368 i--;
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004369 ActivityRecord r = list.get(i);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004370 if (DEBUG_CLEANUP) Slog.v(TAG, "Record #" + i + " " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004371 if (r.app == app) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004372 if (DEBUG_CLEANUP) Slog.v(TAG, "---> REMOVING this entry!");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004373 list.remove(i);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004374 removeTimeoutsForActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004375 }
4376 }
4377 }
4378
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004379 boolean removeHistoryRecordsForAppLocked(ProcessRecord app) {
4380 removeHistoryRecordsForAppLocked(mLRUActivities, app, "mLRUActivities");
4381 removeHistoryRecordsForAppLocked(mStoppingActivities, app, "mStoppingActivities");
4382 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app, "mGoingToSleepActivities");
4383 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app,
4384 "mWaitingVisibleActivities");
4385 removeHistoryRecordsForAppLocked(mFinishingActivities, app, "mFinishingActivities");
4386
4387 boolean hasVisibleActivities = false;
4388
4389 // Clean out the history list.
4390 int i = mHistory.size();
4391 if (DEBUG_CLEANUP) Slog.v(
4392 TAG, "Removing app " + app + " from history with " + i + " entries");
4393 while (i > 0) {
4394 i--;
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004395 ActivityRecord r = mHistory.get(i);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004396 if (DEBUG_CLEANUP) Slog.v(
4397 TAG, "Record #" + i + " " + r + ": app=" + r.app);
4398 if (r.app == app) {
Dianne Hackborn07981492013-01-28 11:36:23 -08004399 boolean remove;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004400 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn07981492013-01-28 11:36:23 -08004401 // Don't currently have state for the activity, or
4402 // it is finishing -- always remove it.
4403 remove = true;
4404 } else if (r.launchCount > 2 &&
4405 r.lastLaunchTime > (SystemClock.uptimeMillis()-60000)) {
4406 // We have launched this activity too many times since it was
4407 // able to run, so give up and remove it.
4408 remove = true;
4409 } else {
4410 // The process may be gone, but the activity lives on!
4411 remove = false;
4412 }
4413 if (remove) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004414 if (ActivityStack.DEBUG_ADD_REMOVE || DEBUG_CLEANUP) {
4415 RuntimeException here = new RuntimeException("here");
4416 here.fillInStackTrace();
4417 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
4418 + ": haveState=" + r.haveState
4419 + " stateNotNeeded=" + r.stateNotNeeded
4420 + " finishing=" + r.finishing
4421 + " state=" + r.state, here);
4422 }
4423 if (!r.finishing) {
4424 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
4425 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
4426 r.userId, System.identityHashCode(r),
4427 r.task.taskId, r.shortComponentName,
4428 "proc died without state saved");
4429 }
4430 removeActivityFromHistoryLocked(r);
4431
4432 } else {
4433 // We have the current state for this activity, so
4434 // it can be restarted later when needed.
4435 if (localLOGV) Slog.v(
4436 TAG, "Keeping entry, setting app to null");
4437 if (r.visible) {
4438 hasVisibleActivities = true;
4439 }
Dianne Hackborn07981492013-01-28 11:36:23 -08004440 if (DEBUG_APP) Slog.v(TAG, "Clearing app during removeHistory for activity "
4441 + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004442 r.app = null;
4443 r.nowVisible = false;
4444 if (!r.haveState) {
4445 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
4446 "App died, clearing saved state of " + r);
4447 r.icicle = null;
4448 }
4449 }
4450
4451 r.stack.cleanUpActivityLocked(r, true, true);
4452 }
4453 }
4454
4455 return hasVisibleActivities;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004456 }
4457
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004458 /**
4459 * Move the current home activity's task (if one exists) to the front
4460 * of the stack.
4461 */
4462 final void moveHomeToFrontLocked() {
4463 TaskRecord homeTask = null;
4464 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004465 ActivityRecord hr = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004466 if (hr.isHomeActivity) {
4467 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08004468 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004469 }
4470 }
4471 if (homeTask != null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004472 moveTaskToFrontLocked(homeTask, null, null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004473 }
4474 }
4475
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004476 final void updateTransitLocked(int transit, Bundle options) {
4477 if (options != null) {
4478 ActivityRecord r = topRunningActivityLocked(null);
4479 if (r != null && r.state != ActivityState.RESUMED) {
4480 r.updateOptionsLocked(options);
4481 } else {
4482 ActivityOptions.abort(options);
4483 }
4484 }
4485 mService.mWindowManager.prepareAppTransition(transit, false);
4486 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004487
Craig Mautnercae015f2013-02-08 14:31:27 -08004488 final boolean findTaskToMoveToFrontLocked(int taskId, int flags, Bundle options) {
4489 for (int i = mHistory.size() - 1; i >= 0; i--) {
4490 ActivityRecord hr = mHistory.get(i);
4491 if (hr.task.taskId == taskId) {
4492 if ((flags & ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
4493 mUserLeaving = true;
4494 }
4495 if ((flags & ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
4496 // Caller wants the home activity moved with it. To accomplish this,
4497 // we'll just move the home task to the top first.
4498 moveHomeToFrontLocked();
4499 }
4500 moveTaskToFrontLocked(hr.task, null, options);
4501 return true;
4502 }
4503 }
4504 return false;
4505 }
4506
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004507 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004508 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
4509
4510 final int task = tr.taskId;
4511 int top = mHistory.size()-1;
4512
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004513 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004514 // nothing to do!
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004515 if (reason != null &&
4516 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
4517 ActivityOptions.abort(options);
4518 } else {
Craig Mautner4b71aa12012-12-27 17:20:01 -08004519 updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options);
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004520 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004521 return;
4522 }
4523
Dianne Hackbornbe707852011-11-11 14:32:10 -08004524 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004525
4526 // Applying the affinities may have removed entries from the history,
4527 // so get the size again.
4528 top = mHistory.size()-1;
4529 int pos = top;
4530
4531 // Shift all activities with this task up to the top
4532 // of the stack, keeping them in the same internal order.
4533 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004534 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004535 if (localLOGV) Slog.v(
4536 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004537 if (r.task.taskId == task) {
4538 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004539 if (DEBUG_ADD_REMOVE) {
4540 RuntimeException here = new RuntimeException("here");
4541 here.fillInStackTrace();
4542 Slog.i(TAG, "Removing and adding activity " + r + " to stack at " + top, here);
4543 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004544 mHistory.remove(pos);
4545 mHistory.add(top, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004546 moved.add(0, r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004547 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004548 }
4549 pos--;
4550 }
4551
4552 if (DEBUG_TRANSITION) Slog.v(TAG,
4553 "Prepare to front transition: task=" + tr);
4554 if (reason != null &&
4555 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004556 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08004557 AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004558 ActivityRecord r = topRunningActivityLocked(null);
4559 if (r != null) {
4560 mNoAnimActivities.add(r);
4561 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004562 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004563 } else {
Craig Mautner4b71aa12012-12-27 17:20:01 -08004564 updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004565 }
4566
4567 mService.mWindowManager.moveAppTokensToTop(moved);
4568 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004569 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004570 }
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004571 mService.mWindowManager.moveTaskToTop(task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004572
4573 finishTaskMoveLocked(task);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004574 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, tr.userId, task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004575 }
4576
4577 private final void finishTaskMoveLocked(int task) {
4578 resumeTopActivityLocked(null);
4579 }
4580
4581 /**
4582 * Worker method for rearranging history stack. Implements the function of moving all
4583 * activities for a specific task (gathering them if disjoint) into a single group at the
4584 * bottom of the stack.
4585 *
4586 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
4587 * to premeptively cancel the move.
4588 *
4589 * @param task The taskId to collect and move to the bottom.
4590 * @return Returns true if the move completed, false if not.
4591 */
4592 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
4593 Slog.i(TAG, "moveTaskToBack: " + task);
4594
4595 // If we have a watcher, preflight the move before committing to it. First check
4596 // for *other* available tasks, but if none are available, then try again allowing the
4597 // current task to be selected.
4598 if (mMainStack && mService.mController != null) {
4599 ActivityRecord next = topRunningActivityLocked(null, task);
4600 if (next == null) {
4601 next = topRunningActivityLocked(null, 0);
4602 }
4603 if (next != null) {
4604 // ask watcher if this is allowed
4605 boolean moveOK = true;
4606 try {
4607 moveOK = mService.mController.activityResuming(next.packageName);
4608 } catch (RemoteException e) {
4609 mService.mController = null;
4610 }
4611 if (!moveOK) {
4612 return false;
4613 }
4614 }
4615 }
4616
Dianne Hackbornbe707852011-11-11 14:32:10 -08004617 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004618
4619 if (DEBUG_TRANSITION) Slog.v(TAG,
4620 "Prepare to back transition: task=" + task);
4621
4622 final int N = mHistory.size();
4623 int bottom = 0;
4624 int pos = 0;
4625
4626 // Shift all activities with this task down to the bottom
4627 // of the stack, keeping them in the same internal order.
4628 while (pos < N) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004629 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004630 if (localLOGV) Slog.v(
4631 TAG, "At " + pos + " ckp " + r.task + ": " + r);
4632 if (r.task.taskId == task) {
4633 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004634 if (DEBUG_ADD_REMOVE) {
4635 RuntimeException here = new RuntimeException("here");
4636 here.fillInStackTrace();
4637 Slog.i(TAG, "Removing and adding activity " + r + " to stack at "
4638 + bottom, here);
4639 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004640 mHistory.remove(pos);
4641 mHistory.add(bottom, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004642 moved.add(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004643 bottom++;
4644 }
4645 pos++;
4646 }
4647
4648 if (reason != null &&
4649 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004650 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08004651 AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004652 ActivityRecord r = topRunningActivityLocked(null);
4653 if (r != null) {
4654 mNoAnimActivities.add(r);
4655 }
4656 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004657 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08004658 AppTransition.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004659 }
4660 mService.mWindowManager.moveAppTokensToBottom(moved);
4661 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004662 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004663 }
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004664 mService.mWindowManager.moveTaskToBottom(task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004665
4666 finishTaskMoveLocked(task);
4667 return true;
4668 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07004669
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004670 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
4671 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4672 ActivityRecord resumed = mResumedActivity;
4673 if (resumed != null && resumed.thumbHolder == tr) {
4674 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004675 }
Dianne Hackborn6a864952012-09-21 18:46:11 -07004676 if (info.mainThumbnail == null) {
4677 info.mainThumbnail = tr.lastThumbnail;
4678 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004679 return info;
4680 }
4681
Dianne Hackborn15491c62012-09-19 10:59:14 -07004682 public Bitmap getTaskTopThumbnailLocked(TaskRecord tr) {
4683 ActivityRecord resumed = mResumedActivity;
4684 if (resumed != null && resumed.task == tr) {
4685 // This task is the current resumed task, we just need to take
4686 // a screenshot of it and return that.
4687 return resumed.stack.screenshotActivities(resumed);
4688 }
4689 // Return the information about the task, to figure out the top
4690 // thumbnail to return.
4691 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4692 if (info.numSubThumbbails <= 0) {
Dianne Hackborn6a864952012-09-21 18:46:11 -07004693 return info.mainThumbnail != null ? info.mainThumbnail : tr.lastThumbnail;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004694 }
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004695 return info.subtasks.get(info.numSubThumbbails-1).holder.lastThumbnail;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004696 }
4697
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004698 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex,
4699 boolean taskRequired) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004700 TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
4701 if (info.root == null) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004702 if (taskRequired) {
4703 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
4704 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004705 return null;
4706 }
4707
4708 if (subTaskIndex < 0) {
4709 // Just remove the entire task.
4710 performClearTaskAtIndexLocked(taskId, info.rootIndex);
4711 return info.root;
4712 }
4713
4714 if (subTaskIndex >= info.subtasks.size()) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004715 if (taskRequired) {
4716 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
4717 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004718 return null;
4719 }
4720
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004721 // Remove all of this task's activities starting at the sub task.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004722 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
4723 performClearTaskAtIndexLocked(taskId, subtask.index);
4724 return subtask.activity;
4725 }
4726
4727 public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004728 final TaskAccessInfo thumbs = new TaskAccessInfo();
4729 // How many different sub-thumbnails?
4730 final int NA = mHistory.size();
4731 int j = 0;
4732 ThumbnailHolder holder = null;
4733 while (j < NA) {
4734 ActivityRecord ar = mHistory.get(j);
4735 if (!ar.finishing && ar.task.taskId == taskId) {
Dianne Hackborn8da429e2012-09-23 12:52:19 -07004736 thumbs.root = ar;
4737 thumbs.rootIndex = j;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004738 holder = ar.thumbHolder;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004739 if (holder != null) {
4740 thumbs.mainThumbnail = holder.lastThumbnail;
4741 }
4742 j++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004743 break;
4744 }
4745 j++;
4746 }
4747
4748 if (j >= NA) {
4749 return thumbs;
4750 }
4751
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004752 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
4753 thumbs.subtasks = subtasks;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004754 while (j < NA) {
4755 ActivityRecord ar = mHistory.get(j);
4756 j++;
4757 if (ar.finishing) {
4758 continue;
4759 }
4760 if (ar.task.taskId != taskId) {
4761 break;
4762 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004763 if (ar.thumbHolder != holder && holder != null) {
4764 thumbs.numSubThumbbails++;
4765 holder = ar.thumbHolder;
4766 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
Dianne Hackborn15491c62012-09-19 10:59:14 -07004767 sub.holder = holder;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004768 sub.activity = ar;
4769 sub.index = j-1;
4770 subtasks.add(sub);
4771 }
4772 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004773 if (thumbs.numSubThumbbails > 0) {
4774 thumbs.retriever = new IThumbnailRetriever.Stub() {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004775 @Override
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004776 public Bitmap getThumbnail(int index) {
4777 if (index < 0 || index >= thumbs.subtasks.size()) {
4778 return null;
4779 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07004780 TaskAccessInfo.SubTask sub = thumbs.subtasks.get(index);
4781 ActivityRecord resumed = mResumedActivity;
4782 if (resumed != null && resumed.thumbHolder == sub.holder) {
4783 return resumed.stack.screenshotActivities(resumed);
4784 }
4785 return sub.holder.lastThumbnail;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004786 }
4787 };
4788 }
4789 return thumbs;
4790 }
4791
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004792 private final void logStartActivity(int tag, ActivityRecord r,
4793 TaskRecord task) {
4794 EventLog.writeEvent(tag,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004795 r.userId, System.identityHashCode(r), task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004796 r.shortComponentName, r.intent.getAction(),
4797 r.intent.getType(), r.intent.getDataString(),
4798 r.intent.getFlags());
4799 }
4800
4801 /**
4802 * Make sure the given activity matches the current configuration. Returns
4803 * false if the activity had to be destroyed. Returns true if the
4804 * configuration is the same, or the activity will remain running as-is
4805 * for whatever reason. Ensures the HistoryRecord is updated with the
4806 * correct configuration and all other bookkeeping is handled.
4807 */
4808 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
4809 int globalChanges) {
4810 if (mConfigWillChange) {
4811 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4812 "Skipping config check (will change): " + r);
4813 return true;
4814 }
4815
4816 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4817 "Ensuring correct configuration: " + r);
4818
4819 // Short circuit: if the two configurations are the exact same
4820 // object (the common case), then there is nothing to do.
4821 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004822 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004823 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4824 "Configuration unchanged in " + r);
4825 return true;
4826 }
4827
4828 // We don't worry about activities that are finishing.
4829 if (r.finishing) {
4830 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4831 "Configuration doesn't matter in finishing " + r);
4832 r.stopFreezingScreenLocked(false);
4833 return true;
4834 }
4835
4836 // Okay we now are going to make this activity have the new config.
4837 // But then we need to figure out how it needs to deal with that.
4838 Configuration oldConfig = r.configuration;
4839 r.configuration = newConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004840
4841 // Determine what has changed. May be nothing, if this is a config
4842 // that has come back from the app after going idle. In that case
4843 // we just want to leave the official config object now in the
4844 // activity and do nothing else.
4845 final int changes = oldConfig.diff(newConfig);
4846 if (changes == 0 && !r.forceNewConfig) {
4847 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4848 "Configuration no differences in " + r);
4849 return true;
4850 }
4851
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004852 // If the activity isn't currently running, just leave the new
4853 // configuration and it will pick that up next time it starts.
4854 if (r.app == null || r.app.thread == null) {
4855 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4856 "Configuration doesn't matter not running " + r);
4857 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004858 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004859 return true;
4860 }
4861
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004862 // Figure out how to handle the changes between the configurations.
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004863 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4864 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
4865 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07004866 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004867 + ", newConfig=" + newConfig);
4868 }
Dianne Hackborne6676352011-06-01 16:51:20 -07004869 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004870 // Aha, the activity isn't handling the change, so DIE DIE DIE.
4871 r.configChangeFlags |= changes;
4872 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004873 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004874 if (r.app == null || r.app.thread == null) {
4875 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004876 "Config is destroying non-running " + r);
Dianne Hackborn28695e02011-11-02 21:59:51 -07004877 destroyActivityLocked(r, true, false, "config");
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004878 } else if (r.state == ActivityState.PAUSING) {
4879 // A little annoying: we are waiting for this activity to
4880 // finish pausing. Let's not do anything now, but just
4881 // flag that it needs to be restarted when done pausing.
4882 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004883 "Config is skipping already pausing " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004884 r.configDestroy = true;
4885 return true;
4886 } else if (r.state == ActivityState.RESUMED) {
4887 // Try to optimize this case: the configuration is changing
4888 // and we need to restart the top, resumed activity.
4889 // Instead of doing the normal handshaking, just say
4890 // "restart!".
4891 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004892 "Config is relaunching resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004893 relaunchActivityLocked(r, r.configChangeFlags, true);
4894 r.configChangeFlags = 0;
4895 } else {
4896 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004897 "Config is relaunching non-resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004898 relaunchActivityLocked(r, r.configChangeFlags, false);
4899 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004900 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004901
4902 // All done... tell the caller we weren't able to keep this
4903 // activity around.
4904 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004905 }
4906
4907 // Default case: the activity can handle this new configuration, so
4908 // hand it over. Note that we don't need to give it the new
4909 // configuration, since we always send configuration changes to all
4910 // process when they happen so it can just use whatever configuration
4911 // it last got.
4912 if (r.app != null && r.app.thread != null) {
4913 try {
4914 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004915 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004916 } catch (RemoteException e) {
4917 // If process died, whatever.
4918 }
4919 }
4920 r.stopFreezingScreenLocked(false);
4921
4922 return true;
4923 }
4924
4925 private final boolean relaunchActivityLocked(ActivityRecord r,
4926 int changes, boolean andResume) {
4927 List<ResultInfo> results = null;
4928 List<Intent> newIntents = null;
4929 if (andResume) {
4930 results = r.results;
4931 newIntents = r.newIntents;
4932 }
4933 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4934 + " with results=" + results + " newIntents=" + newIntents
4935 + " andResume=" + andResume);
4936 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004937 : EventLogTags.AM_RELAUNCH_ACTIVITY, r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004938 r.task.taskId, r.shortComponentName);
4939
4940 r.startFreezingScreenLocked(r.app, 0);
4941
4942 try {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004943 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG,
4944 (andResume ? "Relaunching to RESUMED " : "Relaunching to PAUSED ")
4945 + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004946 r.forceNewConfig = false;
Dianne Hackbornbe707852011-11-11 14:32:10 -08004947 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004948 changes, !andResume, new Configuration(mService.mConfiguration));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004949 // Note: don't need to call pauseIfSleepingLocked() here, because
4950 // the caller will only pass in 'andResume' if this activity is
4951 // currently resumed, which implies we aren't sleeping.
4952 } catch (RemoteException e) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004953 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, "Relaunch failed", e);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004954 }
4955
4956 if (andResume) {
4957 r.results = null;
4958 r.newIntents = null;
4959 if (mMainStack) {
4960 mService.reportResumedActivityLocked(r);
4961 }
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004962 r.state = ActivityState.RESUMED;
4963 } else {
4964 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
4965 r.state = ActivityState.PAUSED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004966 }
4967
4968 return true;
4969 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004970
4971 public void dismissKeyguardOnNextActivityLocked() {
4972 mDismissKeyguardOnNextActivity = true;
4973 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004974
4975 boolean willActivityBeVisibleLocked(IBinder token) {
4976 int i;
4977 for (i = mHistory.size() - 1; i >= 0; i--) {
4978 ActivityRecord r = mHistory.get(i);
4979 if (r.appToken == token) {
4980 return true;
4981 }
4982 if (r.fullscreen && !r.finishing) {
4983 return false;
4984 }
4985 }
4986 return true;
4987 }
4988
4989 void closeSystemDialogsLocked() {
4990 for (int i = mHistory.size() - 1; i >= 0; i--) {
4991 ActivityRecord r = mHistory.get(i);
4992 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
4993 r.stack.finishActivityLocked(r, i,
4994 Activity.RESULT_CANCELED, null, "close-sys", true);
4995 }
4996 }
4997 }
4998
4999 boolean forceStopPackageLocked(String name, boolean doit, boolean evenPersistent, int userId) {
5000 boolean didSomething = false;
5001 TaskRecord lastTask = null;
5002 final int N = mHistory.size();
5003 for (int i = 0; i < N; i++) {
5004 ActivityRecord r = mHistory.get(i);
5005 final boolean samePackage = r.packageName.equals(name)
5006 || (name == null && r.userId == userId);
5007 if ((userId == UserHandle.USER_ALL || r.userId == userId)
5008 && (samePackage || r.task == lastTask)
5009 && (r.app == null || evenPersistent || !r.app.persistent)) {
5010 if (!doit) {
5011 if (r.finishing) {
5012 // If this activity is just finishing, then it is not
5013 // interesting as far as something to stop.
5014 continue;
5015 }
5016 return true;
5017 }
5018 didSomething = true;
5019 Slog.i(TAG, " Force finishing activity " + r);
5020 if (samePackage) {
5021 if (r.app != null) {
5022 r.app.removed = true;
5023 }
5024 r.app = null;
5025 }
5026 lastTask = r.task;
5027 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
5028 null, "force-stop", true)) {
5029 i--;
5030 }
5031 }
5032 }
5033 return didSomething;
5034 }
5035
5036 ActivityRecord getTasksLocked(int maxNum, IThumbnailReceiver receiver,
5037 PendingThumbnailsRecord pending, List<RunningTaskInfo> list) {
5038 ActivityRecord topRecord = null;
5039 int pos = mHistory.size() - 1;
5040 ActivityRecord next = pos >= 0 ? mHistory.get(pos) : null;
5041 ActivityRecord top = null;
5042 TaskRecord curTask = null;
5043 int numActivities = 0;
5044 int numRunning = 0;
5045 while (pos >= 0 && maxNum > 0) {
5046 final ActivityRecord r = next;
5047 pos--;
5048 next = pos >= 0 ? mHistory.get(pos) : null;
5049
5050 // Initialize state for next task if needed.
5051 if (top == null || (top.state == ActivityState.INITIALIZING && top.task == r.task)) {
5052 top = r;
5053 curTask = r.task;
5054 numActivities = numRunning = 0;
5055 }
5056
5057 // Add 'r' into the current task.
5058 numActivities++;
5059 if (r.app != null && r.app.thread != null) {
5060 numRunning++;
5061 }
5062
5063 if (localLOGV) Slog.v(
5064 TAG, r.intent.getComponent().flattenToShortString()
5065 + ": task=" + r.task);
5066
5067 // If the next one is a different task, generate a new
5068 // TaskInfo entry for what we have.
5069 if (next == null || next.task != curTask) {
5070 RunningTaskInfo ci = new RunningTaskInfo();
5071 ci.id = curTask.taskId;
5072 ci.baseActivity = r.intent.getComponent();
5073 ci.topActivity = top.intent.getComponent();
5074 if (top.thumbHolder != null) {
5075 ci.description = top.thumbHolder.lastDescription;
5076 }
5077 ci.numActivities = numActivities;
5078 ci.numRunning = numRunning;
5079 //System.out.println(
5080 // "#" + maxNum + ": " + " descr=" + ci.description);
5081 if (receiver != null) {
5082 if (localLOGV) Slog.v(
5083 TAG, "State=" + top.state + "Idle=" + top.idle
5084 + " app=" + top.app
5085 + " thr=" + (top.app != null ? top.app.thread : null));
5086 if (top.state == ActivityState.RESUMED || top.state == ActivityState.PAUSING) {
5087 if (top.idle && top.app != null && top.app.thread != null) {
5088 topRecord = top;
5089 } else {
5090 top.thumbnailNeeded = true;
5091 }
5092 }
5093 pending.pendingRecords.add(top);
5094 }
5095 list.add(ci);
5096 maxNum--;
5097 top = null;
5098 }
5099 }
5100 return topRecord;
5101 }
5102
5103 public void unhandledBackLocked() {
5104 int top = mHistory.size() - 1;
5105 if (DEBUG_SWITCH) Slog.d(
5106 TAG, "Performing unhandledBack(): top activity at " + top);
5107 if (top > 0) {
5108 finishActivityLocked(mHistory.get(top),
5109 top, Activity.RESULT_CANCELED, null, "unhandled-back", true);
5110 }
5111 }
5112
5113 void handleAppCrashLocked(ProcessRecord app) {
5114 for (int i = mHistory.size() - 1; i >= 0; i--) {
5115 ActivityRecord r = mHistory.get(i);
5116 if (r.app == app) {
5117 Slog.w(TAG, " Force finishing activity "
5118 + r.intent.getComponent().flattenToShortString());
5119 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
5120 null, "crashed", false);
5121 }
5122 }
5123 }
5124
5125 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
5126 boolean dumpClient, String dumpPackage) {
5127 ActivityManagerService.dumpHistoryList(fd, pw, mHistory, " ", "Hist", true, !dumpAll,
5128 dumpClient, dumpPackage);
5129 }
5130
5131 ArrayList<ActivityRecord> getDumpActivitiesLocked(String name) {
5132 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
5133
5134 if ("all".equals(name)) {
5135 for (ActivityRecord r1 : mHistory) {
5136 activities.add(r1);
5137 }
5138 } else if ("top".equals(name)) {
5139 final int N = mHistory.size();
5140 if (N > 0) {
5141 activities.add(mHistory.get(N-1));
5142 }
5143 } else {
5144 ItemMatcher matcher = new ItemMatcher();
5145 matcher.build(name);
5146
5147 for (ActivityRecord r1 : mHistory) {
5148 if (matcher.match(r1, r1.intent.getComponent())) {
5149 activities.add(r1);
5150 }
5151 }
5152 }
5153
5154 return activities;
5155 }
5156
5157 ActivityRecord restartPackage(String packageName) {
5158 ActivityRecord starting = topRunningActivityLocked(null);
5159
5160 // All activities that came from the package must be
5161 // restarted as if there was a config change.
5162 for (int i = mHistory.size() - 1; i >= 0; i--) {
5163 ActivityRecord a = mHistory.get(i);
5164 if (a.info.packageName.equals(packageName)) {
5165 a.forceNewConfig = true;
5166 if (starting != null && a == starting && a.visible) {
5167 a.startFreezingScreenLocked(starting.app, ActivityInfo.CONFIG_SCREEN_LAYOUT);
5168 }
5169 }
5170 }
5171
5172 return starting;
5173 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005174}