blob: fa7a02451a6428f3ca91b23d3b0c59b07b107e21 [file] [log] [blame]
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
Jeff Sharkey35be7562012-04-18 19:16:15 -070019import static android.Manifest.permission.START_ANY_ACTIVITY;
20import static android.content.pm.PackageManager.PERMISSION_GRANTED;
21
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070022import com.android.internal.app.HeavyWeightSwitcherActivity;
23import com.android.internal.os.BatteryStatsImpl;
Craig Mautnerd74f7d72013-02-26 13:41:02 -080024import com.android.internal.util.Objects;
Craig Mautnercae015f2013-02-08 14:31:27 -080025import com.android.server.am.ActivityManagerService.ItemMatcher;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070026import com.android.server.am.ActivityManagerService.PendingActivityLaunch;
Craig Mautner4b71aa12012-12-27 17:20:01 -080027import com.android.server.wm.AppTransition;
Craig Mautner05d6272ba2013-02-11 09:39:27 -080028import com.android.server.wm.TaskGroup;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070029
30import android.app.Activity;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070031import android.app.ActivityManager;
Dianne Hackborn7a2195c2012-03-19 17:38:00 -070032import android.app.ActivityOptions;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070033import android.app.AppGlobals;
Craig Mautner05d6272ba2013-02-11 09:39:27 -080034import android.app.IActivityController;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070035import android.app.IActivityManager;
Craig Mautnercae015f2013-02-08 14:31:27 -080036import android.app.IThumbnailReceiver;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070037import android.app.IThumbnailRetriever;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070038import android.app.IApplicationThread;
39import android.app.PendingIntent;
40import android.app.ResultInfo;
Craig Mautnercae015f2013-02-08 14:31:27 -080041import android.app.ActivityManager.RunningTaskInfo;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070042import android.app.IActivityManager.WaitResult;
43import android.content.ComponentName;
44import android.content.Context;
45import android.content.IIntentSender;
46import android.content.Intent;
47import android.content.IntentSender;
48import android.content.pm.ActivityInfo;
49import android.content.pm.ApplicationInfo;
50import android.content.pm.PackageManager;
51import android.content.pm.ResolveInfo;
52import android.content.res.Configuration;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -080053import android.content.res.Resources;
54import android.graphics.Bitmap;
Craig Mautnerb12428a2012-12-20 16:07:06 -080055import android.graphics.Bitmap.Config;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070056import android.os.Binder;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070057import android.os.Bundle;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070058import android.os.Handler;
59import android.os.IBinder;
Zoran Marcetaf958b322012-08-09 20:27:12 +090060import android.os.Looper;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070061import android.os.Message;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070062import android.os.ParcelFileDescriptor;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070063import android.os.PowerManager;
64import android.os.RemoteException;
65import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070066import android.os.UserHandle;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070067import android.util.EventLog;
68import android.util.Log;
69import android.util.Slog;
Craig Mautner5d9c7be2013-02-15 14:02:56 -080070import android.util.SparseArray;
Craig Mautner59c00972012-07-30 12:10:24 -070071import android.view.Display;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070072
Craig Mautnercae015f2013-02-08 14:31:27 -080073import java.io.FileDescriptor;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070074import java.io.IOException;
Craig Mautnercae015f2013-02-08 14:31:27 -080075import java.io.PrintWriter;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070076import java.lang.ref.WeakReference;
77import java.util.ArrayList;
78import java.util.Iterator;
79import java.util.List;
80
81/**
82 * State and management of a single stack of activities.
83 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070084final class ActivityStack {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070085 static final String TAG = ActivityManagerService.TAG;
Dianne Hackbornb961cd22011-06-21 12:13:37 -070086 static final boolean localLOGV = ActivityManagerService.localLOGV;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070087 static final boolean DEBUG_SWITCH = ActivityManagerService.DEBUG_SWITCH;
88 static final boolean DEBUG_PAUSE = ActivityManagerService.DEBUG_PAUSE;
89 static final boolean DEBUG_VISBILITY = ActivityManagerService.DEBUG_VISBILITY;
90 static final boolean DEBUG_USER_LEAVING = ActivityManagerService.DEBUG_USER_LEAVING;
91 static final boolean DEBUG_TRANSITION = ActivityManagerService.DEBUG_TRANSITION;
92 static final boolean DEBUG_RESULTS = ActivityManagerService.DEBUG_RESULTS;
93 static final boolean DEBUG_CONFIGURATION = ActivityManagerService.DEBUG_CONFIGURATION;
94 static final boolean DEBUG_TASKS = ActivityManagerService.DEBUG_TASKS;
Dianne Hackborncc5a0552012-10-01 16:32:39 -070095 static final boolean DEBUG_CLEANUP = ActivityManagerService.DEBUG_CLEANUP;
Craig Mautner9658b312013-02-28 10:55:59 -080096
Dianne Hackbornce86ba82011-07-13 19:33:41 -070097 static final boolean DEBUG_STATES = false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070098 static final boolean DEBUG_ADD_REMOVE = false;
99 static final boolean DEBUG_SAVED_STATE = false;
Dianne Hackborn07981492013-01-28 11:36:23 -0800100 static final boolean DEBUG_APP = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700101
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700102 static final boolean VALIDATE_TOKENS = ActivityManagerService.VALIDATE_TOKENS;
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800103
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700104 // How long we wait until giving up on the last activity telling us it
105 // is idle.
106 static final int IDLE_TIMEOUT = 10*1000;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700107
108 // Ticks during which we check progress while waiting for an app to launch.
109 static final int LAUNCH_TICK = 500;
110
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700111 // How long we wait until giving up on the last activity to pause. This
112 // is short because it directly impacts the responsiveness of starting the
113 // next activity.
114 static final int PAUSE_TIMEOUT = 500;
115
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700116 // How long we wait for the activity to tell us it has stopped before
117 // giving up. This is a good amount of time because we really need this
118 // from the application in order to get its saved state.
119 static final int STOP_TIMEOUT = 10*1000;
120
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800121 // How long we can hold the sleep wake lock before giving up.
122 static final int SLEEP_TIMEOUT = 5*1000;
123
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700124 // How long we can hold the launch wake lock before giving up.
125 static final int LAUNCH_TIMEOUT = 10*1000;
126
127 // How long we wait until giving up on an activity telling us it has
128 // finished destroying itself.
129 static final int DESTROY_TIMEOUT = 10*1000;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800130
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700131 // How long until we reset a task when the user returns to it. Currently
Dianne Hackborn621e17d2010-11-22 15:59:56 -0800132 // disabled.
133 static final long ACTIVITY_INACTIVE_RESET_TIME = 0;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800134
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700135 // How long between activity launches that we consider safe to not warn
136 // the user about an unexpected activity being launched on top.
137 static final long START_WARN_TIME = 5*1000;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800138
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700139 // Set to false to disable the preview that is shown while a new activity
140 // is being started.
141 static final boolean SHOW_APP_STARTING_PREVIEW = true;
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800142
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700143 enum ActivityState {
144 INITIALIZING,
145 RESUMED,
146 PAUSING,
147 PAUSED,
148 STOPPING,
149 STOPPED,
150 FINISHING,
151 DESTROYING,
152 DESTROYED
153 }
154
155 final ActivityManagerService mService;
156 final boolean mMainStack;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800157
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700158 final Context mContext;
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800159
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700160 /**
161 * The back history of all previous (and possibly still
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800162 * running) activities. It contains #TaskRecord objects.
163 */
164 private ArrayList<TaskRecord> mTaskHistory = new ArrayList<TaskRecord>();
165
166 /**
Dianne Hackbornbe707852011-11-11 14:32:10 -0800167 * Used for validating app tokens with window manager.
168 */
Craig Mautnerb1fd65c02013-02-05 13:34:57 -0800169 final ArrayList<TaskGroup> mValidateAppTokens = new ArrayList<TaskGroup>();
Dianne Hackbornbe707852011-11-11 14:32:10 -0800170
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700171 /**
172 * List of running activities, sorted by recent usage.
173 * The first entry in the list is the least recently used.
174 * It contains HistoryRecord objects.
175 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700176 final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700177
178 /**
179 * List of activities that are waiting for a new activity
180 * to become visible before completing whatever operation they are
181 * supposed to do.
182 */
183 final ArrayList<ActivityRecord> mWaitingVisibleActivities
184 = new ArrayList<ActivityRecord>();
185
186 /**
187 * List of activities that are ready to be stopped, but waiting
188 * for the next activity to settle down before doing so. It contains
189 * HistoryRecord objects.
190 */
191 final ArrayList<ActivityRecord> mStoppingActivities
192 = new ArrayList<ActivityRecord>();
193
194 /**
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800195 * List of activities that are in the process of going to sleep.
196 */
197 final ArrayList<ActivityRecord> mGoingToSleepActivities
198 = new ArrayList<ActivityRecord>();
199
200 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700201 * Animations that for the current transition have requested not to
202 * be considered for the transition animation.
203 */
204 final ArrayList<ActivityRecord> mNoAnimActivities
205 = new ArrayList<ActivityRecord>();
206
207 /**
208 * List of activities that are ready to be finished, but waiting
209 * for the previous activity to settle down before doing so. It contains
210 * HistoryRecord objects.
211 */
212 final ArrayList<ActivityRecord> mFinishingActivities
213 = new ArrayList<ActivityRecord>();
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800214
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700215 /**
216 * List of people waiting to find out about the next launched activity.
217 */
218 final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched
219 = new ArrayList<IActivityManager.WaitResult>();
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800220
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700221 /**
222 * List of people waiting to find out about the next visible activity.
223 */
224 final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible
225 = new ArrayList<IActivityManager.WaitResult>();
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700226
227 final ArrayList<UserStartedState> mStartingUsers
228 = new ArrayList<UserStartedState>();
229
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700230 /**
231 * Set when the system is going to sleep, until we have
232 * successfully paused the current activity and released our wake lock.
233 * At that point the system is allowed to actually sleep.
234 */
235 final PowerManager.WakeLock mGoingToSleep;
236
237 /**
238 * We don't want to allow the device to go to sleep while in the process
239 * of launching an activity. This is primarily to allow alarm intent
240 * receivers to launch an activity and get that to run before the device
241 * goes back to sleep.
242 */
243 final PowerManager.WakeLock mLaunchingActivity;
244
245 /**
246 * When we are in the process of pausing an activity, before starting the
247 * next one, this variable holds the activity that is currently being paused.
248 */
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800249 ActivityRecord mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700250
251 /**
252 * This is the last activity that we put into the paused state. This is
253 * used to determine if we need to do an activity transition while sleeping,
254 * when we normally hold the top activity paused.
255 */
256 ActivityRecord mLastPausedActivity = null;
257
258 /**
259 * Current activity that is resumed, or null if there is none.
260 */
261 ActivityRecord mResumedActivity = null;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800262
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700263 /**
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700264 * This is the last activity that has been started. It is only used to
265 * identify when multiple activities are started at once so that the user
266 * can be warned they may not be in the activity they think they are.
267 */
268 ActivityRecord mLastStartedActivity = null;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800269
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700270 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700271 * Set when we know we are going to be calling updateConfiguration()
272 * soon, so want to skip intermediate config checks.
273 */
274 boolean mConfigWillChange;
275
276 /**
277 * Set to indicate whether to issue an onUserLeaving callback when a
278 * newly launched activity is being brought in front of us.
279 */
280 boolean mUserLeaving = false;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800281
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700282 long mInitialStartTime = 0;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800283
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800284 /**
285 * Set when we have taken too long waiting to go to sleep.
286 */
287 boolean mSleepTimeout = false;
288
Dianne Hackborn90c52de2011-09-23 12:57:44 -0700289 /**
290 * Dismiss the keyguard after the next activity is displayed?
291 */
292 boolean mDismissKeyguardOnNextActivity = false;
293
Craig Mautnerb12428a2012-12-20 16:07:06 -0800294 /**
295 * Save the most recent screenshot for reuse. This keeps Recents from taking two identical
296 * screenshots, one for the Recents thumbnail and one for the pauseActivity thumbnail.
297 */
298 private ActivityRecord mLastScreenshotActivity = null;
299 private Bitmap mLastScreenshotBitmap = null;
300
Craig Mautnercae015f2013-02-08 14:31:27 -0800301 /**
302 * List of ActivityRecord objects that have been finished and must
303 * still report back to a pending thumbnail receiver.
304 */
305 private final ArrayList<ActivityRecord> mCancelledThumbnails = new ArrayList<ActivityRecord>();
306
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800307 int mThumbnailWidth = -1;
308 int mThumbnailHeight = -1;
309
Amith Yamasani742a6712011-05-04 14:49:28 -0700310 private int mCurrentUser;
311
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800312 static final int SLEEP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG;
313 static final int PAUSE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 1;
314 static final int IDLE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 2;
315 static final int IDLE_NOW_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 3;
316 static final int LAUNCH_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 4;
317 static final int DESTROY_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 5;
318 static final int RESUME_TOP_ACTIVITY_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 6;
Dianne Hackborn29ba7e62012-03-16 15:03:36 -0700319 static final int LAUNCH_TICK_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 7;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700320 static final int STOP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 8;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700321 static final int DESTROY_ACTIVITIES_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 9;
322
323 static class ScheduleDestroyArgs {
324 final ProcessRecord mOwner;
325 final boolean mOomAdj;
326 final String mReason;
327 ScheduleDestroyArgs(ProcessRecord owner, boolean oomAdj, String reason) {
328 mOwner = owner;
329 mOomAdj = oomAdj;
330 mReason = reason;
331 }
332 }
333
Zoran Marcetaf958b322012-08-09 20:27:12 +0900334 final Handler mHandler;
335
336 final class ActivityStackHandler extends Handler {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700337 //public Handler() {
338 // if (localLOGV) Slog.v(TAG, "Handler started!");
339 //}
Zoran Marcetaf958b322012-08-09 20:27:12 +0900340 public ActivityStackHandler(Looper looper) {
341 super(looper);
342 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700343
Zoran Marcetaf958b322012-08-09 20:27:12 +0900344 @Override
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700345 public void handleMessage(Message msg) {
346 switch (msg.what) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800347 case SLEEP_TIMEOUT_MSG: {
Dianne Hackborn8e8d65f2011-08-11 19:36:18 -0700348 synchronized (mService) {
349 if (mService.isSleeping()) {
350 Slog.w(TAG, "Sleep timeout! Sleeping now.");
351 mSleepTimeout = true;
352 checkReadyForSleepLocked();
353 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800354 }
355 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700356 case PAUSE_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800357 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700358 // We don't at this point know if the activity is fullscreen,
359 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800360 Slog.w(TAG, "Activity pause timeout for " + r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700361 synchronized (mService) {
362 if (r.app != null) {
363 mService.logAppTooSlow(r.app, r.pauseTime,
364 "pausing " + r);
365 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700366
Craig Mautnerd2328952013-03-05 12:46:26 -0800367 activityPausedLocked(r != null ? r.appToken : null, true);
368 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700369 } break;
370 case IDLE_TIMEOUT_MSG: {
371 if (mService.mDidDexOpt) {
372 mService.mDidDexOpt = false;
373 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
374 nmsg.obj = msg.obj;
375 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
376 return;
377 }
378 // We don't at this point know if the activity is fullscreen,
379 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800380 ActivityRecord r = (ActivityRecord)msg.obj;
381 Slog.w(TAG, "Activity idle timeout for " + r);
382 activityIdleInternal(r != null ? r.appToken : null, true, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700383 } break;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700384 case LAUNCH_TICK_MSG: {
385 ActivityRecord r = (ActivityRecord)msg.obj;
386 synchronized (mService) {
387 if (r.continueLaunchTickingLocked()) {
388 mService.logAppTooSlow(r.app, r.launchTickTime,
389 "launching " + r);
390 }
391 }
392 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700393 case DESTROY_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800394 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700395 // We don't at this point know if the activity is fullscreen,
396 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800397 Slog.w(TAG, "Activity destroy timeout for " + r);
Craig Mautnerd2328952013-03-05 12:46:26 -0800398 synchronized (mService) {
399 activityDestroyedLocked(r != null ? r.appToken : null);
400 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700401 } break;
402 case IDLE_NOW_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800403 ActivityRecord r = (ActivityRecord)msg.obj;
404 activityIdleInternal(r != null ? r.appToken : null, false, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700405 } break;
406 case LAUNCH_TIMEOUT_MSG: {
407 if (mService.mDidDexOpt) {
408 mService.mDidDexOpt = false;
409 Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
410 mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
411 return;
412 }
413 synchronized (mService) {
414 if (mLaunchingActivity.isHeld()) {
415 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
416 mLaunchingActivity.release();
417 }
418 }
419 } break;
420 case RESUME_TOP_ACTIVITY_MSG: {
421 synchronized (mService) {
422 resumeTopActivityLocked(null);
423 }
424 } break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700425 case STOP_TIMEOUT_MSG: {
426 ActivityRecord r = (ActivityRecord)msg.obj;
427 // We don't at this point know if the activity is fullscreen,
428 // so we need to be conservative and assume it isn't.
429 Slog.w(TAG, "Activity stop timeout for " + r);
430 synchronized (mService) {
431 if (r.isInHistory()) {
432 activityStoppedLocked(r, null, null, null);
433 }
434 }
435 } break;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700436 case DESTROY_ACTIVITIES_MSG: {
437 ScheduleDestroyArgs args = (ScheduleDestroyArgs)msg.obj;
438 synchronized (mService) {
439 destroyActivitiesLocked(args.mOwner, args.mOomAdj, args.mReason);
440 }
441 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700442 }
443 }
Craig Mautner4b71aa12012-12-27 17:20:01 -0800444 }
445
Craig Mautner000f0022013-02-26 15:04:29 -0800446 private int numActivities() {
447 int count = 0;
448 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
449 count += mTaskHistory.get(taskNdx).mActivities.size();
450 }
451 return count;
452 }
453
Zoran Marcetaf958b322012-08-09 20:27:12 +0900454 ActivityStack(ActivityManagerService service, Context context, boolean mainStack, Looper looper) {
455 mHandler = new ActivityStackHandler(looper);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700456 mService = service;
457 mContext = context;
458 mMainStack = mainStack;
459 PowerManager pm =
460 (PowerManager)context.getSystemService(Context.POWER_SERVICE);
461 mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
462 mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
463 mLaunchingActivity.setReferenceCounted(false);
464 }
Craig Mautner5962b122012-10-05 14:45:52 -0700465
466 private boolean okToShow(ActivityRecord r) {
467 return r.userId == mCurrentUser
468 || (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0;
469 }
470
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700471 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800472 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
473 final TaskRecord task = mTaskHistory.get(taskNdx);
Craig Mautner11bf9a52013-02-19 14:08:51 -0800474 final ArrayList<ActivityRecord> activities = task.mActivities;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800475 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
476 ActivityRecord r = activities.get(activityNdx);
Craig Mautner11bf9a52013-02-19 14:08:51 -0800477 if (!r.finishing && r != notTop && okToShow(r)) {
478 return r;
479 }
480 }
481 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700482 return null;
483 }
484
485 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800486 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
487 final TaskRecord task = mTaskHistory.get(taskNdx);
Craig Mautner11bf9a52013-02-19 14:08:51 -0800488 final ArrayList<ActivityRecord> activities = task.mActivities;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800489 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
490 ActivityRecord r = activities.get(activityNdx);
Craig Mautner11bf9a52013-02-19 14:08:51 -0800491 if (!r.finishing && !r.delayedResume && r != notTop && okToShow(r)) {
492 return r;
493 }
494 }
495 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700496 return null;
497 }
498
499 /**
500 * This is a simplified version of topRunningActivityLocked that provides a number of
501 * optional skip-over modes. It is intended for use with the ActivityController hook only.
Craig Mautner9658b312013-02-28 10:55:59 -0800502 *
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700503 * @param token If non-null, any history records matching this token will be skipped.
504 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
Craig Mautner9658b312013-02-28 10:55:59 -0800505 *
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700506 * @return Returns the HistoryRecord of the next activity on the stack.
507 */
508 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
Craig Mautner11bf9a52013-02-19 14:08:51 -0800509 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
510 TaskRecord task = mTaskHistory.get(taskNdx);
511 if (task.taskId == taskId) {
512 continue;
513 }
514 ArrayList<ActivityRecord> activities = task.mActivities;
515 for (int i = activities.size() - 1; i >= 0; --i) {
516 final ActivityRecord r = activities.get(i);
517 // Note: the taskId check depends on real taskId fields being non-zero
518 if (!r.finishing && (token != r.appToken) && okToShow(r)) {
519 return r;
520 }
521 }
522 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700523 return null;
524 }
525
Craig Mautnerd2328952013-03-05 12:46:26 -0800526 TaskRecord taskForIdLocked(int id) {
527 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
528 final TaskRecord task = mTaskHistory.get(taskNdx);
529 if (task.taskId == id) {
530 return task;
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800531 }
532 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700533 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700534 }
535
Craig Mautnerd2328952013-03-05 12:46:26 -0800536 ActivityRecord isInStackLocked(IBinder token) {
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800537 final ActivityRecord r = ActivityRecord.forToken(token);
Craig Mautnerd2328952013-03-05 12:46:26 -0800538 if (r != null) {
539 final TaskRecord task = r.task;
540 if (task.mActivities.contains(r) && mTaskHistory.contains(task)) {
541 if (task.stack != this) Slog.w(TAG,
542 "Illegal state! task does not point to stack it is in.");
543 return r;
544 }
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800545 }
Craig Mautnerd2328952013-03-05 12:46:26 -0800546 return null;
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800547 }
548
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700549 private final boolean updateLRUListLocked(ActivityRecord r) {
550 final boolean hadit = mLRUActivities.remove(r);
551 mLRUActivities.add(r);
552 return hadit;
553 }
554
555 /**
556 * Returns the top activity in any existing task matching the given
557 * Intent. Returns null if no such task is found.
558 */
559 private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
560 ComponentName cls = intent.getComponent();
561 if (info.targetActivity != null) {
562 cls = new ComponentName(info.packageName, info.targetActivity);
563 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700564 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Craig Mautner000f0022013-02-26 15:04:29 -0800565
566 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
567 final TaskRecord task = mTaskHistory.get(taskNdx);
568 final ActivityRecord r = task.getTopActivity();
569 if (r == null || r.finishing || r.userId != userId ||
570 r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
571 continue;
572 }
573
574 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
575 // + "/aff=" + r.task.affinity + " to new cls="
576 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
577 if (task.affinity != null) {
578 if (task.affinity.equals(info.taskAffinity)) {
579 //Slog.i(TAG, "Found matching affinity!");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700580 return r;
581 }
Craig Mautner000f0022013-02-26 15:04:29 -0800582 } else if (task.intent != null && task.intent.getComponent().equals(cls)) {
583 //Slog.i(TAG, "Found matching class!");
584 //dump();
585 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
586 return r;
587 } else if (task.affinityIntent != null
588 && task.affinityIntent.getComponent().equals(cls)) {
589 //Slog.i(TAG, "Found matching class!");
590 //dump();
591 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
592 return r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700593 }
594 }
595
596 return null;
597 }
598
599 /**
600 * Returns the first activity (starting from the top of the stack) that
601 * is the same as the given activity. Returns null if no such activity
602 * is found.
603 */
604 private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
605 ComponentName cls = intent.getComponent();
606 if (info.targetActivity != null) {
607 cls = new ComponentName(info.packageName, info.targetActivity);
608 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700609 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700610
Craig Mautner000f0022013-02-26 15:04:29 -0800611 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
612 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
613 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
614 ActivityRecord r = activities.get(activityNdx);
615 if (!r.finishing && r.intent.getComponent().equals(cls) && r.userId == userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700616 //Slog.i(TAG, "Found matching class!");
617 //dump();
618 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
619 return r;
620 }
621 }
622 }
623
624 return null;
625 }
626
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700627 final void showAskCompatModeDialogLocked(ActivityRecord r) {
628 Message msg = Message.obtain();
629 msg.what = ActivityManagerService.SHOW_COMPAT_MODE_DIALOG_MSG;
630 msg.obj = r.task.askedCompatMode ? null : r;
631 mService.mHandler.sendMessage(msg);
632 }
633
Amith Yamasani742a6712011-05-04 14:49:28 -0700634 /*
635 * Move the activities around in the stack to bring a user to the foreground.
636 * @return whether there are any activities for the specified user.
637 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700638 final boolean switchUserLocked(int userId, UserStartedState uss) {
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800639 if (VALIDATE_TOKENS) {
640 validateAppTokensLocked();
641 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700642 mStartingUsers.add(uss);
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800643 if (mCurrentUser == userId) {
644 return true;
645 }
646 mCurrentUser = userId;
647
648 // Move userId's tasks to the top.
649 boolean haveActivities = false;
650 TaskRecord task = null;
651 int index = mTaskHistory.size();
652 for (int i = 0; i < index; ++i) {
653 task = mTaskHistory.get(i);
654 if (task.userId == userId) {
655 haveActivities = true;
656 mTaskHistory.remove(i);
657 mTaskHistory.add(task);
658 --index;
659 }
660 }
661
662 // task is now the original topmost TaskRecord. Transition from the old top to the new top.
663 ActivityRecord top = task != null ? task.getTopActivity() : null;
Craig Mautner000f0022013-02-26 15:04:29 -0800664 resumeTopActivityLocked(top);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700665 return haveActivities;
Amith Yamasani742a6712011-05-04 14:49:28 -0700666 }
667
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700668 final boolean realStartActivityLocked(ActivityRecord r,
669 ProcessRecord app, boolean andResume, boolean checkConfig)
670 throws RemoteException {
671
672 r.startFreezingScreenLocked(app, 0);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800673 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700674
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700675 // schedule launch ticks to collect information about slow apps.
676 r.startLaunchTickingLocked();
677
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700678 // Have the window manager re-evaluate the orientation of
679 // the screen based on the new activity order. Note that
680 // as a result of this, it can call back into the activity
681 // manager with a new orientation. We don't care about that,
682 // because the activity is not currently running so we are
683 // just restarting it anyway.
684 if (checkConfig) {
685 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
686 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -0800687 r.mayFreezeScreenLocked(app) ? r.appToken : null);
Dianne Hackborn813075a62011-11-14 17:45:19 -0800688 mService.updateConfigurationLocked(config, r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700689 }
690
691 r.app = app;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700692 app.waitingToKill = null;
Dianne Hackborn07981492013-01-28 11:36:23 -0800693 r.launchCount++;
694 r.lastLaunchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700695
696 if (localLOGV) Slog.v(TAG, "Launching: " + r);
697
698 int idx = app.activities.indexOf(r);
699 if (idx < 0) {
700 app.activities.add(r);
701 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -0700702 mService.updateLruProcessLocked(app, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700703
704 try {
705 if (app.thread == null) {
706 throw new RemoteException();
707 }
708 List<ResultInfo> results = null;
709 List<Intent> newIntents = null;
710 if (andResume) {
711 results = r.results;
712 newIntents = r.newIntents;
713 }
714 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
715 + " icicle=" + r.icicle
716 + " with results=" + results + " newIntents=" + newIntents
717 + " andResume=" + andResume);
718 if (andResume) {
719 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -0700720 r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700721 r.task.taskId, r.shortComponentName);
722 }
723 if (r.isHomeActivity) {
724 mService.mHomeProcess = app;
725 }
726 mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800727 r.sleeping = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400728 r.forceNewConfig = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700729 showAskCompatModeDialogLocked(r);
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700730 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700731 String profileFile = null;
732 ParcelFileDescriptor profileFd = null;
733 boolean profileAutoStop = false;
734 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
735 if (mService.mProfileProc == null || mService.mProfileProc == app) {
736 mService.mProfileProc = app;
737 profileFile = mService.mProfileFile;
738 profileFd = mService.mProfileFd;
739 profileAutoStop = mService.mAutoStopProfiler;
740 }
741 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -0700742 app.hasShownUi = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700743 app.pendingUiClean = true;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700744 if (profileFd != null) {
745 try {
746 profileFd = profileFd.dup();
747 } catch (IOException e) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -0800748 if (profileFd != null) {
749 try {
750 profileFd.close();
751 } catch (IOException o) {
752 }
753 profileFd = null;
754 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700755 }
756 }
Dianne Hackbornbe707852011-11-11 14:32:10 -0800757 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
Dianne Hackborn813075a62011-11-14 17:45:19 -0800758 System.identityHashCode(r), r.info,
759 new Configuration(mService.mConfiguration),
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700760 r.compat, r.icicle, results, newIntents, !andResume,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700761 mService.isNextTransitionForward(), profileFile, profileFd,
762 profileAutoStop);
Craig Mautner9658b312013-02-28 10:55:59 -0800763
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700764 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700765 // This may be a heavy-weight process! Note that the package
766 // manager will ensure that only activity can run in the main
767 // process of the .apk, which is the only thing that will be
768 // considered heavy-weight.
769 if (app.processName.equals(app.info.packageName)) {
770 if (mService.mHeavyWeightProcess != null
771 && mService.mHeavyWeightProcess != app) {
772 Log.w(TAG, "Starting new heavy weight process " + app
773 + " when already running "
774 + mService.mHeavyWeightProcess);
775 }
776 mService.mHeavyWeightProcess = app;
777 Message msg = mService.mHandler.obtainMessage(
778 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
779 msg.obj = r;
780 mService.mHandler.sendMessage(msg);
781 }
782 }
Craig Mautner9658b312013-02-28 10:55:59 -0800783
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700784 } catch (RemoteException e) {
785 if (r.launchFailed) {
786 // This is the second time we failed -- finish activity
787 // and give up.
788 Slog.e(TAG, "Second failure launching "
789 + r.intent.getComponent().flattenToShortString()
790 + ", giving up", e);
791 mService.appDiedLocked(app, app.pid, app.thread);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800792 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700793 "2nd-crash", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700794 return false;
795 }
796
797 // This is the first time we failed -- restart process and
798 // retry.
799 app.activities.remove(r);
800 throw e;
801 }
802
803 r.launchFailed = false;
804 if (updateLRUListLocked(r)) {
805 Slog.w(TAG, "Activity " + r
806 + " being launched, but already in LRU list");
807 }
808
809 if (andResume) {
810 // As part of the process of launching, ActivityThread also performs
811 // a resume.
812 r.state = ActivityState.RESUMED;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700813 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
814 + " (starting new instance)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700815 r.stopped = false;
816 mResumedActivity = r;
817 r.task.touchActiveTime();
Craig Mautnerd2328952013-03-05 12:46:26 -0800818 mService.addRecentTaskLocked(r.task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700819 completeResumeLocked(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800820 checkReadyForSleepLocked();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700821 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Launch completed; removing icicle of " + r.icicle);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700822 } else {
823 // This activity is not starting in the resumed state... which
824 // should look like we asked it to pause+stop (but remain visible),
825 // and it has done so and reported back the current icicle and
826 // other state.
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700827 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
828 + " (starting in stopped state)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700829 r.state = ActivityState.STOPPED;
830 r.stopped = true;
831 }
832
833 // Launch the new version setup screen if needed. We do this -after-
834 // launching the initial activity (that is, home), so that it can have
835 // a chance to initialize itself while in the background, making the
836 // switch back to it faster and look better.
837 if (mMainStack) {
838 mService.startSetupActivityLocked();
839 }
Craig Mautner9658b312013-02-28 10:55:59 -0800840
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700841 return true;
842 }
843
844 private final void startSpecificActivityLocked(ActivityRecord r,
845 boolean andResume, boolean checkConfig) {
846 // Is this activity's application already running?
847 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
848 r.info.applicationInfo.uid);
Dianne Hackborn07981492013-01-28 11:36:23 -0800849
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700850 if (r.launchTime == 0) {
851 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700852 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700853 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700854 }
855 } else if (mInitialStartTime == 0) {
856 mInitialStartTime = SystemClock.uptimeMillis();
857 }
Craig Mautneraab647e2013-02-28 16:31:36 -0800858
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700859 if (app != null && app.thread != null) {
860 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700861 app.addPackage(r.info.packageName);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700862 realStartActivityLocked(r, app, andResume, checkConfig);
863 return;
864 } catch (RemoteException e) {
865 Slog.w(TAG, "Exception when starting activity "
866 + r.intent.getComponent().flattenToShortString(), e);
867 }
868
869 // If a dead object exception was thrown -- fall through to
870 // restart the application.
871 }
872
873 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800874 "activity", r.intent.getComponent(), false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700875 }
Craig Mautneraab647e2013-02-28 16:31:36 -0800876
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800877 void stopIfSleepingLocked() {
878 if (mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700879 if (!mGoingToSleep.isHeld()) {
880 mGoingToSleep.acquire();
881 if (mLaunchingActivity.isHeld()) {
882 mLaunchingActivity.release();
883 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
884 }
885 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800886 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
887 Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
888 mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
889 checkReadyForSleepLocked();
890 }
891 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700892
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800893 void awakeFromSleepingLocked() {
894 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
895 mSleepTimeout = false;
896 if (mGoingToSleep.isHeld()) {
897 mGoingToSleep.release();
898 }
899 // Ensure activities are no longer sleeping.
Craig Mautnerd44711d2013-02-23 11:24:36 -0800900 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
901 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
902 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
903 activities.get(activityNdx).setSleeping(false);
904 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800905 }
906 mGoingToSleepActivities.clear();
907 }
908
909 void activitySleptLocked(ActivityRecord r) {
910 mGoingToSleepActivities.remove(r);
911 checkReadyForSleepLocked();
912 }
913
914 void checkReadyForSleepLocked() {
915 if (!mService.isSleeping()) {
916 // Do not care.
917 return;
918 }
919
920 if (!mSleepTimeout) {
921 if (mResumedActivity != null) {
922 // Still have something resumed; can't sleep until it is paused.
923 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700924 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
925 startPausingLocked(false, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800926 return;
927 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800928 if (mPausingActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800929 // Still waiting for something to pause; can't sleep yet.
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800930 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800931 return;
932 }
933
934 if (mStoppingActivities.size() > 0) {
935 // Still need to tell some activities to stop; can't sleep yet.
936 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
937 + mStoppingActivities.size() + " activities");
Dianne Hackborn80a7ac12011-09-22 18:32:52 -0700938 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800939 return;
940 }
941
942 ensureActivitiesVisibleLocked(null, 0);
943
944 // Make sure any stopped but visible activities are now sleeping.
945 // This ensures that the activity's onStop() is called.
Craig Mautnerd44711d2013-02-23 11:24:36 -0800946 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
947 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
948 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
949 final ActivityRecord r = activities.get(activityNdx);
950 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
951 r.setSleeping(true);
952 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800953 }
954 }
955
956 if (mGoingToSleepActivities.size() > 0) {
957 // Still need to tell some activities to sleep; can't sleep yet.
958 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
959 + mGoingToSleepActivities.size() + " activities");
960 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700961 }
962 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800963
964 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
965
966 if (mGoingToSleep.isHeld()) {
967 mGoingToSleep.release();
968 }
969 if (mService.mShuttingDown) {
970 mService.notifyAll();
971 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700972 }
Craig Mautner59c00972012-07-30 12:10:24 -0700973
Dianne Hackbornd2835932010-12-13 16:28:46 -0800974 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -0800975 if (who.noDisplay) {
976 return null;
977 }
Craig Mautneraab647e2013-02-28 16:31:36 -0800978
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800979 Resources res = mService.mContext.getResources();
980 int w = mThumbnailWidth;
981 int h = mThumbnailHeight;
982 if (w < 0) {
983 mThumbnailWidth = w =
984 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
985 mThumbnailHeight = h =
986 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
987 }
988
989 if (w > 0) {
Craig Mautnerb12428a2012-12-20 16:07:06 -0800990 if (who != mLastScreenshotActivity || mLastScreenshotBitmap == null
991 || mLastScreenshotBitmap.getWidth() != w
992 || mLastScreenshotBitmap.getHeight() != h) {
993 mLastScreenshotActivity = who;
994 mLastScreenshotBitmap = mService.mWindowManager.screenshotApplications(
995 who.appToken, Display.DEFAULT_DISPLAY, w, h);
996 }
997 if (mLastScreenshotBitmap != null) {
998 return mLastScreenshotBitmap.copy(Config.ARGB_8888, true);
999 }
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001000 }
1001 return null;
1002 }
1003
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001004 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001005 if (mPausingActivity != null) {
1006 RuntimeException e = new RuntimeException();
1007 Slog.e(TAG, "Trying to pause when pause is already pending for "
1008 + mPausingActivity, e);
1009 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001010 ActivityRecord prev = mResumedActivity;
1011 if (prev == null) {
1012 RuntimeException e = new RuntimeException();
1013 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
1014 resumeTopActivityLocked(null);
1015 return;
1016 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001017 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
1018 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001019 mResumedActivity = null;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001020 mPausingActivity = prev;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001021 mLastPausedActivity = prev;
1022 prev.state = ActivityState.PAUSING;
1023 prev.task.touchActiveTime();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001024 prev.updateThumbnail(screenshotActivities(prev), null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001025
1026 mService.updateCpuStats();
Craig Mautneraab647e2013-02-28 16:31:36 -08001027
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001028 if (prev.app != null && prev.app.thread != null) {
1029 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
1030 try {
1031 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001032 prev.userId, System.identityHashCode(prev),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001033 prev.shortComponentName);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001034 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
1035 userLeaving, prev.configChangeFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001036 if (mMainStack) {
1037 mService.updateUsageStats(prev, false);
1038 }
1039 } catch (Exception e) {
1040 // Ignore exception, if process died other code will cleanup.
1041 Slog.w(TAG, "Exception thrown during pause", e);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001042 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001043 mLastPausedActivity = null;
1044 }
1045 } else {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001046 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001047 mLastPausedActivity = null;
1048 }
1049
1050 // If we are not going to sleep, we want to ensure the device is
1051 // awake until the next activity is started.
1052 if (!mService.mSleeping && !mService.mShuttingDown) {
1053 mLaunchingActivity.acquire();
1054 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
1055 // To be safe, don't allow the wake lock to be held for too long.
1056 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
1057 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
1058 }
1059 }
1060
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001061
1062 if (mPausingActivity != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001063 // Have the window manager pause its key dispatching until the new
1064 // activity has started. If we're pausing the activity just because
1065 // the screen is being turned off and the UI is sleeping, don't interrupt
1066 // key dispatch; the same activity will pick it up again on wakeup.
1067 if (!uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001068 prev.pauseKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001069 } else {
1070 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
1071 }
1072
1073 // Schedule a pause timeout in case the app doesn't respond.
1074 // We don't give it much time because this directly impacts the
1075 // responsiveness seen by the user.
1076 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
1077 msg.obj = prev;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001078 prev.pauseTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001079 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
1080 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
1081 } else {
1082 // This activity failed to schedule the
1083 // pause, so just treat it as being paused now.
1084 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001085 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001086 }
1087 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001088
Craig Mautnerd2328952013-03-05 12:46:26 -08001089 final void activityResumedLocked(IBinder token) {
1090 final ActivityRecord r = ActivityRecord.forToken(token);
1091 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Resumed activity; dropping state of: " + r);
1092 r.icicle = null;
1093 r.haveState = false;
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001094 }
1095
Craig Mautnerd2328952013-03-05 12:46:26 -08001096 final void activityPausedLocked(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001097 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001098 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001099
Craig Mautnerd2328952013-03-05 12:46:26 -08001100 final ActivityRecord r = isInStackLocked(token);
1101 if (r != null) {
1102 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
1103 if (mPausingActivity == r) {
1104 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
1105 + (timeout ? " (due to timeout)" : " (pause complete)"));
1106 r.state = ActivityState.PAUSED;
1107 completePauseLocked();
1108 } else {
1109 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
1110 r.userId, System.identityHashCode(r), r.shortComponentName,
1111 mPausingActivity != null
1112 ? mPausingActivity.shortComponentName : "(none)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001113 }
1114 }
1115 }
1116
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001117 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
1118 CharSequence description) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07001119 if (r.state != ActivityState.STOPPING) {
1120 Slog.i(TAG, "Activity reported stop, but no longer stopping: " + r);
1121 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1122 return;
1123 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001124 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Saving icicle of " + r + ": " + icicle);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001125 if (icicle != null) {
1126 // If icicle is null, this is happening due to a timeout, so we
1127 // haven't really saved the state.
1128 r.icicle = icicle;
1129 r.haveState = true;
Dianne Hackborn07981492013-01-28 11:36:23 -08001130 r.launchCount = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001131 r.updateThumbnail(thumbnail, description);
1132 }
1133 if (!r.stopped) {
1134 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
1135 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1136 r.stopped = true;
1137 r.state = ActivityState.STOPPED;
Dianne Hackborn6e3d6da2012-06-15 12:05:27 -07001138 if (r.finishing) {
1139 r.clearOptionsLocked();
1140 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001141 if (r.configDestroy) {
1142 destroyActivityLocked(r, true, false, "stop-config");
1143 resumeTopActivityLocked(null);
1144 } else {
1145 // Now that this process has stopped, we may want to consider
1146 // it to be the previous app to try to keep around in case
1147 // the user wants to return to it.
1148 ProcessRecord fgApp = null;
1149 if (mResumedActivity != null) {
1150 fgApp = mResumedActivity.app;
1151 } else if (mPausingActivity != null) {
1152 fgApp = mPausingActivity.app;
1153 }
1154 if (r.app != null && fgApp != null && r.app != fgApp
1155 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
1156 && r.app != mService.mHomeProcess) {
1157 mService.mPreviousProcess = r.app;
1158 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
1159 }
Dianne Hackborn50685602011-12-01 12:23:37 -08001160 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001161 }
1162 }
1163 }
1164
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001165 private final void completePauseLocked() {
1166 ActivityRecord prev = mPausingActivity;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001167 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
Craig Mautneraab647e2013-02-28 16:31:36 -08001168
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001169 if (prev != null) {
1170 if (prev.finishing) {
1171 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001172 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001173 } else if (prev.app != null) {
1174 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
1175 if (prev.waitingVisible) {
1176 prev.waitingVisible = false;
1177 mWaitingVisibleActivities.remove(prev);
1178 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
1179 TAG, "Complete pause, no longer waiting: " + prev);
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001180 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001181 if (prev.configDestroy) {
1182 // The previous is being paused because the configuration
1183 // is changing, which means it is actually stopping...
1184 // To juggle the fact that we are also starting a new
1185 // instance right now, we need to first completely stop
1186 // the current instance before starting the new one.
1187 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
1188 destroyActivityLocked(prev, true, false, "pause-config");
1189 } else {
1190 mStoppingActivities.add(prev);
1191 if (mStoppingActivities.size() > 3) {
1192 // If we already have a few activities waiting to stop,
1193 // then give up on things going idle and start clearing
1194 // them out.
1195 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
1196 scheduleIdleLocked();
1197 } else {
1198 checkReadyForSleepLocked();
1199 }
1200 }
1201 } else {
1202 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
1203 prev = null;
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001204 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001205 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001206 }
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001207
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001208 if (!mService.isSleeping()) {
1209 resumeTopActivityLocked(prev);
1210 } else {
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001211 checkReadyForSleepLocked();
Dianne Hackborncc5a0552012-10-01 16:32:39 -07001212 ActivityRecord top = topRunningActivityLocked(null);
1213 if (top == null || (prev != null && top != prev)) {
1214 // If there are no more activities available to run,
1215 // do resume anyway to start something. Also if the top
1216 // activity on the stack is not the just paused activity,
1217 // we need to go ahead and resume it to ensure we complete
1218 // an in-flight app switch.
Dianne Hackborn42e620c2012-06-24 13:20:51 -07001219 resumeTopActivityLocked(null);
1220 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001221 }
Craig Mautneraab647e2013-02-28 16:31:36 -08001222
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001223 if (prev != null) {
1224 prev.resumeKeyDispatchingLocked();
1225 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001226
1227 if (prev.app != null && prev.cpuTimeAtResume > 0
1228 && mService.mBatteryStatsService.isOnBattery()) {
1229 long diff = 0;
1230 synchronized (mService.mProcessStatsThread) {
1231 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
1232 - prev.cpuTimeAtResume;
1233 }
1234 if (diff > 0) {
1235 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
1236 synchronized (bsi) {
1237 BatteryStatsImpl.Uid.Proc ps =
1238 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
1239 prev.info.packageName);
1240 if (ps != null) {
1241 ps.addForegroundTimeLocked(diff);
1242 }
1243 }
1244 }
1245 }
1246 prev.cpuTimeAtResume = 0; // reset it
1247 }
1248
1249 /**
1250 * Once we know that we have asked an application to put an activity in
1251 * the resumed state (either by launching it or explicitly telling it),
1252 * this function updates the rest of our state to match that fact.
1253 */
1254 private final void completeResumeLocked(ActivityRecord next) {
1255 next.idle = false;
1256 next.results = null;
1257 next.newIntents = null;
1258
1259 // schedule an idle timeout in case the app doesn't do it for us.
1260 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1261 msg.obj = next;
1262 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
1263
1264 if (false) {
1265 // The activity was never told to pause, so just keep
1266 // things going as-is. To maintain our own state,
1267 // we need to emulate it coming back and saying it is
1268 // idle.
1269 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
1270 msg.obj = next;
1271 mHandler.sendMessage(msg);
1272 }
1273
1274 if (mMainStack) {
1275 mService.reportResumedActivityLocked(next);
1276 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07001277
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001278 if (mMainStack) {
1279 mService.setFocusedActivityLocked(next);
1280 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001281 next.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001282 ensureActivitiesVisibleLocked(null, 0);
1283 mService.mWindowManager.executeAppTransition();
1284 mNoAnimActivities.clear();
1285
1286 // Mark the point when the activity is resuming
1287 // TODO: To be more accurate, the mark should be before the onCreate,
1288 // not after the onResume. But for subsequent starts, onResume is fine.
1289 if (next.app != null) {
1290 synchronized (mService.mProcessStatsThread) {
1291 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1292 }
1293 } else {
1294 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1295 }
1296 }
1297
1298 /**
1299 * Make sure that all activities that need to be visible (that is, they
1300 * currently can be seen by the user) actually are.
1301 */
1302 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1303 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1304 if (DEBUG_VISBILITY) Slog.v(
1305 TAG, "ensureActivitiesVisible behind " + top
1306 + " configChanges=0x" + Integer.toHexString(configChanges));
1307
1308 // If the top activity is not fullscreen, then we need to
1309 // make sure any activities under it are now visible.
Craig Mautnerd44711d2013-02-23 11:24:36 -08001310 boolean aboveTop = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001311 boolean behindFullscreen = false;
Craig Mautnerd44711d2013-02-23 11:24:36 -08001312 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
1313 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
1314 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
1315 final ActivityRecord r = activities.get(activityNdx);
1316 if (r.finishing) {
1317 continue;
1318 }
1319 if (aboveTop && r != top) {
1320 continue;
1321 }
1322 aboveTop = false;
1323 if (!behindFullscreen) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001324 if (DEBUG_VISBILITY) Slog.v(
Craig Mautnerd44711d2013-02-23 11:24:36 -08001325 TAG, "Make visible? " + r + " finishing=" + r.finishing
1326 + " state=" + r.state);
Craig Mautner58547802013-03-05 08:23:53 -08001327
Craig Mautnerd44711d2013-02-23 11:24:36 -08001328 final boolean doThisProcess = onlyThisProcess == null
1329 || onlyThisProcess.equals(r.processName);
1330
1331 // First: if this is not the current activity being started, make
1332 // sure it matches the current configuration.
1333 if (r != starting && doThisProcess) {
1334 ensureActivityConfigurationLocked(r, 0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001335 }
Craig Mautnerd44711d2013-02-23 11:24:36 -08001336
1337 if (r.app == null || r.app.thread == null) {
1338 if (onlyThisProcess == null
1339 || onlyThisProcess.equals(r.processName)) {
1340 // This activity needs to be visible, but isn't even
1341 // running... get it started, but don't resume it
1342 // at this point.
1343 if (DEBUG_VISBILITY) Slog.v(
1344 TAG, "Start and freeze screen for " + r);
1345 if (r != starting) {
1346 r.startFreezingScreenLocked(r.app, configChanges);
1347 }
1348 if (!r.visible) {
1349 if (DEBUG_VISBILITY) Slog.v(
1350 TAG, "Starting and making visible: " + r);
1351 mService.mWindowManager.setAppVisibility(r.appToken, true);
1352 }
1353 if (r != starting) {
1354 startSpecificActivityLocked(r, false, false);
1355 }
1356 }
1357
1358 } else if (r.visible) {
1359 // If this activity is already visible, then there is nothing
1360 // else to do here.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001361 if (DEBUG_VISBILITY) Slog.v(
Craig Mautnerd44711d2013-02-23 11:24:36 -08001362 TAG, "Skipping: already visible at " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001363 r.stopFreezingScreenLocked(false);
Craig Mautnerd44711d2013-02-23 11:24:36 -08001364
1365 } else if (onlyThisProcess == null) {
1366 // This activity is not currently visible, but is running.
1367 // Tell it to become visible.
1368 r.visible = true;
1369 if (r.state != ActivityState.RESUMED && r != starting) {
1370 // If this activity is paused, tell it
1371 // to now show its window.
1372 if (DEBUG_VISBILITY) Slog.v(
1373 TAG, "Making visible and scheduling visibility: " + r);
1374 try {
1375 mService.mWindowManager.setAppVisibility(r.appToken, true);
1376 r.sleeping = false;
1377 r.app.pendingUiClean = true;
1378 r.app.thread.scheduleWindowVisibility(r.appToken, true);
1379 r.stopFreezingScreenLocked(false);
1380 } catch (Exception e) {
1381 // Just skip on any failure; we'll make it
1382 // visible when it next restarts.
1383 Slog.w(TAG, "Exception thrown making visibile: "
1384 + r.intent.getComponent(), e);
1385 }
1386 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001387 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001388
Craig Mautnerd44711d2013-02-23 11:24:36 -08001389 // Aggregate current change flags.
1390 configChanges |= r.configChangeFlags;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001391
Craig Mautnerd44711d2013-02-23 11:24:36 -08001392 if (r.fullscreen) {
1393 // At this point, nothing else needs to be shown
1394 if (DEBUG_VISBILITY) Slog.v(
1395 TAG, "Stopping: fullscreen at " + r);
1396 behindFullscreen = true;
1397 }
1398 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001399 if (r.visible) {
1400 if (DEBUG_VISBILITY) Slog.v(
1401 TAG, "Making invisible: " + r);
1402 r.visible = false;
1403 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001404 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001405 if ((r.state == ActivityState.STOPPING
1406 || r.state == ActivityState.STOPPED)
1407 && r.app != null && r.app.thread != null) {
1408 if (DEBUG_VISBILITY) Slog.v(
1409 TAG, "Scheduling invisibility: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001410 r.app.thread.scheduleWindowVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001411 }
1412 } catch (Exception e) {
1413 // Just skip on any failure; we'll make it
1414 // visible when it next restarts.
1415 Slog.w(TAG, "Exception thrown making hidden: "
1416 + r.intent.getComponent(), e);
1417 }
1418 } else {
1419 if (DEBUG_VISBILITY) Slog.v(
1420 TAG, "Already invisible: " + r);
1421 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001422 }
1423 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001424 }
1425 }
1426
1427 /**
1428 * Version of ensureActivitiesVisible that can easily be called anywhere.
1429 */
1430 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1431 int configChanges) {
1432 ActivityRecord r = topRunningActivityLocked(null);
1433 if (r != null) {
1434 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1435 }
1436 }
Craig Mautner58547802013-03-05 08:23:53 -08001437
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001438 /**
1439 * Ensure that the top activity in the stack is resumed.
1440 *
1441 * @param prev The previously resumed activity, for when in the process
1442 * of pausing; can be null to call from elsewhere.
1443 *
1444 * @return Returns true if something is being resumed, or false if
1445 * nothing happened.
1446 */
1447 final boolean resumeTopActivityLocked(ActivityRecord prev) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001448 return resumeTopActivityLocked(prev, null);
1449 }
1450
1451 final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001452 // Find the first activity that is not finishing.
1453 ActivityRecord next = topRunningActivityLocked(null);
1454
1455 // Remember how we'll process this pause/resume situation, and ensure
1456 // that the state is reset however we wind up proceeding.
1457 final boolean userLeaving = mUserLeaving;
1458 mUserLeaving = false;
1459
1460 if (next == null) {
1461 // There are no more activities! Let's just start up the
1462 // Launcher...
1463 if (mMainStack) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001464 ActivityOptions.abort(options);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001465 return mService.startHomeActivityLocked(mCurrentUser);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001466 }
1467 }
1468
1469 next.delayedResume = false;
Craig Mautner58547802013-03-05 08:23:53 -08001470
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001471 // If the top activity is the resumed one, nothing to do.
1472 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1473 // Make sure we have executed any pending transitions, since there
1474 // should be nothing left to do at this point.
1475 mService.mWindowManager.executeAppTransition();
1476 mNoAnimActivities.clear();
Dianne Hackborn84375872012-06-01 19:03:50 -07001477 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001478 return false;
1479 }
1480
1481 // If we are sleeping, and there is no resumed activity, and the top
1482 // activity is paused, well that is the state we want.
1483 if ((mService.mSleeping || mService.mShuttingDown)
p13451dbad2872012-04-18 11:39:23 +09001484 && mLastPausedActivity == next
1485 && (next.state == ActivityState.PAUSED
1486 || next.state == ActivityState.STOPPED
1487 || next.state == ActivityState.STOPPING)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001488 // 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 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001495
1496 // Make sure that the user who owns this activity is started. If not,
1497 // we will just leave it as is because someone should be bringing
1498 // another user's activities to the top of the stack.
1499 if (mService.mStartedUsers.get(next.userId) == null) {
1500 Slog.w(TAG, "Skipping resume of top activity " + next
1501 + ": user " + next.userId + " is stopped");
1502 return false;
1503 }
1504
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001505 // The activity may be waiting for stop, but that is no longer
1506 // appropriate for it.
1507 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001508 mGoingToSleepActivities.remove(next);
1509 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001510 mWaitingVisibleActivities.remove(next);
1511
Dianne Hackborn84375872012-06-01 19:03:50 -07001512 next.updateOptionsLocked(options);
1513
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001514 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1515
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001516 // If we are currently pausing an activity, then don't do anything
1517 // until that is done.
1518 if (mPausingActivity != null) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07001519 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(TAG,
1520 "Skip resume: pausing=" + mPausingActivity);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001521 return false;
1522 }
1523
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001524 // Okay we are now going to start a switch, to 'next'. We may first
1525 // have to pause the current activity, but this is an important point
1526 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001527 // XXX "App Redirected" dialog is getting too many false positives
1528 // at this point, so turn off for now.
1529 if (false) {
1530 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1531 long now = SystemClock.uptimeMillis();
1532 final boolean inTime = mLastStartedActivity.startTime != 0
1533 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1534 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1535 final int nextUid = next.info.applicationInfo.uid;
1536 if (inTime && lastUid != nextUid
1537 && lastUid != next.launchedFromUid
1538 && mService.checkPermission(
1539 android.Manifest.permission.STOP_APP_SWITCHES,
1540 -1, next.launchedFromUid)
1541 != PackageManager.PERMISSION_GRANTED) {
1542 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1543 } else {
1544 next.startTime = now;
1545 mLastStartedActivity = next;
1546 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001547 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001548 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001549 mLastStartedActivity = next;
1550 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001551 }
Craig Mautner58547802013-03-05 08:23:53 -08001552
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001553 // We need to start pausing the current activity so the top one
1554 // can be resumed...
1555 if (mResumedActivity != null) {
1556 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001557 // At this point we want to put the upcoming activity's process
1558 // at the top of the LRU list, since we know we will be needing it
1559 // very soon and it would be a waste to let it get killed if it
1560 // happens to be sitting towards the end.
1561 if (next.app != null && next.app.thread != null) {
1562 // No reason to do full oom adj update here; we'll let that
1563 // happen whenever it needs to later.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001564 mService.updateLruProcessLocked(next.app, false);
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001565 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001566 startPausingLocked(userLeaving, false);
1567 return true;
1568 }
1569
Christopher Tated3f175c2012-06-14 14:16:54 -07001570 // If the most recent activity was noHistory but was only stopped rather
1571 // than stopped+finished because the device went to sleep, we need to make
1572 // sure to finish it as we're making a new activity topmost.
1573 final ActivityRecord last = mLastPausedActivity;
1574 if (mService.mSleeping && last != null && !last.finishing) {
1575 if ((last.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
1576 || (last.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
1577 if (DEBUG_STATES) {
1578 Slog.d(TAG, "no-history finish of " + last + " on new resume");
1579 }
1580 requestFinishActivityLocked(last.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001581 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07001582 }
1583 }
1584
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001585 if (prev != null && prev != next) {
1586 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1587 prev.waitingVisible = true;
1588 mWaitingVisibleActivities.add(prev);
1589 if (DEBUG_SWITCH) Slog.v(
1590 TAG, "Resuming top, waiting visible to hide: " + prev);
1591 } else {
1592 // The next activity is already visible, so hide the previous
1593 // activity's windows right now so we can show the new one ASAP.
1594 // We only do this if the previous is finishing, which should mean
1595 // it is on top of the one being resumed so hiding it quickly
1596 // is good. Otherwise, we want to do the normal route of allowing
1597 // the resumed activity to be shown so we can decide if the
1598 // previous should actually be hidden depending on whether the
1599 // new one is found to be full-screen or not.
1600 if (prev.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001601 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001602 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1603 + prev + ", waitingVisible="
1604 + (prev != null ? prev.waitingVisible : null)
1605 + ", nowVisible=" + next.nowVisible);
1606 } else {
1607 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1608 + prev + ", waitingVisible="
1609 + (prev != null ? prev.waitingVisible : null)
1610 + ", nowVisible=" + next.nowVisible);
1611 }
1612 }
1613 }
1614
Dianne Hackborne7f97212011-02-24 14:40:20 -08001615 // Launching this app's activity, make sure the app is no longer
1616 // considered stopped.
1617 try {
1618 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001619 next.packageName, false, next.userId); /* TODO: Verify if correct userid */
Dianne Hackborne7f97212011-02-24 14:40:20 -08001620 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001621 } catch (IllegalArgumentException e) {
1622 Slog.w(TAG, "Failed trying to unstop package "
1623 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001624 }
1625
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001626 // We are starting up the next activity, so tell the window manager
1627 // that the previous one will be hidden soon. This way it can know
1628 // to ignore it when computing the desired screen orientation.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001629 boolean noAnim = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001630 if (prev != null) {
1631 if (prev.finishing) {
1632 if (DEBUG_TRANSITION) Slog.v(TAG,
1633 "Prepare close transition: prev=" + prev);
1634 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001635 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001636 AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001637 } else {
1638 mService.mWindowManager.prepareAppTransition(prev.task == next.task
Craig Mautner4b71aa12012-12-27 17:20:01 -08001639 ? AppTransition.TRANSIT_ACTIVITY_CLOSE
1640 : AppTransition.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001641 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001642 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1643 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001644 } else {
1645 if (DEBUG_TRANSITION) Slog.v(TAG,
1646 "Prepare open transition: prev=" + prev);
1647 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001648 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001649 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001650 AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001651 } else {
1652 mService.mWindowManager.prepareAppTransition(prev.task == next.task
Craig Mautner4b71aa12012-12-27 17:20:01 -08001653 ? AppTransition.TRANSIT_ACTIVITY_OPEN
1654 : AppTransition.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001655 }
1656 }
1657 if (false) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001658 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1659 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001660 }
Craig Mautner000f0022013-02-26 15:04:29 -08001661 } else if (numActivities() > 1) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001662 if (DEBUG_TRANSITION) Slog.v(TAG,
1663 "Prepare open transition: no previous");
1664 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001665 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001666 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001667 AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001668 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001669 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001670 AppTransition.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001671 }
1672 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001673 if (!noAnim) {
1674 next.applyOptionsLocked();
1675 } else {
1676 next.clearOptionsLocked();
1677 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001678
1679 if (next.app != null && next.app.thread != null) {
1680 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1681
1682 // This activity is now becoming visible.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001683 mService.mWindowManager.setAppVisibility(next.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001684
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001685 // schedule launch ticks to collect information about slow apps.
1686 next.startLaunchTickingLocked();
1687
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001688 ActivityRecord lastResumedActivity = mResumedActivity;
1689 ActivityState lastState = next.state;
1690
1691 mService.updateCpuStats();
Craig Mautner58547802013-03-05 08:23:53 -08001692
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001693 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001694 next.state = ActivityState.RESUMED;
1695 mResumedActivity = next;
1696 next.task.touchActiveTime();
Craig Mautnerd2328952013-03-05 12:46:26 -08001697 mService.addRecentTaskLocked(next.task);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001698 mService.updateLruProcessLocked(next.app, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001699 updateLRUListLocked(next);
1700
1701 // Have the window manager re-evaluate the orientation of
1702 // the screen based on the new activity order.
1703 boolean updated = false;
1704 if (mMainStack) {
1705 synchronized (mService) {
1706 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1707 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001708 next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001709 if (config != null) {
1710 next.frozenBeforeDestroy = true;
1711 }
Dianne Hackborn813075a62011-11-14 17:45:19 -08001712 updated = mService.updateConfigurationLocked(config, next, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001713 }
1714 }
1715 if (!updated) {
1716 // The configuration update wasn't able to keep the existing
1717 // instance of the activity, and instead started a new one.
1718 // We should be all done, but let's just make sure our activity
1719 // is still at the top and schedule another run if something
1720 // weird happened.
1721 ActivityRecord nextNext = topRunningActivityLocked(null);
1722 if (DEBUG_SWITCH) Slog.i(TAG,
1723 "Activity config changed during resume: " + next
1724 + ", new next: " + nextNext);
1725 if (nextNext != next) {
1726 // Do over!
1727 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1728 }
1729 if (mMainStack) {
1730 mService.setFocusedActivityLocked(next);
1731 }
1732 ensureActivitiesVisibleLocked(null, 0);
1733 mService.mWindowManager.executeAppTransition();
1734 mNoAnimActivities.clear();
1735 return true;
1736 }
Craig Mautner58547802013-03-05 08:23:53 -08001737
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001738 try {
1739 // Deliver all pending results.
Craig Mautner05d6272ba2013-02-11 09:39:27 -08001740 ArrayList<ResultInfo> a = next.results;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001741 if (a != null) {
1742 final int N = a.size();
1743 if (!next.finishing && N > 0) {
1744 if (DEBUG_RESULTS) Slog.v(
1745 TAG, "Delivering results to " + next
1746 + ": " + a);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001747 next.app.thread.scheduleSendResult(next.appToken, a);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001748 }
1749 }
1750
1751 if (next.newIntents != null) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001752 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001753 }
1754
1755 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001756 next.userId, System.identityHashCode(next),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001757 next.task.taskId, next.shortComponentName);
Craig Mautner58547802013-03-05 08:23:53 -08001758
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001759 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001760 showAskCompatModeDialogLocked(next);
Dianne Hackborn905577f2011-09-07 18:31:28 -07001761 next.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001762 next.app.thread.scheduleResumeActivity(next.appToken,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001763 mService.isNextTransitionForward());
Craig Mautner58547802013-03-05 08:23:53 -08001764
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001765 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001766
1767 } catch (Exception e) {
1768 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001769 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1770 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001771 next.state = lastState;
1772 mResumedActivity = lastResumedActivity;
1773 Slog.i(TAG, "Restarting because process died: " + next);
1774 if (!next.hasBeenLaunched) {
1775 next.hasBeenLaunched = true;
1776 } else {
1777 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1778 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001779 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001780 mService.compatibilityInfoForPackageLocked(
1781 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001782 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001783 next.labelRes, next.icon, next.windowFlags,
1784 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001785 }
1786 }
1787 startSpecificActivityLocked(next, true, false);
1788 return true;
1789 }
1790
1791 // From this point on, if something goes wrong there is no way
1792 // to recover the activity.
1793 try {
1794 next.visible = true;
1795 completeResumeLocked(next);
1796 } catch (Exception e) {
1797 // If any exception gets thrown, toss away this
1798 // activity and try the next one.
1799 Slog.w(TAG, "Exception thrown during resume of " + next, e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001800 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001801 "resume-exception", true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001802 return true;
1803 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001804 next.stopped = false;
1805
1806 } else {
1807 // Whoops, need to restart this activity!
1808 if (!next.hasBeenLaunched) {
1809 next.hasBeenLaunched = true;
1810 } else {
1811 if (SHOW_APP_STARTING_PREVIEW) {
1812 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001813 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001814 mService.compatibilityInfoForPackageLocked(
1815 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001816 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001817 next.labelRes, next.icon, next.windowFlags,
1818 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001819 }
1820 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1821 }
1822 startSpecificActivityLocked(next, true, true);
1823 }
1824
1825 return true;
1826 }
1827
Craig Mautner11bf9a52013-02-19 14:08:51 -08001828
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001829 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001830 boolean doResume, boolean keepCurTransition, Bundle options) {
Craig Mautner70a86932013-02-28 22:37:44 -08001831 TaskRecord task = null;
Craig Mautnerd2328952013-03-05 12:46:26 -08001832 TaskRecord rTask = r.task;
1833 final int taskId = rTask.taskId;
1834 if (taskForIdLocked(taskId) == null || newTask) {
Craig Mautner77878772013-03-04 19:46:24 -08001835 // Last activity in task had been removed or ActivityManagerService is reusing task.
1836 // Insert or replace.
Craig Mautner77878772013-03-04 19:46:24 -08001837 // Might not even be in.
Craig Mautnerd2328952013-03-05 12:46:26 -08001838 mTaskHistory.remove(rTask);
Craig Mautner77878772013-03-04 19:46:24 -08001839 // Now put task at top.
Craig Mautnerd2328952013-03-05 12:46:26 -08001840 mTaskHistory.add(rTask);
1841 mService.mWindowManager.moveTaskToTop(taskId);
Craig Mautner77878772013-03-04 19:46:24 -08001842 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001843 if (!newTask) {
1844 // If starting in an existing task, find where that is...
Craig Mautner70a86932013-02-28 22:37:44 -08001845 boolean startIt = true;
1846 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
1847 task = mTaskHistory.get(taskNdx);
1848 if (task == r.task) {
1849 // Here it is! Now, if this is not yet visible to the
1850 // user, then just add it without starting; it will
1851 // get started when the user navigates back to it.
Craig Mautner70a86932013-02-28 22:37:44 -08001852 if (!startIt) {
1853 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to task "
1854 + task, new RuntimeException("here").fillInStackTrace());
1855 task.addActivityToTop(r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001856 r.putInHistory();
Craig Mautner70a86932013-02-28 22:37:44 -08001857 mService.mWindowManager.addAppToken(task.mActivities.indexOf(r),
Craig Mautner58547802013-03-05 08:23:53 -08001858 r.appToken, r.task.taskId, r.info.screenOrientation, r.fullscreen,
Craig Mautner5962b122012-10-05 14:45:52 -07001859 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001860 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001861 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001862 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001863 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001864 return;
1865 }
1866 break;
Craig Mautner70a86932013-02-28 22:37:44 -08001867 } else if (task.numFullscreen > 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001868 startIt = false;
1869 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001870 }
1871 }
1872
1873 // Place a new activity at top of stack, so it is next to interact
1874 // with the user.
Craig Mautner70a86932013-02-28 22:37:44 -08001875
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001876 // If we are not placing the new activity frontmost, we do not want
1877 // to deliver the onUserLeaving callback to the actual frontmost
1878 // activity
Craig Mautner70a86932013-02-28 22:37:44 -08001879 if (task == r.task && mTaskHistory.indexOf(task) != (mTaskHistory.size() - 1)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001880 mUserLeaving = false;
Craig Mautner70a86932013-02-28 22:37:44 -08001881 if (DEBUG_USER_LEAVING) Slog.v(TAG,
1882 "startActivity() behind front, mUserLeaving=false");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001883 }
Craig Mautner70a86932013-02-28 22:37:44 -08001884
1885 task = r.task;
1886
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001887 // Slot the activity into the history stack and proceed
Craig Mautner70a86932013-02-28 22:37:44 -08001888 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to stack to task " + task,
Craig Mautner56f52db2013-02-25 10:03:01 -08001889 new RuntimeException("here").fillInStackTrace());
Craig Mautner70a86932013-02-28 22:37:44 -08001890 task.addActivityToTop(r);
1891
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001892 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001893 r.frontOfTask = newTask;
Craig Mautner70a86932013-02-28 22:37:44 -08001894 if (numActivities() > 1) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001895 // We want to show the starting preview window if we are
1896 // switching to a new task, or the next activity's process is
1897 // not currently running.
1898 boolean showStartingIcon = newTask;
1899 ProcessRecord proc = r.app;
1900 if (proc == null) {
1901 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1902 }
1903 if (proc == null || proc.thread == null) {
1904 showStartingIcon = true;
1905 }
1906 if (DEBUG_TRANSITION) Slog.v(TAG,
1907 "Prepare open transition: starting " + r);
1908 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001909 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001910 AppTransition.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001911 mNoAnimActivities.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001912 } else {
1913 mService.mWindowManager.prepareAppTransition(newTask
Craig Mautner4b71aa12012-12-27 17:20:01 -08001914 ? AppTransition.TRANSIT_TASK_OPEN
1915 : AppTransition.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001916 mNoAnimActivities.remove(r);
1917 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001918 r.updateOptionsLocked(options);
Craig Mautner70a86932013-02-28 22:37:44 -08001919 mService.mWindowManager.addAppToken(task.mActivities.indexOf(r),
Craig Mautner11bf9a52013-02-19 14:08:51 -08001920 r.appToken, r.task.taskId, r.info.screenOrientation, r.fullscreen,
Craig Mautner5962b122012-10-05 14:45:52 -07001921 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001922 boolean doShow = true;
1923 if (newTask) {
1924 // Even though this activity is starting fresh, we still need
1925 // to reset it to make sure we apply affinities to move any
1926 // existing activities from other tasks in to it.
1927 // If the caller has requested that the target task be
1928 // reset, then do so.
1929 if ((r.intent.getFlags()
1930 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1931 resetTaskIfNeededLocked(r, r);
1932 doShow = topRunningNonDelayedActivityLocked(null) == r;
1933 }
1934 }
1935 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1936 // Figure out if we are transitioning from another activity that is
1937 // "has the same starting icon" as the next one. This allows the
1938 // window manager to keep the previous window it had previously
1939 // created, if it still had one.
1940 ActivityRecord prev = mResumedActivity;
1941 if (prev != null) {
1942 // We don't want to reuse the previous starting preview if:
1943 // (1) The current activity is in a different task.
1944 if (prev.task != r.task) prev = null;
1945 // (2) The current activity is already displayed.
1946 else if (prev.nowVisible) prev = null;
1947 }
1948 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001949 r.appToken, r.packageName, r.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001950 mService.compatibilityInfoForPackageLocked(
1951 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001952 r.labelRes, r.icon, r.windowFlags,
1953 prev != null ? prev.appToken : null, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001954 }
1955 } else {
1956 // If this is the first activity, don't do any fancy animations,
1957 // because there is nothing for it to animate on top of.
Craig Mautner70a86932013-02-28 22:37:44 -08001958 mService.mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken,
1959 r.task.taskId, r.info.screenOrientation, r.fullscreen,
Craig Mautner5962b122012-10-05 14:45:52 -07001960 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001961 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001962 }
1963 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001964 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001965 }
1966
1967 if (doResume) {
1968 resumeTopActivityLocked(null);
1969 }
1970 }
1971
Dianne Hackbornbe707852011-11-11 14:32:10 -08001972 final void validateAppTokensLocked() {
1973 mValidateAppTokens.clear();
Craig Mautner000f0022013-02-26 15:04:29 -08001974 mValidateAppTokens.ensureCapacity(numActivities());
1975 final int numTasks = mTaskHistory.size();
1976 for (int taskNdx = 0; taskNdx < numTasks; ++taskNdx) {
1977 TaskRecord task = mTaskHistory.get(taskNdx);
1978 final ArrayList<ActivityRecord> activities = task.mActivities;
1979 if (activities.size() == 0) {
1980 continue;
Craig Mautnerb1fd65c02013-02-05 13:34:57 -08001981 }
Craig Mautner000f0022013-02-26 15:04:29 -08001982 TaskGroup group = new TaskGroup();
1983 group.taskId = task.taskId;
1984 mValidateAppTokens.add(group);
1985 final int numActivities = activities.size();
1986 for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) {
1987 final ActivityRecord r = activities.get(activityNdx);
1988 group.tokens.add(r.appToken);
1989 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001990 }
1991 mService.mWindowManager.validateAppTokens(mValidateAppTokens);
1992 }
1993
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001994 /**
1995 * Perform a reset of the given task, if needed as part of launching it.
1996 * Returns the new HistoryRecord at the top of the task.
1997 */
Craig Mautnere3a74d52013-02-22 14:14:58 -08001998 /**
1999 * Helper method for #resetTaskIfNeededLocked.
2000 * We are inside of the task being reset... we'll either finish this activity, push it out
2001 * for another task, or leave it as-is.
2002 * @param task The task containing the Activity (taskTop) that might be reset.
2003 * @param forceReset
2004 * @return An ActivityOptions that needs to be processed.
2005 */
2006 private final ActivityOptions resetTargetTaskIfNeededLocked(TaskRecord task,
2007 boolean forceReset) {
2008 ActivityOptions topOptions = null;
2009
2010 int replyChainEnd = -1;
2011 boolean canMoveOptions = true;
2012
2013 // We only do this for activities that are not the root of the task (since if we finish
2014 // the root, we may no longer have the task!).
2015 final ArrayList<ActivityRecord> activities = task.mActivities;
2016 final int numActivities = activities.size();
2017 for (int i = numActivities - 1; i > 0; --i ) {
2018 ActivityRecord target = activities.get(i);
2019
2020 final int flags = target.info.flags;
2021 final boolean finishOnTaskLaunch =
2022 (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
2023 final boolean allowTaskReparenting =
2024 (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
2025 final boolean clearWhenTaskReset =
2026 (target.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
2027
2028 if (!finishOnTaskLaunch
2029 && !clearWhenTaskReset
2030 && target.resultTo != null) {
2031 // If this activity is sending a reply to a previous
2032 // activity, we can't do anything with it now until
2033 // we reach the start of the reply chain.
2034 // XXX note that we are assuming the result is always
2035 // to the previous activity, which is almost always
2036 // the case but we really shouldn't count on.
2037 if (replyChainEnd < 0) {
2038 replyChainEnd = i;
2039 }
2040 } else if (!finishOnTaskLaunch
2041 && !clearWhenTaskReset
2042 && allowTaskReparenting
2043 && target.taskAffinity != null
2044 && !target.taskAffinity.equals(task.affinity)) {
2045 // If this activity has an affinity for another
2046 // task, then we need to move it out of here. We will
2047 // move it as far out of the way as possible, to the
2048 // bottom of the activity stack. This also keeps it
2049 // correctly ordered with any activities we previously
2050 // moved.
2051 TaskRecord bottomTask = mTaskHistory.get(0);
2052 ActivityRecord p = bottomTask.mActivities.get(0);
2053 if (target.taskAffinity != null
2054 && target.taskAffinity.equals(p.task.affinity)) {
2055 // If the activity currently at the bottom has the
2056 // same task affinity as the one we are moving,
2057 // then merge it into the same task.
Craig Mautner0247fc82013-02-28 14:32:06 -08002058 setTask(target, p.task, p.thumbHolder, false);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002059 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2060 + " out to bottom task " + p.task);
2061 } else {
Craig Mautnerd2328952013-03-05 12:46:26 -08002062 setTask(target, createTaskRecord(mService.getNextTaskId(), target.info, null,
2063 false), null, false);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002064 target.task.affinityIntent = target.intent;
2065 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2066 + " out to new task " + target.task);
2067 }
2068
2069 final TaskRecord targetTask = target.task;
2070 final int targetTaskId = targetTask.taskId;
2071 mService.mWindowManager.setAppGroupId(target.appToken, targetTaskId);
2072
2073 ThumbnailHolder curThumbHolder = target.thumbHolder;
2074 boolean gotOptions = !canMoveOptions;
2075
2076 final int start = replyChainEnd < 0 ? i : replyChainEnd;
2077 for (int srcPos = start; srcPos >= i; --srcPos) {
2078 p = activities.get(srcPos);
2079 if (p.finishing) {
2080 continue;
2081 }
2082
2083 curThumbHolder = p.thumbHolder;
2084 canMoveOptions = false;
2085 if (!gotOptions && topOptions == null) {
2086 topOptions = p.takeOptionsLocked();
2087 if (topOptions != null) {
2088 gotOptions = true;
2089 }
2090 }
2091 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Removing activity " + p + " from task="
2092 + task + " adding to task=" + targetTask,
2093 new RuntimeException("here").fillInStackTrace());
2094 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
2095 + " out to target's task " + target.task);
Craig Mautner0247fc82013-02-28 14:32:06 -08002096 setTask(p, targetTask, curThumbHolder, false);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002097 targetTask.addActivityAtBottom(p);
Craig Mautner0247fc82013-02-28 14:32:06 -08002098
Craig Mautnere3a74d52013-02-22 14:14:58 -08002099 mService.mWindowManager.setAppGroupId(p.appToken, targetTaskId);
2100 }
2101
2102 mService.mWindowManager.moveTaskToBottom(targetTaskId);
2103 if (VALIDATE_TOKENS) {
2104 validateAppTokensLocked();
2105 }
2106
2107 replyChainEnd = -1;
2108 } else if (forceReset || finishOnTaskLaunch || clearWhenTaskReset) {
2109 // If the activity should just be removed -- either
2110 // because it asks for it, or the task should be
2111 // cleared -- then finish it and anything that is
2112 // part of its reply chain.
2113 int end;
2114 if (clearWhenTaskReset) {
2115 // In this case, we want to finish this activity
2116 // and everything above it, so be sneaky and pretend
2117 // like these are all in the reply chain.
2118 end = numActivities - 1;
2119 } else if (replyChainEnd < 0) {
2120 end = i;
2121 } else {
2122 end = replyChainEnd;
2123 }
2124 ActivityRecord p = null;
2125 boolean gotOptions = !canMoveOptions;
2126 for (int srcPos = i; srcPos <= end; srcPos++) {
2127 p = activities.get(srcPos);
2128 if (p.finishing) {
2129 continue;
2130 }
2131 canMoveOptions = false;
2132 if (!gotOptions && topOptions == null) {
2133 topOptions = p.takeOptionsLocked();
2134 if (topOptions != null) {
2135 gotOptions = true;
2136 }
2137 }
Craig Mautner58547802013-03-05 08:23:53 -08002138 if (DEBUG_TASKS) Slog.w(TAG,
2139 "resetTaskIntendedTask: calling finishActivity on " + p);
Craig Mautnerd44711d2013-02-23 11:24:36 -08002140 if (finishActivityLocked(p, Activity.RESULT_CANCELED, null, "reset", false)) {
Craig Mautnere3a74d52013-02-22 14:14:58 -08002141 end--;
2142 srcPos--;
2143 }
2144 }
2145 replyChainEnd = -1;
2146 } else {
2147 // If we were in the middle of a chain, well the
2148 // activity that started it all doesn't want anything
2149 // special, so leave it all as-is.
2150 replyChainEnd = -1;
2151 }
2152 }
2153
2154 return topOptions;
2155 }
2156
2157 /**
2158 * Helper method for #resetTaskIfNeededLocked. Processes all of the activities in a given
2159 * TaskRecord looking for an affinity with the task of resetTaskIfNeededLocked.taskTop.
2160 * @param affinityTask The task we are looking for an affinity to.
2161 * @param task Task that resetTaskIfNeededLocked.taskTop belongs to.
2162 * @param topTaskIsHigher True if #task has already been processed by resetTaskIfNeededLocked.
2163 * @param forceReset Flag passed in to resetTaskIfNeededLocked.
2164 */
Craig Mautner77878772013-03-04 19:46:24 -08002165 private final int resetAffinityTaskIfNeededLocked(TaskRecord affinityTask, TaskRecord task,
2166 boolean topTaskIsHigher, boolean forceReset, int taskInsertionPoint) {
Craig Mautnere3a74d52013-02-22 14:14:58 -08002167 int replyChainEnd = -1;
2168 final int taskId = task.taskId;
2169 final String taskAffinity = task.affinity;
2170
2171 final ArrayList<ActivityRecord> activities = affinityTask.mActivities;
2172 final int numActivities = activities.size();
2173 // Do not operate on the root Activity.
2174 for (int i = numActivities - 1; i > 0; --i) {
2175 ActivityRecord target = activities.get(i);
2176
2177 final int flags = target.info.flags;
2178 boolean finishOnTaskLaunch = (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
2179 boolean allowTaskReparenting = (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
2180
2181 if (target.resultTo != null) {
2182 // If this activity is sending a reply to a previous
2183 // activity, we can't do anything with it now until
2184 // we reach the start of the reply chain.
2185 // XXX note that we are assuming the result is always
2186 // to the previous activity, which is almost always
2187 // the case but we really shouldn't count on.
2188 if (replyChainEnd < 0) {
2189 replyChainEnd = i;
2190 }
2191 } else if (topTaskIsHigher
2192 && allowTaskReparenting
2193 && taskAffinity != null
2194 && taskAffinity.equals(target.taskAffinity)) {
2195 // This activity has an affinity for our task. Either remove it if we are
2196 // clearing or move it over to our task. Note that
2197 // we currently punt on the case where we are resetting a
2198 // task that is not at the top but who has activities above
2199 // with an affinity to it... this is really not a normal
2200 // case, and we will need to later pull that task to the front
2201 // and usually at that point we will do the reset and pick
2202 // up those remaining activities. (This only happens if
2203 // someone starts an activity in a new task from an activity
2204 // in a task that is not currently on top.)
2205 if (forceReset || finishOnTaskLaunch) {
2206 final int start = replyChainEnd >= 0 ? replyChainEnd : i;
2207 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index " + start + " to " + i);
2208 for (int srcPos = start; srcPos >= i; --srcPos) {
2209 final ActivityRecord p = activities.get(srcPos);
2210 if (p.finishing) {
2211 continue;
2212 }
Craig Mautnerd44711d2013-02-23 11:24:36 -08002213 finishActivityLocked(p, Activity.RESULT_CANCELED, null, "reset", false);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002214 }
2215 } else {
Craig Mautner77878772013-03-04 19:46:24 -08002216 if (taskInsertionPoint < 0) {
2217 taskInsertionPoint = task.mActivities.size();
Craig Mautnerd2328952013-03-05 12:46:26 -08002218
Craig Mautner77878772013-03-04 19:46:24 -08002219 }
Craig Mautner77878772013-03-04 19:46:24 -08002220
2221 final int start = replyChainEnd >= 0 ? replyChainEnd : i;
2222 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting from task=" + affinityTask + ":"
2223 + start + "-" + i + " to task=" + task + ":" + taskInsertionPoint);
2224 for (int srcPos = start; srcPos >= i; --srcPos) {
Craig Mautnere3a74d52013-02-22 14:14:58 -08002225 final ActivityRecord p = activities.get(srcPos);
Craig Mautner0247fc82013-02-28 14:32:06 -08002226 setTask(p, task, null, false);
Craig Mautner77878772013-03-04 19:46:24 -08002227 task.addActivityAtIndex(taskInsertionPoint, p);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002228
Craig Mautnere3a74d52013-02-22 14:14:58 -08002229 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Removing and adding activity " + p
2230 + " to stack at " + task,
2231 new RuntimeException("here").fillInStackTrace());
2232 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p + " from " + srcPos
2233 + " in to resetting task " + task);
2234 mService.mWindowManager.setAppGroupId(p.appToken, taskId);
2235 }
2236 mService.mWindowManager.moveTaskToTop(taskId);
Craig Mautner9658b312013-02-28 10:55:59 -08002237 if (VALIDATE_TOKENS) {
2238 validateAppTokensLocked();
2239 }
Craig Mautnere3a74d52013-02-22 14:14:58 -08002240
2241 // Now we've moved it in to place... but what if this is
2242 // a singleTop activity and we have put it on top of another
2243 // instance of the same activity? Then we drop the instance
2244 // below so it remains singleTop.
2245 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2246 ArrayList<ActivityRecord> taskActivities = task.mActivities;
2247 boolean found = false;
2248 int targetNdx = taskActivities.indexOf(target);
2249 if (targetNdx > 0) {
2250 ActivityRecord p = taskActivities.get(targetNdx - 1);
2251 if (p.intent.getComponent().equals(target.intent.getComponent())) {
Craig Mautner58547802013-03-05 08:23:53 -08002252 finishActivityLocked(p, Activity.RESULT_CANCELED, null, "replace",
2253 false);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002254 }
2255 }
2256 }
2257 }
2258
2259 replyChainEnd = -1;
2260 }
2261 }
Craig Mautner77878772013-03-04 19:46:24 -08002262 return taskInsertionPoint;
Craig Mautnere3a74d52013-02-22 14:14:58 -08002263 }
2264
2265 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
2266 ActivityRecord newActivity) {
2267 boolean forceReset =
2268 (newActivity.info.flags & ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
2269 if (ACTIVITY_INACTIVE_RESET_TIME > 0
2270 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
2271 if ((newActivity.info.flags & ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
2272 forceReset = true;
2273 }
2274 }
2275
2276 final TaskRecord task = taskTop.task;
2277
2278 /** False until we evaluate the TaskRecord associated with taskTop. Switches to true
2279 * for remaining tasks. Used for later tasks to reparent to task. */
2280 boolean taskFound = false;
2281
2282 /** If ActivityOptions are moved out and need to be aborted or moved to taskTop. */
2283 ActivityOptions topOptions = null;
2284
Craig Mautner77878772013-03-04 19:46:24 -08002285 // Preserve the location for reparenting in the new task.
2286 int reparentInsertionPoint = -1;
2287
Craig Mautnere3a74d52013-02-22 14:14:58 -08002288 for (int i = mTaskHistory.size() - 1; i >= 0; --i) {
2289 final TaskRecord targetTask = mTaskHistory.get(i);
2290
2291 if (targetTask == task) {
2292 topOptions = resetTargetTaskIfNeededLocked(task, forceReset);
2293 taskFound = true;
2294 } else {
Craig Mautner77878772013-03-04 19:46:24 -08002295 reparentInsertionPoint = resetAffinityTaskIfNeededLocked(targetTask, task,
2296 taskFound, forceReset, reparentInsertionPoint);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002297 }
2298 }
2299
Craig Mautner70a86932013-02-28 22:37:44 -08002300 int taskNdx = mTaskHistory.indexOf(task);
2301 do {
2302 taskTop = mTaskHistory.get(taskNdx--).getTopActivity();
2303 } while (taskTop == null && taskNdx >= 0);
2304
Craig Mautnere3a74d52013-02-22 14:14:58 -08002305 if (topOptions != null) {
2306 // If we got some ActivityOptions from an activity on top that
2307 // was removed from the task, propagate them to the new real top.
2308 if (taskTop != null) {
Craig Mautnere3a74d52013-02-22 14:14:58 -08002309 taskTop.updateOptionsLocked(topOptions);
2310 } else {
Craig Mautnere3a74d52013-02-22 14:14:58 -08002311 topOptions.abort();
2312 }
2313 }
2314
2315 return taskTop;
2316 }
2317
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002318 /**
2319 * Perform clear operation as requested by
2320 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2321 * stack to the given task, then look for
2322 * an instance of that activity in the stack and, if found, finish all
2323 * activities on top of it and return the instance.
2324 *
2325 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002326 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002327 * or null if none was found.
2328 */
Craig Mautner16030772013-02-26 16:05:47 -08002329 private final ActivityRecord performClearTaskLocked(TaskRecord task,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002330 ActivityRecord newR, int launchFlags) {
Craig Mautner16030772013-02-26 16:05:47 -08002331
2332 final ArrayList<ActivityRecord> activities = task.mActivities;
2333 int numActivities = activities.size();
2334 for (int activityNdx = numActivities - 1; activityNdx >= 0; --activityNdx) {
2335 ActivityRecord r = activities.get(activityNdx);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002336 if (r.finishing) {
2337 continue;
2338 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002339 if (r.realActivity.equals(newR.realActivity)) {
2340 // Here it is! Now finish everything in front...
2341 ActivityRecord ret = r;
Craig Mautner16030772013-02-26 16:05:47 -08002342
2343 for (++activityNdx; activityNdx < numActivities; ++activityNdx) {
2344 r = activities.get(activityNdx);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002345 if (r.finishing) {
2346 continue;
2347 }
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002348 ActivityOptions opts = r.takeOptionsLocked();
2349 if (opts != null) {
2350 ret.updateOptionsLocked(opts);
2351 }
Craig Mautner16030772013-02-26 16:05:47 -08002352 if (finishActivityLocked(r, Activity.RESULT_CANCELED, null, "clear", false)) {
Craig Mautner9658b312013-02-28 10:55:59 -08002353 --activityNdx;
Craig Mautner16030772013-02-26 16:05:47 -08002354 --numActivities;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002355 }
2356 }
Craig Mautner16030772013-02-26 16:05:47 -08002357
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002358 // Finally, if this is a normal launch mode (that is, not
2359 // expecting onNewIntent()), then we will finish the current
2360 // instance of the activity so a new fresh one can be started.
2361 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
Craig Mautner16030772013-02-26 16:05:47 -08002362 && (launchFlags & Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002363 if (!ret.finishing) {
Craig Mautner16030772013-02-26 16:05:47 -08002364 if (activities.contains(ret)) {
Craig Mautnerd44711d2013-02-23 11:24:36 -08002365 finishActivityLocked(ret, Activity.RESULT_CANCELED, null,
2366 "clear", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002367 }
2368 return null;
2369 }
2370 }
Craig Mautner16030772013-02-26 16:05:47 -08002371
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002372 return ret;
2373 }
2374 }
2375
2376 return null;
2377 }
2378
2379 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002380 * Completely remove all activities associated with an existing
2381 * task starting at a specified index.
2382 */
Craig Mautner16030772013-02-26 16:05:47 -08002383 private final void performClearTaskAtIndexLocked(TaskRecord task, int activityNdx) {
2384 final ArrayList<ActivityRecord> activities = task.mActivities;
2385 int numActivities = activities.size();
2386 for ( ; activityNdx < numActivities; ++activityNdx) {
2387 final ActivityRecord r = activities.get(activityNdx);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002388 if (r.finishing) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002389 continue;
2390 }
Craig Mautner16030772013-02-26 16:05:47 -08002391 if (finishActivityLocked(r, Activity.RESULT_CANCELED, null, "clear", false)) {
2392 --activityNdx;
2393 --numActivities;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002394 }
2395 }
2396 }
2397
2398 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002399 * Completely remove all activities associated with an existing task.
2400 */
Craig Mautner16030772013-02-26 16:05:47 -08002401 private final void performClearTaskLocked(TaskRecord task) {
2402 performClearTaskAtIndexLocked(task, 0);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002403 }
2404
2405 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002406 * Find the activity in the history stack within the given task. Returns
2407 * the index within the history at which it's found, or < 0 if not found.
2408 */
Craig Mautner56f52db2013-02-25 10:03:01 -08002409 private final ActivityRecord findActivityInHistoryLocked(ActivityRecord r, TaskRecord task) {
2410 final ComponentName realActivity = r.realActivity;
2411 ArrayList<ActivityRecord> activities = task.mActivities;
2412 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2413 ActivityRecord candidate = activities.get(activityNdx);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07002414 if (candidate.finishing) {
2415 continue;
2416 }
Craig Mautner56f52db2013-02-25 10:03:01 -08002417 if (candidate.realActivity.equals(realActivity)) {
2418 return candidate;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002419 }
2420 }
Craig Mautner56f52db2013-02-25 10:03:01 -08002421 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002422 }
2423
2424 /**
2425 * Reorder the history stack so that the activity at the given index is
2426 * brought to the front.
2427 */
Craig Mautner56f52db2013-02-25 10:03:01 -08002428 private final void moveActivityToFrontLocked(ActivityRecord newTop) {
2429 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Removing and adding activity " + newTop
2430 + " to stack at top", new RuntimeException("here").fillInStackTrace());
2431
2432 final TaskRecord task = newTop.task;
2433 task.getTopActivity().frontOfTask = false;
2434 task.mActivities.remove(newTop);
2435 task.mActivities.add(newTop);
2436 newTop.frontOfTask = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002437 }
2438
2439 final int startActivityLocked(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002440 Intent intent, String resolvedType, ActivityInfo aInfo, IBinder resultTo,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002441 String resultWho, int requestCode,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002442 int callingPid, int callingUid, String callingPackage, int startFlags, Bundle options,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002443 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackborna4972e92012-03-14 10:38:05 -07002444 int err = ActivityManager.START_SUCCESS;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002445
2446 ProcessRecord callerApp = null;
2447 if (caller != null) {
2448 callerApp = mService.getRecordForAppLocked(caller);
2449 if (callerApp != null) {
2450 callingPid = callerApp.pid;
2451 callingUid = callerApp.info.uid;
2452 } else {
2453 Slog.w(TAG, "Unable to find app for caller " + caller
2454 + " (pid=" + callingPid + ") when starting: "
2455 + intent.toString());
Dianne Hackborna4972e92012-03-14 10:38:05 -07002456 err = ActivityManager.START_PERMISSION_DENIED;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002457 }
2458 }
2459
Dianne Hackborna4972e92012-03-14 10:38:05 -07002460 if (err == ActivityManager.START_SUCCESS) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002461 final int userId = aInfo != null ? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0;
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07002462 Slog.i(TAG, "START u" + userId + " {" + intent.toShortString(true, true, true, false)
2463 + "} from pid " + (callerApp != null ? callerApp.pid : callingPid));
Dianne Hackbornefb58102010-10-14 16:47:34 -07002464 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002465
2466 ActivityRecord sourceRecord = null;
2467 ActivityRecord resultRecord = null;
2468 if (resultTo != null) {
Craig Mautner56f52db2013-02-25 10:03:01 -08002469 sourceRecord = isInStackLocked(resultTo);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002470 if (DEBUG_RESULTS) Slog.v(
Craig Mautner56f52db2013-02-25 10:03:01 -08002471 TAG, "Will send result to " + resultTo + " " + sourceRecord);
2472 if (sourceRecord != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002473 if (requestCode >= 0 && !sourceRecord.finishing) {
2474 resultRecord = sourceRecord;
2475 }
2476 }
2477 }
2478
2479 int launchFlags = intent.getFlags();
2480
2481 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2482 && sourceRecord != null) {
2483 // Transfer the result target from the source activity to the new
2484 // one being started, including any failures.
2485 if (requestCode >= 0) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002486 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002487 return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002488 }
2489 resultRecord = sourceRecord.resultTo;
2490 resultWho = sourceRecord.resultWho;
2491 requestCode = sourceRecord.requestCode;
2492 sourceRecord.resultTo = null;
2493 if (resultRecord != null) {
2494 resultRecord.removeResultsLocked(
2495 sourceRecord, resultWho, requestCode);
2496 }
2497 }
2498
Dianne Hackborna4972e92012-03-14 10:38:05 -07002499 if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002500 // We couldn't find a class that can handle the given Intent.
2501 // That's the end of that!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002502 err = ActivityManager.START_INTENT_NOT_RESOLVED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002503 }
2504
Dianne Hackborna4972e92012-03-14 10:38:05 -07002505 if (err == ActivityManager.START_SUCCESS && aInfo == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002506 // We couldn't find the specific class specified in the Intent.
2507 // Also the end of the line.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002508 err = ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002509 }
2510
Dianne Hackborna4972e92012-03-14 10:38:05 -07002511 if (err != ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002512 if (resultRecord != null) {
2513 sendActivityResultLocked(-1,
2514 resultRecord, resultWho, requestCode,
2515 Activity.RESULT_CANCELED, null);
2516 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002517 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002518 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002519 return err;
2520 }
2521
Jeff Sharkey35be7562012-04-18 19:16:15 -07002522 final int startAnyPerm = mService.checkPermission(
2523 START_ANY_ACTIVITY, callingPid, callingUid);
2524 final int componentPerm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002525 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Jeff Sharkey35be7562012-04-18 19:16:15 -07002526 if (startAnyPerm != PERMISSION_GRANTED && componentPerm != PERMISSION_GRANTED) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002527 if (resultRecord != null) {
2528 sendActivityResultLocked(-1,
2529 resultRecord, resultWho, requestCode,
2530 Activity.RESULT_CANCELED, null);
2531 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002532 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002533 String msg;
2534 if (!aInfo.exported) {
2535 msg = "Permission Denial: starting " + intent.toString()
2536 + " from " + callerApp + " (pid=" + callingPid
2537 + ", uid=" + callingUid + ")"
2538 + " not exported from uid " + aInfo.applicationInfo.uid;
2539 } else {
2540 msg = "Permission Denial: starting " + intent.toString()
2541 + " from " + callerApp + " (pid=" + callingPid
2542 + ", uid=" + callingUid + ")"
2543 + " requires " + aInfo.permission;
2544 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002545 Slog.w(TAG, msg);
2546 throw new SecurityException(msg);
2547 }
2548
2549 if (mMainStack) {
2550 if (mService.mController != null) {
2551 boolean abort = false;
2552 try {
2553 // The Intent we give to the watcher has the extra data
2554 // stripped off, since it can contain private information.
2555 Intent watchIntent = intent.cloneFilter();
2556 abort = !mService.mController.activityStarting(watchIntent,
2557 aInfo.applicationInfo.packageName);
2558 } catch (RemoteException e) {
2559 mService.mController = null;
2560 }
Craig Mautnerd2328952013-03-05 12:46:26 -08002561
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002562 if (abort) {
2563 if (resultRecord != null) {
2564 sendActivityResultLocked(-1,
2565 resultRecord, resultWho, requestCode,
2566 Activity.RESULT_CANCELED, null);
2567 }
2568 // We pretend to the caller that it was really started, but
2569 // they will just get a cancel result.
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002570 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002571 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002572 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002573 }
2574 }
2575 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002576
Craig Mautnerd2328952013-03-05 12:46:26 -08002577 ActivityRecord r = new ActivityRecord(mService, callerApp, callingUid, callingPackage,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002578 intent, resolvedType, aInfo, mService.mConfiguration,
2579 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002580 if (outActivity != null) {
2581 outActivity[0] = r;
2582 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002583
2584 if (mMainStack) {
2585 if (mResumedActivity == null
2586 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2587 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2588 PendingActivityLaunch pal = new PendingActivityLaunch();
2589 pal.r = r;
2590 pal.sourceRecord = sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002591 pal.startFlags = startFlags;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002592 mService.mPendingActivityLaunches.add(pal);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002593 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002594 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002595 return ActivityManager.START_SWITCHES_CANCELED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002596 }
2597 }
Craig Mautnerd2328952013-03-05 12:46:26 -08002598
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002599 if (mService.mDidAppSwitch) {
2600 // This is the second allowed switch since we stopped switches,
2601 // so now just generally allow switches. Use case: user presses
2602 // home (switches disabled, switch to home, mDidAppSwitch now true);
2603 // user taps a home icon (coming from home so allowed, we hit here
2604 // and now allow anyone to switch again).
2605 mService.mAppSwitchesAllowedTime = 0;
2606 } else {
2607 mService.mDidAppSwitch = true;
2608 }
Craig Mautnerd2328952013-03-05 12:46:26 -08002609
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002610 mService.doPendingActivityLaunchesLocked(false);
2611 }
Craig Mautnerd2328952013-03-05 12:46:26 -08002612
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002613 err = startActivityUncheckedLocked(r, sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002614 startFlags, true, options);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002615 if (mDismissKeyguardOnNextActivity && mPausingActivity == null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002616 // Someone asked to have the keyguard dismissed on the next
2617 // activity start, but we are not actually doing an activity
2618 // switch... just dismiss the keyguard now, because we
2619 // probably want to see whatever is behind it.
2620 mDismissKeyguardOnNextActivity = false;
2621 mService.mWindowManager.dismissKeyguard();
2622 }
2623 return err;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002624 }
Craig Mautnerd2328952013-03-05 12:46:26 -08002625
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002626 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2627 if ((launchFlags &
2628 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2629 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2630 // Caller wants to appear on home activity, so before starting
2631 // their own activity we will bring home to the front.
2632 moveHomeToFrontLocked();
2633 }
2634 }
2635
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002636 final int startActivityUncheckedLocked(ActivityRecord r,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002637 ActivityRecord sourceRecord, int startFlags, boolean doResume,
2638 Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002639 final Intent intent = r.intent;
2640 final int callingUid = r.launchedFromUid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002641
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002642 int launchFlags = intent.getFlags();
Craig Mautnerd2328952013-03-05 12:46:26 -08002643
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002644 // We'll invoke onUserLeaving before onPause only if the launching
2645 // activity did not explicitly state that this is an automated launch.
2646 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2647 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2648 "startActivity() => mUserLeaving=" + mUserLeaving);
Craig Mautnerd2328952013-03-05 12:46:26 -08002649
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002650 // If the caller has asked not to resume at this point, we make note
2651 // of this in the record so that we can skip it when trying to find
2652 // the top running activity.
2653 if (!doResume) {
2654 r.delayedResume = true;
2655 }
Craig Mautnerd2328952013-03-05 12:46:26 -08002656
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002657 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2658 != 0 ? r : null;
2659
2660 // If the onlyIfNeeded flag is set, then we can do this if the activity
2661 // being launched is the same as the one making the call... or, as
2662 // a special case, if we do not know the caller then we count the
2663 // current top activity as the caller.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002664 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002665 ActivityRecord checkedCaller = sourceRecord;
2666 if (checkedCaller == null) {
2667 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2668 }
2669 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2670 // Caller is not the same as launcher, so always needed.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002671 startFlags &= ~ActivityManager.START_FLAG_ONLY_IF_NEEDED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002672 }
2673 }
2674
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002675 if (sourceRecord == null) {
2676 // This activity is not being started from another... in this
2677 // case we -always- start a new task.
2678 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2679 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2680 + intent);
2681 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2682 }
2683 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2684 // The original activity who is starting us is running as a single
2685 // instance... this new activity it is starting must go on its
2686 // own task.
2687 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2688 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2689 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2690 // The activity being started is a single instance... it always
2691 // gets launched into its own task.
2692 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2693 }
2694
2695 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2696 // For whatever reason this activity is being launched into a new
2697 // task... yet the caller has requested a result back. Well, that
2698 // is pretty messed up, so instead immediately send back a cancel
2699 // and let the new task continue launched as normal without a
2700 // dependency on its originator.
2701 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2702 sendActivityResultLocked(-1,
2703 r.resultTo, r.resultWho, r.requestCode,
2704 Activity.RESULT_CANCELED, null);
2705 r.resultTo = null;
2706 }
2707
2708 boolean addingToTask = false;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002709 boolean movedHome = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002710 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002711 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2712 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2713 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2714 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2715 // If bring to front is requested, and no result is requested, and
2716 // we can find a task that was started with this same
2717 // component, then instead of launching bring that one to the front.
2718 if (r.resultTo == null) {
2719 // See if there is a task to bring to the front. If this is
2720 // a SINGLE_INSTANCE activity, there can be one and only one
2721 // instance of it in the history, and it is always in its own
2722 // unique task, so we do a special search.
2723 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2724 ? findTaskLocked(intent, r.info)
2725 : findActivityLocked(intent, r.info);
2726 if (taskTop != null) {
2727 if (taskTop.task.intent == null) {
2728 // This task was started because of movement of
2729 // the activity based on affinity... now that we
2730 // are actually launching it, we can assign the
2731 // base intent.
2732 taskTop.task.setIntent(intent, r.info);
2733 }
2734 // If the target task is not in the front, then we need
2735 // to bring it to the front... except... well, with
2736 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2737 // to have the same behavior as if a new instance was
2738 // being started, which means not bringing it to the front
2739 // if the caller is not itself in the front.
2740 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002741 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002742 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2743 boolean callerAtFront = sourceRecord == null
2744 || curTop.task == sourceRecord.task;
2745 if (callerAtFront) {
2746 // We really do want to push this one into the
2747 // user's face, right now.
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002748 movedHome = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002749 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002750 moveTaskToFrontLocked(taskTop.task, r, options);
Dianne Hackborn84375872012-06-01 19:03:50 -07002751 options = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002752 }
2753 }
2754 // If the caller has requested that the target task be
2755 // reset, then do so.
2756 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2757 taskTop = resetTaskIfNeededLocked(taskTop, r);
2758 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002759 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002760 // We don't need to start a new activity, and
2761 // the client said not to do anything if that
2762 // is the case, so this is it! And for paranoia, make
2763 // sure we have correctly resumed the top activity.
2764 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07002765 resumeTopActivityLocked(null, options);
2766 } else {
2767 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002768 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002769 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002770 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002771 if ((launchFlags &
2772 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2773 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2774 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002775 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002776 // not be too hard...
2777 reuseTask = taskTop.task;
Craig Mautner16030772013-02-26 16:05:47 -08002778 performClearTaskLocked(taskTop.task);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002779 reuseTask.setIntent(r.intent, r.info);
2780 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002781 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2782 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2783 // In this situation we want to remove all activities
2784 // from the task up to the one being started. In most
2785 // cases this means we are resetting the task to its
2786 // initial state.
Craig Mautner16030772013-02-26 16:05:47 -08002787 ActivityRecord top = performClearTaskLocked(taskTop.task, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002788 if (top != null) {
2789 if (top.frontOfTask) {
2790 // Activity aliases may mean we use different
2791 // intents for the top activity, so make sure
2792 // the task now has the identity of the new
2793 // intent.
2794 top.task.setIntent(r.intent, r.info);
2795 }
2796 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002797 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002798 } else {
2799 // A special case: we need to
2800 // start the activity because it is not currently
2801 // running, and the caller has asked to clear the
2802 // current task to have this activity at the top.
2803 addingToTask = true;
2804 // Now pretend like this activity is being started
2805 // by the top of its task, so it is put in the
2806 // right place.
2807 sourceRecord = taskTop;
2808 }
2809 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2810 // In this case the top activity on the task is the
2811 // same as the one being launched, so we take that
2812 // as a request to bring the task to the foreground.
2813 // If the top activity in the task is the root
2814 // activity, deliver this new intent to it if it
2815 // desires.
Johan Viktorssonf363dfd2012-02-16 17:05:16 +01002816 if (((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2817 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP)
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002818 && taskTop.realActivity.equals(r.realActivity)) {
2819 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2820 if (taskTop.frontOfTask) {
2821 taskTop.task.setIntent(r.intent, r.info);
2822 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002823 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002824 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2825 // In this case we are launching the root activity
2826 // of the task, but with a different intent. We
2827 // should start a new instance on top.
2828 addingToTask = true;
2829 sourceRecord = taskTop;
2830 }
2831 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2832 // In this case an activity is being launched in to an
2833 // existing task, without resetting that task. This
2834 // is typically the situation of launching an activity
2835 // from a notification or shortcut. We want to place
2836 // the new activity on top of the current task.
2837 addingToTask = true;
2838 sourceRecord = taskTop;
2839 } else if (!taskTop.task.rootWasReset) {
2840 // In this case we are launching in to an existing task
2841 // that has not yet been started from its front door.
2842 // The current task has been brought to the front.
2843 // Ideally, we'd probably like to place this new task
2844 // at the bottom of its stack, but that's a little hard
2845 // to do with the current organization of the code so
2846 // for now we'll just drop it.
2847 taskTop.task.setIntent(r.intent, r.info);
2848 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002849 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002850 // We didn't do anything... but it was needed (a.k.a., client
2851 // don't use that intent!) And for paranoia, make
2852 // sure we have correctly resumed the top activity.
2853 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07002854 resumeTopActivityLocked(null, options);
2855 } else {
2856 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002857 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002858 return ActivityManager.START_TASK_TO_FRONT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002859 }
2860 }
2861 }
2862 }
2863
2864 //String uri = r.intent.toURI();
2865 //Intent intent2 = new Intent(uri);
2866 //Slog.i(TAG, "Given intent: " + r.intent);
2867 //Slog.i(TAG, "URI is: " + uri);
2868 //Slog.i(TAG, "To intent: " + intent2);
2869
2870 if (r.packageName != null) {
2871 // If the activity being launched is the same as the one currently
2872 // at the top, then we need to check if it should only be launched
2873 // once.
2874 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2875 if (top != null && r.resultTo == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002876 if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002877 if (top.app != null && top.app.thread != null) {
2878 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2879 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2880 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2881 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2882 // For paranoia, make sure we have correctly
2883 // resumed the top activity.
2884 if (doResume) {
2885 resumeTopActivityLocked(null);
2886 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002887 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002888 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002889 // We don't need to start a new activity, and
2890 // the client said not to do anything if that
2891 // is the case, so this is it!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002892 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002893 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002894 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002895 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002896 }
2897 }
2898 }
2899 }
2900
2901 } else {
2902 if (r.resultTo != null) {
2903 sendActivityResultLocked(-1,
2904 r.resultTo, r.resultWho, r.requestCode,
2905 Activity.RESULT_CANCELED, null);
2906 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002907 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002908 return ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002909 }
2910
2911 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002912 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002913
2914 // Should this be considered a new task?
2915 if (r.resultTo == null && !addingToTask
2916 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002917 if (reuseTask == null) {
Craig Mautnerd2328952013-03-05 12:46:26 -08002918 setTask(r, createTaskRecord(mService.getNextTaskId(), r.info, intent, true), null,
2919 true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002920 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2921 + " in new task " + r.task);
2922 } else {
Craig Mautner0247fc82013-02-28 14:32:06 -08002923 setTask(r, reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002924 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002925 newTask = true;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002926 if (!movedHome) {
2927 moveHomeToFrontFromLaunchLocked(launchFlags);
2928 }
Craig Mautnerd2328952013-03-05 12:46:26 -08002929
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002930 } else if (sourceRecord != null) {
2931 if (!addingToTask &&
2932 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2933 // In this case, we are adding the activity to an existing
2934 // task, but the caller has asked to clear that task if the
2935 // activity is already running.
Craig Mautner16030772013-02-26 16:05:47 -08002936 ActivityRecord top = performClearTaskLocked(sourceRecord.task, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002937 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002938 if (top != null) {
2939 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002940 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002941 // For paranoia, make sure we have correctly
2942 // resumed the top activity.
2943 if (doResume) {
2944 resumeTopActivityLocked(null);
2945 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002946 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002947 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002948 }
2949 } else if (!addingToTask &&
2950 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2951 // In this case, we are launching an activity in our own task
2952 // that may already be running somewhere in the history, and
2953 // we want to shuffle it to the front of the stack if so.
Craig Mautner56f52db2013-02-25 10:03:01 -08002954 final ActivityRecord top = findActivityInHistoryLocked(r, sourceRecord.task);
2955 if (top != null) {
2956 moveActivityToFrontLocked(top);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002957 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002958 top.updateOptionsLocked(options);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002959 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002960 if (doResume) {
2961 resumeTopActivityLocked(null);
2962 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002963 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002964 }
2965 }
2966 // An existing activity is starting this new activity, so we want
2967 // to keep the new one in the same task as the one that is starting
2968 // it.
Craig Mautner0247fc82013-02-28 14:32:06 -08002969 setTask(r, sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002970 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2971 + " in existing task " + r.task);
2972
2973 } else {
2974 // This not being started from an existing activity, and not part
2975 // of a new task... just put it in the top task, though these days
2976 // this case should never happen.
Craig Mautner9658b312013-02-28 10:55:59 -08002977 ActivityRecord prev = null;
2978 // Iterate to find the first non-empty task stack. Note that this code can
2979 // go away once we stop storing tasks with empty mActivities lists.
2980 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
2981 ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
2982 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2983 prev = activities.get(activityNdx);
2984 break;
2985 }
2986 }
Craig Mautner0247fc82013-02-28 14:32:06 -08002987 setTask(r, prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002988 ? prev.task
Craig Mautnerd2328952013-03-05 12:46:26 -08002989 : createTaskRecord(mService.getNextTaskId(), r.info, intent, true), null,
2990 true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002991 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2992 + " in new guessed " + r.task);
2993 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002994
Dianne Hackborn39792d22010-08-19 18:01:52 -07002995 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002996 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002997
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002998 if (newTask) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002999 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.userId, r.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003000 }
3001 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003002 startActivityLocked(r, newTask, doResume, keepCurTransition, options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003003 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003004 }
3005
Dianne Hackborna4972e92012-03-14 10:38:05 -07003006 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003007 String profileFile, ParcelFileDescriptor profileFd, int userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003008 // Collect information about the target of the Intent.
3009 ActivityInfo aInfo;
3010 try {
3011 ResolveInfo rInfo =
3012 AppGlobals.getPackageManager().resolveIntent(
3013 intent, resolvedType,
3014 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07003015 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003016 aInfo = rInfo != null ? rInfo.activityInfo : null;
3017 } catch (RemoteException e) {
3018 aInfo = null;
3019 }
3020
3021 if (aInfo != null) {
3022 // Store the found target back into the intent, because now that
3023 // we have it we never want to do this again. For example, if the
3024 // user navigates back to this point in the history, we should
3025 // always restart the exact same activity.
3026 intent.setComponent(new ComponentName(
3027 aInfo.applicationInfo.packageName, aInfo.name));
3028
3029 // Don't debug things in the system process
Dianne Hackborna4972e92012-03-14 10:38:05 -07003030 if ((startFlags&ActivityManager.START_FLAG_DEBUG) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003031 if (!aInfo.processName.equals("system")) {
3032 mService.setDebugApp(aInfo.processName, true, false);
3033 }
3034 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003035
Dianne Hackborna4972e92012-03-14 10:38:05 -07003036 if ((startFlags&ActivityManager.START_FLAG_OPENGL_TRACES) != 0) {
Siva Velusamy92a8b222012-03-09 16:24:04 -08003037 if (!aInfo.processName.equals("system")) {
3038 mService.setOpenGlTraceApp(aInfo.applicationInfo, aInfo.processName);
3039 }
3040 }
3041
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003042 if (profileFile != null) {
3043 if (!aInfo.processName.equals("system")) {
3044 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003045 profileFile, profileFd,
3046 (startFlags&ActivityManager.START_FLAG_AUTO_STOP_PROFILER) != 0);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003047 }
3048 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003049 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003050 return aInfo;
3051 }
3052
3053 final int startActivityMayWait(IApplicationThread caller, int callingUid,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003054 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003055 String resultWho, int requestCode, int startFlags, String profileFile,
3056 ParcelFileDescriptor profileFd, WaitResult outResult, Configuration config,
3057 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003058 // Refuse possible leaked file descriptors
3059 if (intent != null && intent.hasFileDescriptors()) {
3060 throw new IllegalArgumentException("File descriptors passed in Intent");
3061 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003062 boolean componentSpecified = intent.getComponent() != null;
3063
3064 // Don't modify the client's object!
3065 intent = new Intent(intent);
3066
3067 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003068 ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003069 profileFile, profileFd, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003070
3071 synchronized (mService) {
3072 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003073 if (callingUid >= 0) {
3074 callingPid = -1;
3075 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003076 callingPid = Binder.getCallingPid();
3077 callingUid = Binder.getCallingUid();
3078 } else {
3079 callingPid = callingUid = -1;
3080 }
3081
3082 mConfigWillChange = config != null
3083 && mService.mConfiguration.diff(config) != 0;
3084 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3085 "Starting activity when config will change = " + mConfigWillChange);
3086
3087 final long origId = Binder.clearCallingIdentity();
3088
3089 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07003090 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003091 // This may be a heavy-weight process! Check to see if we already
3092 // have another, different heavy-weight process running.
3093 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
3094 if (mService.mHeavyWeightProcess != null &&
3095 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
3096 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
3097 int realCallingPid = callingPid;
3098 int realCallingUid = callingUid;
3099 if (caller != null) {
3100 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
3101 if (callerApp != null) {
3102 realCallingPid = callerApp.pid;
3103 realCallingUid = callerApp.info.uid;
3104 } else {
3105 Slog.w(TAG, "Unable to find app for caller " + caller
3106 + " (pid=" + realCallingPid + ") when starting: "
3107 + intent.toString());
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003108 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003109 return ActivityManager.START_PERMISSION_DENIED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003110 }
3111 }
3112
3113 IIntentSender target = mService.getIntentSenderLocked(
Dianne Hackborna4972e92012-03-14 10:38:05 -07003114 ActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn41203752012-08-31 14:05:51 -07003115 realCallingUid, userId, null, null, 0, new Intent[] { intent },
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003116 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003117 | PendingIntent.FLAG_ONE_SHOT, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003118
3119 Intent newIntent = new Intent();
3120 if (requestCode >= 0) {
3121 // Caller is requesting a result.
3122 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
3123 }
3124 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
3125 new IntentSender(target));
3126 if (mService.mHeavyWeightProcess.activities.size() > 0) {
3127 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
3128 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
3129 hist.packageName);
3130 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
3131 hist.task.taskId);
3132 }
3133 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
3134 aInfo.packageName);
3135 newIntent.setFlags(intent.getFlags());
3136 newIntent.setClassName("android",
3137 HeavyWeightSwitcherActivity.class.getName());
3138 intent = newIntent;
3139 resolvedType = null;
3140 caller = null;
3141 callingUid = Binder.getCallingUid();
3142 callingPid = Binder.getCallingPid();
3143 componentSpecified = true;
3144 try {
3145 ResolveInfo rInfo =
3146 AppGlobals.getPackageManager().resolveIntent(
3147 intent, null,
3148 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07003149 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003150 aInfo = rInfo != null ? rInfo.activityInfo : null;
Amith Yamasani742a6712011-05-04 14:49:28 -07003151 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003152 } catch (RemoteException e) {
3153 aInfo = null;
3154 }
3155 }
3156 }
3157 }
3158
3159 int res = startActivityLocked(caller, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003160 aInfo, resultTo, resultWho, requestCode, callingPid, callingUid,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003161 callingPackage, startFlags, options, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003162
3163 if (mConfigWillChange && mMainStack) {
3164 // If the caller also wants to switch to a new configuration,
3165 // do so now. This allows a clean switch, as we are waiting
3166 // for the current activity to pause (so we will not destroy
3167 // it), and have not yet started the next activity.
3168 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
3169 "updateConfiguration()");
3170 mConfigWillChange = false;
3171 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3172 "Updating to new configuration after starting activity.");
Dianne Hackborn813075a62011-11-14 17:45:19 -08003173 mService.updateConfigurationLocked(config, null, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003174 }
3175
3176 Binder.restoreCallingIdentity(origId);
3177
3178 if (outResult != null) {
3179 outResult.result = res;
Dianne Hackborna4972e92012-03-14 10:38:05 -07003180 if (res == ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003181 mWaitingActivityLaunched.add(outResult);
3182 do {
3183 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003184 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003185 } catch (InterruptedException e) {
3186 }
3187 } while (!outResult.timeout && outResult.who == null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003188 } else if (res == ActivityManager.START_TASK_TO_FRONT) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003189 ActivityRecord r = this.topRunningActivityLocked(null);
3190 if (r.nowVisible) {
3191 outResult.timeout = false;
3192 outResult.who = new ComponentName(r.info.packageName, r.info.name);
3193 outResult.totalTime = 0;
3194 outResult.thisTime = 0;
3195 } else {
3196 outResult.thisTime = SystemClock.uptimeMillis();
3197 mWaitingActivityVisible.add(outResult);
3198 do {
3199 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003200 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003201 } catch (InterruptedException e) {
3202 }
3203 } while (!outResult.timeout && outResult.who == null);
3204 }
3205 }
3206 }
3207
3208 return res;
3209 }
3210 }
3211
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003212 final int startActivities(IApplicationThread caller, int callingUid, String callingPackage,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003213 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
3214 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003215 if (intents == null) {
3216 throw new NullPointerException("intents is null");
3217 }
3218 if (resolvedTypes == null) {
3219 throw new NullPointerException("resolvedTypes is null");
3220 }
3221 if (intents.length != resolvedTypes.length) {
3222 throw new IllegalArgumentException("intents are length different than resolvedTypes");
3223 }
3224
3225 ActivityRecord[] outActivity = new ActivityRecord[1];
3226
3227 int callingPid;
3228 if (callingUid >= 0) {
3229 callingPid = -1;
3230 } else if (caller == null) {
3231 callingPid = Binder.getCallingPid();
3232 callingUid = Binder.getCallingUid();
3233 } else {
3234 callingPid = callingUid = -1;
3235 }
3236 final long origId = Binder.clearCallingIdentity();
3237 try {
3238 synchronized (mService) {
3239
3240 for (int i=0; i<intents.length; i++) {
3241 Intent intent = intents[i];
3242 if (intent == null) {
3243 continue;
3244 }
3245
3246 // Refuse possible leaked file descriptors
3247 if (intent != null && intent.hasFileDescriptors()) {
3248 throw new IllegalArgumentException("File descriptors passed in Intent");
3249 }
3250
3251 boolean componentSpecified = intent.getComponent() != null;
3252
3253 // Don't modify the client's object!
3254 intent = new Intent(intent);
3255
3256 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003257 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i],
Amith Yamasani483f3b02012-03-13 16:08:00 -07003258 0, null, null, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07003259 // TODO: New, check if this is correct
3260 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003261
3262 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
3263 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
3264 throw new IllegalArgumentException(
3265 "FLAG_CANT_SAVE_STATE not supported here");
3266 }
3267
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003268 Bundle theseOptions;
3269 if (options != null && i == intents.length-1) {
3270 theseOptions = options;
3271 } else {
3272 theseOptions = null;
3273 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003274 int res = startActivityLocked(caller, intent, resolvedTypes[i],
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003275 aInfo, resultTo, null, -1, callingPid, callingUid, callingPackage,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003276 0, theseOptions, componentSpecified, outActivity);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003277 if (res < 0) {
3278 return res;
3279 }
3280
Dianne Hackbornbe707852011-11-11 14:32:10 -08003281 resultTo = outActivity[0] != null ? outActivity[0].appToken : null;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003282 }
3283 }
3284 } finally {
3285 Binder.restoreCallingIdentity(origId);
3286 }
3287
Dianne Hackborna4972e92012-03-14 10:38:05 -07003288 return ActivityManager.START_SUCCESS;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003289 }
3290
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003291 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
3292 long thisTime, long totalTime) {
3293 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
3294 WaitResult w = mWaitingActivityLaunched.get(i);
3295 w.timeout = timeout;
3296 if (r != null) {
3297 w.who = new ComponentName(r.info.packageName, r.info.name);
3298 }
3299 w.thisTime = thisTime;
3300 w.totalTime = totalTime;
3301 }
3302 mService.notifyAll();
3303 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003304
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003305 void reportActivityVisibleLocked(ActivityRecord r) {
3306 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
3307 WaitResult w = mWaitingActivityVisible.get(i);
3308 w.timeout = false;
3309 if (r != null) {
3310 w.who = new ComponentName(r.info.packageName, r.info.name);
3311 }
3312 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
3313 w.thisTime = w.totalTime;
3314 }
3315 mService.notifyAll();
Dianne Hackborn90c52de2011-09-23 12:57:44 -07003316
3317 if (mDismissKeyguardOnNextActivity) {
3318 mDismissKeyguardOnNextActivity = false;
3319 mService.mWindowManager.dismissKeyguard();
3320 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003321 }
3322
3323 void sendActivityResultLocked(int callingUid, ActivityRecord r,
3324 String resultWho, int requestCode, int resultCode, Intent data) {
3325
3326 if (callingUid > 0) {
3327 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003328 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003329 }
3330
3331 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3332 + " : who=" + resultWho + " req=" + requestCode
3333 + " res=" + resultCode + " data=" + data);
3334 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3335 try {
3336 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3337 list.add(new ResultInfo(resultWho, requestCode,
3338 resultCode, data));
Dianne Hackbornbe707852011-11-11 14:32:10 -08003339 r.app.thread.scheduleSendResult(r.appToken, list);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003340 return;
3341 } catch (Exception e) {
3342 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3343 }
3344 }
3345
3346 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3347 }
3348
3349 private final void stopActivityLocked(ActivityRecord r) {
3350 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3351 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3352 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3353 if (!r.finishing) {
Christopher Tated3f175c2012-06-14 14:16:54 -07003354 if (!mService.mSleeping) {
3355 if (DEBUG_STATES) {
3356 Slog.d(TAG, "no-history finish of " + r);
3357 }
3358 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003359 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07003360 } else {
3361 if (DEBUG_STATES) Slog.d(TAG, "Not finishing noHistory " + r
3362 + " on stop because we're just sleeping");
3363 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003364 }
Christopher Tate5007ddd2012-06-12 13:08:18 -07003365 }
3366
3367 if (r.app != null && r.app.thread != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003368 if (mMainStack) {
3369 if (mService.mFocusedActivity == r) {
3370 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3371 }
3372 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003373 r.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003374 try {
3375 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003376 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3377 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003378 r.state = ActivityState.STOPPING;
3379 if (DEBUG_VISBILITY) Slog.v(
3380 TAG, "Stopping visible=" + r.visible + " for " + r);
3381 if (!r.visible) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003382 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003383 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003384 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003385 if (mService.isSleeping()) {
3386 r.setSleeping(true);
3387 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003388 Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG);
3389 msg.obj = r;
3390 mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003391 } catch (Exception e) {
3392 // Maybe just ignore exceptions here... if the process
3393 // has crashed, our death notification will clean things
3394 // up.
3395 Slog.w(TAG, "Exception thrown during pause", e);
3396 // Just in case, assume it to be stopped.
3397 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003398 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003399 r.state = ActivityState.STOPPED;
3400 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003401 destroyActivityLocked(r, true, false, "stop-except");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003402 }
3403 }
3404 }
3405 }
3406
3407 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3408 boolean remove) {
3409 int N = mStoppingActivities.size();
3410 if (N <= 0) return null;
3411
3412 ArrayList<ActivityRecord> stops = null;
3413
3414 final boolean nowVisible = mResumedActivity != null
3415 && mResumedActivity.nowVisible
3416 && !mResumedActivity.waitingVisible;
3417 for (int i=0; i<N; i++) {
3418 ActivityRecord s = mStoppingActivities.get(i);
3419 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3420 + nowVisible + " waitingVisible=" + s.waitingVisible
3421 + " finishing=" + s.finishing);
3422 if (s.waitingVisible && nowVisible) {
3423 mWaitingVisibleActivities.remove(s);
3424 s.waitingVisible = false;
3425 if (s.finishing) {
3426 // If this activity is finishing, it is sitting on top of
3427 // everyone else but we now know it is no longer needed...
3428 // so get rid of it. Otherwise, we need to go through the
3429 // normal flow and hide it once we determine that it is
3430 // hidden by the activities in front of it.
3431 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003432 mService.mWindowManager.setAppVisibility(s.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003433 }
3434 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003435 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003436 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3437 if (stops == null) {
3438 stops = new ArrayList<ActivityRecord>();
3439 }
3440 stops.add(s);
3441 mStoppingActivities.remove(i);
3442 N--;
3443 i--;
3444 }
3445 }
3446
3447 return stops;
3448 }
3449
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003450 final void scheduleIdleLocked() {
3451 Message msg = Message.obtain();
3452 msg.what = IDLE_NOW_MSG;
3453 mHandler.sendMessage(msg);
3454 }
3455
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003456 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003457 Configuration config) {
3458 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3459
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003460 ActivityRecord res = null;
3461
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003462 ArrayList<ActivityRecord> stops = null;
3463 ArrayList<ActivityRecord> finishes = null;
3464 ArrayList<ActivityRecord> thumbnails = null;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003465 ArrayList<UserStartedState> startingUsers = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003466 int NS = 0;
3467 int NF = 0;
3468 int NT = 0;
3469 IApplicationThread sendThumbnail = null;
3470 boolean booting = false;
3471 boolean enableScreen = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003472 boolean activityRemoved = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003473
3474 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003475 ActivityRecord r = ActivityRecord.forToken(token);
3476 if (r != null) {
3477 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003478 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003479 }
3480
3481 // Get the activity record.
Craig Mautnerd44711d2013-02-23 11:24:36 -08003482 if (isInStackLocked(token) != null) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003483 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003484
3485 if (fromTimeout) {
3486 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3487 }
3488
3489 // This is a hack to semi-deal with a race condition
3490 // in the client where it can be constructed with a
3491 // newer configuration from when we asked it to launch.
3492 // We'll update with whatever configuration it now says
3493 // it used to launch.
3494 if (config != null) {
3495 r.configuration = config;
3496 }
3497
3498 // No longer need to keep the device awake.
3499 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3500 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3501 mLaunchingActivity.release();
3502 }
3503
3504 // We are now idle. If someone is waiting for a thumbnail from
3505 // us, we can now deliver.
3506 r.idle = true;
3507 mService.scheduleAppGcsLocked();
3508 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3509 sendThumbnail = r.app.thread;
3510 r.thumbnailNeeded = false;
3511 }
3512
3513 // If this activity is fullscreen, set up to hide those under it.
3514
3515 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3516 ensureActivitiesVisibleLocked(null, 0);
3517
3518 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3519 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003520 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003521 mService.mBooted = true;
3522 enableScreen = true;
3523 }
3524 }
3525
3526 } else if (fromTimeout) {
3527 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3528 }
3529
3530 // Atomically retrieve all of the other things to do.
3531 stops = processStoppingActivitiesLocked(true);
3532 NS = stops != null ? stops.size() : 0;
3533 if ((NF=mFinishingActivities.size()) > 0) {
3534 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3535 mFinishingActivities.clear();
3536 }
Craig Mautnercae015f2013-02-08 14:31:27 -08003537 if ((NT=mCancelledThumbnails.size()) > 0) {
3538 thumbnails = new ArrayList<ActivityRecord>(mCancelledThumbnails);
3539 mCancelledThumbnails.clear();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003540 }
3541
3542 if (mMainStack) {
3543 booting = mService.mBooting;
3544 mService.mBooting = false;
3545 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003546 if (mStartingUsers.size() > 0) {
3547 startingUsers = new ArrayList<UserStartedState>(mStartingUsers);
3548 mStartingUsers.clear();
3549 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003550 }
3551
3552 int i;
3553
3554 // Send thumbnail if requested.
3555 if (sendThumbnail != null) {
3556 try {
3557 sendThumbnail.requestThumbnail(token);
3558 } catch (Exception e) {
3559 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3560 mService.sendPendingThumbnail(null, token, null, null, true);
3561 }
3562 }
3563
3564 // Stop any activities that are scheduled to do so but have been
3565 // waiting for the next one to start.
3566 for (i=0; i<NS; i++) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003567 ActivityRecord r = stops.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003568 synchronized (mService) {
3569 if (r.finishing) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003570 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003571 } else {
3572 stopActivityLocked(r);
3573 }
3574 }
3575 }
3576
3577 // Finish any activities that are scheduled to do so but have been
3578 // waiting for the next one to start.
3579 for (i=0; i<NF; i++) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003580 ActivityRecord r = finishes.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003581 synchronized (mService) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003582 activityRemoved = destroyActivityLocked(r, true, false, "finish-idle");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003583 }
3584 }
3585
3586 // Report back to any thumbnail receivers.
3587 for (i=0; i<NT; i++) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003588 ActivityRecord r = thumbnails.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003589 mService.sendPendingThumbnail(r, null, null, null, true);
3590 }
3591
3592 if (booting) {
3593 mService.finishBooting();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003594 } else if (startingUsers != null) {
3595 for (i=0; i<startingUsers.size(); i++) {
3596 mService.finishUserSwitch(startingUsers.get(i));
3597 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003598 }
3599
3600 mService.trimApplications();
3601 //dump();
3602 //mWindowManager.dump();
3603
3604 if (enableScreen) {
3605 mService.enableScreenAfterBoot();
3606 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003607
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003608 if (activityRemoved) {
3609 resumeTopActivityLocked(null);
3610 }
3611
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003612 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003613 }
3614
3615 /**
3616 * @return Returns true if the activity is being finished, false if for
3617 * some reason it is being left as-is.
3618 */
3619 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003620 Intent resultData, String reason, boolean oomAdj) {
Craig Mautnerd74f7d72013-02-26 13:41:02 -08003621 ActivityRecord r = isInStackLocked(token);
Christopher Tated3f175c2012-06-14 14:16:54 -07003622 if (DEBUG_RESULTS || DEBUG_STATES) Slog.v(
Craig Mautnerd74f7d72013-02-26 13:41:02 -08003623 TAG, "Finishing activity token=" + token + " r="
Christopher Tated3f175c2012-06-14 14:16:54 -07003624 + ", result=" + resultCode + ", data=" + resultData
3625 + ", reason=" + reason);
Craig Mautnerd74f7d72013-02-26 13:41:02 -08003626 if (r == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003627 return false;
3628 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003629
Craig Mautnerd44711d2013-02-23 11:24:36 -08003630 finishActivityLocked(r, resultCode, resultData, reason, oomAdj);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003631 return true;
3632 }
3633
Craig Mautnerd2328952013-03-05 12:46:26 -08003634 final void finishSubActivityLocked(ActivityRecord self, String resultWho, int requestCode) {
Craig Mautner9658b312013-02-28 10:55:59 -08003635 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3636 ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3637 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3638 ActivityRecord r = activities.get(activityNdx);
3639 if (r.resultTo == self && r.requestCode == requestCode) {
3640 if ((r.resultWho == null && resultWho == null) ||
3641 (r.resultWho != null && r.resultWho.equals(resultWho))) {
3642 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "request-sub",
3643 false);
3644 }
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003645 }
3646 }
3647 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003648 mService.updateOomAdjLocked();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003649 }
3650
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003651 final void finishTopRunningActivityLocked(ProcessRecord app) {
3652 ActivityRecord r = topRunningActivityLocked(null);
3653 if (r != null && r.app == app) {
3654 // If the top running activity is from this crashing
3655 // process, then terminate it to avoid getting in a loop.
3656 Slog.w(TAG, " Force finishing activity "
3657 + r.intent.getComponent().flattenToShortString());
Craig Mautner9658b312013-02-28 10:55:59 -08003658 int taskNdx = mTaskHistory.indexOf(r.task);
3659 int activityNdx = r.task.mActivities.indexOf(r);
Craig Mautnerd2328952013-03-05 12:46:26 -08003660 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003661 // Also terminate any activities below it that aren't yet
3662 // stopped, to avoid a situation where one will get
3663 // re-start our crashing activity once it gets resumed again.
Craig Mautner9658b312013-02-28 10:55:59 -08003664 --activityNdx;
3665 if (activityNdx < 0) {
3666 do {
3667 --taskNdx;
3668 if (taskNdx < 0) {
3669 break;
3670 }
3671 activityNdx = mTaskHistory.get(taskNdx).mActivities.size() - 1;
3672 } while (activityNdx < 0);
3673 }
3674 if (activityNdx >= 0) {
3675 r = mTaskHistory.get(taskNdx).mActivities.get(activityNdx);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003676 if (r.state == ActivityState.RESUMED
3677 || r.state == ActivityState.PAUSING
3678 || r.state == ActivityState.PAUSED) {
3679 if (!r.isHomeActivity || mService.mHomeProcess != r.app) {
3680 Slog.w(TAG, " Force finishing activity "
3681 + r.intent.getComponent().flattenToShortString());
Craig Mautnerd2328952013-03-05 12:46:26 -08003682 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003683 }
3684 }
3685 }
3686 }
3687 }
3688
Craig Mautnerd2328952013-03-05 12:46:26 -08003689 final boolean finishActivityAffinityLocked(ActivityRecord r) {
Craig Mautnerd74f7d72013-02-26 13:41:02 -08003690 ArrayList<ActivityRecord> activities = r.task.mActivities;
3691 for (int index = activities.indexOf(r); index >= 0; --index) {
3692 ActivityRecord cur = activities.get(index);
3693 if (!Objects.equal(cur.taskAffinity, r.taskAffinity)) {
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003694 break;
3695 }
Craig Mautnerd44711d2013-02-23 11:24:36 -08003696 finishActivityLocked(cur, Activity.RESULT_CANCELED, null, "request-affinity",
3697 true);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003698 }
3699 return true;
3700 }
3701
Dianne Hackborn5c607432012-02-28 14:44:19 -08003702 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
3703 // send the result
3704 ActivityRecord resultTo = r.resultTo;
3705 if (resultTo != null) {
3706 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3707 + " who=" + r.resultWho + " req=" + r.requestCode
3708 + " res=" + resultCode + " data=" + resultData);
3709 if (r.info.applicationInfo.uid > 0) {
3710 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3711 resultTo.packageName, resultData,
3712 resultTo.getUriPermissionsLocked());
3713 }
3714 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3715 resultData);
3716 r.resultTo = null;
3717 }
3718 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3719
3720 // Make sure this HistoryRecord is not holding on to other resources,
3721 // because clients have remote IPC references to this object so we
3722 // can't assume that will go away and want to avoid circular IPC refs.
3723 r.results = null;
3724 r.pendingResults = null;
3725 r.newIntents = null;
3726 r.icicle = null;
3727 }
3728
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003729 /**
3730 * @return Returns true if this activity has been removed from the history
3731 * list, or false if it is still in the list and will be removed later.
3732 */
Craig Mautnerd44711d2013-02-23 11:24:36 -08003733 final boolean finishActivityLocked(ActivityRecord r, int resultCode,
3734 Intent resultData, String reason, boolean oomAdj) {
3735 return finishActivityLocked(r, resultCode, resultData, reason, false, oomAdj);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003736 }
3737
3738 /**
3739 * @return Returns true if this activity has been removed from the history
3740 * list, or false if it is still in the list and will be removed later.
3741 */
Craig Mautnerd44711d2013-02-23 11:24:36 -08003742 final boolean finishActivityLocked(ActivityRecord r, int resultCode, Intent resultData,
3743 String reason, boolean immediate, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003744 if (r.finishing) {
3745 Slog.w(TAG, "Duplicate finish request for " + r);
3746 return false;
3747 }
3748
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003749 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003750 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003751 r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003752 r.task.taskId, r.shortComponentName, reason);
Craig Mautnerd44711d2013-02-23 11:24:36 -08003753 final ArrayList<ActivityRecord> activities = r.task.mActivities;
3754 final int index = activities.indexOf(r);
3755 if (index < (activities.size() - 1)) {
3756 ActivityRecord next = activities.get(index+1);
3757 if (r.frontOfTask) {
3758 // The next activity is now the front of the task.
3759 next.frontOfTask = true;
3760 }
3761 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3762 // If the caller asked that this activity (and all above it)
3763 // be cleared when the task is reset, don't lose that information,
3764 // but propagate it up to the next activity.
3765 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003766 }
3767 }
3768
3769 r.pauseKeyDispatchingLocked();
3770 if (mMainStack) {
3771 if (mService.mFocusedActivity == r) {
3772 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3773 }
3774 }
3775
Dianne Hackborn5c607432012-02-28 14:44:19 -08003776 finishActivityResultsLocked(r, resultCode, resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003777
3778 if (mService.mPendingThumbnails.size() > 0) {
3779 // There are clients waiting to receive thumbnails so, in case
3780 // this is an activity that someone is waiting for, add it
3781 // to the pending list so we can correctly update the clients.
Craig Mautnercae015f2013-02-08 14:31:27 -08003782 mCancelledThumbnails.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003783 }
3784
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003785 if (immediate) {
Craig Mautnerd44711d2013-02-23 11:24:36 -08003786 return finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, oomAdj) == null;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003787 } else if (mResumedActivity == r) {
Craig Mautner0247fc82013-02-28 14:32:06 -08003788 boolean endTask = index <= 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003789 if (DEBUG_TRANSITION) Slog.v(TAG,
3790 "Prepare close transition: finishing " + r);
3791 mService.mWindowManager.prepareAppTransition(endTask
Craig Mautner4b71aa12012-12-27 17:20:01 -08003792 ? AppTransition.TRANSIT_TASK_CLOSE
3793 : AppTransition.TRANSIT_ACTIVITY_CLOSE, false);
Craig Mautner0247fc82013-02-28 14:32:06 -08003794
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003795 // Tell window manager to prepare for this one to be removed.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003796 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003797
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003798 if (mPausingActivity == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003799 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3800 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3801 startPausingLocked(false, false);
3802 }
3803
3804 } else if (r.state != ActivityState.PAUSING) {
3805 // If the activity is PAUSING, we will complete the finish once
3806 // it is done pausing; else we can just directly finish it here.
3807 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
Craig Mautnerd44711d2013-02-23 11:24:36 -08003808 return finishCurrentActivityLocked(r, FINISH_AFTER_PAUSE, oomAdj) == null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003809 } else {
3810 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3811 }
3812
3813 return false;
3814 }
3815
3816 private static final int FINISH_IMMEDIATELY = 0;
3817 private static final int FINISH_AFTER_PAUSE = 1;
3818 private static final int FINISH_AFTER_VISIBLE = 2;
3819
Craig Mautnerd44711d2013-02-23 11:24:36 -08003820
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003821 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003822 int mode, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003823 // First things first: if this activity is currently visible,
3824 // and the resumed activity is not yet visible, then hold off on
3825 // finishing until the resumed one becomes visible.
3826 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3827 if (!mStoppingActivities.contains(r)) {
3828 mStoppingActivities.add(r);
3829 if (mStoppingActivities.size() > 3) {
3830 // If we already have a few activities waiting to stop,
3831 // then give up on things going idle and start clearing
3832 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003833 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003834 } else {
3835 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003836 }
3837 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003838 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3839 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003840 r.state = ActivityState.STOPPING;
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003841 if (oomAdj) {
3842 mService.updateOomAdjLocked();
3843 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003844 return r;
3845 }
3846
3847 // make sure the record is cleaned out of other places.
3848 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003849 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003850 mWaitingVisibleActivities.remove(r);
3851 if (mResumedActivity == r) {
3852 mResumedActivity = null;
3853 }
3854 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003855 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003856 r.state = ActivityState.FINISHING;
3857
3858 if (mode == FINISH_IMMEDIATELY
3859 || prevState == ActivityState.STOPPED
3860 || prevState == ActivityState.INITIALIZING) {
3861 // If this activity is already stopped, we can just finish
3862 // it right now.
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003863 boolean activityRemoved = destroyActivityLocked(r, true,
3864 oomAdj, "finish-imm");
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003865 if (activityRemoved) {
3866 resumeTopActivityLocked(null);
3867 }
3868 return activityRemoved ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003869 }
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003870
3871 // Need to go through the full pause cycle to get this
3872 // activity into the stopped state and then finish it.
3873 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3874 mFinishingActivities.add(r);
3875 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003876 return r;
3877 }
3878
Craig Mautnerd2328952013-03-05 12:46:26 -08003879 final boolean navigateUpToLocked(IBinder token, Intent destIntent, int resultCode,
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003880 Intent resultData) {
Craig Mautnerd2328952013-03-05 12:46:26 -08003881 final ActivityRecord srec = ActivityRecord.forToken(token);
Craig Mautner0247fc82013-02-28 14:32:06 -08003882 final TaskRecord task = srec.task;
3883 final ArrayList<ActivityRecord> activities = task.mActivities;
3884 final int start = activities.indexOf(srec);
3885 if (!mTaskHistory.contains(task) || (start < 0)) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003886 return false;
3887 }
3888 int finishTo = start - 1;
Craig Mautner0247fc82013-02-28 14:32:06 -08003889 ActivityRecord parent = finishTo < 0 ? null : activities.get(finishTo);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003890 boolean foundParentInTask = false;
Craig Mautner0247fc82013-02-28 14:32:06 -08003891 final ComponentName dest = destIntent.getComponent();
3892 if (start > 0 && dest != null) {
3893 for (int i = finishTo; i >= 0; i--) {
3894 ActivityRecord r = activities.get(i);
3895 if (r.info.packageName.equals(dest.getPackageName()) &&
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003896 r.info.name.equals(dest.getClassName())) {
3897 finishTo = i;
3898 parent = r;
3899 foundParentInTask = true;
3900 break;
3901 }
3902 }
3903 }
3904
3905 IActivityController controller = mService.mController;
3906 if (controller != null) {
3907 ActivityRecord next = topRunningActivityLocked(srec.appToken, 0);
3908 if (next != null) {
3909 // ask watcher if this is allowed
3910 boolean resumeOK = true;
3911 try {
3912 resumeOK = controller.activityResuming(next.packageName);
3913 } catch (RemoteException e) {
3914 mService.mController = null;
3915 }
3916
3917 if (!resumeOK) {
3918 return false;
3919 }
3920 }
3921 }
3922 final long origId = Binder.clearCallingIdentity();
3923 for (int i = start; i > finishTo; i--) {
Craig Mautner0247fc82013-02-28 14:32:06 -08003924 ActivityRecord r = activities.get(i);
3925 requestFinishActivityLocked(r.appToken, resultCode, resultData, "navigate-up", true);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003926 // Only return the supplied result for the first activity finished
3927 resultCode = Activity.RESULT_CANCELED;
3928 resultData = null;
3929 }
3930
3931 if (parent != null && foundParentInTask) {
3932 final int parentLaunchMode = parent.info.launchMode;
3933 final int destIntentFlags = destIntent.getFlags();
3934 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
3935 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
3936 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
3937 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
3938 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
3939 } else {
3940 try {
3941 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
3942 destIntent.getComponent(), 0, srec.userId);
3943 int res = startActivityLocked(srec.app.thread, destIntent,
3944 null, aInfo, parent.appToken, null,
3945 0, -1, parent.launchedFromUid, parent.launchedFromPackage,
3946 0, null, true, null);
3947 foundParentInTask = res == ActivityManager.START_SUCCESS;
3948 } catch (RemoteException e) {
3949 foundParentInTask = false;
3950 }
3951 requestFinishActivityLocked(parent.appToken, resultCode,
3952 resultData, "navigate-up", true);
3953 }
3954 }
3955 Binder.restoreCallingIdentity(origId);
3956 return foundParentInTask;
3957 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003958 /**
3959 * Perform the common clean-up of an activity record. This is called both
3960 * as part of destroyActivityLocked() (when destroying the client-side
3961 * representation) and cleaning things up as a result of its hosting
3962 * processing going away, in which case there is no remaining client-side
3963 * state to destroy so only the cleanup here is needed.
3964 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003965 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3966 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003967 if (mResumedActivity == r) {
3968 mResumedActivity = null;
3969 }
3970 if (mService.mFocusedActivity == r) {
3971 mService.mFocusedActivity = null;
3972 }
3973
3974 r.configDestroy = false;
3975 r.frozenBeforeDestroy = false;
3976
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003977 if (setState) {
3978 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3979 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08003980 if (DEBUG_APP) Slog.v(TAG, "Clearing app during cleanUp for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003981 r.app = null;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003982 }
3983
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003984 // Make sure this record is no longer in the pending finishes list.
3985 // This could happen, for example, if we are trimming activities
3986 // down to the max limit while they are still waiting to finish.
3987 mFinishingActivities.remove(r);
3988 mWaitingVisibleActivities.remove(r);
3989
3990 // Remove any pending results.
3991 if (r.finishing && r.pendingResults != null) {
3992 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3993 PendingIntentRecord rec = apr.get();
3994 if (rec != null) {
3995 mService.cancelIntentSenderLocked(rec, false);
3996 }
3997 }
3998 r.pendingResults = null;
3999 }
4000
4001 if (cleanServices) {
4002 cleanUpActivityServicesLocked(r);
4003 }
4004
4005 if (mService.mPendingThumbnails.size() > 0) {
4006 // There are clients waiting to receive thumbnails so, in case
4007 // this is an activity that someone is waiting for, add it
4008 // to the pending list so we can correctly update the clients.
Craig Mautnercae015f2013-02-08 14:31:27 -08004009 mCancelledThumbnails.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004010 }
4011
4012 // Get rid of any pending idle timeouts.
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004013 removeTimeoutsForActivityLocked(r);
4014 }
4015
4016 private void removeTimeoutsForActivityLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004017 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07004018 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004019 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004020 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07004021 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004022 }
4023
Dianne Hackborn5c607432012-02-28 14:44:19 -08004024 final void removeActivityFromHistoryLocked(ActivityRecord r) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004025 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
4026 r.makeFinishing();
4027 if (DEBUG_ADD_REMOVE) {
4028 RuntimeException here = new RuntimeException("here");
4029 here.fillInStackTrace();
4030 Slog.i(TAG, "Removing activity " + r + " from stack");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004031 }
Craig Mautner0247fc82013-02-28 14:32:06 -08004032 if (r.task != null) {
4033 removeActivity(r);
Craig Mautner5d9c7be2013-02-15 14:02:56 -08004034 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004035 r.takeFromHistory();
4036 removeTimeoutsForActivityLocked(r);
Craig Mautner0247fc82013-02-28 14:32:06 -08004037 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (removed from history)");
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004038 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08004039 if (DEBUG_APP) Slog.v(TAG, "Clearing app during remove for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004040 r.app = null;
4041 mService.mWindowManager.removeAppToken(r.appToken);
4042 if (VALIDATE_TOKENS) {
4043 validateAppTokensLocked();
4044 }
4045 cleanUpActivityServicesLocked(r);
4046 r.removeUriPermissionsLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004047 }
4048
4049 /**
4050 * Perform clean-up of service connections in an activity record.
4051 */
4052 final void cleanUpActivityServicesLocked(ActivityRecord r) {
4053 // Throw away any services that have been bound by this activity.
4054 if (r.connections != null) {
4055 Iterator<ConnectionRecord> it = r.connections.iterator();
4056 while (it.hasNext()) {
4057 ConnectionRecord c = it.next();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004058 mService.mServices.removeConnectionLocked(c, null, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004059 }
4060 r.connections = null;
4061 }
4062 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004063
4064 final void scheduleDestroyActivities(ProcessRecord owner, boolean oomAdj, String reason) {
4065 Message msg = mHandler.obtainMessage(DESTROY_ACTIVITIES_MSG);
4066 msg.obj = new ScheduleDestroyArgs(owner, oomAdj, reason);
4067 mHandler.sendMessage(msg);
4068 }
4069
Dianne Hackborn28695e02011-11-02 21:59:51 -07004070 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004071 boolean lastIsOpaque = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004072 boolean activityRemoved = false;
Craig Mautnerd44711d2013-02-23 11:24:36 -08004073 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4074 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4075 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4076 final ActivityRecord r = activities.get(activityNdx);
4077 if (r.finishing) {
4078 continue;
4079 }
4080 if (r.fullscreen) {
4081 lastIsOpaque = true;
4082 }
4083 if (owner != null && r.app != owner) {
4084 continue;
4085 }
4086 if (!lastIsOpaque) {
4087 continue;
4088 }
4089 // We can destroy this one if we have its icicle saved and
4090 // it is not in the process of pausing/stopping/finishing.
4091 if (r.app != null && r != mResumedActivity && r != mPausingActivity
4092 && r.haveState && !r.visible && r.stopped
4093 && r.state != ActivityState.DESTROYING
4094 && r.state != ActivityState.DESTROYED) {
4095 if (DEBUG_SWITCH) Slog.v(TAG, "Destroying " + r + " in state " + r.state
4096 + " resumed=" + mResumedActivity
4097 + " pausing=" + mPausingActivity);
4098 if (destroyActivityLocked(r, true, oomAdj, reason)) {
4099 activityRemoved = true;
4100 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004101 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004102 }
4103 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004104 if (activityRemoved) {
4105 resumeTopActivityLocked(null);
4106 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004107 }
4108
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004109 /**
4110 * Destroy the current CLIENT SIDE instance of an activity. This may be
4111 * called both when actually finishing an activity, or when performing
4112 * a configuration switch where we destroy the current client-side object
4113 * but then create a new client-side object for this same HistoryRecord.
4114 */
4115 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackborn28695e02011-11-02 21:59:51 -07004116 boolean removeFromApp, boolean oomAdj, String reason) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004117 if (DEBUG_SWITCH || DEBUG_CLEANUP) Slog.v(
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004118 TAG, "Removing activity from " + reason + ": token=" + r
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004119 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
4120 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004121 r.userId, System.identityHashCode(r),
Dianne Hackborn28695e02011-11-02 21:59:51 -07004122 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004123
4124 boolean removedFromHistory = false;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004125
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004126 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004127
4128 final boolean hadApp = r.app != null;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004129
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004130 if (hadApp) {
4131 if (removeFromApp) {
Craig Mautnerd2328952013-03-05 12:46:26 -08004132 r.app.activities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004133 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
4134 mService.mHeavyWeightProcess = null;
4135 mService.mHandler.sendEmptyMessage(
4136 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
4137 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004138 if (r.app.activities.size() == 0) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07004139 // No longer have activities, so update oom adj.
4140 mService.updateOomAdjLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004141 }
4142 }
4143
4144 boolean skipDestroy = false;
4145
4146 try {
4147 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004148 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004149 r.configChangeFlags);
4150 } catch (Exception e) {
4151 // We can just ignore exceptions here... if the process
4152 // has crashed, our death notification will clean things
4153 // up.
4154 //Slog.w(TAG, "Exception thrown during finish", e);
4155 if (r.finishing) {
4156 removeActivityFromHistoryLocked(r);
4157 removedFromHistory = true;
4158 skipDestroy = true;
4159 }
4160 }
4161
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004162 r.nowVisible = false;
4163
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004164 // If the activity is finishing, we need to wait on removing it
4165 // from the list to give it a chance to do its cleanup. During
4166 // that time it may make calls back with its token so we need to
4167 // be able to find it on the list and so we don't want to remove
4168 // it from the list yet. Otherwise, we can just immediately put
4169 // it in the destroyed state since we are not removing it from the
4170 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004171 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004172 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
4173 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004174 r.state = ActivityState.DESTROYING;
4175 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
4176 msg.obj = r;
4177 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
4178 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004179 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4180 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004181 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08004182 if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004183 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004184 }
4185 } else {
4186 // remove this record from the history.
4187 if (r.finishing) {
4188 removeActivityFromHistoryLocked(r);
4189 removedFromHistory = true;
4190 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004191 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4192 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004193 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08004194 if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004195 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004196 }
4197 }
4198
4199 r.configChangeFlags = 0;
4200
4201 if (!mLRUActivities.remove(r) && hadApp) {
4202 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
4203 }
4204
4205 return removedFromHistory;
4206 }
4207
Craig Mautnerd2328952013-03-05 12:46:26 -08004208 final void activityDestroyedLocked(IBinder token) {
4209 final long origId = Binder.clearCallingIdentity();
4210 try {
4211 ActivityRecord r = ActivityRecord.forToken(token);
4212 if (r != null) {
4213 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004214 }
Craig Mautnerd2328952013-03-05 12:46:26 -08004215
4216 if (isInStackLocked(token) != null) {
4217 if (r.state == ActivityState.DESTROYING) {
4218 cleanUpActivityLocked(r, true, false);
4219 removeActivityFromHistoryLocked(r);
4220 }
4221 }
4222 resumeTopActivityLocked(null);
4223 } finally {
4224 Binder.restoreCallingIdentity(origId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004225 }
4226 }
4227
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004228 private void removeHistoryRecordsForAppLocked(ArrayList<ActivityRecord> list,
4229 ProcessRecord app, String listName) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004230 int i = list.size();
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004231 if (DEBUG_CLEANUP) Slog.v(
4232 TAG, "Removing app " + app + " from list " + listName
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004233 + " with " + i + " entries");
4234 while (i > 0) {
4235 i--;
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004236 ActivityRecord r = list.get(i);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004237 if (DEBUG_CLEANUP) Slog.v(TAG, "Record #" + i + " " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004238 if (r.app == app) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004239 if (DEBUG_CLEANUP) Slog.v(TAG, "---> REMOVING this entry!");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004240 list.remove(i);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004241 removeTimeoutsForActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004242 }
4243 }
4244 }
4245
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004246 boolean removeHistoryRecordsForAppLocked(ProcessRecord app) {
4247 removeHistoryRecordsForAppLocked(mLRUActivities, app, "mLRUActivities");
4248 removeHistoryRecordsForAppLocked(mStoppingActivities, app, "mStoppingActivities");
4249 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app, "mGoingToSleepActivities");
4250 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app,
4251 "mWaitingVisibleActivities");
4252 removeHistoryRecordsForAppLocked(mFinishingActivities, app, "mFinishingActivities");
4253
4254 boolean hasVisibleActivities = false;
4255
4256 // Clean out the history list.
Craig Mautner0247fc82013-02-28 14:32:06 -08004257 int i = numActivities();
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004258 if (DEBUG_CLEANUP) Slog.v(
4259 TAG, "Removing app " + app + " from history with " + i + " entries");
Craig Mautner0247fc82013-02-28 14:32:06 -08004260 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4261 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4262 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4263 final ActivityRecord r = activities.get(activityNdx);
4264 --i;
4265 if (DEBUG_CLEANUP) Slog.v(
4266 TAG, "Record #" + i + " " + r + ": app=" + r.app);
4267 if (r.app == app) {
4268 boolean remove;
4269 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
4270 // Don't currently have state for the activity, or
4271 // it is finishing -- always remove it.
4272 remove = true;
4273 } else if (r.launchCount > 2 &&
4274 r.lastLaunchTime > (SystemClock.uptimeMillis()-60000)) {
4275 // We have launched this activity too many times since it was
4276 // able to run, so give up and remove it.
4277 remove = true;
4278 } else {
4279 // The process may be gone, but the activity lives on!
4280 remove = false;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004281 }
Craig Mautner0247fc82013-02-28 14:32:06 -08004282 if (remove) {
4283 if (ActivityStack.DEBUG_ADD_REMOVE || DEBUG_CLEANUP) {
4284 RuntimeException here = new RuntimeException("here");
4285 here.fillInStackTrace();
4286 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
4287 + ": haveState=" + r.haveState
4288 + " stateNotNeeded=" + r.stateNotNeeded
4289 + " finishing=" + r.finishing
4290 + " state=" + r.state, here);
4291 }
4292 if (!r.finishing) {
4293 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
4294 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
4295 r.userId, System.identityHashCode(r),
4296 r.task.taskId, r.shortComponentName,
4297 "proc died without state saved");
4298 }
4299 removeActivityFromHistoryLocked(r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004300
Craig Mautner0247fc82013-02-28 14:32:06 -08004301 } else {
4302 // We have the current state for this activity, so
4303 // it can be restarted later when needed.
4304 if (localLOGV) Slog.v(
4305 TAG, "Keeping entry, setting app to null");
4306 if (r.visible) {
4307 hasVisibleActivities = true;
4308 }
4309 if (DEBUG_APP) Slog.v(TAG, "Clearing app during removeHistory for activity "
4310 + r);
4311 r.app = null;
4312 r.nowVisible = false;
4313 if (!r.haveState) {
4314 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
4315 "App died, clearing saved state of " + r);
4316 r.icicle = null;
4317 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004318 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004319
Craig Mautnerd2328952013-03-05 12:46:26 -08004320 cleanUpActivityLocked(r, true, true);
Craig Mautner0247fc82013-02-28 14:32:06 -08004321 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004322 }
4323 }
4324
4325 return hasVisibleActivities;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004326 }
Craig Mautner0247fc82013-02-28 14:32:06 -08004327
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004328 /**
4329 * Move the current home activity's task (if one exists) to the front
4330 * of the stack.
4331 */
4332 final void moveHomeToFrontLocked() {
Craig Mautner0247fc82013-02-28 14:32:06 -08004333 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4334 final TaskRecord task = mTaskHistory.get(taskNdx);
4335 final ArrayList<ActivityRecord> activities = task.mActivities;
Craig Mautner11bf9a52013-02-19 14:08:51 -08004336 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4337 final ActivityRecord r = activities.get(activityNdx);
4338 if (r.isHomeActivity) {
Craig Mautner0247fc82013-02-28 14:32:06 -08004339 moveTaskToFrontLocked(task, null, null);
4340 return;
Craig Mautner11bf9a52013-02-19 14:08:51 -08004341 }
4342 }
4343 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004344 }
4345
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004346 final void updateTransitLocked(int transit, Bundle options) {
4347 if (options != null) {
4348 ActivityRecord r = topRunningActivityLocked(null);
4349 if (r != null && r.state != ActivityState.RESUMED) {
4350 r.updateOptionsLocked(options);
4351 } else {
4352 ActivityOptions.abort(options);
4353 }
4354 }
4355 mService.mWindowManager.prepareAppTransition(transit, false);
4356 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004357
Craig Mautnercae015f2013-02-08 14:31:27 -08004358 final boolean findTaskToMoveToFrontLocked(int taskId, int flags, Bundle options) {
Craig Mautnerd2328952013-03-05 12:46:26 -08004359 final TaskRecord task = taskForIdLocked(taskId);
4360 if (task != null) {
Craig Mautneraab647e2013-02-28 16:31:36 -08004361 if ((flags & ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
4362 mUserLeaving = true;
Craig Mautnercae015f2013-02-08 14:31:27 -08004363 }
Craig Mautneraab647e2013-02-28 16:31:36 -08004364 if ((flags & ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
4365 // Caller wants the home activity moved with it. To accomplish this,
4366 // we'll just move the home task to the top first.
4367 moveHomeToFrontLocked();
4368 }
4369 moveTaskToFrontLocked(task, null, options);
4370 return true;
Craig Mautnercae015f2013-02-08 14:31:27 -08004371 }
4372 return false;
4373 }
4374
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004375 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason, Bundle options) {
Craig Mautner11bf9a52013-02-19 14:08:51 -08004376 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004377
Craig Mautner11bf9a52013-02-19 14:08:51 -08004378 final int numTasks = mTaskHistory.size();
4379 final int index = mTaskHistory.indexOf(tr);
4380 if (numTasks == 0 || index < 0 || index == numTasks - 1) {
4381 // nothing to do!
4382 if (reason != null &&
4383 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
4384 ActivityOptions.abort(options);
4385 } else {
4386 updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options);
4387 }
4388 return;
4389 }
4390
4391 // Shift all activities with this task up to the top
4392 // of the stack, keeping them in the same internal order.
4393 mTaskHistory.remove(tr);
4394 mTaskHistory.add(tr);
4395
4396 if (DEBUG_TRANSITION) Slog.v(TAG, "Prepare to front transition: task=" + tr);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004397 if (reason != null &&
4398 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Craig Mautner11bf9a52013-02-19 14:08:51 -08004399 mService.mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004400 ActivityRecord r = topRunningActivityLocked(null);
4401 if (r != null) {
4402 mNoAnimActivities.add(r);
4403 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004404 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004405 } else {
Craig Mautner4b71aa12012-12-27 17:20:01 -08004406 updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004407 }
Craig Mautner30e2d722013-02-12 11:30:16 -08004408
Craig Mautner58547802013-03-05 08:23:53 -08004409 mService.mWindowManager.moveTaskToTop(tr.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004410
Craig Mautner58547802013-03-05 08:23:53 -08004411 resumeTopActivityLocked(null);
4412 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, tr.userId, tr.taskId);
Craig Mautner11bf9a52013-02-19 14:08:51 -08004413
4414 if (VALIDATE_TOKENS) {
4415 validateAppTokensLocked();
4416 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004417 }
4418
4419 /**
4420 * Worker method for rearranging history stack. Implements the function of moving all
4421 * activities for a specific task (gathering them if disjoint) into a single group at the
4422 * bottom of the stack.
4423 *
4424 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
4425 * to premeptively cancel the move.
4426 *
4427 * @param task The taskId to collect and move to the bottom.
4428 * @return Returns true if the move completed, false if not.
4429 */
4430 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
4431 Slog.i(TAG, "moveTaskToBack: " + task);
Craig Mautnerb44de0d2013-02-21 20:00:58 -08004432
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004433 // If we have a watcher, preflight the move before committing to it. First check
4434 // for *other* available tasks, but if none are available, then try again allowing the
4435 // current task to be selected.
4436 if (mMainStack && mService.mController != null) {
4437 ActivityRecord next = topRunningActivityLocked(null, task);
4438 if (next == null) {
4439 next = topRunningActivityLocked(null, 0);
4440 }
4441 if (next != null) {
4442 // ask watcher if this is allowed
4443 boolean moveOK = true;
4444 try {
4445 moveOK = mService.mController.activityResuming(next.packageName);
4446 } catch (RemoteException e) {
4447 mService.mController = null;
4448 }
4449 if (!moveOK) {
4450 return false;
4451 }
4452 }
4453 }
4454
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004455 if (DEBUG_TRANSITION) Slog.v(TAG,
4456 "Prepare to back transition: task=" + task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004457
Craig Mautnerd2328952013-03-05 12:46:26 -08004458 final TaskRecord tr = taskForIdLocked(task);
4459 if (tr == null) {
4460 return false;
4461 }
Craig Mautner11bf9a52013-02-19 14:08:51 -08004462 mTaskHistory.remove(tr);
4463 mTaskHistory.add(0, tr);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004464
4465 if (reason != null &&
4466 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Craig Mautner11bf9a52013-02-19 14:08:51 -08004467 mService.mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004468 ActivityRecord r = topRunningActivityLocked(null);
4469 if (r != null) {
4470 mNoAnimActivities.add(r);
4471 }
4472 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004473 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08004474 AppTransition.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004475 }
Craig Mautner30e2d722013-02-12 11:30:16 -08004476 mService.mWindowManager.moveTaskToBottom(task);
Craig Mautnerb44de0d2013-02-21 20:00:58 -08004477
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004478 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004479 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004480 }
4481
Craig Mautner58547802013-03-05 08:23:53 -08004482 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004483 return true;
4484 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07004485
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004486 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
Craig Mautner16030772013-02-26 16:05:47 -08004487 TaskAccessInfo info = getTaskAccessInfoLocked(tr, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004488 ActivityRecord resumed = mResumedActivity;
4489 if (resumed != null && resumed.thumbHolder == tr) {
Craig Mautnerd2328952013-03-05 12:46:26 -08004490 info.mainThumbnail = screenshotActivities(resumed);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004491 }
Dianne Hackborn6a864952012-09-21 18:46:11 -07004492 if (info.mainThumbnail == null) {
4493 info.mainThumbnail = tr.lastThumbnail;
4494 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004495 return info;
4496 }
4497
Dianne Hackborn15491c62012-09-19 10:59:14 -07004498 public Bitmap getTaskTopThumbnailLocked(TaskRecord tr) {
4499 ActivityRecord resumed = mResumedActivity;
4500 if (resumed != null && resumed.task == tr) {
4501 // This task is the current resumed task, we just need to take
4502 // a screenshot of it and return that.
Craig Mautnerd2328952013-03-05 12:46:26 -08004503 return screenshotActivities(resumed);
Dianne Hackborn15491c62012-09-19 10:59:14 -07004504 }
4505 // Return the information about the task, to figure out the top
4506 // thumbnail to return.
Craig Mautner16030772013-02-26 16:05:47 -08004507 TaskAccessInfo info = getTaskAccessInfoLocked(tr, true);
Dianne Hackborn15491c62012-09-19 10:59:14 -07004508 if (info.numSubThumbbails <= 0) {
Dianne Hackborn6a864952012-09-21 18:46:11 -07004509 return info.mainThumbnail != null ? info.mainThumbnail : tr.lastThumbnail;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004510 }
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004511 return info.subtasks.get(info.numSubThumbbails-1).holder.lastThumbnail;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004512 }
4513
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004514 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex,
4515 boolean taskRequired) {
Craig Mautnerd2328952013-03-05 12:46:26 -08004516 final TaskRecord task = taskForIdLocked(taskId);
4517 if (task == null) {
4518 return null;
4519 }
Craig Mautner16030772013-02-26 16:05:47 -08004520 TaskAccessInfo info = getTaskAccessInfoLocked(task, false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004521 if (info.root == null) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004522 if (taskRequired) {
4523 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
4524 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004525 return null;
4526 }
4527
4528 if (subTaskIndex < 0) {
4529 // Just remove the entire task.
Craig Mautner16030772013-02-26 16:05:47 -08004530 performClearTaskAtIndexLocked(task, info.rootIndex);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004531 return info.root;
4532 }
4533
4534 if (subTaskIndex >= info.subtasks.size()) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004535 if (taskRequired) {
4536 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
4537 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004538 return null;
4539 }
4540
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004541 // Remove all of this task's activities starting at the sub task.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004542 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
Craig Mautner16030772013-02-26 16:05:47 -08004543 performClearTaskAtIndexLocked(task, subtask.index);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004544 return subtask.activity;
4545 }
4546
Craig Mautner16030772013-02-26 16:05:47 -08004547 public TaskAccessInfo getTaskAccessInfoLocked(TaskRecord task, boolean inclThumbs) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004548 final TaskAccessInfo thumbs = new TaskAccessInfo();
4549 // How many different sub-thumbnails?
Craig Mautner16030772013-02-26 16:05:47 -08004550 final ArrayList<ActivityRecord> activities = task.mActivities;
4551 final int NA = activities.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004552 int j = 0;
4553 ThumbnailHolder holder = null;
4554 while (j < NA) {
Craig Mautner16030772013-02-26 16:05:47 -08004555 ActivityRecord ar = activities.get(j);
4556 if (!ar.finishing) {
Dianne Hackborn8da429e2012-09-23 12:52:19 -07004557 thumbs.root = ar;
4558 thumbs.rootIndex = j;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004559 holder = ar.thumbHolder;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004560 if (holder != null) {
4561 thumbs.mainThumbnail = holder.lastThumbnail;
4562 }
4563 j++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004564 break;
4565 }
4566 j++;
4567 }
4568
4569 if (j >= NA) {
4570 return thumbs;
4571 }
4572
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004573 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
4574 thumbs.subtasks = subtasks;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004575 while (j < NA) {
Craig Mautner16030772013-02-26 16:05:47 -08004576 ActivityRecord ar = activities.get(j);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004577 j++;
4578 if (ar.finishing) {
4579 continue;
4580 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004581 if (ar.thumbHolder != holder && holder != null) {
4582 thumbs.numSubThumbbails++;
4583 holder = ar.thumbHolder;
4584 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
Dianne Hackborn15491c62012-09-19 10:59:14 -07004585 sub.holder = holder;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004586 sub.activity = ar;
4587 sub.index = j-1;
4588 subtasks.add(sub);
4589 }
4590 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004591 if (thumbs.numSubThumbbails > 0) {
4592 thumbs.retriever = new IThumbnailRetriever.Stub() {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004593 @Override
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004594 public Bitmap getThumbnail(int index) {
4595 if (index < 0 || index >= thumbs.subtasks.size()) {
4596 return null;
4597 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07004598 TaskAccessInfo.SubTask sub = thumbs.subtasks.get(index);
4599 ActivityRecord resumed = mResumedActivity;
4600 if (resumed != null && resumed.thumbHolder == sub.holder) {
Craig Mautnerd2328952013-03-05 12:46:26 -08004601 return screenshotActivities(resumed);
Dianne Hackborn15491c62012-09-19 10:59:14 -07004602 }
4603 return sub.holder.lastThumbnail;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004604 }
4605 };
4606 }
4607 return thumbs;
4608 }
4609
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004610 private final void logStartActivity(int tag, ActivityRecord r,
4611 TaskRecord task) {
4612 EventLog.writeEvent(tag,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004613 r.userId, System.identityHashCode(r), task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004614 r.shortComponentName, r.intent.getAction(),
4615 r.intent.getType(), r.intent.getDataString(),
4616 r.intent.getFlags());
4617 }
4618
4619 /**
4620 * Make sure the given activity matches the current configuration. Returns
4621 * false if the activity had to be destroyed. Returns true if the
4622 * configuration is the same, or the activity will remain running as-is
4623 * for whatever reason. Ensures the HistoryRecord is updated with the
4624 * correct configuration and all other bookkeeping is handled.
4625 */
4626 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
4627 int globalChanges) {
4628 if (mConfigWillChange) {
4629 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4630 "Skipping config check (will change): " + r);
4631 return true;
4632 }
4633
4634 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4635 "Ensuring correct configuration: " + r);
4636
4637 // Short circuit: if the two configurations are the exact same
4638 // object (the common case), then there is nothing to do.
4639 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004640 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004641 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4642 "Configuration unchanged in " + r);
4643 return true;
4644 }
4645
4646 // We don't worry about activities that are finishing.
4647 if (r.finishing) {
4648 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4649 "Configuration doesn't matter in finishing " + r);
4650 r.stopFreezingScreenLocked(false);
4651 return true;
4652 }
4653
4654 // Okay we now are going to make this activity have the new config.
4655 // But then we need to figure out how it needs to deal with that.
4656 Configuration oldConfig = r.configuration;
4657 r.configuration = newConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004658
4659 // Determine what has changed. May be nothing, if this is a config
4660 // that has come back from the app after going idle. In that case
4661 // we just want to leave the official config object now in the
4662 // activity and do nothing else.
4663 final int changes = oldConfig.diff(newConfig);
4664 if (changes == 0 && !r.forceNewConfig) {
4665 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4666 "Configuration no differences in " + r);
4667 return true;
4668 }
4669
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004670 // If the activity isn't currently running, just leave the new
4671 // configuration and it will pick that up next time it starts.
4672 if (r.app == null || r.app.thread == null) {
4673 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4674 "Configuration doesn't matter not running " + r);
4675 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004676 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004677 return true;
4678 }
4679
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004680 // Figure out how to handle the changes between the configurations.
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004681 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4682 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
4683 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07004684 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004685 + ", newConfig=" + newConfig);
4686 }
Dianne Hackborne6676352011-06-01 16:51:20 -07004687 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004688 // Aha, the activity isn't handling the change, so DIE DIE DIE.
4689 r.configChangeFlags |= changes;
4690 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004691 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004692 if (r.app == null || r.app.thread == null) {
4693 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004694 "Config is destroying non-running " + r);
Dianne Hackborn28695e02011-11-02 21:59:51 -07004695 destroyActivityLocked(r, true, false, "config");
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004696 } else if (r.state == ActivityState.PAUSING) {
4697 // A little annoying: we are waiting for this activity to
4698 // finish pausing. Let's not do anything now, but just
4699 // flag that it needs to be restarted when done pausing.
4700 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004701 "Config is skipping already pausing " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004702 r.configDestroy = true;
4703 return true;
4704 } else if (r.state == ActivityState.RESUMED) {
4705 // Try to optimize this case: the configuration is changing
4706 // and we need to restart the top, resumed activity.
4707 // Instead of doing the normal handshaking, just say
4708 // "restart!".
4709 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004710 "Config is relaunching resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004711 relaunchActivityLocked(r, r.configChangeFlags, true);
4712 r.configChangeFlags = 0;
4713 } else {
4714 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004715 "Config is relaunching non-resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004716 relaunchActivityLocked(r, r.configChangeFlags, false);
4717 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004718 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004719
4720 // All done... tell the caller we weren't able to keep this
4721 // activity around.
4722 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004723 }
4724
4725 // Default case: the activity can handle this new configuration, so
4726 // hand it over. Note that we don't need to give it the new
4727 // configuration, since we always send configuration changes to all
4728 // process when they happen so it can just use whatever configuration
4729 // it last got.
4730 if (r.app != null && r.app.thread != null) {
4731 try {
4732 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004733 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004734 } catch (RemoteException e) {
4735 // If process died, whatever.
4736 }
4737 }
4738 r.stopFreezingScreenLocked(false);
4739
4740 return true;
4741 }
4742
4743 private final boolean relaunchActivityLocked(ActivityRecord r,
4744 int changes, boolean andResume) {
4745 List<ResultInfo> results = null;
4746 List<Intent> newIntents = null;
4747 if (andResume) {
4748 results = r.results;
4749 newIntents = r.newIntents;
4750 }
4751 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4752 + " with results=" + results + " newIntents=" + newIntents
4753 + " andResume=" + andResume);
4754 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004755 : EventLogTags.AM_RELAUNCH_ACTIVITY, r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004756 r.task.taskId, r.shortComponentName);
4757
4758 r.startFreezingScreenLocked(r.app, 0);
4759
4760 try {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004761 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG,
4762 (andResume ? "Relaunching to RESUMED " : "Relaunching to PAUSED ")
4763 + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004764 r.forceNewConfig = false;
Dianne Hackbornbe707852011-11-11 14:32:10 -08004765 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004766 changes, !andResume, new Configuration(mService.mConfiguration));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004767 // Note: don't need to call pauseIfSleepingLocked() here, because
4768 // the caller will only pass in 'andResume' if this activity is
4769 // currently resumed, which implies we aren't sleeping.
4770 } catch (RemoteException e) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004771 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, "Relaunch failed", e);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004772 }
4773
4774 if (andResume) {
4775 r.results = null;
4776 r.newIntents = null;
4777 if (mMainStack) {
4778 mService.reportResumedActivityLocked(r);
4779 }
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004780 r.state = ActivityState.RESUMED;
4781 } else {
4782 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
4783 r.state = ActivityState.PAUSED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004784 }
4785
4786 return true;
4787 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004788
4789 public void dismissKeyguardOnNextActivityLocked() {
4790 mDismissKeyguardOnNextActivity = true;
4791 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004792
4793 boolean willActivityBeVisibleLocked(IBinder token) {
Craig Mautnerd44711d2013-02-23 11:24:36 -08004794 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4795 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4796 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4797 final ActivityRecord r = activities.get(activityNdx);
4798 if (r.appToken == token) {
4799 return true;
4800 }
4801 if (r.fullscreen && !r.finishing) {
4802 return false;
4803 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004804 }
4805 }
4806 return true;
4807 }
4808
4809 void closeSystemDialogsLocked() {
Craig Mautnerd44711d2013-02-23 11:24:36 -08004810 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4811 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4812 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4813 final ActivityRecord r = activities.get(activityNdx);
4814 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Craig Mautnerd2328952013-03-05 12:46:26 -08004815 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "close-sys", true);
Craig Mautnerd44711d2013-02-23 11:24:36 -08004816 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004817 }
4818 }
4819 }
4820
4821 boolean forceStopPackageLocked(String name, boolean doit, boolean evenPersistent, int userId) {
4822 boolean didSomething = false;
4823 TaskRecord lastTask = null;
Craig Mautner56f52db2013-02-25 10:03:01 -08004824 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4825 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4826 int numActivities = activities.size();
4827 for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) {
4828 ActivityRecord r = activities.get(activityNdx);
4829 final boolean samePackage = r.packageName.equals(name)
4830 || (name == null && r.userId == userId);
4831 if ((userId == UserHandle.USER_ALL || r.userId == userId)
4832 && (samePackage || r.task == lastTask)
4833 && (r.app == null || evenPersistent || !r.app.persistent)) {
4834 if (!doit) {
4835 if (r.finishing) {
4836 // If this activity is just finishing, then it is not
4837 // interesting as far as something to stop.
4838 continue;
4839 }
4840 return true;
Craig Mautnercae015f2013-02-08 14:31:27 -08004841 }
Craig Mautner56f52db2013-02-25 10:03:01 -08004842 didSomething = true;
4843 Slog.i(TAG, " Force finishing activity " + r);
4844 if (samePackage) {
4845 if (r.app != null) {
4846 r.app.removed = true;
4847 }
4848 r.app = null;
Craig Mautnercae015f2013-02-08 14:31:27 -08004849 }
Craig Mautner56f52db2013-02-25 10:03:01 -08004850 lastTask = r.task;
Craig Mautnerd2328952013-03-05 12:46:26 -08004851 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "force-stop", true);
Craig Mautnercae015f2013-02-08 14:31:27 -08004852 }
4853 }
4854 }
4855 return didSomething;
4856 }
4857
4858 ActivityRecord getTasksLocked(int maxNum, IThumbnailReceiver receiver,
Craig Mautneraab647e2013-02-28 16:31:36 -08004859 PendingThumbnailsRecord pending, List<RunningTaskInfo> list) {
Craig Mautnercae015f2013-02-08 14:31:27 -08004860 ActivityRecord topRecord = null;
Craig Mautneraab647e2013-02-28 16:31:36 -08004861 for (int taskNdx = mTaskHistory.size() - 1; maxNum > 0 && taskNdx >= 0;
4862 --maxNum, --taskNdx) {
4863 final TaskRecord task = mTaskHistory.get(taskNdx);
4864 ActivityRecord r = null;
4865 ActivityRecord top = null;
4866 int numActivities = 0;
4867 int numRunning = 0;
4868 final ArrayList<ActivityRecord> activities = task.mActivities;
4869 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4870 r = activities.get(activityNdx);
Craig Mautnercae015f2013-02-08 14:31:27 -08004871
Craig Mautneraab647e2013-02-28 16:31:36 -08004872 // Initialize state for next task if needed.
4873 if (top == null || (top.state == ActivityState.INITIALIZING)) {
4874 top = r;
4875 numActivities = numRunning = 0;
Craig Mautnercae015f2013-02-08 14:31:27 -08004876 }
Craig Mautneraab647e2013-02-28 16:31:36 -08004877
4878 // Add 'r' into the current task.
4879 numActivities++;
4880 if (r.app != null && r.app.thread != null) {
4881 numRunning++;
4882 }
4883
4884 if (localLOGV) Slog.v(
4885 TAG, r.intent.getComponent().flattenToShortString()
4886 + ": task=" + r.task);
4887 }
4888
4889 RunningTaskInfo ci = new RunningTaskInfo();
4890 ci.id = task.taskId;
4891 ci.baseActivity = r.intent.getComponent();
4892 ci.topActivity = top.intent.getComponent();
4893 if (top.thumbHolder != null) {
4894 ci.description = top.thumbHolder.lastDescription;
4895 }
4896 ci.numActivities = numActivities;
4897 ci.numRunning = numRunning;
4898 //System.out.println(
4899 // "#" + maxNum + ": " + " descr=" + ci.description);
4900 if (receiver != null) {
4901 if (localLOGV) Slog.v(
4902 TAG, "State=" + top.state + "Idle=" + top.idle
4903 + " app=" + top.app
4904 + " thr=" + (top.app != null ? top.app.thread : null));
4905 if (top.state == ActivityState.RESUMED || top.state == ActivityState.PAUSING) {
4906 if (top.idle && top.app != null && top.app.thread != null) {
4907 topRecord = top;
4908 } else {
4909 top.thumbnailNeeded = true;
Craig Mautnercae015f2013-02-08 14:31:27 -08004910 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004911 }
Craig Mautneraab647e2013-02-28 16:31:36 -08004912 pending.pendingRecords.add(top);
Craig Mautnercae015f2013-02-08 14:31:27 -08004913 }
Craig Mautneraab647e2013-02-28 16:31:36 -08004914 list.add(ci);
Craig Mautnercae015f2013-02-08 14:31:27 -08004915 }
4916 return topRecord;
4917 }
4918
4919 public void unhandledBackLocked() {
Craig Mautneraab647e2013-02-28 16:31:36 -08004920 final int top = mTaskHistory.size() - 1;
Craig Mautnercae015f2013-02-08 14:31:27 -08004921 if (DEBUG_SWITCH) Slog.d(
4922 TAG, "Performing unhandledBack(): top activity at " + top);
Craig Mautneraab647e2013-02-28 16:31:36 -08004923 if (top >= 0) {
4924 final ArrayList<ActivityRecord> activities = mTaskHistory.get(top).mActivities;
4925 int activityTop = activities.size() - 1;
4926 if (activityTop > 0) {
4927 finishActivityLocked(activities.get(activityTop), Activity.RESULT_CANCELED, null,
4928 "unhandled-back", true);
4929 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004930 }
4931 }
4932
4933 void handleAppCrashLocked(ProcessRecord app) {
Craig Mautnerd44711d2013-02-23 11:24:36 -08004934 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4935 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4936 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4937 final ActivityRecord r = activities.get(activityNdx);
4938 if (r.app == app) {
4939 Slog.w(TAG, " Force finishing activity "
4940 + r.intent.getComponent().flattenToShortString());
Craig Mautnerd2328952013-03-05 12:46:26 -08004941 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false);
Craig Mautnerd44711d2013-02-23 11:24:36 -08004942 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004943 }
4944 }
4945 }
4946
4947 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
4948 boolean dumpClient, String dumpPackage) {
Craig Mautneraab647e2013-02-28 16:31:36 -08004949 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4950 final TaskRecord task = mTaskHistory.get(taskNdx);
4951 pw.print(" Task "); pw.print(taskNdx); pw.print(": id #"); pw.println(task.taskId);
4952 ActivityManagerService.dumpHistoryList(fd, pw, mTaskHistory.get(taskNdx).mActivities,
4953 " ", "Hist", true, !dumpAll, dumpClient, dumpPackage);
4954 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004955 }
4956
4957 ArrayList<ActivityRecord> getDumpActivitiesLocked(String name) {
4958 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
4959
4960 if ("all".equals(name)) {
Craig Mautneraab647e2013-02-28 16:31:36 -08004961 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4962 activities.addAll(mTaskHistory.get(taskNdx).mActivities);
Craig Mautnercae015f2013-02-08 14:31:27 -08004963 }
4964 } else if ("top".equals(name)) {
Craig Mautneraab647e2013-02-28 16:31:36 -08004965 final int top = mTaskHistory.size() - 1;
4966 if (top >= 0) {
4967 final ArrayList<ActivityRecord> list = mTaskHistory.get(top).mActivities;
4968 int listTop = list.size() - 1;
4969 if (listTop >= 0) {
4970 activities.add(list.get(listTop));
4971 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004972 }
4973 } else {
4974 ItemMatcher matcher = new ItemMatcher();
4975 matcher.build(name);
4976
Craig Mautneraab647e2013-02-28 16:31:36 -08004977 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4978 for (ActivityRecord r1 : mTaskHistory.get(taskNdx).mActivities) {
4979 if (matcher.match(r1, r1.intent.getComponent())) {
4980 activities.add(r1);
4981 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004982 }
4983 }
4984 }
4985
4986 return activities;
4987 }
4988
4989 ActivityRecord restartPackage(String packageName) {
4990 ActivityRecord starting = topRunningActivityLocked(null);
4991
4992 // All activities that came from the package must be
4993 // restarted as if there was a config change.
Craig Mautneraab647e2013-02-28 16:31:36 -08004994 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4995 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4996 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4997 final ActivityRecord a = activities.get(activityNdx);
4998 if (a.info.packageName.equals(packageName)) {
4999 a.forceNewConfig = true;
5000 if (starting != null && a == starting && a.visible) {
5001 a.startFreezingScreenLocked(starting.app,
5002 ActivityInfo.CONFIG_SCREEN_LAYOUT);
5003 }
Craig Mautnercae015f2013-02-08 14:31:27 -08005004 }
5005 }
5006 }
5007
5008 return starting;
5009 }
Craig Mautner5d9c7be2013-02-15 14:02:56 -08005010
Craig Mautner0247fc82013-02-28 14:32:06 -08005011 private void removeActivity(ActivityRecord r) {
5012 final TaskRecord task = r.task;
Craig Mautnerd2328952013-03-05 12:46:26 -08005013 // TODO: use ActivityManagerService.removeTask to do this.
Craig Mautner0247fc82013-02-28 14:32:06 -08005014 if (task.removeActivity(r)) {
5015 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "removeActivity: Removing from history, task="
5016 + task);
5017 mTaskHistory.remove(task);
Craig Mautner0247fc82013-02-28 14:32:06 -08005018 }
5019 }
5020
5021 private void setTask(ActivityRecord r, TaskRecord newTask, ThumbnailHolder newThumbHolder,
5022 boolean isRoot) {
5023 if (r.task != null) {
5024 removeActivity(r);
5025 }
5026 r.setTask(newTask, newThumbHolder, isRoot);
5027 }
5028
Craig Mautner5d9c7be2013-02-15 14:02:56 -08005029 private TaskRecord createTaskRecord(int taskId, ActivityInfo info, Intent intent,
5030 boolean toTop) {
Craig Mautnerd2328952013-03-05 12:46:26 -08005031 TaskRecord task = new TaskRecord(taskId, info, intent, this);
Craig Mautner5d9c7be2013-02-15 14:02:56 -08005032 if (toTop) {
5033 mTaskHistory.add(task);
5034 } else {
5035 mTaskHistory.add(0, task);
5036 }
5037 return task;
5038 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005039}