blob: f98d2d295f7657006df6c6571709c5d3a20d9969 [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 Mautner59c00972012-07-30 12:10:24 -070070import android.view.Display;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070071
Craig Mautnercae015f2013-02-08 14:31:27 -080072import java.io.FileDescriptor;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070073import java.io.IOException;
Craig Mautnercae015f2013-02-08 14:31:27 -080074import java.io.PrintWriter;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070075import java.lang.ref.WeakReference;
76import java.util.ArrayList;
77import java.util.Iterator;
78import java.util.List;
79
80/**
81 * State and management of a single stack of activities.
82 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070083final class ActivityStack {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070084 static final String TAG = ActivityManagerService.TAG;
Dianne Hackbornb961cd22011-06-21 12:13:37 -070085 static final boolean localLOGV = ActivityManagerService.localLOGV;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070086 static final boolean DEBUG_SWITCH = ActivityManagerService.DEBUG_SWITCH;
87 static final boolean DEBUG_PAUSE = ActivityManagerService.DEBUG_PAUSE;
88 static final boolean DEBUG_VISBILITY = ActivityManagerService.DEBUG_VISBILITY;
89 static final boolean DEBUG_USER_LEAVING = ActivityManagerService.DEBUG_USER_LEAVING;
90 static final boolean DEBUG_TRANSITION = ActivityManagerService.DEBUG_TRANSITION;
91 static final boolean DEBUG_RESULTS = ActivityManagerService.DEBUG_RESULTS;
92 static final boolean DEBUG_CONFIGURATION = ActivityManagerService.DEBUG_CONFIGURATION;
93 static final boolean DEBUG_TASKS = ActivityManagerService.DEBUG_TASKS;
Dianne Hackborncc5a0552012-10-01 16:32:39 -070094 static final boolean DEBUG_CLEANUP = ActivityManagerService.DEBUG_CLEANUP;
Craig Mautner9658b312013-02-28 10:55:59 -080095
Dianne Hackbornce86ba82011-07-13 19:33:41 -070096 static final boolean DEBUG_STATES = false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070097 static final boolean DEBUG_ADD_REMOVE = false;
98 static final boolean DEBUG_SAVED_STATE = false;
Dianne Hackborn07981492013-01-28 11:36:23 -080099 static final boolean DEBUG_APP = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700100
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700101 static final boolean VALIDATE_TOKENS = ActivityManagerService.VALIDATE_TOKENS;
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800102
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700103 // How long we wait until giving up on the last activity telling us it
104 // is idle.
105 static final int IDLE_TIMEOUT = 10*1000;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700106
107 // Ticks during which we check progress while waiting for an app to launch.
108 static final int LAUNCH_TICK = 500;
109
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700110 // How long we wait until giving up on the last activity to pause. This
111 // is short because it directly impacts the responsiveness of starting the
112 // next activity.
113 static final int PAUSE_TIMEOUT = 500;
114
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700115 // How long we wait for the activity to tell us it has stopped before
116 // giving up. This is a good amount of time because we really need this
117 // from the application in order to get its saved state.
118 static final int STOP_TIMEOUT = 10*1000;
119
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800120 // How long we can hold the sleep wake lock before giving up.
121 static final int SLEEP_TIMEOUT = 5*1000;
122
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700123 // How long we can hold the launch wake lock before giving up.
124 static final int LAUNCH_TIMEOUT = 10*1000;
125
126 // How long we wait until giving up on an activity telling us it has
127 // finished destroying itself.
128 static final int DESTROY_TIMEOUT = 10*1000;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800129
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700130 // How long until we reset a task when the user returns to it. Currently
Dianne Hackborn621e17d2010-11-22 15:59:56 -0800131 // disabled.
132 static final long ACTIVITY_INACTIVE_RESET_TIME = 0;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800133
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700134 // How long between activity launches that we consider safe to not warn
135 // the user about an unexpected activity being launched on top.
136 static final long START_WARN_TIME = 5*1000;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800137
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700138 // Set to false to disable the preview that is shown while a new activity
139 // is being started.
140 static final boolean SHOW_APP_STARTING_PREVIEW = true;
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800141
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700142 enum ActivityState {
143 INITIALIZING,
144 RESUMED,
145 PAUSING,
146 PAUSED,
147 STOPPING,
148 STOPPED,
149 FINISHING,
150 DESTROYING,
151 DESTROYED
152 }
153
154 final ActivityManagerService mService;
155 final boolean mMainStack;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800156
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700157 final Context mContext;
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800158
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700159 /**
160 * The back history of all previous (and possibly still
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800161 * running) activities. It contains #TaskRecord objects.
162 */
163 private ArrayList<TaskRecord> mTaskHistory = new ArrayList<TaskRecord>();
164
165 /**
Dianne Hackbornbe707852011-11-11 14:32:10 -0800166 * Used for validating app tokens with window manager.
167 */
Craig Mautnerb1fd65c02013-02-05 13:34:57 -0800168 final ArrayList<TaskGroup> mValidateAppTokens = new ArrayList<TaskGroup>();
Dianne Hackbornbe707852011-11-11 14:32:10 -0800169
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700170 /**
171 * List of running activities, sorted by recent usage.
172 * The first entry in the list is the least recently used.
173 * It contains HistoryRecord objects.
174 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700175 final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700176
177 /**
178 * List of activities that are waiting for a new activity
179 * to become visible before completing whatever operation they are
180 * supposed to do.
181 */
182 final ArrayList<ActivityRecord> mWaitingVisibleActivities
183 = new ArrayList<ActivityRecord>();
184
185 /**
186 * List of activities that are ready to be stopped, but waiting
187 * for the next activity to settle down before doing so. It contains
188 * HistoryRecord objects.
189 */
190 final ArrayList<ActivityRecord> mStoppingActivities
191 = new ArrayList<ActivityRecord>();
192
193 /**
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800194 * List of activities that are in the process of going to sleep.
195 */
196 final ArrayList<ActivityRecord> mGoingToSleepActivities
197 = new ArrayList<ActivityRecord>();
198
199 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700200 * Animations that for the current transition have requested not to
201 * be considered for the transition animation.
202 */
203 final ArrayList<ActivityRecord> mNoAnimActivities
204 = new ArrayList<ActivityRecord>();
205
206 /**
207 * List of activities that are ready to be finished, but waiting
208 * for the previous activity to settle down before doing so. It contains
209 * HistoryRecord objects.
210 */
211 final ArrayList<ActivityRecord> mFinishingActivities
212 = new ArrayList<ActivityRecord>();
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800213
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700214 /**
215 * List of people waiting to find out about the next launched activity.
216 */
217 final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched
218 = new ArrayList<IActivityManager.WaitResult>();
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800219
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700220 /**
221 * List of people waiting to find out about the next visible activity.
222 */
223 final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible
224 = new ArrayList<IActivityManager.WaitResult>();
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700225
226 final ArrayList<UserStartedState> mStartingUsers
227 = new ArrayList<UserStartedState>();
228
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700229 /**
230 * Set when the system is going to sleep, until we have
231 * successfully paused the current activity and released our wake lock.
232 * At that point the system is allowed to actually sleep.
233 */
234 final PowerManager.WakeLock mGoingToSleep;
235
236 /**
237 * We don't want to allow the device to go to sleep while in the process
238 * of launching an activity. This is primarily to allow alarm intent
239 * receivers to launch an activity and get that to run before the device
240 * goes back to sleep.
241 */
242 final PowerManager.WakeLock mLaunchingActivity;
243
244 /**
245 * When we are in the process of pausing an activity, before starting the
246 * next one, this variable holds the activity that is currently being paused.
247 */
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800248 ActivityRecord mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700249
250 /**
251 * This is the last activity that we put into the paused state. This is
252 * used to determine if we need to do an activity transition while sleeping,
253 * when we normally hold the top activity paused.
254 */
255 ActivityRecord mLastPausedActivity = null;
256
257 /**
258 * Current activity that is resumed, or null if there is none.
259 */
260 ActivityRecord mResumedActivity = null;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800261
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700262 /**
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700263 * This is the last activity that has been started. It is only used to
264 * identify when multiple activities are started at once so that the user
265 * can be warned they may not be in the activity they think they are.
266 */
267 ActivityRecord mLastStartedActivity = null;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800268
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700269 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700270 * Set when we know we are going to be calling updateConfiguration()
271 * soon, so want to skip intermediate config checks.
272 */
273 boolean mConfigWillChange;
274
275 /**
276 * Set to indicate whether to issue an onUserLeaving callback when a
277 * newly launched activity is being brought in front of us.
278 */
279 boolean mUserLeaving = false;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800280
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700281 long mInitialStartTime = 0;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800282
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800283 /**
284 * Set when we have taken too long waiting to go to sleep.
285 */
286 boolean mSleepTimeout = false;
287
Dianne Hackborn90c52de2011-09-23 12:57:44 -0700288 /**
Craig Mautnerb12428a2012-12-20 16:07:06 -0800289 * Save the most recent screenshot for reuse. This keeps Recents from taking two identical
290 * screenshots, one for the Recents thumbnail and one for the pauseActivity thumbnail.
291 */
292 private ActivityRecord mLastScreenshotActivity = null;
293 private Bitmap mLastScreenshotBitmap = null;
294
Craig Mautnercae015f2013-02-08 14:31:27 -0800295 /**
296 * List of ActivityRecord objects that have been finished and must
297 * still report back to a pending thumbnail receiver.
298 */
299 private final ArrayList<ActivityRecord> mCancelledThumbnails = new ArrayList<ActivityRecord>();
300
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800301 int mThumbnailWidth = -1;
302 int mThumbnailHeight = -1;
303
Amith Yamasani742a6712011-05-04 14:49:28 -0700304 private int mCurrentUser;
305
Craig Mautnerc00204b2013-03-05 15:02:14 -0800306 final int mStackId;
307
Craig Mautner27084302013-03-25 08:05:25 -0700308 /** Run all ActivityStacks through this */
309 final ActivityStackSupervisor mStackSupervisor;
310
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800311 static final int SLEEP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG;
312 static final int PAUSE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 1;
313 static final int IDLE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 2;
314 static final int IDLE_NOW_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 3;
315 static final int LAUNCH_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 4;
316 static final int DESTROY_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 5;
317 static final int RESUME_TOP_ACTIVITY_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 6;
Dianne Hackborn29ba7e62012-03-16 15:03:36 -0700318 static final int LAUNCH_TICK_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 7;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700319 static final int STOP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 8;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700320 static final int DESTROY_ACTIVITIES_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 9;
321
322 static class ScheduleDestroyArgs {
323 final ProcessRecord mOwner;
324 final boolean mOomAdj;
325 final String mReason;
326 ScheduleDestroyArgs(ProcessRecord owner, boolean oomAdj, String reason) {
327 mOwner = owner;
328 mOomAdj = oomAdj;
329 mReason = reason;
330 }
331 }
332
Zoran Marcetaf958b322012-08-09 20:27:12 +0900333 final Handler mHandler;
334
335 final class ActivityStackHandler extends Handler {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700336 //public Handler() {
337 // if (localLOGV) Slog.v(TAG, "Handler started!");
338 //}
Zoran Marcetaf958b322012-08-09 20:27:12 +0900339 public ActivityStackHandler(Looper looper) {
340 super(looper);
341 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700342
Zoran Marcetaf958b322012-08-09 20:27:12 +0900343 @Override
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700344 public void handleMessage(Message msg) {
345 switch (msg.what) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800346 case SLEEP_TIMEOUT_MSG: {
Dianne Hackborn8e8d65f2011-08-11 19:36:18 -0700347 synchronized (mService) {
348 if (mService.isSleeping()) {
349 Slog.w(TAG, "Sleep timeout! Sleeping now.");
350 mSleepTimeout = true;
351 checkReadyForSleepLocked();
352 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800353 }
354 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700355 case PAUSE_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800356 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700357 // We don't at this point know if the activity is fullscreen,
358 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800359 Slog.w(TAG, "Activity pause timeout for " + r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700360 synchronized (mService) {
361 if (r.app != null) {
362 mService.logAppTooSlow(r.app, r.pauseTime,
363 "pausing " + r);
364 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700365
Craig Mautnerd2328952013-03-05 12:46:26 -0800366 activityPausedLocked(r != null ? r.appToken : null, true);
367 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700368 } break;
369 case IDLE_TIMEOUT_MSG: {
370 if (mService.mDidDexOpt) {
371 mService.mDidDexOpt = false;
372 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
373 nmsg.obj = msg.obj;
374 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
375 return;
376 }
377 // We don't at this point know if the activity is fullscreen,
378 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800379 ActivityRecord r = (ActivityRecord)msg.obj;
380 Slog.w(TAG, "Activity idle timeout for " + r);
381 activityIdleInternal(r != null ? r.appToken : null, true, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700382 } break;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700383 case LAUNCH_TICK_MSG: {
384 ActivityRecord r = (ActivityRecord)msg.obj;
385 synchronized (mService) {
386 if (r.continueLaunchTickingLocked()) {
387 mService.logAppTooSlow(r.app, r.launchTickTime,
388 "launching " + r);
389 }
390 }
391 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700392 case DESTROY_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800393 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700394 // We don't at this point know if the activity is fullscreen,
395 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800396 Slog.w(TAG, "Activity destroy timeout for " + r);
Craig Mautnerd2328952013-03-05 12:46:26 -0800397 synchronized (mService) {
398 activityDestroyedLocked(r != null ? r.appToken : null);
399 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700400 } break;
401 case IDLE_NOW_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800402 ActivityRecord r = (ActivityRecord)msg.obj;
403 activityIdleInternal(r != null ? r.appToken : null, false, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700404 } break;
405 case LAUNCH_TIMEOUT_MSG: {
406 if (mService.mDidDexOpt) {
407 mService.mDidDexOpt = false;
408 Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
409 mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
410 return;
411 }
412 synchronized (mService) {
413 if (mLaunchingActivity.isHeld()) {
414 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
415 mLaunchingActivity.release();
416 }
417 }
418 } break;
419 case RESUME_TOP_ACTIVITY_MSG: {
420 synchronized (mService) {
421 resumeTopActivityLocked(null);
422 }
423 } break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700424 case STOP_TIMEOUT_MSG: {
425 ActivityRecord r = (ActivityRecord)msg.obj;
426 // We don't at this point know if the activity is fullscreen,
427 // so we need to be conservative and assume it isn't.
428 Slog.w(TAG, "Activity stop timeout for " + r);
429 synchronized (mService) {
430 if (r.isInHistory()) {
431 activityStoppedLocked(r, null, null, null);
432 }
433 }
434 } break;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700435 case DESTROY_ACTIVITIES_MSG: {
436 ScheduleDestroyArgs args = (ScheduleDestroyArgs)msg.obj;
437 synchronized (mService) {
438 destroyActivitiesLocked(args.mOwner, args.mOomAdj, args.mReason);
439 }
440 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700441 }
442 }
Craig Mautner4b71aa12012-12-27 17:20:01 -0800443 }
444
Craig Mautner000f0022013-02-26 15:04:29 -0800445 private int numActivities() {
446 int count = 0;
447 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
448 count += mTaskHistory.get(taskNdx).mActivities.size();
449 }
450 return count;
451 }
452
Craig Mautnerc00204b2013-03-05 15:02:14 -0800453 ActivityStack(ActivityManagerService service, Context context, boolean mainStack, Looper looper,
Craig Mautner27084302013-03-25 08:05:25 -0700454 int stackId, ActivityStackSupervisor supervisor) {
Zoran Marcetaf958b322012-08-09 20:27:12 +0900455 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);
Craig Mautnerc00204b2013-03-05 15:02:14 -0800464 mStackId = stackId;
Craig Mautner27084302013-03-25 08:05:25 -0700465 mStackSupervisor = supervisor;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700466 }
Craig Mautner5962b122012-10-05 14:45:52 -0700467
468 private boolean okToShow(ActivityRecord r) {
469 return r.userId == mCurrentUser
470 || (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0;
471 }
472
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700473 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800474 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
475 final TaskRecord task = mTaskHistory.get(taskNdx);
Craig Mautner11bf9a52013-02-19 14:08:51 -0800476 final ArrayList<ActivityRecord> activities = task.mActivities;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800477 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
478 ActivityRecord r = activities.get(activityNdx);
Craig Mautner11bf9a52013-02-19 14:08:51 -0800479 if (!r.finishing && r != notTop && okToShow(r)) {
480 return r;
481 }
482 }
483 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700484 return null;
485 }
486
487 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800488 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
489 final TaskRecord task = mTaskHistory.get(taskNdx);
Craig Mautner11bf9a52013-02-19 14:08:51 -0800490 final ArrayList<ActivityRecord> activities = task.mActivities;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800491 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
492 ActivityRecord r = activities.get(activityNdx);
Craig Mautner11bf9a52013-02-19 14:08:51 -0800493 if (!r.finishing && !r.delayedResume && r != notTop && okToShow(r)) {
494 return r;
495 }
496 }
497 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700498 return null;
499 }
500
501 /**
502 * This is a simplified version of topRunningActivityLocked that provides a number of
503 * optional skip-over modes. It is intended for use with the ActivityController hook only.
Craig Mautner9658b312013-02-28 10:55:59 -0800504 *
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700505 * @param token If non-null, any history records matching this token will be skipped.
506 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
Craig Mautner9658b312013-02-28 10:55:59 -0800507 *
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700508 * @return Returns the HistoryRecord of the next activity on the stack.
509 */
510 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
Craig Mautner11bf9a52013-02-19 14:08:51 -0800511 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
512 TaskRecord task = mTaskHistory.get(taskNdx);
513 if (task.taskId == taskId) {
514 continue;
515 }
516 ArrayList<ActivityRecord> activities = task.mActivities;
517 for (int i = activities.size() - 1; i >= 0; --i) {
518 final ActivityRecord r = activities.get(i);
519 // Note: the taskId check depends on real taskId fields being non-zero
520 if (!r.finishing && (token != r.appToken) && okToShow(r)) {
521 return r;
522 }
523 }
524 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700525 return null;
526 }
527
Craig Mautnerd2328952013-03-05 12:46:26 -0800528 TaskRecord taskForIdLocked(int id) {
529 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
530 final TaskRecord task = mTaskHistory.get(taskNdx);
531 if (task.taskId == id) {
532 return task;
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800533 }
534 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700535 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700536 }
537
Craig Mautnerd2328952013-03-05 12:46:26 -0800538 ActivityRecord isInStackLocked(IBinder token) {
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800539 final ActivityRecord r = ActivityRecord.forToken(token);
Craig Mautnerd2328952013-03-05 12:46:26 -0800540 if (r != null) {
541 final TaskRecord task = r.task;
542 if (task.mActivities.contains(r) && mTaskHistory.contains(task)) {
543 if (task.stack != this) Slog.w(TAG,
544 "Illegal state! task does not point to stack it is in.");
545 return r;
546 }
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800547 }
Craig Mautnerd2328952013-03-05 12:46:26 -0800548 return null;
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800549 }
550
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700551 private final boolean updateLRUListLocked(ActivityRecord r) {
552 final boolean hadit = mLRUActivities.remove(r);
553 mLRUActivities.add(r);
554 return hadit;
555 }
556
557 /**
558 * Returns the top activity in any existing task matching the given
559 * Intent. Returns null if no such task is found.
560 */
561 private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
562 ComponentName cls = intent.getComponent();
563 if (info.targetActivity != null) {
564 cls = new ComponentName(info.packageName, info.targetActivity);
565 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700566 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Craig Mautner000f0022013-02-26 15:04:29 -0800567
568 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
569 final TaskRecord task = mTaskHistory.get(taskNdx);
570 final ActivityRecord r = task.getTopActivity();
571 if (r == null || r.finishing || r.userId != userId ||
572 r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
573 continue;
574 }
575
576 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
577 // + "/aff=" + r.task.affinity + " to new cls="
578 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
579 if (task.affinity != null) {
580 if (task.affinity.equals(info.taskAffinity)) {
581 //Slog.i(TAG, "Found matching affinity!");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700582 return r;
583 }
Craig Mautner000f0022013-02-26 15:04:29 -0800584 } else if (task.intent != null && task.intent.getComponent().equals(cls)) {
585 //Slog.i(TAG, "Found matching class!");
586 //dump();
587 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
588 return r;
589 } else if (task.affinityIntent != null
590 && task.affinityIntent.getComponent().equals(cls)) {
591 //Slog.i(TAG, "Found matching class!");
592 //dump();
593 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
594 return r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700595 }
596 }
597
598 return null;
599 }
600
601 /**
602 * Returns the first activity (starting from the top of the stack) that
603 * is the same as the given activity. Returns null if no such activity
604 * is found.
605 */
606 private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
607 ComponentName cls = intent.getComponent();
608 if (info.targetActivity != null) {
609 cls = new ComponentName(info.packageName, info.targetActivity);
610 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700611 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700612
Craig Mautner000f0022013-02-26 15:04:29 -0800613 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
614 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
615 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
616 ActivityRecord r = activities.get(activityNdx);
617 if (!r.finishing && r.intent.getComponent().equals(cls) && r.userId == userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700618 //Slog.i(TAG, "Found matching class!");
619 //dump();
620 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
621 return r;
622 }
623 }
624 }
625
626 return null;
627 }
628
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700629 final void showAskCompatModeDialogLocked(ActivityRecord r) {
630 Message msg = Message.obtain();
631 msg.what = ActivityManagerService.SHOW_COMPAT_MODE_DIALOG_MSG;
632 msg.obj = r.task.askedCompatMode ? null : r;
633 mService.mHandler.sendMessage(msg);
634 }
635
Amith Yamasani742a6712011-05-04 14:49:28 -0700636 /*
637 * Move the activities around in the stack to bring a user to the foreground.
638 * @return whether there are any activities for the specified user.
639 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700640 final boolean switchUserLocked(int userId, UserStartedState uss) {
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800641 if (VALIDATE_TOKENS) {
642 validateAppTokensLocked();
643 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700644 mStartingUsers.add(uss);
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800645 if (mCurrentUser == userId) {
646 return true;
647 }
648 mCurrentUser = userId;
649
650 // Move userId's tasks to the top.
651 boolean haveActivities = false;
652 TaskRecord task = null;
653 int index = mTaskHistory.size();
654 for (int i = 0; i < index; ++i) {
655 task = mTaskHistory.get(i);
656 if (task.userId == userId) {
657 haveActivities = true;
658 mTaskHistory.remove(i);
659 mTaskHistory.add(task);
660 --index;
661 }
662 }
663
664 // task is now the original topmost TaskRecord. Transition from the old top to the new top.
665 ActivityRecord top = task != null ? task.getTopActivity() : null;
Craig Mautner000f0022013-02-26 15:04:29 -0800666 resumeTopActivityLocked(top);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700667 return haveActivities;
Amith Yamasani742a6712011-05-04 14:49:28 -0700668 }
669
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700670 final boolean realStartActivityLocked(ActivityRecord r,
671 ProcessRecord app, boolean andResume, boolean checkConfig)
672 throws RemoteException {
673
674 r.startFreezingScreenLocked(app, 0);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800675 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700676
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700677 // schedule launch ticks to collect information about slow apps.
678 r.startLaunchTickingLocked();
679
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700680 // Have the window manager re-evaluate the orientation of
681 // the screen based on the new activity order. Note that
682 // as a result of this, it can call back into the activity
683 // manager with a new orientation. We don't care about that,
684 // because the activity is not currently running so we are
685 // just restarting it anyway.
686 if (checkConfig) {
687 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
688 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -0800689 r.mayFreezeScreenLocked(app) ? r.appToken : null);
Dianne Hackborn813075a62011-11-14 17:45:19 -0800690 mService.updateConfigurationLocked(config, r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700691 }
692
693 r.app = app;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700694 app.waitingToKill = null;
Dianne Hackborn07981492013-01-28 11:36:23 -0800695 r.launchCount++;
696 r.lastLaunchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700697
698 if (localLOGV) Slog.v(TAG, "Launching: " + r);
699
700 int idx = app.activities.indexOf(r);
701 if (idx < 0) {
702 app.activities.add(r);
703 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -0700704 mService.updateLruProcessLocked(app, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700705
706 try {
707 if (app.thread == null) {
708 throw new RemoteException();
709 }
710 List<ResultInfo> results = null;
711 List<Intent> newIntents = null;
712 if (andResume) {
713 results = r.results;
714 newIntents = r.newIntents;
715 }
716 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
717 + " icicle=" + r.icicle
718 + " with results=" + results + " newIntents=" + newIntents
719 + " andResume=" + andResume);
720 if (andResume) {
721 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -0700722 r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700723 r.task.taskId, r.shortComponentName);
724 }
725 if (r.isHomeActivity) {
726 mService.mHomeProcess = app;
727 }
728 mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800729 r.sleeping = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400730 r.forceNewConfig = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700731 showAskCompatModeDialogLocked(r);
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700732 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700733 String profileFile = null;
734 ParcelFileDescriptor profileFd = null;
735 boolean profileAutoStop = false;
736 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
737 if (mService.mProfileProc == null || mService.mProfileProc == app) {
738 mService.mProfileProc = app;
739 profileFile = mService.mProfileFile;
740 profileFd = mService.mProfileFd;
741 profileAutoStop = mService.mAutoStopProfiler;
742 }
743 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -0700744 app.hasShownUi = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700745 app.pendingUiClean = true;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700746 if (profileFd != null) {
747 try {
748 profileFd = profileFd.dup();
749 } catch (IOException e) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -0800750 if (profileFd != null) {
751 try {
752 profileFd.close();
753 } catch (IOException o) {
754 }
755 profileFd = null;
756 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700757 }
758 }
Dianne Hackbornbe707852011-11-11 14:32:10 -0800759 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
Dianne Hackborn813075a62011-11-14 17:45:19 -0800760 System.identityHashCode(r), r.info,
761 new Configuration(mService.mConfiguration),
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700762 r.compat, r.icicle, results, newIntents, !andResume,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700763 mService.isNextTransitionForward(), profileFile, profileFd,
764 profileAutoStop);
Craig Mautner9658b312013-02-28 10:55:59 -0800765
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700766 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700767 // This may be a heavy-weight process! Note that the package
768 // manager will ensure that only activity can run in the main
769 // process of the .apk, which is the only thing that will be
770 // considered heavy-weight.
771 if (app.processName.equals(app.info.packageName)) {
772 if (mService.mHeavyWeightProcess != null
773 && mService.mHeavyWeightProcess != app) {
774 Log.w(TAG, "Starting new heavy weight process " + app
775 + " when already running "
776 + mService.mHeavyWeightProcess);
777 }
778 mService.mHeavyWeightProcess = app;
779 Message msg = mService.mHandler.obtainMessage(
780 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
781 msg.obj = r;
782 mService.mHandler.sendMessage(msg);
783 }
784 }
Craig Mautner9658b312013-02-28 10:55:59 -0800785
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700786 } catch (RemoteException e) {
787 if (r.launchFailed) {
788 // This is the second time we failed -- finish activity
789 // and give up.
790 Slog.e(TAG, "Second failure launching "
791 + r.intent.getComponent().flattenToShortString()
792 + ", giving up", e);
793 mService.appDiedLocked(app, app.pid, app.thread);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800794 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700795 "2nd-crash", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700796 return false;
797 }
798
799 // This is the first time we failed -- restart process and
800 // retry.
801 app.activities.remove(r);
802 throw e;
803 }
804
805 r.launchFailed = false;
806 if (updateLRUListLocked(r)) {
807 Slog.w(TAG, "Activity " + r
808 + " being launched, but already in LRU list");
809 }
810
811 if (andResume) {
812 // As part of the process of launching, ActivityThread also performs
813 // a resume.
814 r.state = ActivityState.RESUMED;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700815 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
816 + " (starting new instance)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700817 r.stopped = false;
818 mResumedActivity = r;
819 r.task.touchActiveTime();
Craig Mautnerd2328952013-03-05 12:46:26 -0800820 mService.addRecentTaskLocked(r.task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700821 completeResumeLocked(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800822 checkReadyForSleepLocked();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700823 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Launch completed; removing icicle of " + r.icicle);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700824 } else {
825 // This activity is not starting in the resumed state... which
826 // should look like we asked it to pause+stop (but remain visible),
827 // and it has done so and reported back the current icicle and
828 // other state.
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700829 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
830 + " (starting in stopped state)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700831 r.state = ActivityState.STOPPED;
832 r.stopped = true;
833 }
834
835 // Launch the new version setup screen if needed. We do this -after-
836 // launching the initial activity (that is, home), so that it can have
837 // a chance to initialize itself while in the background, making the
838 // switch back to it faster and look better.
839 if (mMainStack) {
840 mService.startSetupActivityLocked();
841 }
Craig Mautner9658b312013-02-28 10:55:59 -0800842
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700843 return true;
844 }
845
846 private final void startSpecificActivityLocked(ActivityRecord r,
847 boolean andResume, boolean checkConfig) {
848 // Is this activity's application already running?
849 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
850 r.info.applicationInfo.uid);
Dianne Hackborn07981492013-01-28 11:36:23 -0800851
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700852 if (r.launchTime == 0) {
853 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700854 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700855 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700856 }
857 } else if (mInitialStartTime == 0) {
858 mInitialStartTime = SystemClock.uptimeMillis();
859 }
Craig Mautneraab647e2013-02-28 16:31:36 -0800860
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700861 if (app != null && app.thread != null) {
862 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700863 app.addPackage(r.info.packageName);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700864 realStartActivityLocked(r, app, andResume, checkConfig);
865 return;
866 } catch (RemoteException e) {
867 Slog.w(TAG, "Exception when starting activity "
868 + r.intent.getComponent().flattenToShortString(), e);
869 }
870
871 // If a dead object exception was thrown -- fall through to
872 // restart the application.
873 }
874
875 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800876 "activity", r.intent.getComponent(), false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700877 }
Craig Mautneraab647e2013-02-28 16:31:36 -0800878
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800879 void stopIfSleepingLocked() {
880 if (mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700881 if (!mGoingToSleep.isHeld()) {
882 mGoingToSleep.acquire();
883 if (mLaunchingActivity.isHeld()) {
884 mLaunchingActivity.release();
885 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
886 }
887 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800888 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
889 Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
890 mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
891 checkReadyForSleepLocked();
892 }
893 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700894
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800895 void awakeFromSleepingLocked() {
896 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
897 mSleepTimeout = false;
898 if (mGoingToSleep.isHeld()) {
899 mGoingToSleep.release();
900 }
901 // Ensure activities are no longer sleeping.
Craig Mautnerd44711d2013-02-23 11:24:36 -0800902 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
903 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
904 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
905 activities.get(activityNdx).setSleeping(false);
906 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800907 }
908 mGoingToSleepActivities.clear();
909 }
910
911 void activitySleptLocked(ActivityRecord r) {
912 mGoingToSleepActivities.remove(r);
913 checkReadyForSleepLocked();
914 }
915
916 void checkReadyForSleepLocked() {
917 if (!mService.isSleeping()) {
918 // Do not care.
919 return;
920 }
921
922 if (!mSleepTimeout) {
923 if (mResumedActivity != null) {
924 // Still have something resumed; can't sleep until it is paused.
925 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700926 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
927 startPausingLocked(false, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800928 return;
929 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800930 if (mPausingActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800931 // Still waiting for something to pause; can't sleep yet.
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800932 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800933 return;
934 }
935
936 if (mStoppingActivities.size() > 0) {
937 // Still need to tell some activities to stop; can't sleep yet.
938 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
939 + mStoppingActivities.size() + " activities");
Dianne Hackborn80a7ac12011-09-22 18:32:52 -0700940 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800941 return;
942 }
943
944 ensureActivitiesVisibleLocked(null, 0);
945
946 // Make sure any stopped but visible activities are now sleeping.
947 // This ensures that the activity's onStop() is called.
Craig Mautnerd44711d2013-02-23 11:24:36 -0800948 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
949 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
950 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
951 final ActivityRecord r = activities.get(activityNdx);
952 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
953 r.setSleeping(true);
954 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800955 }
956 }
957
958 if (mGoingToSleepActivities.size() > 0) {
959 // Still need to tell some activities to sleep; can't sleep yet.
960 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
961 + mGoingToSleepActivities.size() + " activities");
962 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700963 }
964 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800965
966 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
967
968 if (mGoingToSleep.isHeld()) {
969 mGoingToSleep.release();
970 }
971 if (mService.mShuttingDown) {
972 mService.notifyAll();
973 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700974 }
Craig Mautner59c00972012-07-30 12:10:24 -0700975
Dianne Hackbornd2835932010-12-13 16:28:46 -0800976 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -0800977 if (who.noDisplay) {
978 return null;
979 }
Craig Mautneraab647e2013-02-28 16:31:36 -0800980
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800981 Resources res = mService.mContext.getResources();
982 int w = mThumbnailWidth;
983 int h = mThumbnailHeight;
984 if (w < 0) {
985 mThumbnailWidth = w =
986 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
987 mThumbnailHeight = h =
988 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
989 }
990
991 if (w > 0) {
Craig Mautnerb12428a2012-12-20 16:07:06 -0800992 if (who != mLastScreenshotActivity || mLastScreenshotBitmap == null
993 || mLastScreenshotBitmap.getWidth() != w
994 || mLastScreenshotBitmap.getHeight() != h) {
995 mLastScreenshotActivity = who;
996 mLastScreenshotBitmap = mService.mWindowManager.screenshotApplications(
997 who.appToken, Display.DEFAULT_DISPLAY, w, h);
998 }
999 if (mLastScreenshotBitmap != null) {
1000 return mLastScreenshotBitmap.copy(Config.ARGB_8888, true);
1001 }
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001002 }
1003 return null;
1004 }
1005
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001006 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001007 if (mPausingActivity != null) {
1008 RuntimeException e = new RuntimeException();
1009 Slog.e(TAG, "Trying to pause when pause is already pending for "
1010 + mPausingActivity, e);
1011 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001012 ActivityRecord prev = mResumedActivity;
1013 if (prev == null) {
1014 RuntimeException e = new RuntimeException();
1015 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
1016 resumeTopActivityLocked(null);
1017 return;
1018 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001019 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
1020 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001021 mResumedActivity = null;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001022 mPausingActivity = prev;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001023 mLastPausedActivity = prev;
1024 prev.state = ActivityState.PAUSING;
1025 prev.task.touchActiveTime();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001026 prev.updateThumbnail(screenshotActivities(prev), null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001027
1028 mService.updateCpuStats();
Craig Mautneraab647e2013-02-28 16:31:36 -08001029
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001030 if (prev.app != null && prev.app.thread != null) {
1031 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
1032 try {
1033 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001034 prev.userId, System.identityHashCode(prev),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001035 prev.shortComponentName);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001036 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
1037 userLeaving, prev.configChangeFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001038 if (mMainStack) {
1039 mService.updateUsageStats(prev, false);
1040 }
1041 } catch (Exception e) {
1042 // Ignore exception, if process died other code will cleanup.
1043 Slog.w(TAG, "Exception thrown during pause", e);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001044 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001045 mLastPausedActivity = null;
1046 }
1047 } else {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001048 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001049 mLastPausedActivity = null;
1050 }
1051
1052 // If we are not going to sleep, we want to ensure the device is
1053 // awake until the next activity is started.
1054 if (!mService.mSleeping && !mService.mShuttingDown) {
1055 mLaunchingActivity.acquire();
1056 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
1057 // To be safe, don't allow the wake lock to be held for too long.
1058 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
1059 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
1060 }
1061 }
1062
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001063
1064 if (mPausingActivity != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001065 // Have the window manager pause its key dispatching until the new
1066 // activity has started. If we're pausing the activity just because
1067 // the screen is being turned off and the UI is sleeping, don't interrupt
1068 // key dispatch; the same activity will pick it up again on wakeup.
1069 if (!uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001070 prev.pauseKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001071 } else {
1072 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
1073 }
1074
1075 // Schedule a pause timeout in case the app doesn't respond.
1076 // We don't give it much time because this directly impacts the
1077 // responsiveness seen by the user.
1078 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
1079 msg.obj = prev;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001080 prev.pauseTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001081 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
1082 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
1083 } else {
1084 // This activity failed to schedule the
1085 // pause, so just treat it as being paused now.
1086 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001087 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001088 }
1089 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001090
Craig Mautnerd2328952013-03-05 12:46:26 -08001091 final void activityResumedLocked(IBinder token) {
1092 final ActivityRecord r = ActivityRecord.forToken(token);
1093 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Resumed activity; dropping state of: " + r);
1094 r.icicle = null;
1095 r.haveState = false;
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001096 }
1097
Craig Mautnerd2328952013-03-05 12:46:26 -08001098 final void activityPausedLocked(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001099 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001100 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001101
Craig Mautnerd2328952013-03-05 12:46:26 -08001102 final ActivityRecord r = isInStackLocked(token);
1103 if (r != null) {
1104 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
1105 if (mPausingActivity == r) {
1106 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
1107 + (timeout ? " (due to timeout)" : " (pause complete)"));
1108 r.state = ActivityState.PAUSED;
1109 completePauseLocked();
1110 } else {
1111 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
1112 r.userId, System.identityHashCode(r), r.shortComponentName,
1113 mPausingActivity != null
1114 ? mPausingActivity.shortComponentName : "(none)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001115 }
1116 }
1117 }
1118
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001119 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
1120 CharSequence description) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07001121 if (r.state != ActivityState.STOPPING) {
1122 Slog.i(TAG, "Activity reported stop, but no longer stopping: " + r);
1123 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1124 return;
1125 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001126 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Saving icicle of " + r + ": " + icicle);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001127 if (icicle != null) {
1128 // If icicle is null, this is happening due to a timeout, so we
1129 // haven't really saved the state.
1130 r.icicle = icicle;
1131 r.haveState = true;
Dianne Hackborn07981492013-01-28 11:36:23 -08001132 r.launchCount = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001133 r.updateThumbnail(thumbnail, description);
1134 }
1135 if (!r.stopped) {
1136 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
1137 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1138 r.stopped = true;
1139 r.state = ActivityState.STOPPED;
Dianne Hackborn6e3d6da2012-06-15 12:05:27 -07001140 if (r.finishing) {
1141 r.clearOptionsLocked();
1142 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001143 if (r.configDestroy) {
1144 destroyActivityLocked(r, true, false, "stop-config");
1145 resumeTopActivityLocked(null);
1146 } else {
1147 // Now that this process has stopped, we may want to consider
1148 // it to be the previous app to try to keep around in case
1149 // the user wants to return to it.
1150 ProcessRecord fgApp = null;
1151 if (mResumedActivity != null) {
1152 fgApp = mResumedActivity.app;
1153 } else if (mPausingActivity != null) {
1154 fgApp = mPausingActivity.app;
1155 }
1156 if (r.app != null && fgApp != null && r.app != fgApp
1157 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
1158 && r.app != mService.mHomeProcess) {
1159 mService.mPreviousProcess = r.app;
1160 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
1161 }
Dianne Hackborn50685602011-12-01 12:23:37 -08001162 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001163 }
1164 }
1165 }
1166
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001167 private final void completePauseLocked() {
1168 ActivityRecord prev = mPausingActivity;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001169 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
Craig Mautneraab647e2013-02-28 16:31:36 -08001170
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001171 if (prev != null) {
1172 if (prev.finishing) {
1173 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001174 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001175 } else if (prev.app != null) {
1176 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
1177 if (prev.waitingVisible) {
1178 prev.waitingVisible = false;
1179 mWaitingVisibleActivities.remove(prev);
1180 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
1181 TAG, "Complete pause, no longer waiting: " + prev);
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001182 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001183 if (prev.configDestroy) {
1184 // The previous is being paused because the configuration
1185 // is changing, which means it is actually stopping...
1186 // To juggle the fact that we are also starting a new
1187 // instance right now, we need to first completely stop
1188 // the current instance before starting the new one.
1189 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
1190 destroyActivityLocked(prev, true, false, "pause-config");
1191 } else {
1192 mStoppingActivities.add(prev);
1193 if (mStoppingActivities.size() > 3) {
1194 // If we already have a few activities waiting to stop,
1195 // then give up on things going idle and start clearing
1196 // them out.
1197 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
1198 scheduleIdleLocked();
1199 } else {
1200 checkReadyForSleepLocked();
1201 }
1202 }
1203 } else {
1204 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
1205 prev = null;
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001206 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001207 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001208 }
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001209
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001210 if (!mService.isSleeping()) {
1211 resumeTopActivityLocked(prev);
1212 } else {
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001213 checkReadyForSleepLocked();
Dianne Hackborncc5a0552012-10-01 16:32:39 -07001214 ActivityRecord top = topRunningActivityLocked(null);
1215 if (top == null || (prev != null && top != prev)) {
1216 // If there are no more activities available to run,
1217 // do resume anyway to start something. Also if the top
1218 // activity on the stack is not the just paused activity,
1219 // we need to go ahead and resume it to ensure we complete
1220 // an in-flight app switch.
Dianne Hackborn42e620c2012-06-24 13:20:51 -07001221 resumeTopActivityLocked(null);
1222 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001223 }
Craig Mautneraab647e2013-02-28 16:31:36 -08001224
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001225 if (prev != null) {
1226 prev.resumeKeyDispatchingLocked();
1227 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001228
1229 if (prev.app != null && prev.cpuTimeAtResume > 0
1230 && mService.mBatteryStatsService.isOnBattery()) {
1231 long diff = 0;
1232 synchronized (mService.mProcessStatsThread) {
1233 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
1234 - prev.cpuTimeAtResume;
1235 }
1236 if (diff > 0) {
1237 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
1238 synchronized (bsi) {
1239 BatteryStatsImpl.Uid.Proc ps =
1240 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
1241 prev.info.packageName);
1242 if (ps != null) {
1243 ps.addForegroundTimeLocked(diff);
1244 }
1245 }
1246 }
1247 }
1248 prev.cpuTimeAtResume = 0; // reset it
1249 }
1250
1251 /**
1252 * Once we know that we have asked an application to put an activity in
1253 * the resumed state (either by launching it or explicitly telling it),
1254 * this function updates the rest of our state to match that fact.
1255 */
1256 private final void completeResumeLocked(ActivityRecord next) {
1257 next.idle = false;
1258 next.results = null;
1259 next.newIntents = null;
1260
1261 // schedule an idle timeout in case the app doesn't do it for us.
1262 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1263 msg.obj = next;
1264 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
1265
1266 if (false) {
1267 // The activity was never told to pause, so just keep
1268 // things going as-is. To maintain our own state,
1269 // we need to emulate it coming back and saying it is
1270 // idle.
1271 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
1272 msg.obj = next;
1273 mHandler.sendMessage(msg);
1274 }
1275
1276 if (mMainStack) {
1277 mService.reportResumedActivityLocked(next);
1278 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07001279
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001280 if (mMainStack) {
1281 mService.setFocusedActivityLocked(next);
1282 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001283 next.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001284 ensureActivitiesVisibleLocked(null, 0);
1285 mService.mWindowManager.executeAppTransition();
1286 mNoAnimActivities.clear();
1287
1288 // Mark the point when the activity is resuming
1289 // TODO: To be more accurate, the mark should be before the onCreate,
1290 // not after the onResume. But for subsequent starts, onResume is fine.
1291 if (next.app != null) {
1292 synchronized (mService.mProcessStatsThread) {
1293 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1294 }
1295 } else {
1296 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1297 }
1298 }
1299
1300 /**
1301 * Make sure that all activities that need to be visible (that is, they
1302 * currently can be seen by the user) actually are.
1303 */
1304 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1305 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1306 if (DEBUG_VISBILITY) Slog.v(
1307 TAG, "ensureActivitiesVisible behind " + top
1308 + " configChanges=0x" + Integer.toHexString(configChanges));
1309
1310 // If the top activity is not fullscreen, then we need to
1311 // make sure any activities under it are now visible.
Craig Mautnerd44711d2013-02-23 11:24:36 -08001312 boolean aboveTop = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001313 boolean behindFullscreen = false;
Craig Mautnerd44711d2013-02-23 11:24:36 -08001314 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
1315 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
1316 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
1317 final ActivityRecord r = activities.get(activityNdx);
1318 if (r.finishing) {
1319 continue;
1320 }
1321 if (aboveTop && r != top) {
1322 continue;
1323 }
1324 aboveTop = false;
1325 if (!behindFullscreen) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001326 if (DEBUG_VISBILITY) Slog.v(
Craig Mautnerd44711d2013-02-23 11:24:36 -08001327 TAG, "Make visible? " + r + " finishing=" + r.finishing
1328 + " state=" + r.state);
Craig Mautner58547802013-03-05 08:23:53 -08001329
Craig Mautnerd44711d2013-02-23 11:24:36 -08001330 final boolean doThisProcess = onlyThisProcess == null
1331 || onlyThisProcess.equals(r.processName);
1332
1333 // First: if this is not the current activity being started, make
1334 // sure it matches the current configuration.
1335 if (r != starting && doThisProcess) {
1336 ensureActivityConfigurationLocked(r, 0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001337 }
Craig Mautnerd44711d2013-02-23 11:24:36 -08001338
1339 if (r.app == null || r.app.thread == null) {
1340 if (onlyThisProcess == null
1341 || onlyThisProcess.equals(r.processName)) {
1342 // This activity needs to be visible, but isn't even
1343 // running... get it started, but don't resume it
1344 // at this point.
1345 if (DEBUG_VISBILITY) Slog.v(
1346 TAG, "Start and freeze screen for " + r);
1347 if (r != starting) {
1348 r.startFreezingScreenLocked(r.app, configChanges);
1349 }
1350 if (!r.visible) {
1351 if (DEBUG_VISBILITY) Slog.v(
1352 TAG, "Starting and making visible: " + r);
1353 mService.mWindowManager.setAppVisibility(r.appToken, true);
1354 }
1355 if (r != starting) {
1356 startSpecificActivityLocked(r, false, false);
1357 }
1358 }
1359
1360 } else if (r.visible) {
1361 // If this activity is already visible, then there is nothing
1362 // else to do here.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001363 if (DEBUG_VISBILITY) Slog.v(
Craig Mautnerd44711d2013-02-23 11:24:36 -08001364 TAG, "Skipping: already visible at " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001365 r.stopFreezingScreenLocked(false);
Craig Mautnerd44711d2013-02-23 11:24:36 -08001366
1367 } else if (onlyThisProcess == null) {
1368 // This activity is not currently visible, but is running.
1369 // Tell it to become visible.
1370 r.visible = true;
1371 if (r.state != ActivityState.RESUMED && r != starting) {
1372 // If this activity is paused, tell it
1373 // to now show its window.
1374 if (DEBUG_VISBILITY) Slog.v(
1375 TAG, "Making visible and scheduling visibility: " + r);
1376 try {
1377 mService.mWindowManager.setAppVisibility(r.appToken, true);
1378 r.sleeping = false;
1379 r.app.pendingUiClean = true;
1380 r.app.thread.scheduleWindowVisibility(r.appToken, true);
1381 r.stopFreezingScreenLocked(false);
1382 } catch (Exception e) {
1383 // Just skip on any failure; we'll make it
1384 // visible when it next restarts.
1385 Slog.w(TAG, "Exception thrown making visibile: "
1386 + r.intent.getComponent(), e);
1387 }
1388 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001389 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001390
Craig Mautnerd44711d2013-02-23 11:24:36 -08001391 // Aggregate current change flags.
1392 configChanges |= r.configChangeFlags;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001393
Craig Mautnerd44711d2013-02-23 11:24:36 -08001394 if (r.fullscreen) {
1395 // At this point, nothing else needs to be shown
1396 if (DEBUG_VISBILITY) Slog.v(
1397 TAG, "Stopping: fullscreen at " + r);
1398 behindFullscreen = true;
1399 }
1400 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001401 if (r.visible) {
1402 if (DEBUG_VISBILITY) Slog.v(
1403 TAG, "Making invisible: " + r);
1404 r.visible = false;
1405 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001406 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001407 if ((r.state == ActivityState.STOPPING
1408 || r.state == ActivityState.STOPPED)
1409 && r.app != null && r.app.thread != null) {
1410 if (DEBUG_VISBILITY) Slog.v(
1411 TAG, "Scheduling invisibility: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001412 r.app.thread.scheduleWindowVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001413 }
1414 } catch (Exception e) {
1415 // Just skip on any failure; we'll make it
1416 // visible when it next restarts.
1417 Slog.w(TAG, "Exception thrown making hidden: "
1418 + r.intent.getComponent(), e);
1419 }
1420 } else {
1421 if (DEBUG_VISBILITY) Slog.v(
1422 TAG, "Already invisible: " + r);
1423 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001424 }
1425 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001426 }
1427 }
1428
1429 /**
1430 * Version of ensureActivitiesVisible that can easily be called anywhere.
1431 */
1432 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1433 int configChanges) {
1434 ActivityRecord r = topRunningActivityLocked(null);
1435 if (r != null) {
1436 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1437 }
1438 }
Craig Mautner58547802013-03-05 08:23:53 -08001439
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001440 /**
1441 * Ensure that the top activity in the stack is resumed.
1442 *
1443 * @param prev The previously resumed activity, for when in the process
1444 * of pausing; can be null to call from elsewhere.
1445 *
1446 * @return Returns true if something is being resumed, or false if
1447 * nothing happened.
1448 */
1449 final boolean resumeTopActivityLocked(ActivityRecord prev) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001450 return resumeTopActivityLocked(prev, null);
1451 }
1452
1453 final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001454 // Find the first activity that is not finishing.
1455 ActivityRecord next = topRunningActivityLocked(null);
1456
1457 // Remember how we'll process this pause/resume situation, and ensure
1458 // that the state is reset however we wind up proceeding.
1459 final boolean userLeaving = mUserLeaving;
1460 mUserLeaving = false;
1461
1462 if (next == null) {
1463 // There are no more activities! Let's just start up the
1464 // Launcher...
1465 if (mMainStack) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001466 ActivityOptions.abort(options);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001467 return mService.startHomeActivityLocked(mCurrentUser);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001468 }
1469 }
1470
1471 next.delayedResume = false;
Craig Mautner58547802013-03-05 08:23:53 -08001472
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001473 // If the top activity is the resumed one, nothing to do.
1474 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1475 // Make sure we have executed any pending transitions, since there
1476 // should be nothing left to do at this point.
1477 mService.mWindowManager.executeAppTransition();
1478 mNoAnimActivities.clear();
Dianne Hackborn84375872012-06-01 19:03:50 -07001479 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001480 return false;
1481 }
1482
1483 // If we are sleeping, and there is no resumed activity, and the top
1484 // activity is paused, well that is the state we want.
1485 if ((mService.mSleeping || mService.mShuttingDown)
p13451dbad2872012-04-18 11:39:23 +09001486 && mLastPausedActivity == next
1487 && (next.state == ActivityState.PAUSED
1488 || next.state == ActivityState.STOPPED
1489 || next.state == ActivityState.STOPPING)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001490 // Make sure we have executed any pending transitions, since there
1491 // should be nothing left to do at this point.
1492 mService.mWindowManager.executeAppTransition();
1493 mNoAnimActivities.clear();
Dianne Hackborn84375872012-06-01 19:03:50 -07001494 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001495 return false;
1496 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001497
1498 // Make sure that the user who owns this activity is started. If not,
1499 // we will just leave it as is because someone should be bringing
1500 // another user's activities to the top of the stack.
1501 if (mService.mStartedUsers.get(next.userId) == null) {
1502 Slog.w(TAG, "Skipping resume of top activity " + next
1503 + ": user " + next.userId + " is stopped");
1504 return false;
1505 }
1506
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001507 // The activity may be waiting for stop, but that is no longer
1508 // appropriate for it.
1509 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001510 mGoingToSleepActivities.remove(next);
1511 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001512 mWaitingVisibleActivities.remove(next);
1513
Dianne Hackborn84375872012-06-01 19:03:50 -07001514 next.updateOptionsLocked(options);
1515
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001516 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1517
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001518 // If we are currently pausing an activity, then don't do anything
1519 // until that is done.
1520 if (mPausingActivity != null) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07001521 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(TAG,
1522 "Skip resume: pausing=" + mPausingActivity);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001523 return false;
1524 }
1525
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001526 // Okay we are now going to start a switch, to 'next'. We may first
1527 // have to pause the current activity, but this is an important point
1528 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001529 // XXX "App Redirected" dialog is getting too many false positives
1530 // at this point, so turn off for now.
1531 if (false) {
1532 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1533 long now = SystemClock.uptimeMillis();
1534 final boolean inTime = mLastStartedActivity.startTime != 0
1535 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1536 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1537 final int nextUid = next.info.applicationInfo.uid;
1538 if (inTime && lastUid != nextUid
1539 && lastUid != next.launchedFromUid
1540 && mService.checkPermission(
1541 android.Manifest.permission.STOP_APP_SWITCHES,
1542 -1, next.launchedFromUid)
1543 != PackageManager.PERMISSION_GRANTED) {
1544 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1545 } else {
1546 next.startTime = now;
1547 mLastStartedActivity = next;
1548 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001549 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001550 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001551 mLastStartedActivity = next;
1552 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001553 }
Craig Mautner58547802013-03-05 08:23:53 -08001554
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001555 // We need to start pausing the current activity so the top one
1556 // can be resumed...
1557 if (mResumedActivity != null) {
1558 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001559 // At this point we want to put the upcoming activity's process
1560 // at the top of the LRU list, since we know we will be needing it
1561 // very soon and it would be a waste to let it get killed if it
1562 // happens to be sitting towards the end.
1563 if (next.app != null && next.app.thread != null) {
1564 // No reason to do full oom adj update here; we'll let that
1565 // happen whenever it needs to later.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001566 mService.updateLruProcessLocked(next.app, false);
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001567 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001568 startPausingLocked(userLeaving, false);
1569 return true;
1570 }
1571
Christopher Tated3f175c2012-06-14 14:16:54 -07001572 // If the most recent activity was noHistory but was only stopped rather
1573 // than stopped+finished because the device went to sleep, we need to make
1574 // sure to finish it as we're making a new activity topmost.
1575 final ActivityRecord last = mLastPausedActivity;
1576 if (mService.mSleeping && last != null && !last.finishing) {
1577 if ((last.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
1578 || (last.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
1579 if (DEBUG_STATES) {
1580 Slog.d(TAG, "no-history finish of " + last + " on new resume");
1581 }
1582 requestFinishActivityLocked(last.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001583 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07001584 }
1585 }
1586
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001587 if (prev != null && prev != next) {
1588 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1589 prev.waitingVisible = true;
1590 mWaitingVisibleActivities.add(prev);
1591 if (DEBUG_SWITCH) Slog.v(
1592 TAG, "Resuming top, waiting visible to hide: " + prev);
1593 } else {
1594 // The next activity is already visible, so hide the previous
1595 // activity's windows right now so we can show the new one ASAP.
1596 // We only do this if the previous is finishing, which should mean
1597 // it is on top of the one being resumed so hiding it quickly
1598 // is good. Otherwise, we want to do the normal route of allowing
1599 // the resumed activity to be shown so we can decide if the
1600 // previous should actually be hidden depending on whether the
1601 // new one is found to be full-screen or not.
1602 if (prev.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001603 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001604 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1605 + prev + ", waitingVisible="
1606 + (prev != null ? prev.waitingVisible : null)
1607 + ", nowVisible=" + next.nowVisible);
1608 } else {
1609 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1610 + prev + ", waitingVisible="
1611 + (prev != null ? prev.waitingVisible : null)
1612 + ", nowVisible=" + next.nowVisible);
1613 }
1614 }
1615 }
1616
Dianne Hackborne7f97212011-02-24 14:40:20 -08001617 // Launching this app's activity, make sure the app is no longer
1618 // considered stopped.
1619 try {
1620 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001621 next.packageName, false, next.userId); /* TODO: Verify if correct userid */
Dianne Hackborne7f97212011-02-24 14:40:20 -08001622 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001623 } catch (IllegalArgumentException e) {
1624 Slog.w(TAG, "Failed trying to unstop package "
1625 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001626 }
1627
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001628 // We are starting up the next activity, so tell the window manager
1629 // that the previous one will be hidden soon. This way it can know
1630 // to ignore it when computing the desired screen orientation.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001631 boolean noAnim = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001632 if (prev != null) {
1633 if (prev.finishing) {
1634 if (DEBUG_TRANSITION) Slog.v(TAG,
1635 "Prepare close transition: prev=" + prev);
1636 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001637 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001638 AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001639 } else {
1640 mService.mWindowManager.prepareAppTransition(prev.task == next.task
Craig Mautner4b71aa12012-12-27 17:20:01 -08001641 ? AppTransition.TRANSIT_ACTIVITY_CLOSE
1642 : AppTransition.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001643 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001644 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1645 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001646 } else {
1647 if (DEBUG_TRANSITION) Slog.v(TAG,
1648 "Prepare open transition: prev=" + prev);
1649 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001650 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001651 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001652 AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001653 } else {
1654 mService.mWindowManager.prepareAppTransition(prev.task == next.task
Craig Mautner4b71aa12012-12-27 17:20:01 -08001655 ? AppTransition.TRANSIT_ACTIVITY_OPEN
1656 : AppTransition.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001657 }
1658 }
1659 if (false) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001660 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1661 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001662 }
Craig Mautner000f0022013-02-26 15:04:29 -08001663 } else if (numActivities() > 1) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001664 if (DEBUG_TRANSITION) Slog.v(TAG,
1665 "Prepare open transition: no previous");
1666 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001667 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001668 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001669 AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001670 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001671 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001672 AppTransition.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001673 }
1674 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001675 if (!noAnim) {
1676 next.applyOptionsLocked();
1677 } else {
1678 next.clearOptionsLocked();
1679 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001680
1681 if (next.app != null && next.app.thread != null) {
1682 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1683
1684 // This activity is now becoming visible.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001685 mService.mWindowManager.setAppVisibility(next.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001686
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001687 // schedule launch ticks to collect information about slow apps.
1688 next.startLaunchTickingLocked();
1689
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001690 ActivityRecord lastResumedActivity = mResumedActivity;
1691 ActivityState lastState = next.state;
1692
1693 mService.updateCpuStats();
Craig Mautner58547802013-03-05 08:23:53 -08001694
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001695 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001696 next.state = ActivityState.RESUMED;
1697 mResumedActivity = next;
1698 next.task.touchActiveTime();
Craig Mautnerd2328952013-03-05 12:46:26 -08001699 mService.addRecentTaskLocked(next.task);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001700 mService.updateLruProcessLocked(next.app, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001701 updateLRUListLocked(next);
1702
1703 // Have the window manager re-evaluate the orientation of
1704 // the screen based on the new activity order.
1705 boolean updated = false;
1706 if (mMainStack) {
1707 synchronized (mService) {
1708 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1709 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001710 next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001711 if (config != null) {
1712 next.frozenBeforeDestroy = true;
1713 }
Dianne Hackborn813075a62011-11-14 17:45:19 -08001714 updated = mService.updateConfigurationLocked(config, next, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001715 }
1716 }
1717 if (!updated) {
1718 // The configuration update wasn't able to keep the existing
1719 // instance of the activity, and instead started a new one.
1720 // We should be all done, but let's just make sure our activity
1721 // is still at the top and schedule another run if something
1722 // weird happened.
1723 ActivityRecord nextNext = topRunningActivityLocked(null);
1724 if (DEBUG_SWITCH) Slog.i(TAG,
1725 "Activity config changed during resume: " + next
1726 + ", new next: " + nextNext);
1727 if (nextNext != next) {
1728 // Do over!
1729 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1730 }
1731 if (mMainStack) {
1732 mService.setFocusedActivityLocked(next);
1733 }
1734 ensureActivitiesVisibleLocked(null, 0);
1735 mService.mWindowManager.executeAppTransition();
1736 mNoAnimActivities.clear();
1737 return true;
1738 }
Craig Mautner58547802013-03-05 08:23:53 -08001739
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001740 try {
1741 // Deliver all pending results.
Craig Mautner05d6272ba2013-02-11 09:39:27 -08001742 ArrayList<ResultInfo> a = next.results;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001743 if (a != null) {
1744 final int N = a.size();
1745 if (!next.finishing && N > 0) {
1746 if (DEBUG_RESULTS) Slog.v(
1747 TAG, "Delivering results to " + next
1748 + ": " + a);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001749 next.app.thread.scheduleSendResult(next.appToken, a);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001750 }
1751 }
1752
1753 if (next.newIntents != null) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001754 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001755 }
1756
1757 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001758 next.userId, System.identityHashCode(next),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001759 next.task.taskId, next.shortComponentName);
Craig Mautner58547802013-03-05 08:23:53 -08001760
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001761 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001762 showAskCompatModeDialogLocked(next);
Dianne Hackborn905577f2011-09-07 18:31:28 -07001763 next.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001764 next.app.thread.scheduleResumeActivity(next.appToken,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001765 mService.isNextTransitionForward());
Craig Mautner58547802013-03-05 08:23:53 -08001766
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001767 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001768
1769 } catch (Exception e) {
1770 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001771 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1772 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001773 next.state = lastState;
1774 mResumedActivity = lastResumedActivity;
1775 Slog.i(TAG, "Restarting because process died: " + next);
1776 if (!next.hasBeenLaunched) {
1777 next.hasBeenLaunched = true;
1778 } else {
1779 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1780 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001781 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001782 mService.compatibilityInfoForPackageLocked(
1783 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001784 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001785 next.labelRes, next.icon, next.windowFlags,
1786 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001787 }
1788 }
1789 startSpecificActivityLocked(next, true, false);
1790 return true;
1791 }
1792
1793 // From this point on, if something goes wrong there is no way
1794 // to recover the activity.
1795 try {
1796 next.visible = true;
1797 completeResumeLocked(next);
1798 } catch (Exception e) {
1799 // If any exception gets thrown, toss away this
1800 // activity and try the next one.
1801 Slog.w(TAG, "Exception thrown during resume of " + next, e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001802 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001803 "resume-exception", true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001804 return true;
1805 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001806 next.stopped = false;
1807
1808 } else {
1809 // Whoops, need to restart this activity!
1810 if (!next.hasBeenLaunched) {
1811 next.hasBeenLaunched = true;
1812 } else {
1813 if (SHOW_APP_STARTING_PREVIEW) {
1814 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001815 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001816 mService.compatibilityInfoForPackageLocked(
1817 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001818 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001819 next.labelRes, next.icon, next.windowFlags,
1820 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001821 }
1822 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1823 }
1824 startSpecificActivityLocked(next, true, true);
1825 }
1826
1827 return true;
1828 }
1829
Craig Mautner11bf9a52013-02-19 14:08:51 -08001830
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001831 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001832 boolean doResume, boolean keepCurTransition, Bundle options) {
Craig Mautner70a86932013-02-28 22:37:44 -08001833 TaskRecord task = null;
Craig Mautnerd2328952013-03-05 12:46:26 -08001834 TaskRecord rTask = r.task;
1835 final int taskId = rTask.taskId;
1836 if (taskForIdLocked(taskId) == null || newTask) {
Craig Mautner77878772013-03-04 19:46:24 -08001837 // Last activity in task had been removed or ActivityManagerService is reusing task.
1838 // Insert or replace.
Craig Mautner77878772013-03-04 19:46:24 -08001839 // Might not even be in.
Craig Mautnerd2328952013-03-05 12:46:26 -08001840 mTaskHistory.remove(rTask);
Craig Mautner77878772013-03-04 19:46:24 -08001841 // Now put task at top.
Craig Mautnerd2328952013-03-05 12:46:26 -08001842 mTaskHistory.add(rTask);
1843 mService.mWindowManager.moveTaskToTop(taskId);
Craig Mautner77878772013-03-04 19:46:24 -08001844 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001845 if (!newTask) {
1846 // If starting in an existing task, find where that is...
Craig Mautner70a86932013-02-28 22:37:44 -08001847 boolean startIt = true;
1848 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
1849 task = mTaskHistory.get(taskNdx);
1850 if (task == r.task) {
1851 // Here it is! Now, if this is not yet visible to the
1852 // user, then just add it without starting; it will
1853 // get started when the user navigates back to it.
Craig Mautner70a86932013-02-28 22:37:44 -08001854 if (!startIt) {
1855 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to task "
1856 + task, new RuntimeException("here").fillInStackTrace());
1857 task.addActivityToTop(r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001858 r.putInHistory();
Craig Mautner70a86932013-02-28 22:37:44 -08001859 mService.mWindowManager.addAppToken(task.mActivities.indexOf(r),
Craig Mautnerc00204b2013-03-05 15:02:14 -08001860 r.appToken, r.task.taskId, mStackId, r.info.screenOrientation,
1861 r.fullscreen,
Craig Mautner5962b122012-10-05 14:45:52 -07001862 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001863 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001864 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001865 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001866 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001867 return;
1868 }
1869 break;
Craig Mautner70a86932013-02-28 22:37:44 -08001870 } else if (task.numFullscreen > 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001871 startIt = false;
1872 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001873 }
1874 }
1875
1876 // Place a new activity at top of stack, so it is next to interact
1877 // with the user.
Craig Mautner70a86932013-02-28 22:37:44 -08001878
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001879 // If we are not placing the new activity frontmost, we do not want
1880 // to deliver the onUserLeaving callback to the actual frontmost
1881 // activity
Craig Mautner70a86932013-02-28 22:37:44 -08001882 if (task == r.task && mTaskHistory.indexOf(task) != (mTaskHistory.size() - 1)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001883 mUserLeaving = false;
Craig Mautner70a86932013-02-28 22:37:44 -08001884 if (DEBUG_USER_LEAVING) Slog.v(TAG,
1885 "startActivity() behind front, mUserLeaving=false");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001886 }
Craig Mautner70a86932013-02-28 22:37:44 -08001887
1888 task = r.task;
1889
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001890 // Slot the activity into the history stack and proceed
Craig Mautner70a86932013-02-28 22:37:44 -08001891 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to stack to task " + task,
Craig Mautner56f52db2013-02-25 10:03:01 -08001892 new RuntimeException("here").fillInStackTrace());
Craig Mautner70a86932013-02-28 22:37:44 -08001893 task.addActivityToTop(r);
1894
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001895 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001896 r.frontOfTask = newTask;
Craig Mautner70a86932013-02-28 22:37:44 -08001897 if (numActivities() > 1) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001898 // We want to show the starting preview window if we are
1899 // switching to a new task, or the next activity's process is
1900 // not currently running.
1901 boolean showStartingIcon = newTask;
1902 ProcessRecord proc = r.app;
1903 if (proc == null) {
1904 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1905 }
1906 if (proc == null || proc.thread == null) {
1907 showStartingIcon = true;
1908 }
1909 if (DEBUG_TRANSITION) Slog.v(TAG,
1910 "Prepare open transition: starting " + r);
1911 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001912 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001913 AppTransition.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001914 mNoAnimActivities.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001915 } else {
1916 mService.mWindowManager.prepareAppTransition(newTask
Craig Mautner4b71aa12012-12-27 17:20:01 -08001917 ? AppTransition.TRANSIT_TASK_OPEN
1918 : AppTransition.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001919 mNoAnimActivities.remove(r);
1920 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001921 r.updateOptionsLocked(options);
Craig Mautner70a86932013-02-28 22:37:44 -08001922 mService.mWindowManager.addAppToken(task.mActivities.indexOf(r),
Craig Mautnerc00204b2013-03-05 15:02:14 -08001923 r.appToken, r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,
Craig Mautner5962b122012-10-05 14:45:52 -07001924 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001925 boolean doShow = true;
1926 if (newTask) {
1927 // Even though this activity is starting fresh, we still need
1928 // to reset it to make sure we apply affinities to move any
1929 // existing activities from other tasks in to it.
1930 // If the caller has requested that the target task be
1931 // reset, then do so.
1932 if ((r.intent.getFlags()
1933 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1934 resetTaskIfNeededLocked(r, r);
1935 doShow = topRunningNonDelayedActivityLocked(null) == r;
1936 }
1937 }
1938 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1939 // Figure out if we are transitioning from another activity that is
1940 // "has the same starting icon" as the next one. This allows the
1941 // window manager to keep the previous window it had previously
1942 // created, if it still had one.
1943 ActivityRecord prev = mResumedActivity;
1944 if (prev != null) {
1945 // We don't want to reuse the previous starting preview if:
1946 // (1) The current activity is in a different task.
1947 if (prev.task != r.task) prev = null;
1948 // (2) The current activity is already displayed.
1949 else if (prev.nowVisible) prev = null;
1950 }
1951 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001952 r.appToken, r.packageName, r.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001953 mService.compatibilityInfoForPackageLocked(
1954 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001955 r.labelRes, r.icon, r.windowFlags,
1956 prev != null ? prev.appToken : null, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001957 }
1958 } else {
1959 // If this is the first activity, don't do any fancy animations,
1960 // because there is nothing for it to animate on top of.
Craig Mautner70a86932013-02-28 22:37:44 -08001961 mService.mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken,
Craig Mautnerc00204b2013-03-05 15:02:14 -08001962 r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,
Craig Mautner5962b122012-10-05 14:45:52 -07001963 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001964 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001965 }
1966 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001967 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001968 }
1969
1970 if (doResume) {
1971 resumeTopActivityLocked(null);
1972 }
1973 }
1974
Dianne Hackbornbe707852011-11-11 14:32:10 -08001975 final void validateAppTokensLocked() {
1976 mValidateAppTokens.clear();
Craig Mautner000f0022013-02-26 15:04:29 -08001977 mValidateAppTokens.ensureCapacity(numActivities());
1978 final int numTasks = mTaskHistory.size();
1979 for (int taskNdx = 0; taskNdx < numTasks; ++taskNdx) {
1980 TaskRecord task = mTaskHistory.get(taskNdx);
1981 final ArrayList<ActivityRecord> activities = task.mActivities;
1982 if (activities.size() == 0) {
1983 continue;
Craig Mautnerb1fd65c02013-02-05 13:34:57 -08001984 }
Craig Mautner000f0022013-02-26 15:04:29 -08001985 TaskGroup group = new TaskGroup();
1986 group.taskId = task.taskId;
1987 mValidateAppTokens.add(group);
1988 final int numActivities = activities.size();
1989 for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) {
1990 final ActivityRecord r = activities.get(activityNdx);
1991 group.tokens.add(r.appToken);
1992 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001993 }
1994 mService.mWindowManager.validateAppTokens(mValidateAppTokens);
1995 }
1996
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001997 /**
1998 * Perform a reset of the given task, if needed as part of launching it.
1999 * Returns the new HistoryRecord at the top of the task.
2000 */
Craig Mautnere3a74d52013-02-22 14:14:58 -08002001 /**
2002 * Helper method for #resetTaskIfNeededLocked.
2003 * We are inside of the task being reset... we'll either finish this activity, push it out
2004 * for another task, or leave it as-is.
2005 * @param task The task containing the Activity (taskTop) that might be reset.
2006 * @param forceReset
2007 * @return An ActivityOptions that needs to be processed.
2008 */
2009 private final ActivityOptions resetTargetTaskIfNeededLocked(TaskRecord task,
2010 boolean forceReset) {
2011 ActivityOptions topOptions = null;
2012
2013 int replyChainEnd = -1;
2014 boolean canMoveOptions = true;
2015
2016 // We only do this for activities that are not the root of the task (since if we finish
2017 // the root, we may no longer have the task!).
2018 final ArrayList<ActivityRecord> activities = task.mActivities;
2019 final int numActivities = activities.size();
2020 for (int i = numActivities - 1; i > 0; --i ) {
2021 ActivityRecord target = activities.get(i);
2022
2023 final int flags = target.info.flags;
2024 final boolean finishOnTaskLaunch =
2025 (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
2026 final boolean allowTaskReparenting =
2027 (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
2028 final boolean clearWhenTaskReset =
2029 (target.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
2030
2031 if (!finishOnTaskLaunch
2032 && !clearWhenTaskReset
2033 && target.resultTo != null) {
2034 // If this activity is sending a reply to a previous
2035 // activity, we can't do anything with it now until
2036 // we reach the start of the reply chain.
2037 // XXX note that we are assuming the result is always
2038 // to the previous activity, which is almost always
2039 // the case but we really shouldn't count on.
2040 if (replyChainEnd < 0) {
2041 replyChainEnd = i;
2042 }
2043 } else if (!finishOnTaskLaunch
2044 && !clearWhenTaskReset
2045 && allowTaskReparenting
2046 && target.taskAffinity != null
2047 && !target.taskAffinity.equals(task.affinity)) {
2048 // If this activity has an affinity for another
2049 // task, then we need to move it out of here. We will
2050 // move it as far out of the way as possible, to the
2051 // bottom of the activity stack. This also keeps it
2052 // correctly ordered with any activities we previously
2053 // moved.
2054 TaskRecord bottomTask = mTaskHistory.get(0);
2055 ActivityRecord p = bottomTask.mActivities.get(0);
2056 if (target.taskAffinity != null
2057 && target.taskAffinity.equals(p.task.affinity)) {
2058 // If the activity currently at the bottom has the
2059 // same task affinity as the one we are moving,
2060 // then merge it into the same task.
Craig Mautner0247fc82013-02-28 14:32:06 -08002061 setTask(target, p.task, p.thumbHolder, false);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002062 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2063 + " out to bottom task " + p.task);
2064 } else {
Craig Mautnerd2328952013-03-05 12:46:26 -08002065 setTask(target, createTaskRecord(mService.getNextTaskId(), target.info, null,
2066 false), null, false);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002067 target.task.affinityIntent = target.intent;
2068 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2069 + " out to new task " + target.task);
2070 }
2071
2072 final TaskRecord targetTask = target.task;
2073 final int targetTaskId = targetTask.taskId;
2074 mService.mWindowManager.setAppGroupId(target.appToken, targetTaskId);
2075
2076 ThumbnailHolder curThumbHolder = target.thumbHolder;
2077 boolean gotOptions = !canMoveOptions;
2078
2079 final int start = replyChainEnd < 0 ? i : replyChainEnd;
2080 for (int srcPos = start; srcPos >= i; --srcPos) {
2081 p = activities.get(srcPos);
2082 if (p.finishing) {
2083 continue;
2084 }
2085
2086 curThumbHolder = p.thumbHolder;
2087 canMoveOptions = false;
2088 if (!gotOptions && topOptions == null) {
2089 topOptions = p.takeOptionsLocked();
2090 if (topOptions != null) {
2091 gotOptions = true;
2092 }
2093 }
2094 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Removing activity " + p + " from task="
2095 + task + " adding to task=" + targetTask,
2096 new RuntimeException("here").fillInStackTrace());
2097 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
2098 + " out to target's task " + target.task);
Craig Mautner0247fc82013-02-28 14:32:06 -08002099 setTask(p, targetTask, curThumbHolder, false);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002100 targetTask.addActivityAtBottom(p);
Craig Mautner0247fc82013-02-28 14:32:06 -08002101
Craig Mautnere3a74d52013-02-22 14:14:58 -08002102 mService.mWindowManager.setAppGroupId(p.appToken, targetTaskId);
2103 }
2104
2105 mService.mWindowManager.moveTaskToBottom(targetTaskId);
2106 if (VALIDATE_TOKENS) {
2107 validateAppTokensLocked();
2108 }
2109
2110 replyChainEnd = -1;
2111 } else if (forceReset || finishOnTaskLaunch || clearWhenTaskReset) {
2112 // If the activity should just be removed -- either
2113 // because it asks for it, or the task should be
2114 // cleared -- then finish it and anything that is
2115 // part of its reply chain.
2116 int end;
2117 if (clearWhenTaskReset) {
2118 // In this case, we want to finish this activity
2119 // and everything above it, so be sneaky and pretend
2120 // like these are all in the reply chain.
2121 end = numActivities - 1;
2122 } else if (replyChainEnd < 0) {
2123 end = i;
2124 } else {
2125 end = replyChainEnd;
2126 }
2127 ActivityRecord p = null;
2128 boolean gotOptions = !canMoveOptions;
2129 for (int srcPos = i; srcPos <= end; srcPos++) {
2130 p = activities.get(srcPos);
2131 if (p.finishing) {
2132 continue;
2133 }
2134 canMoveOptions = false;
2135 if (!gotOptions && topOptions == null) {
2136 topOptions = p.takeOptionsLocked();
2137 if (topOptions != null) {
2138 gotOptions = true;
2139 }
2140 }
Craig Mautner58547802013-03-05 08:23:53 -08002141 if (DEBUG_TASKS) Slog.w(TAG,
2142 "resetTaskIntendedTask: calling finishActivity on " + p);
Craig Mautnerd44711d2013-02-23 11:24:36 -08002143 if (finishActivityLocked(p, Activity.RESULT_CANCELED, null, "reset", false)) {
Craig Mautnere3a74d52013-02-22 14:14:58 -08002144 end--;
2145 srcPos--;
2146 }
2147 }
2148 replyChainEnd = -1;
2149 } else {
2150 // If we were in the middle of a chain, well the
2151 // activity that started it all doesn't want anything
2152 // special, so leave it all as-is.
2153 replyChainEnd = -1;
2154 }
2155 }
2156
2157 return topOptions;
2158 }
2159
2160 /**
2161 * Helper method for #resetTaskIfNeededLocked. Processes all of the activities in a given
2162 * TaskRecord looking for an affinity with the task of resetTaskIfNeededLocked.taskTop.
2163 * @param affinityTask The task we are looking for an affinity to.
2164 * @param task Task that resetTaskIfNeededLocked.taskTop belongs to.
2165 * @param topTaskIsHigher True if #task has already been processed by resetTaskIfNeededLocked.
2166 * @param forceReset Flag passed in to resetTaskIfNeededLocked.
2167 */
Craig Mautner77878772013-03-04 19:46:24 -08002168 private final int resetAffinityTaskIfNeededLocked(TaskRecord affinityTask, TaskRecord task,
2169 boolean topTaskIsHigher, boolean forceReset, int taskInsertionPoint) {
Craig Mautnere3a74d52013-02-22 14:14:58 -08002170 int replyChainEnd = -1;
2171 final int taskId = task.taskId;
2172 final String taskAffinity = task.affinity;
2173
2174 final ArrayList<ActivityRecord> activities = affinityTask.mActivities;
2175 final int numActivities = activities.size();
2176 // Do not operate on the root Activity.
2177 for (int i = numActivities - 1; i > 0; --i) {
2178 ActivityRecord target = activities.get(i);
2179
2180 final int flags = target.info.flags;
2181 boolean finishOnTaskLaunch = (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
2182 boolean allowTaskReparenting = (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
2183
2184 if (target.resultTo != null) {
2185 // If this activity is sending a reply to a previous
2186 // activity, we can't do anything with it now until
2187 // we reach the start of the reply chain.
2188 // XXX note that we are assuming the result is always
2189 // to the previous activity, which is almost always
2190 // the case but we really shouldn't count on.
2191 if (replyChainEnd < 0) {
2192 replyChainEnd = i;
2193 }
2194 } else if (topTaskIsHigher
2195 && allowTaskReparenting
2196 && taskAffinity != null
2197 && taskAffinity.equals(target.taskAffinity)) {
2198 // This activity has an affinity for our task. Either remove it if we are
2199 // clearing or move it over to our task. Note that
2200 // we currently punt on the case where we are resetting a
2201 // task that is not at the top but who has activities above
2202 // with an affinity to it... this is really not a normal
2203 // case, and we will need to later pull that task to the front
2204 // and usually at that point we will do the reset and pick
2205 // up those remaining activities. (This only happens if
2206 // someone starts an activity in a new task from an activity
2207 // in a task that is not currently on top.)
2208 if (forceReset || finishOnTaskLaunch) {
2209 final int start = replyChainEnd >= 0 ? replyChainEnd : i;
2210 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index " + start + " to " + i);
2211 for (int srcPos = start; srcPos >= i; --srcPos) {
2212 final ActivityRecord p = activities.get(srcPos);
2213 if (p.finishing) {
2214 continue;
2215 }
Craig Mautnerd44711d2013-02-23 11:24:36 -08002216 finishActivityLocked(p, Activity.RESULT_CANCELED, null, "reset", false);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002217 }
2218 } else {
Craig Mautner77878772013-03-04 19:46:24 -08002219 if (taskInsertionPoint < 0) {
2220 taskInsertionPoint = task.mActivities.size();
Craig Mautnerd2328952013-03-05 12:46:26 -08002221
Craig Mautner77878772013-03-04 19:46:24 -08002222 }
Craig Mautner77878772013-03-04 19:46:24 -08002223
2224 final int start = replyChainEnd >= 0 ? replyChainEnd : i;
2225 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting from task=" + affinityTask + ":"
2226 + start + "-" + i + " to task=" + task + ":" + taskInsertionPoint);
2227 for (int srcPos = start; srcPos >= i; --srcPos) {
Craig Mautnere3a74d52013-02-22 14:14:58 -08002228 final ActivityRecord p = activities.get(srcPos);
Craig Mautner0247fc82013-02-28 14:32:06 -08002229 setTask(p, task, null, false);
Craig Mautner77878772013-03-04 19:46:24 -08002230 task.addActivityAtIndex(taskInsertionPoint, p);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002231
Craig Mautnere3a74d52013-02-22 14:14:58 -08002232 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Removing and adding activity " + p
2233 + " to stack at " + task,
2234 new RuntimeException("here").fillInStackTrace());
2235 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p + " from " + srcPos
2236 + " in to resetting task " + task);
2237 mService.mWindowManager.setAppGroupId(p.appToken, taskId);
2238 }
2239 mService.mWindowManager.moveTaskToTop(taskId);
Craig Mautner9658b312013-02-28 10:55:59 -08002240 if (VALIDATE_TOKENS) {
2241 validateAppTokensLocked();
2242 }
Craig Mautnere3a74d52013-02-22 14:14:58 -08002243
2244 // Now we've moved it in to place... but what if this is
2245 // a singleTop activity and we have put it on top of another
2246 // instance of the same activity? Then we drop the instance
2247 // below so it remains singleTop.
2248 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2249 ArrayList<ActivityRecord> taskActivities = task.mActivities;
2250 boolean found = false;
2251 int targetNdx = taskActivities.indexOf(target);
2252 if (targetNdx > 0) {
2253 ActivityRecord p = taskActivities.get(targetNdx - 1);
2254 if (p.intent.getComponent().equals(target.intent.getComponent())) {
Craig Mautner58547802013-03-05 08:23:53 -08002255 finishActivityLocked(p, Activity.RESULT_CANCELED, null, "replace",
2256 false);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002257 }
2258 }
2259 }
2260 }
2261
2262 replyChainEnd = -1;
2263 }
2264 }
Craig Mautner77878772013-03-04 19:46:24 -08002265 return taskInsertionPoint;
Craig Mautnere3a74d52013-02-22 14:14:58 -08002266 }
2267
2268 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
2269 ActivityRecord newActivity) {
2270 boolean forceReset =
2271 (newActivity.info.flags & ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
2272 if (ACTIVITY_INACTIVE_RESET_TIME > 0
2273 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
2274 if ((newActivity.info.flags & ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
2275 forceReset = true;
2276 }
2277 }
2278
2279 final TaskRecord task = taskTop.task;
2280
2281 /** False until we evaluate the TaskRecord associated with taskTop. Switches to true
2282 * for remaining tasks. Used for later tasks to reparent to task. */
2283 boolean taskFound = false;
2284
2285 /** If ActivityOptions are moved out and need to be aborted or moved to taskTop. */
2286 ActivityOptions topOptions = null;
2287
Craig Mautner77878772013-03-04 19:46:24 -08002288 // Preserve the location for reparenting in the new task.
2289 int reparentInsertionPoint = -1;
2290
Craig Mautnere3a74d52013-02-22 14:14:58 -08002291 for (int i = mTaskHistory.size() - 1; i >= 0; --i) {
2292 final TaskRecord targetTask = mTaskHistory.get(i);
2293
2294 if (targetTask == task) {
2295 topOptions = resetTargetTaskIfNeededLocked(task, forceReset);
2296 taskFound = true;
2297 } else {
Craig Mautner77878772013-03-04 19:46:24 -08002298 reparentInsertionPoint = resetAffinityTaskIfNeededLocked(targetTask, task,
2299 taskFound, forceReset, reparentInsertionPoint);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002300 }
2301 }
2302
Craig Mautner70a86932013-02-28 22:37:44 -08002303 int taskNdx = mTaskHistory.indexOf(task);
2304 do {
2305 taskTop = mTaskHistory.get(taskNdx--).getTopActivity();
2306 } while (taskTop == null && taskNdx >= 0);
2307
Craig Mautnere3a74d52013-02-22 14:14:58 -08002308 if (topOptions != null) {
2309 // If we got some ActivityOptions from an activity on top that
2310 // was removed from the task, propagate them to the new real top.
2311 if (taskTop != null) {
Craig Mautnere3a74d52013-02-22 14:14:58 -08002312 taskTop.updateOptionsLocked(topOptions);
2313 } else {
Craig Mautnere3a74d52013-02-22 14:14:58 -08002314 topOptions.abort();
2315 }
2316 }
2317
2318 return taskTop;
2319 }
2320
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002321 /**
2322 * Perform clear operation as requested by
2323 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2324 * stack to the given task, then look for
2325 * an instance of that activity in the stack and, if found, finish all
2326 * activities on top of it and return the instance.
2327 *
2328 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002329 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002330 * or null if none was found.
2331 */
Craig Mautner16030772013-02-26 16:05:47 -08002332 private final ActivityRecord performClearTaskLocked(TaskRecord task,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002333 ActivityRecord newR, int launchFlags) {
Craig Mautner16030772013-02-26 16:05:47 -08002334
2335 final ArrayList<ActivityRecord> activities = task.mActivities;
2336 int numActivities = activities.size();
2337 for (int activityNdx = numActivities - 1; activityNdx >= 0; --activityNdx) {
2338 ActivityRecord r = activities.get(activityNdx);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002339 if (r.finishing) {
2340 continue;
2341 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002342 if (r.realActivity.equals(newR.realActivity)) {
2343 // Here it is! Now finish everything in front...
2344 ActivityRecord ret = r;
Craig Mautner16030772013-02-26 16:05:47 -08002345
2346 for (++activityNdx; activityNdx < numActivities; ++activityNdx) {
2347 r = activities.get(activityNdx);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002348 if (r.finishing) {
2349 continue;
2350 }
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002351 ActivityOptions opts = r.takeOptionsLocked();
2352 if (opts != null) {
2353 ret.updateOptionsLocked(opts);
2354 }
Craig Mautner16030772013-02-26 16:05:47 -08002355 if (finishActivityLocked(r, Activity.RESULT_CANCELED, null, "clear", false)) {
Craig Mautner9658b312013-02-28 10:55:59 -08002356 --activityNdx;
Craig Mautner16030772013-02-26 16:05:47 -08002357 --numActivities;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002358 }
2359 }
Craig Mautner16030772013-02-26 16:05:47 -08002360
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002361 // Finally, if this is a normal launch mode (that is, not
2362 // expecting onNewIntent()), then we will finish the current
2363 // instance of the activity so a new fresh one can be started.
2364 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
Craig Mautner16030772013-02-26 16:05:47 -08002365 && (launchFlags & Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002366 if (!ret.finishing) {
Craig Mautner16030772013-02-26 16:05:47 -08002367 if (activities.contains(ret)) {
Craig Mautnerd44711d2013-02-23 11:24:36 -08002368 finishActivityLocked(ret, Activity.RESULT_CANCELED, null,
2369 "clear", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002370 }
2371 return null;
2372 }
2373 }
Craig Mautner16030772013-02-26 16:05:47 -08002374
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002375 return ret;
2376 }
2377 }
2378
2379 return null;
2380 }
2381
2382 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002383 * Completely remove all activities associated with an existing
2384 * task starting at a specified index.
2385 */
Craig Mautner16030772013-02-26 16:05:47 -08002386 private final void performClearTaskAtIndexLocked(TaskRecord task, int activityNdx) {
2387 final ArrayList<ActivityRecord> activities = task.mActivities;
2388 int numActivities = activities.size();
2389 for ( ; activityNdx < numActivities; ++activityNdx) {
2390 final ActivityRecord r = activities.get(activityNdx);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002391 if (r.finishing) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002392 continue;
2393 }
Craig Mautner16030772013-02-26 16:05:47 -08002394 if (finishActivityLocked(r, Activity.RESULT_CANCELED, null, "clear", false)) {
2395 --activityNdx;
2396 --numActivities;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002397 }
2398 }
2399 }
2400
2401 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002402 * Completely remove all activities associated with an existing task.
2403 */
Craig Mautner16030772013-02-26 16:05:47 -08002404 private final void performClearTaskLocked(TaskRecord task) {
2405 performClearTaskAtIndexLocked(task, 0);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002406 }
2407
2408 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002409 * Find the activity in the history stack within the given task. Returns
2410 * the index within the history at which it's found, or < 0 if not found.
2411 */
Craig Mautner56f52db2013-02-25 10:03:01 -08002412 private final ActivityRecord findActivityInHistoryLocked(ActivityRecord r, TaskRecord task) {
2413 final ComponentName realActivity = r.realActivity;
2414 ArrayList<ActivityRecord> activities = task.mActivities;
2415 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2416 ActivityRecord candidate = activities.get(activityNdx);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07002417 if (candidate.finishing) {
2418 continue;
2419 }
Craig Mautner56f52db2013-02-25 10:03:01 -08002420 if (candidate.realActivity.equals(realActivity)) {
2421 return candidate;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002422 }
2423 }
Craig Mautner56f52db2013-02-25 10:03:01 -08002424 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002425 }
2426
2427 /**
2428 * Reorder the history stack so that the activity at the given index is
2429 * brought to the front.
2430 */
Craig Mautner56f52db2013-02-25 10:03:01 -08002431 private final void moveActivityToFrontLocked(ActivityRecord newTop) {
2432 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Removing and adding activity " + newTop
2433 + " to stack at top", new RuntimeException("here").fillInStackTrace());
2434
2435 final TaskRecord task = newTop.task;
2436 task.getTopActivity().frontOfTask = false;
2437 task.mActivities.remove(newTop);
2438 task.mActivities.add(newTop);
2439 newTop.frontOfTask = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002440 }
2441
2442 final int startActivityLocked(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002443 Intent intent, String resolvedType, ActivityInfo aInfo, IBinder resultTo,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002444 String resultWho, int requestCode,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002445 int callingPid, int callingUid, String callingPackage, int startFlags, Bundle options,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002446 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackborna4972e92012-03-14 10:38:05 -07002447 int err = ActivityManager.START_SUCCESS;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002448
2449 ProcessRecord callerApp = null;
2450 if (caller != null) {
2451 callerApp = mService.getRecordForAppLocked(caller);
2452 if (callerApp != null) {
2453 callingPid = callerApp.pid;
2454 callingUid = callerApp.info.uid;
2455 } else {
2456 Slog.w(TAG, "Unable to find app for caller " + caller
2457 + " (pid=" + callingPid + ") when starting: "
2458 + intent.toString());
Dianne Hackborna4972e92012-03-14 10:38:05 -07002459 err = ActivityManager.START_PERMISSION_DENIED;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002460 }
2461 }
2462
Dianne Hackborna4972e92012-03-14 10:38:05 -07002463 if (err == ActivityManager.START_SUCCESS) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002464 final int userId = aInfo != null ? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0;
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07002465 Slog.i(TAG, "START u" + userId + " {" + intent.toShortString(true, true, true, false)
2466 + "} from pid " + (callerApp != null ? callerApp.pid : callingPid));
Dianne Hackbornefb58102010-10-14 16:47:34 -07002467 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002468
2469 ActivityRecord sourceRecord = null;
2470 ActivityRecord resultRecord = null;
2471 if (resultTo != null) {
Craig Mautner56f52db2013-02-25 10:03:01 -08002472 sourceRecord = isInStackLocked(resultTo);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002473 if (DEBUG_RESULTS) Slog.v(
Craig Mautner56f52db2013-02-25 10:03:01 -08002474 TAG, "Will send result to " + resultTo + " " + sourceRecord);
2475 if (sourceRecord != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002476 if (requestCode >= 0 && !sourceRecord.finishing) {
2477 resultRecord = sourceRecord;
2478 }
2479 }
2480 }
2481
2482 int launchFlags = intent.getFlags();
2483
2484 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2485 && sourceRecord != null) {
2486 // Transfer the result target from the source activity to the new
2487 // one being started, including any failures.
2488 if (requestCode >= 0) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002489 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002490 return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002491 }
2492 resultRecord = sourceRecord.resultTo;
2493 resultWho = sourceRecord.resultWho;
2494 requestCode = sourceRecord.requestCode;
2495 sourceRecord.resultTo = null;
2496 if (resultRecord != null) {
2497 resultRecord.removeResultsLocked(
2498 sourceRecord, resultWho, requestCode);
2499 }
2500 }
2501
Dianne Hackborna4972e92012-03-14 10:38:05 -07002502 if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002503 // We couldn't find a class that can handle the given Intent.
2504 // That's the end of that!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002505 err = ActivityManager.START_INTENT_NOT_RESOLVED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002506 }
2507
Dianne Hackborna4972e92012-03-14 10:38:05 -07002508 if (err == ActivityManager.START_SUCCESS && aInfo == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002509 // We couldn't find the specific class specified in the Intent.
2510 // Also the end of the line.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002511 err = ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002512 }
2513
Dianne Hackborna4972e92012-03-14 10:38:05 -07002514 if (err != ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002515 if (resultRecord != null) {
2516 sendActivityResultLocked(-1,
2517 resultRecord, resultWho, requestCode,
2518 Activity.RESULT_CANCELED, null);
2519 }
Craig Mautner27084302013-03-25 08:05:25 -07002520 mStackSupervisor.setDismissKeyguard(false);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002521 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002522 return err;
2523 }
2524
Jeff Sharkey35be7562012-04-18 19:16:15 -07002525 final int startAnyPerm = mService.checkPermission(
2526 START_ANY_ACTIVITY, callingPid, callingUid);
2527 final int componentPerm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002528 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Jeff Sharkey35be7562012-04-18 19:16:15 -07002529 if (startAnyPerm != PERMISSION_GRANTED && componentPerm != PERMISSION_GRANTED) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002530 if (resultRecord != null) {
2531 sendActivityResultLocked(-1,
2532 resultRecord, resultWho, requestCode,
2533 Activity.RESULT_CANCELED, null);
2534 }
Craig Mautner27084302013-03-25 08:05:25 -07002535 mStackSupervisor.setDismissKeyguard(false);
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002536 String msg;
2537 if (!aInfo.exported) {
2538 msg = "Permission Denial: starting " + intent.toString()
2539 + " from " + callerApp + " (pid=" + callingPid
2540 + ", uid=" + callingUid + ")"
2541 + " not exported from uid " + aInfo.applicationInfo.uid;
2542 } else {
2543 msg = "Permission Denial: starting " + intent.toString()
2544 + " from " + callerApp + " (pid=" + callingPid
2545 + ", uid=" + callingUid + ")"
2546 + " requires " + aInfo.permission;
2547 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002548 Slog.w(TAG, msg);
2549 throw new SecurityException(msg);
2550 }
2551
2552 if (mMainStack) {
2553 if (mService.mController != null) {
2554 boolean abort = false;
2555 try {
2556 // The Intent we give to the watcher has the extra data
2557 // stripped off, since it can contain private information.
2558 Intent watchIntent = intent.cloneFilter();
2559 abort = !mService.mController.activityStarting(watchIntent,
2560 aInfo.applicationInfo.packageName);
2561 } catch (RemoteException e) {
2562 mService.mController = null;
2563 }
Craig Mautnerd2328952013-03-05 12:46:26 -08002564
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002565 if (abort) {
2566 if (resultRecord != null) {
2567 sendActivityResultLocked(-1,
2568 resultRecord, resultWho, requestCode,
2569 Activity.RESULT_CANCELED, null);
2570 }
2571 // We pretend to the caller that it was really started, but
2572 // they will just get a cancel result.
Craig Mautner27084302013-03-25 08:05:25 -07002573 mStackSupervisor.setDismissKeyguard(false);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002574 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002575 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002576 }
2577 }
2578 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002579
Craig Mautnerd2328952013-03-05 12:46:26 -08002580 ActivityRecord r = new ActivityRecord(mService, callerApp, callingUid, callingPackage,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002581 intent, resolvedType, aInfo, mService.mConfiguration,
2582 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002583 if (outActivity != null) {
2584 outActivity[0] = r;
2585 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002586
2587 if (mMainStack) {
2588 if (mResumedActivity == null
2589 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2590 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
Craig Mautner64f2b172013-03-11 11:40:31 -07002591 PendingActivityLaunch pal =
2592 new PendingActivityLaunch(r, sourceRecord, startFlags, this);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002593 mService.mPendingActivityLaunches.add(pal);
Craig Mautner27084302013-03-25 08:05:25 -07002594 mStackSupervisor.setDismissKeyguard(false);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002595 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002596 return ActivityManager.START_SWITCHES_CANCELED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002597 }
2598 }
Craig Mautnerd2328952013-03-05 12:46:26 -08002599
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002600 if (mService.mDidAppSwitch) {
2601 // This is the second allowed switch since we stopped switches,
2602 // so now just generally allow switches. Use case: user presses
2603 // home (switches disabled, switch to home, mDidAppSwitch now true);
2604 // user taps a home icon (coming from home so allowed, we hit here
2605 // and now allow anyone to switch again).
2606 mService.mAppSwitchesAllowedTime = 0;
2607 } else {
2608 mService.mDidAppSwitch = true;
2609 }
Craig Mautnerd2328952013-03-05 12:46:26 -08002610
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002611 mService.doPendingActivityLaunchesLocked(false);
2612 }
Craig Mautnerd2328952013-03-05 12:46:26 -08002613
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002614 err = startActivityUncheckedLocked(r, sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002615 startFlags, true, options);
Craig Mautner27084302013-03-25 08:05:25 -07002616 if (mPausingActivity == null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002617 // Someone asked to have the keyguard dismissed on the next
2618 // activity start, but we are not actually doing an activity
2619 // switch... just dismiss the keyguard now, because we
2620 // probably want to see whatever is behind it.
Craig Mautner27084302013-03-25 08:05:25 -07002621 mStackSupervisor.dismissKeyguard();
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002622 }
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 }
Craig Mautner27084302013-03-25 08:05:25 -07003081
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003082 mConfigWillChange = config != null
3083 && mService.mConfiguration.diff(config) != 0;
3084 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3085 "Starting activity when config will change = " + mConfigWillChange);
Craig Mautner27084302013-03-25 08:05:25 -07003086
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003087 final long origId = Binder.clearCallingIdentity();
Craig Mautner27084302013-03-25 08:05:25 -07003088
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003089 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 }
Craig Mautner27084302013-03-25 08:05:25 -07003112
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003113 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);
Craig Mautner27084302013-03-25 08:05:25 -07003118
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003119 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 }
Craig Mautner27084302013-03-25 08:05:25 -07003158
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003159 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);
Craig Mautner27084302013-03-25 08:05:25 -07003162
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003163 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 }
Craig Mautner27084302013-03-25 08:05:25 -07003175
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003176 Binder.restoreCallingIdentity(origId);
Craig Mautner27084302013-03-25 08:05:25 -07003177
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003178 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 }
Craig Mautner27084302013-03-25 08:05:25 -07003207
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003208 return res;
3209 }
3210 }
Craig Mautner27084302013-03-25 08:05:25 -07003211
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();
Craig Mautner27084302013-03-25 08:05:25 -07003316 mStackSupervisor.dismissKeyguard();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003317 }
3318
3319 void sendActivityResultLocked(int callingUid, ActivityRecord r,
3320 String resultWho, int requestCode, int resultCode, Intent data) {
3321
3322 if (callingUid > 0) {
3323 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003324 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003325 }
3326
3327 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3328 + " : who=" + resultWho + " req=" + requestCode
3329 + " res=" + resultCode + " data=" + data);
3330 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3331 try {
3332 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3333 list.add(new ResultInfo(resultWho, requestCode,
3334 resultCode, data));
Dianne Hackbornbe707852011-11-11 14:32:10 -08003335 r.app.thread.scheduleSendResult(r.appToken, list);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003336 return;
3337 } catch (Exception e) {
3338 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3339 }
3340 }
3341
3342 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3343 }
3344
3345 private final void stopActivityLocked(ActivityRecord r) {
3346 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3347 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3348 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3349 if (!r.finishing) {
Christopher Tated3f175c2012-06-14 14:16:54 -07003350 if (!mService.mSleeping) {
3351 if (DEBUG_STATES) {
3352 Slog.d(TAG, "no-history finish of " + r);
3353 }
3354 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003355 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07003356 } else {
3357 if (DEBUG_STATES) Slog.d(TAG, "Not finishing noHistory " + r
3358 + " on stop because we're just sleeping");
3359 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003360 }
Christopher Tate5007ddd2012-06-12 13:08:18 -07003361 }
3362
3363 if (r.app != null && r.app.thread != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003364 if (mMainStack) {
3365 if (mService.mFocusedActivity == r) {
3366 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3367 }
3368 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003369 r.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003370 try {
3371 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003372 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3373 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003374 r.state = ActivityState.STOPPING;
3375 if (DEBUG_VISBILITY) Slog.v(
3376 TAG, "Stopping visible=" + r.visible + " for " + r);
3377 if (!r.visible) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003378 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003379 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003380 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003381 if (mService.isSleeping()) {
3382 r.setSleeping(true);
3383 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003384 Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG);
3385 msg.obj = r;
3386 mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003387 } catch (Exception e) {
3388 // Maybe just ignore exceptions here... if the process
3389 // has crashed, our death notification will clean things
3390 // up.
3391 Slog.w(TAG, "Exception thrown during pause", e);
3392 // Just in case, assume it to be stopped.
3393 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003394 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003395 r.state = ActivityState.STOPPED;
3396 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003397 destroyActivityLocked(r, true, false, "stop-except");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003398 }
3399 }
3400 }
3401 }
3402
3403 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3404 boolean remove) {
3405 int N = mStoppingActivities.size();
3406 if (N <= 0) return null;
3407
3408 ArrayList<ActivityRecord> stops = null;
3409
3410 final boolean nowVisible = mResumedActivity != null
3411 && mResumedActivity.nowVisible
3412 && !mResumedActivity.waitingVisible;
3413 for (int i=0; i<N; i++) {
3414 ActivityRecord s = mStoppingActivities.get(i);
3415 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3416 + nowVisible + " waitingVisible=" + s.waitingVisible
3417 + " finishing=" + s.finishing);
3418 if (s.waitingVisible && nowVisible) {
3419 mWaitingVisibleActivities.remove(s);
3420 s.waitingVisible = false;
3421 if (s.finishing) {
3422 // If this activity is finishing, it is sitting on top of
3423 // everyone else but we now know it is no longer needed...
3424 // so get rid of it. Otherwise, we need to go through the
3425 // normal flow and hide it once we determine that it is
3426 // hidden by the activities in front of it.
3427 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003428 mService.mWindowManager.setAppVisibility(s.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003429 }
3430 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003431 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003432 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3433 if (stops == null) {
3434 stops = new ArrayList<ActivityRecord>();
3435 }
3436 stops.add(s);
3437 mStoppingActivities.remove(i);
3438 N--;
3439 i--;
3440 }
3441 }
3442
3443 return stops;
3444 }
3445
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003446 final void scheduleIdleLocked() {
3447 Message msg = Message.obtain();
3448 msg.what = IDLE_NOW_MSG;
3449 mHandler.sendMessage(msg);
3450 }
3451
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003452 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003453 Configuration config) {
3454 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3455
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003456 ActivityRecord res = null;
3457
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003458 ArrayList<ActivityRecord> stops = null;
3459 ArrayList<ActivityRecord> finishes = null;
3460 ArrayList<ActivityRecord> thumbnails = null;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003461 ArrayList<UserStartedState> startingUsers = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003462 int NS = 0;
3463 int NF = 0;
3464 int NT = 0;
3465 IApplicationThread sendThumbnail = null;
3466 boolean booting = false;
3467 boolean enableScreen = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003468 boolean activityRemoved = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003469
3470 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003471 ActivityRecord r = ActivityRecord.forToken(token);
3472 if (r != null) {
3473 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003474 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003475 }
3476
3477 // Get the activity record.
Craig Mautnerd44711d2013-02-23 11:24:36 -08003478 if (isInStackLocked(token) != null) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003479 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003480
3481 if (fromTimeout) {
3482 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3483 }
3484
3485 // This is a hack to semi-deal with a race condition
3486 // in the client where it can be constructed with a
3487 // newer configuration from when we asked it to launch.
3488 // We'll update with whatever configuration it now says
3489 // it used to launch.
3490 if (config != null) {
3491 r.configuration = config;
3492 }
3493
3494 // No longer need to keep the device awake.
3495 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3496 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3497 mLaunchingActivity.release();
3498 }
3499
3500 // We are now idle. If someone is waiting for a thumbnail from
3501 // us, we can now deliver.
3502 r.idle = true;
3503 mService.scheduleAppGcsLocked();
3504 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3505 sendThumbnail = r.app.thread;
3506 r.thumbnailNeeded = false;
3507 }
3508
3509 // If this activity is fullscreen, set up to hide those under it.
3510
3511 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3512 ensureActivitiesVisibleLocked(null, 0);
3513
3514 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3515 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003516 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003517 mService.mBooted = true;
3518 enableScreen = true;
3519 }
3520 }
3521
3522 } else if (fromTimeout) {
3523 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3524 }
3525
3526 // Atomically retrieve all of the other things to do.
3527 stops = processStoppingActivitiesLocked(true);
3528 NS = stops != null ? stops.size() : 0;
3529 if ((NF=mFinishingActivities.size()) > 0) {
3530 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3531 mFinishingActivities.clear();
3532 }
Craig Mautnercae015f2013-02-08 14:31:27 -08003533 if ((NT=mCancelledThumbnails.size()) > 0) {
3534 thumbnails = new ArrayList<ActivityRecord>(mCancelledThumbnails);
3535 mCancelledThumbnails.clear();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003536 }
3537
3538 if (mMainStack) {
3539 booting = mService.mBooting;
3540 mService.mBooting = false;
3541 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003542 if (mStartingUsers.size() > 0) {
3543 startingUsers = new ArrayList<UserStartedState>(mStartingUsers);
3544 mStartingUsers.clear();
3545 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003546 }
3547
3548 int i;
3549
3550 // Send thumbnail if requested.
3551 if (sendThumbnail != null) {
3552 try {
3553 sendThumbnail.requestThumbnail(token);
3554 } catch (Exception e) {
3555 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3556 mService.sendPendingThumbnail(null, token, null, null, true);
3557 }
3558 }
3559
3560 // Stop any activities that are scheduled to do so but have been
3561 // waiting for the next one to start.
3562 for (i=0; i<NS; i++) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003563 ActivityRecord r = stops.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003564 synchronized (mService) {
3565 if (r.finishing) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003566 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003567 } else {
3568 stopActivityLocked(r);
3569 }
3570 }
3571 }
3572
3573 // Finish any activities that are scheduled to do so but have been
3574 // waiting for the next one to start.
3575 for (i=0; i<NF; i++) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003576 ActivityRecord r = finishes.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003577 synchronized (mService) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003578 activityRemoved = destroyActivityLocked(r, true, false, "finish-idle");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003579 }
3580 }
3581
3582 // Report back to any thumbnail receivers.
3583 for (i=0; i<NT; i++) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003584 ActivityRecord r = thumbnails.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003585 mService.sendPendingThumbnail(r, null, null, null, true);
3586 }
3587
3588 if (booting) {
3589 mService.finishBooting();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003590 } else if (startingUsers != null) {
3591 for (i=0; i<startingUsers.size(); i++) {
3592 mService.finishUserSwitch(startingUsers.get(i));
3593 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003594 }
3595
3596 mService.trimApplications();
3597 //dump();
3598 //mWindowManager.dump();
3599
3600 if (enableScreen) {
3601 mService.enableScreenAfterBoot();
3602 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003603
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003604 if (activityRemoved) {
3605 resumeTopActivityLocked(null);
3606 }
3607
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003608 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003609 }
3610
3611 /**
3612 * @return Returns true if the activity is being finished, false if for
3613 * some reason it is being left as-is.
3614 */
3615 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003616 Intent resultData, String reason, boolean oomAdj) {
Craig Mautnerd74f7d72013-02-26 13:41:02 -08003617 ActivityRecord r = isInStackLocked(token);
Christopher Tated3f175c2012-06-14 14:16:54 -07003618 if (DEBUG_RESULTS || DEBUG_STATES) Slog.v(
Craig Mautnerd74f7d72013-02-26 13:41:02 -08003619 TAG, "Finishing activity token=" + token + " r="
Christopher Tated3f175c2012-06-14 14:16:54 -07003620 + ", result=" + resultCode + ", data=" + resultData
3621 + ", reason=" + reason);
Craig Mautnerd74f7d72013-02-26 13:41:02 -08003622 if (r == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003623 return false;
3624 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003625
Craig Mautnerd44711d2013-02-23 11:24:36 -08003626 finishActivityLocked(r, resultCode, resultData, reason, oomAdj);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003627 return true;
3628 }
3629
Craig Mautnerd2328952013-03-05 12:46:26 -08003630 final void finishSubActivityLocked(ActivityRecord self, String resultWho, int requestCode) {
Craig Mautner9658b312013-02-28 10:55:59 -08003631 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3632 ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3633 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3634 ActivityRecord r = activities.get(activityNdx);
3635 if (r.resultTo == self && r.requestCode == requestCode) {
3636 if ((r.resultWho == null && resultWho == null) ||
3637 (r.resultWho != null && r.resultWho.equals(resultWho))) {
3638 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "request-sub",
3639 false);
3640 }
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003641 }
3642 }
3643 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003644 mService.updateOomAdjLocked();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003645 }
3646
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003647 final void finishTopRunningActivityLocked(ProcessRecord app) {
3648 ActivityRecord r = topRunningActivityLocked(null);
3649 if (r != null && r.app == app) {
3650 // If the top running activity is from this crashing
3651 // process, then terminate it to avoid getting in a loop.
3652 Slog.w(TAG, " Force finishing activity "
3653 + r.intent.getComponent().flattenToShortString());
Craig Mautner9658b312013-02-28 10:55:59 -08003654 int taskNdx = mTaskHistory.indexOf(r.task);
3655 int activityNdx = r.task.mActivities.indexOf(r);
Craig Mautnerd2328952013-03-05 12:46:26 -08003656 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003657 // Also terminate any activities below it that aren't yet
3658 // stopped, to avoid a situation where one will get
3659 // re-start our crashing activity once it gets resumed again.
Craig Mautner9658b312013-02-28 10:55:59 -08003660 --activityNdx;
3661 if (activityNdx < 0) {
3662 do {
3663 --taskNdx;
3664 if (taskNdx < 0) {
3665 break;
3666 }
3667 activityNdx = mTaskHistory.get(taskNdx).mActivities.size() - 1;
3668 } while (activityNdx < 0);
3669 }
3670 if (activityNdx >= 0) {
3671 r = mTaskHistory.get(taskNdx).mActivities.get(activityNdx);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003672 if (r.state == ActivityState.RESUMED
3673 || r.state == ActivityState.PAUSING
3674 || r.state == ActivityState.PAUSED) {
3675 if (!r.isHomeActivity || mService.mHomeProcess != r.app) {
3676 Slog.w(TAG, " Force finishing activity "
3677 + r.intent.getComponent().flattenToShortString());
Craig Mautnerd2328952013-03-05 12:46:26 -08003678 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003679 }
3680 }
3681 }
3682 }
3683 }
3684
Craig Mautnerd2328952013-03-05 12:46:26 -08003685 final boolean finishActivityAffinityLocked(ActivityRecord r) {
Craig Mautnerd74f7d72013-02-26 13:41:02 -08003686 ArrayList<ActivityRecord> activities = r.task.mActivities;
3687 for (int index = activities.indexOf(r); index >= 0; --index) {
3688 ActivityRecord cur = activities.get(index);
3689 if (!Objects.equal(cur.taskAffinity, r.taskAffinity)) {
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003690 break;
3691 }
Craig Mautnerd44711d2013-02-23 11:24:36 -08003692 finishActivityLocked(cur, Activity.RESULT_CANCELED, null, "request-affinity",
3693 true);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003694 }
3695 return true;
3696 }
3697
Dianne Hackborn5c607432012-02-28 14:44:19 -08003698 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
3699 // send the result
3700 ActivityRecord resultTo = r.resultTo;
3701 if (resultTo != null) {
3702 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3703 + " who=" + r.resultWho + " req=" + r.requestCode
3704 + " res=" + resultCode + " data=" + resultData);
3705 if (r.info.applicationInfo.uid > 0) {
3706 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3707 resultTo.packageName, resultData,
3708 resultTo.getUriPermissionsLocked());
3709 }
3710 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3711 resultData);
3712 r.resultTo = null;
3713 }
3714 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3715
3716 // Make sure this HistoryRecord is not holding on to other resources,
3717 // because clients have remote IPC references to this object so we
3718 // can't assume that will go away and want to avoid circular IPC refs.
3719 r.results = null;
3720 r.pendingResults = null;
3721 r.newIntents = null;
3722 r.icicle = null;
3723 }
3724
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003725 /**
3726 * @return Returns true if this activity has been removed from the history
3727 * list, or false if it is still in the list and will be removed later.
3728 */
Craig Mautnerd44711d2013-02-23 11:24:36 -08003729 final boolean finishActivityLocked(ActivityRecord r, int resultCode,
3730 Intent resultData, String reason, boolean oomAdj) {
3731 return finishActivityLocked(r, resultCode, resultData, reason, false, oomAdj);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003732 }
3733
3734 /**
3735 * @return Returns true if this activity has been removed from the history
3736 * list, or false if it is still in the list and will be removed later.
3737 */
Craig Mautnerd44711d2013-02-23 11:24:36 -08003738 final boolean finishActivityLocked(ActivityRecord r, int resultCode, Intent resultData,
3739 String reason, boolean immediate, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003740 if (r.finishing) {
3741 Slog.w(TAG, "Duplicate finish request for " + r);
3742 return false;
3743 }
3744
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003745 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003746 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003747 r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003748 r.task.taskId, r.shortComponentName, reason);
Craig Mautnerd44711d2013-02-23 11:24:36 -08003749 final ArrayList<ActivityRecord> activities = r.task.mActivities;
3750 final int index = activities.indexOf(r);
3751 if (index < (activities.size() - 1)) {
3752 ActivityRecord next = activities.get(index+1);
3753 if (r.frontOfTask) {
3754 // The next activity is now the front of the task.
3755 next.frontOfTask = true;
3756 }
3757 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3758 // If the caller asked that this activity (and all above it)
3759 // be cleared when the task is reset, don't lose that information,
3760 // but propagate it up to the next activity.
3761 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003762 }
3763 }
3764
3765 r.pauseKeyDispatchingLocked();
3766 if (mMainStack) {
3767 if (mService.mFocusedActivity == r) {
3768 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3769 }
3770 }
3771
Dianne Hackborn5c607432012-02-28 14:44:19 -08003772 finishActivityResultsLocked(r, resultCode, resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003773
3774 if (mService.mPendingThumbnails.size() > 0) {
3775 // There are clients waiting to receive thumbnails so, in case
3776 // this is an activity that someone is waiting for, add it
3777 // to the pending list so we can correctly update the clients.
Craig Mautnercae015f2013-02-08 14:31:27 -08003778 mCancelledThumbnails.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003779 }
3780
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003781 if (immediate) {
Craig Mautnerd44711d2013-02-23 11:24:36 -08003782 return finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, oomAdj) == null;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003783 } else if (mResumedActivity == r) {
Craig Mautner0247fc82013-02-28 14:32:06 -08003784 boolean endTask = index <= 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003785 if (DEBUG_TRANSITION) Slog.v(TAG,
3786 "Prepare close transition: finishing " + r);
3787 mService.mWindowManager.prepareAppTransition(endTask
Craig Mautner4b71aa12012-12-27 17:20:01 -08003788 ? AppTransition.TRANSIT_TASK_CLOSE
3789 : AppTransition.TRANSIT_ACTIVITY_CLOSE, false);
Craig Mautner0247fc82013-02-28 14:32:06 -08003790
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003791 // Tell window manager to prepare for this one to be removed.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003792 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003793
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003794 if (mPausingActivity == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003795 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3796 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3797 startPausingLocked(false, false);
3798 }
3799
3800 } else if (r.state != ActivityState.PAUSING) {
3801 // If the activity is PAUSING, we will complete the finish once
3802 // it is done pausing; else we can just directly finish it here.
3803 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
Craig Mautnerd44711d2013-02-23 11:24:36 -08003804 return finishCurrentActivityLocked(r, FINISH_AFTER_PAUSE, oomAdj) == null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003805 } else {
3806 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3807 }
3808
3809 return false;
3810 }
3811
3812 private static final int FINISH_IMMEDIATELY = 0;
3813 private static final int FINISH_AFTER_PAUSE = 1;
3814 private static final int FINISH_AFTER_VISIBLE = 2;
3815
Craig Mautnerd44711d2013-02-23 11:24:36 -08003816
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003817 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003818 int mode, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003819 // First things first: if this activity is currently visible,
3820 // and the resumed activity is not yet visible, then hold off on
3821 // finishing until the resumed one becomes visible.
3822 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3823 if (!mStoppingActivities.contains(r)) {
3824 mStoppingActivities.add(r);
3825 if (mStoppingActivities.size() > 3) {
3826 // If we already have a few activities waiting to stop,
3827 // then give up on things going idle and start clearing
3828 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003829 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003830 } else {
3831 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003832 }
3833 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003834 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3835 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003836 r.state = ActivityState.STOPPING;
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003837 if (oomAdj) {
3838 mService.updateOomAdjLocked();
3839 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003840 return r;
3841 }
3842
3843 // make sure the record is cleaned out of other places.
3844 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003845 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003846 mWaitingVisibleActivities.remove(r);
3847 if (mResumedActivity == r) {
3848 mResumedActivity = null;
3849 }
3850 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003851 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003852 r.state = ActivityState.FINISHING;
3853
3854 if (mode == FINISH_IMMEDIATELY
3855 || prevState == ActivityState.STOPPED
3856 || prevState == ActivityState.INITIALIZING) {
3857 // If this activity is already stopped, we can just finish
3858 // it right now.
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003859 boolean activityRemoved = destroyActivityLocked(r, true,
3860 oomAdj, "finish-imm");
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003861 if (activityRemoved) {
3862 resumeTopActivityLocked(null);
3863 }
3864 return activityRemoved ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003865 }
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003866
3867 // Need to go through the full pause cycle to get this
3868 // activity into the stopped state and then finish it.
3869 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3870 mFinishingActivities.add(r);
3871 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003872 return r;
3873 }
3874
Craig Mautnerd2328952013-03-05 12:46:26 -08003875 final boolean navigateUpToLocked(IBinder token, Intent destIntent, int resultCode,
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003876 Intent resultData) {
Craig Mautnerd2328952013-03-05 12:46:26 -08003877 final ActivityRecord srec = ActivityRecord.forToken(token);
Craig Mautner0247fc82013-02-28 14:32:06 -08003878 final TaskRecord task = srec.task;
3879 final ArrayList<ActivityRecord> activities = task.mActivities;
3880 final int start = activities.indexOf(srec);
3881 if (!mTaskHistory.contains(task) || (start < 0)) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003882 return false;
3883 }
3884 int finishTo = start - 1;
Craig Mautner0247fc82013-02-28 14:32:06 -08003885 ActivityRecord parent = finishTo < 0 ? null : activities.get(finishTo);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003886 boolean foundParentInTask = false;
Craig Mautner0247fc82013-02-28 14:32:06 -08003887 final ComponentName dest = destIntent.getComponent();
3888 if (start > 0 && dest != null) {
3889 for (int i = finishTo; i >= 0; i--) {
3890 ActivityRecord r = activities.get(i);
3891 if (r.info.packageName.equals(dest.getPackageName()) &&
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003892 r.info.name.equals(dest.getClassName())) {
3893 finishTo = i;
3894 parent = r;
3895 foundParentInTask = true;
3896 break;
3897 }
3898 }
3899 }
3900
3901 IActivityController controller = mService.mController;
3902 if (controller != null) {
3903 ActivityRecord next = topRunningActivityLocked(srec.appToken, 0);
3904 if (next != null) {
3905 // ask watcher if this is allowed
3906 boolean resumeOK = true;
3907 try {
3908 resumeOK = controller.activityResuming(next.packageName);
3909 } catch (RemoteException e) {
3910 mService.mController = null;
3911 }
3912
3913 if (!resumeOK) {
3914 return false;
3915 }
3916 }
3917 }
3918 final long origId = Binder.clearCallingIdentity();
3919 for (int i = start; i > finishTo; i--) {
Craig Mautner0247fc82013-02-28 14:32:06 -08003920 ActivityRecord r = activities.get(i);
3921 requestFinishActivityLocked(r.appToken, resultCode, resultData, "navigate-up", true);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003922 // Only return the supplied result for the first activity finished
3923 resultCode = Activity.RESULT_CANCELED;
3924 resultData = null;
3925 }
3926
3927 if (parent != null && foundParentInTask) {
3928 final int parentLaunchMode = parent.info.launchMode;
3929 final int destIntentFlags = destIntent.getFlags();
3930 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
3931 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
3932 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
3933 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
3934 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
3935 } else {
3936 try {
3937 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
3938 destIntent.getComponent(), 0, srec.userId);
3939 int res = startActivityLocked(srec.app.thread, destIntent,
3940 null, aInfo, parent.appToken, null,
3941 0, -1, parent.launchedFromUid, parent.launchedFromPackage,
3942 0, null, true, null);
3943 foundParentInTask = res == ActivityManager.START_SUCCESS;
3944 } catch (RemoteException e) {
3945 foundParentInTask = false;
3946 }
3947 requestFinishActivityLocked(parent.appToken, resultCode,
3948 resultData, "navigate-up", true);
3949 }
3950 }
3951 Binder.restoreCallingIdentity(origId);
3952 return foundParentInTask;
3953 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003954 /**
3955 * Perform the common clean-up of an activity record. This is called both
3956 * as part of destroyActivityLocked() (when destroying the client-side
3957 * representation) and cleaning things up as a result of its hosting
3958 * processing going away, in which case there is no remaining client-side
3959 * state to destroy so only the cleanup here is needed.
3960 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003961 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3962 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003963 if (mResumedActivity == r) {
3964 mResumedActivity = null;
3965 }
3966 if (mService.mFocusedActivity == r) {
3967 mService.mFocusedActivity = null;
3968 }
3969
3970 r.configDestroy = false;
3971 r.frozenBeforeDestroy = false;
3972
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003973 if (setState) {
3974 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3975 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08003976 if (DEBUG_APP) Slog.v(TAG, "Clearing app during cleanUp for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003977 r.app = null;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003978 }
3979
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003980 // Make sure this record is no longer in the pending finishes list.
3981 // This could happen, for example, if we are trimming activities
3982 // down to the max limit while they are still waiting to finish.
3983 mFinishingActivities.remove(r);
3984 mWaitingVisibleActivities.remove(r);
3985
3986 // Remove any pending results.
3987 if (r.finishing && r.pendingResults != null) {
3988 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3989 PendingIntentRecord rec = apr.get();
3990 if (rec != null) {
3991 mService.cancelIntentSenderLocked(rec, false);
3992 }
3993 }
3994 r.pendingResults = null;
3995 }
3996
3997 if (cleanServices) {
3998 cleanUpActivityServicesLocked(r);
3999 }
4000
4001 if (mService.mPendingThumbnails.size() > 0) {
4002 // There are clients waiting to receive thumbnails so, in case
4003 // this is an activity that someone is waiting for, add it
4004 // to the pending list so we can correctly update the clients.
Craig Mautnercae015f2013-02-08 14:31:27 -08004005 mCancelledThumbnails.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004006 }
4007
4008 // Get rid of any pending idle timeouts.
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004009 removeTimeoutsForActivityLocked(r);
4010 }
4011
4012 private void removeTimeoutsForActivityLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004013 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07004014 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004015 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004016 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07004017 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004018 }
4019
Dianne Hackborn5c607432012-02-28 14:44:19 -08004020 final void removeActivityFromHistoryLocked(ActivityRecord r) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004021 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
4022 r.makeFinishing();
4023 if (DEBUG_ADD_REMOVE) {
4024 RuntimeException here = new RuntimeException("here");
4025 here.fillInStackTrace();
4026 Slog.i(TAG, "Removing activity " + r + " from stack");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004027 }
Craig Mautner0247fc82013-02-28 14:32:06 -08004028 if (r.task != null) {
4029 removeActivity(r);
Craig Mautner5d9c7be2013-02-15 14:02:56 -08004030 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004031 r.takeFromHistory();
4032 removeTimeoutsForActivityLocked(r);
Craig Mautner0247fc82013-02-28 14:32:06 -08004033 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (removed from history)");
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004034 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08004035 if (DEBUG_APP) Slog.v(TAG, "Clearing app during remove for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004036 r.app = null;
4037 mService.mWindowManager.removeAppToken(r.appToken);
4038 if (VALIDATE_TOKENS) {
4039 validateAppTokensLocked();
4040 }
4041 cleanUpActivityServicesLocked(r);
4042 r.removeUriPermissionsLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004043 }
4044
4045 /**
4046 * Perform clean-up of service connections in an activity record.
4047 */
4048 final void cleanUpActivityServicesLocked(ActivityRecord r) {
4049 // Throw away any services that have been bound by this activity.
4050 if (r.connections != null) {
4051 Iterator<ConnectionRecord> it = r.connections.iterator();
4052 while (it.hasNext()) {
4053 ConnectionRecord c = it.next();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004054 mService.mServices.removeConnectionLocked(c, null, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004055 }
4056 r.connections = null;
4057 }
4058 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004059
4060 final void scheduleDestroyActivities(ProcessRecord owner, boolean oomAdj, String reason) {
4061 Message msg = mHandler.obtainMessage(DESTROY_ACTIVITIES_MSG);
4062 msg.obj = new ScheduleDestroyArgs(owner, oomAdj, reason);
4063 mHandler.sendMessage(msg);
4064 }
4065
Dianne Hackborn28695e02011-11-02 21:59:51 -07004066 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004067 boolean lastIsOpaque = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004068 boolean activityRemoved = false;
Craig Mautnerd44711d2013-02-23 11:24:36 -08004069 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4070 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4071 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4072 final ActivityRecord r = activities.get(activityNdx);
4073 if (r.finishing) {
4074 continue;
4075 }
4076 if (r.fullscreen) {
4077 lastIsOpaque = true;
4078 }
4079 if (owner != null && r.app != owner) {
4080 continue;
4081 }
4082 if (!lastIsOpaque) {
4083 continue;
4084 }
4085 // We can destroy this one if we have its icicle saved and
4086 // it is not in the process of pausing/stopping/finishing.
4087 if (r.app != null && r != mResumedActivity && r != mPausingActivity
4088 && r.haveState && !r.visible && r.stopped
4089 && r.state != ActivityState.DESTROYING
4090 && r.state != ActivityState.DESTROYED) {
4091 if (DEBUG_SWITCH) Slog.v(TAG, "Destroying " + r + " in state " + r.state
4092 + " resumed=" + mResumedActivity
4093 + " pausing=" + mPausingActivity);
4094 if (destroyActivityLocked(r, true, oomAdj, reason)) {
4095 activityRemoved = true;
4096 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004097 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004098 }
4099 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004100 if (activityRemoved) {
4101 resumeTopActivityLocked(null);
4102 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004103 }
4104
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004105 /**
4106 * Destroy the current CLIENT SIDE instance of an activity. This may be
4107 * called both when actually finishing an activity, or when performing
4108 * a configuration switch where we destroy the current client-side object
4109 * but then create a new client-side object for this same HistoryRecord.
4110 */
4111 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackborn28695e02011-11-02 21:59:51 -07004112 boolean removeFromApp, boolean oomAdj, String reason) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004113 if (DEBUG_SWITCH || DEBUG_CLEANUP) Slog.v(
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004114 TAG, "Removing activity from " + reason + ": token=" + r
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004115 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
4116 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004117 r.userId, System.identityHashCode(r),
Dianne Hackborn28695e02011-11-02 21:59:51 -07004118 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004119
4120 boolean removedFromHistory = false;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004121
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004122 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004123
4124 final boolean hadApp = r.app != null;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004125
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004126 if (hadApp) {
4127 if (removeFromApp) {
Craig Mautnerd2328952013-03-05 12:46:26 -08004128 r.app.activities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004129 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
4130 mService.mHeavyWeightProcess = null;
4131 mService.mHandler.sendEmptyMessage(
4132 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
4133 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004134 if (r.app.activities.size() == 0) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07004135 // No longer have activities, so update oom adj.
4136 mService.updateOomAdjLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004137 }
4138 }
4139
4140 boolean skipDestroy = false;
4141
4142 try {
4143 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004144 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004145 r.configChangeFlags);
4146 } catch (Exception e) {
4147 // We can just ignore exceptions here... if the process
4148 // has crashed, our death notification will clean things
4149 // up.
4150 //Slog.w(TAG, "Exception thrown during finish", e);
4151 if (r.finishing) {
4152 removeActivityFromHistoryLocked(r);
4153 removedFromHistory = true;
4154 skipDestroy = true;
4155 }
4156 }
4157
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004158 r.nowVisible = false;
4159
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004160 // If the activity is finishing, we need to wait on removing it
4161 // from the list to give it a chance to do its cleanup. During
4162 // that time it may make calls back with its token so we need to
4163 // be able to find it on the list and so we don't want to remove
4164 // it from the list yet. Otherwise, we can just immediately put
4165 // it in the destroyed state since we are not removing it from the
4166 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004167 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004168 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
4169 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004170 r.state = ActivityState.DESTROYING;
4171 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
4172 msg.obj = r;
4173 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
4174 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004175 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4176 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004177 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08004178 if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004179 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004180 }
4181 } else {
4182 // remove this record from the history.
4183 if (r.finishing) {
4184 removeActivityFromHistoryLocked(r);
4185 removedFromHistory = true;
4186 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004187 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4188 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004189 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08004190 if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004191 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004192 }
4193 }
4194
4195 r.configChangeFlags = 0;
4196
4197 if (!mLRUActivities.remove(r) && hadApp) {
4198 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
4199 }
4200
4201 return removedFromHistory;
4202 }
4203
Craig Mautnerd2328952013-03-05 12:46:26 -08004204 final void activityDestroyedLocked(IBinder token) {
4205 final long origId = Binder.clearCallingIdentity();
4206 try {
4207 ActivityRecord r = ActivityRecord.forToken(token);
4208 if (r != null) {
4209 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004210 }
Craig Mautnerd2328952013-03-05 12:46:26 -08004211
4212 if (isInStackLocked(token) != null) {
4213 if (r.state == ActivityState.DESTROYING) {
4214 cleanUpActivityLocked(r, true, false);
4215 removeActivityFromHistoryLocked(r);
4216 }
4217 }
4218 resumeTopActivityLocked(null);
4219 } finally {
4220 Binder.restoreCallingIdentity(origId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004221 }
4222 }
4223
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004224 private void removeHistoryRecordsForAppLocked(ArrayList<ActivityRecord> list,
4225 ProcessRecord app, String listName) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004226 int i = list.size();
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004227 if (DEBUG_CLEANUP) Slog.v(
4228 TAG, "Removing app " + app + " from list " + listName
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004229 + " with " + i + " entries");
4230 while (i > 0) {
4231 i--;
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004232 ActivityRecord r = list.get(i);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004233 if (DEBUG_CLEANUP) Slog.v(TAG, "Record #" + i + " " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004234 if (r.app == app) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004235 if (DEBUG_CLEANUP) Slog.v(TAG, "---> REMOVING this entry!");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004236 list.remove(i);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004237 removeTimeoutsForActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004238 }
4239 }
4240 }
4241
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004242 boolean removeHistoryRecordsForAppLocked(ProcessRecord app) {
4243 removeHistoryRecordsForAppLocked(mLRUActivities, app, "mLRUActivities");
4244 removeHistoryRecordsForAppLocked(mStoppingActivities, app, "mStoppingActivities");
4245 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app, "mGoingToSleepActivities");
4246 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app,
4247 "mWaitingVisibleActivities");
4248 removeHistoryRecordsForAppLocked(mFinishingActivities, app, "mFinishingActivities");
4249
4250 boolean hasVisibleActivities = false;
4251
4252 // Clean out the history list.
Craig Mautner0247fc82013-02-28 14:32:06 -08004253 int i = numActivities();
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004254 if (DEBUG_CLEANUP) Slog.v(
4255 TAG, "Removing app " + app + " from history with " + i + " entries");
Craig Mautner0247fc82013-02-28 14:32:06 -08004256 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4257 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4258 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4259 final ActivityRecord r = activities.get(activityNdx);
4260 --i;
4261 if (DEBUG_CLEANUP) Slog.v(
4262 TAG, "Record #" + i + " " + r + ": app=" + r.app);
4263 if (r.app == app) {
4264 boolean remove;
4265 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
4266 // Don't currently have state for the activity, or
4267 // it is finishing -- always remove it.
4268 remove = true;
4269 } else if (r.launchCount > 2 &&
4270 r.lastLaunchTime > (SystemClock.uptimeMillis()-60000)) {
4271 // We have launched this activity too many times since it was
4272 // able to run, so give up and remove it.
4273 remove = true;
4274 } else {
4275 // The process may be gone, but the activity lives on!
4276 remove = false;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004277 }
Craig Mautner0247fc82013-02-28 14:32:06 -08004278 if (remove) {
4279 if (ActivityStack.DEBUG_ADD_REMOVE || DEBUG_CLEANUP) {
4280 RuntimeException here = new RuntimeException("here");
4281 here.fillInStackTrace();
4282 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
4283 + ": haveState=" + r.haveState
4284 + " stateNotNeeded=" + r.stateNotNeeded
4285 + " finishing=" + r.finishing
4286 + " state=" + r.state, here);
4287 }
4288 if (!r.finishing) {
4289 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
4290 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
4291 r.userId, System.identityHashCode(r),
4292 r.task.taskId, r.shortComponentName,
4293 "proc died without state saved");
4294 }
4295 removeActivityFromHistoryLocked(r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004296
Craig Mautner0247fc82013-02-28 14:32:06 -08004297 } else {
4298 // We have the current state for this activity, so
4299 // it can be restarted later when needed.
4300 if (localLOGV) Slog.v(
4301 TAG, "Keeping entry, setting app to null");
4302 if (r.visible) {
4303 hasVisibleActivities = true;
4304 }
4305 if (DEBUG_APP) Slog.v(TAG, "Clearing app during removeHistory for activity "
4306 + r);
4307 r.app = null;
4308 r.nowVisible = false;
4309 if (!r.haveState) {
4310 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
4311 "App died, clearing saved state of " + r);
4312 r.icicle = null;
4313 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004314 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004315
Craig Mautnerd2328952013-03-05 12:46:26 -08004316 cleanUpActivityLocked(r, true, true);
Craig Mautner0247fc82013-02-28 14:32:06 -08004317 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004318 }
4319 }
4320
4321 return hasVisibleActivities;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004322 }
Craig Mautner0247fc82013-02-28 14:32:06 -08004323
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004324 /**
4325 * Move the current home activity's task (if one exists) to the front
4326 * of the stack.
4327 */
4328 final void moveHomeToFrontLocked() {
Craig Mautner0247fc82013-02-28 14:32:06 -08004329 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4330 final TaskRecord task = mTaskHistory.get(taskNdx);
4331 final ArrayList<ActivityRecord> activities = task.mActivities;
Craig Mautner11bf9a52013-02-19 14:08:51 -08004332 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4333 final ActivityRecord r = activities.get(activityNdx);
4334 if (r.isHomeActivity) {
Craig Mautner0247fc82013-02-28 14:32:06 -08004335 moveTaskToFrontLocked(task, null, null);
4336 return;
Craig Mautner11bf9a52013-02-19 14:08:51 -08004337 }
4338 }
4339 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004340 }
4341
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004342 final void updateTransitLocked(int transit, Bundle options) {
4343 if (options != null) {
4344 ActivityRecord r = topRunningActivityLocked(null);
4345 if (r != null && r.state != ActivityState.RESUMED) {
4346 r.updateOptionsLocked(options);
4347 } else {
4348 ActivityOptions.abort(options);
4349 }
4350 }
4351 mService.mWindowManager.prepareAppTransition(transit, false);
4352 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004353
Craig Mautnercae015f2013-02-08 14:31:27 -08004354 final boolean findTaskToMoveToFrontLocked(int taskId, int flags, Bundle options) {
Craig Mautnerd2328952013-03-05 12:46:26 -08004355 final TaskRecord task = taskForIdLocked(taskId);
4356 if (task != null) {
Craig Mautneraab647e2013-02-28 16:31:36 -08004357 if ((flags & ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
4358 mUserLeaving = true;
Craig Mautnercae015f2013-02-08 14:31:27 -08004359 }
Craig Mautneraab647e2013-02-28 16:31:36 -08004360 if ((flags & ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
4361 // Caller wants the home activity moved with it. To accomplish this,
4362 // we'll just move the home task to the top first.
4363 moveHomeToFrontLocked();
4364 }
4365 moveTaskToFrontLocked(task, null, options);
4366 return true;
Craig Mautnercae015f2013-02-08 14:31:27 -08004367 }
4368 return false;
4369 }
4370
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004371 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason, Bundle options) {
Craig Mautner11bf9a52013-02-19 14:08:51 -08004372 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004373
Craig Mautner11bf9a52013-02-19 14:08:51 -08004374 final int numTasks = mTaskHistory.size();
4375 final int index = mTaskHistory.indexOf(tr);
4376 if (numTasks == 0 || index < 0 || index == numTasks - 1) {
4377 // nothing to do!
4378 if (reason != null &&
4379 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
4380 ActivityOptions.abort(options);
4381 } else {
4382 updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options);
4383 }
4384 return;
4385 }
4386
4387 // Shift all activities with this task up to the top
4388 // of the stack, keeping them in the same internal order.
4389 mTaskHistory.remove(tr);
4390 mTaskHistory.add(tr);
4391
4392 if (DEBUG_TRANSITION) Slog.v(TAG, "Prepare to front transition: task=" + tr);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004393 if (reason != null &&
4394 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Craig Mautner11bf9a52013-02-19 14:08:51 -08004395 mService.mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004396 ActivityRecord r = topRunningActivityLocked(null);
4397 if (r != null) {
4398 mNoAnimActivities.add(r);
4399 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004400 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004401 } else {
Craig Mautner4b71aa12012-12-27 17:20:01 -08004402 updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004403 }
Craig Mautner30e2d722013-02-12 11:30:16 -08004404
Craig Mautner58547802013-03-05 08:23:53 -08004405 mService.mWindowManager.moveTaskToTop(tr.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004406
Craig Mautner58547802013-03-05 08:23:53 -08004407 resumeTopActivityLocked(null);
4408 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, tr.userId, tr.taskId);
Craig Mautner11bf9a52013-02-19 14:08:51 -08004409
4410 if (VALIDATE_TOKENS) {
4411 validateAppTokensLocked();
4412 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004413 }
4414
4415 /**
4416 * Worker method for rearranging history stack. Implements the function of moving all
4417 * activities for a specific task (gathering them if disjoint) into a single group at the
4418 * bottom of the stack.
4419 *
4420 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
4421 * to premeptively cancel the move.
4422 *
4423 * @param task The taskId to collect and move to the bottom.
4424 * @return Returns true if the move completed, false if not.
4425 */
4426 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
4427 Slog.i(TAG, "moveTaskToBack: " + task);
Craig Mautnerb44de0d2013-02-21 20:00:58 -08004428
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004429 // If we have a watcher, preflight the move before committing to it. First check
4430 // for *other* available tasks, but if none are available, then try again allowing the
4431 // current task to be selected.
4432 if (mMainStack && mService.mController != null) {
4433 ActivityRecord next = topRunningActivityLocked(null, task);
4434 if (next == null) {
4435 next = topRunningActivityLocked(null, 0);
4436 }
4437 if (next != null) {
4438 // ask watcher if this is allowed
4439 boolean moveOK = true;
4440 try {
4441 moveOK = mService.mController.activityResuming(next.packageName);
4442 } catch (RemoteException e) {
4443 mService.mController = null;
4444 }
4445 if (!moveOK) {
4446 return false;
4447 }
4448 }
4449 }
4450
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004451 if (DEBUG_TRANSITION) Slog.v(TAG,
4452 "Prepare to back transition: task=" + task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004453
Craig Mautnerd2328952013-03-05 12:46:26 -08004454 final TaskRecord tr = taskForIdLocked(task);
4455 if (tr == null) {
4456 return false;
4457 }
Craig Mautner11bf9a52013-02-19 14:08:51 -08004458 mTaskHistory.remove(tr);
4459 mTaskHistory.add(0, tr);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004460
4461 if (reason != null &&
4462 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Craig Mautner11bf9a52013-02-19 14:08:51 -08004463 mService.mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004464 ActivityRecord r = topRunningActivityLocked(null);
4465 if (r != null) {
4466 mNoAnimActivities.add(r);
4467 }
4468 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004469 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08004470 AppTransition.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004471 }
Craig Mautner30e2d722013-02-12 11:30:16 -08004472 mService.mWindowManager.moveTaskToBottom(task);
Craig Mautnerb44de0d2013-02-21 20:00:58 -08004473
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004474 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004475 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004476 }
4477
Craig Mautner58547802013-03-05 08:23:53 -08004478 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004479 return true;
4480 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07004481
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004482 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
Craig Mautner16030772013-02-26 16:05:47 -08004483 TaskAccessInfo info = getTaskAccessInfoLocked(tr, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004484 ActivityRecord resumed = mResumedActivity;
4485 if (resumed != null && resumed.thumbHolder == tr) {
Craig Mautnerd2328952013-03-05 12:46:26 -08004486 info.mainThumbnail = screenshotActivities(resumed);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004487 }
Dianne Hackborn6a864952012-09-21 18:46:11 -07004488 if (info.mainThumbnail == null) {
4489 info.mainThumbnail = tr.lastThumbnail;
4490 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004491 return info;
4492 }
4493
Dianne Hackborn15491c62012-09-19 10:59:14 -07004494 public Bitmap getTaskTopThumbnailLocked(TaskRecord tr) {
4495 ActivityRecord resumed = mResumedActivity;
4496 if (resumed != null && resumed.task == tr) {
4497 // This task is the current resumed task, we just need to take
4498 // a screenshot of it and return that.
Craig Mautnerd2328952013-03-05 12:46:26 -08004499 return screenshotActivities(resumed);
Dianne Hackborn15491c62012-09-19 10:59:14 -07004500 }
4501 // Return the information about the task, to figure out the top
4502 // thumbnail to return.
Craig Mautner16030772013-02-26 16:05:47 -08004503 TaskAccessInfo info = getTaskAccessInfoLocked(tr, true);
Dianne Hackborn15491c62012-09-19 10:59:14 -07004504 if (info.numSubThumbbails <= 0) {
Dianne Hackborn6a864952012-09-21 18:46:11 -07004505 return info.mainThumbnail != null ? info.mainThumbnail : tr.lastThumbnail;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004506 }
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004507 return info.subtasks.get(info.numSubThumbbails-1).holder.lastThumbnail;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004508 }
4509
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004510 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex,
4511 boolean taskRequired) {
Craig Mautnerd2328952013-03-05 12:46:26 -08004512 final TaskRecord task = taskForIdLocked(taskId);
4513 if (task == null) {
4514 return null;
4515 }
Craig Mautner16030772013-02-26 16:05:47 -08004516 TaskAccessInfo info = getTaskAccessInfoLocked(task, false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004517 if (info.root == null) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004518 if (taskRequired) {
4519 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
4520 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004521 return null;
4522 }
4523
4524 if (subTaskIndex < 0) {
4525 // Just remove the entire task.
Craig Mautner16030772013-02-26 16:05:47 -08004526 performClearTaskAtIndexLocked(task, info.rootIndex);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004527 return info.root;
4528 }
4529
4530 if (subTaskIndex >= info.subtasks.size()) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004531 if (taskRequired) {
4532 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
4533 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004534 return null;
4535 }
4536
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004537 // Remove all of this task's activities starting at the sub task.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004538 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
Craig Mautner16030772013-02-26 16:05:47 -08004539 performClearTaskAtIndexLocked(task, subtask.index);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004540 return subtask.activity;
4541 }
4542
Craig Mautner16030772013-02-26 16:05:47 -08004543 public TaskAccessInfo getTaskAccessInfoLocked(TaskRecord task, boolean inclThumbs) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004544 final TaskAccessInfo thumbs = new TaskAccessInfo();
4545 // How many different sub-thumbnails?
Craig Mautner16030772013-02-26 16:05:47 -08004546 final ArrayList<ActivityRecord> activities = task.mActivities;
4547 final int NA = activities.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004548 int j = 0;
4549 ThumbnailHolder holder = null;
4550 while (j < NA) {
Craig Mautner16030772013-02-26 16:05:47 -08004551 ActivityRecord ar = activities.get(j);
4552 if (!ar.finishing) {
Dianne Hackborn8da429e2012-09-23 12:52:19 -07004553 thumbs.root = ar;
4554 thumbs.rootIndex = j;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004555 holder = ar.thumbHolder;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004556 if (holder != null) {
4557 thumbs.mainThumbnail = holder.lastThumbnail;
4558 }
4559 j++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004560 break;
4561 }
4562 j++;
4563 }
4564
4565 if (j >= NA) {
4566 return thumbs;
4567 }
4568
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004569 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
4570 thumbs.subtasks = subtasks;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004571 while (j < NA) {
Craig Mautner16030772013-02-26 16:05:47 -08004572 ActivityRecord ar = activities.get(j);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004573 j++;
4574 if (ar.finishing) {
4575 continue;
4576 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004577 if (ar.thumbHolder != holder && holder != null) {
4578 thumbs.numSubThumbbails++;
4579 holder = ar.thumbHolder;
4580 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
Dianne Hackborn15491c62012-09-19 10:59:14 -07004581 sub.holder = holder;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004582 sub.activity = ar;
4583 sub.index = j-1;
4584 subtasks.add(sub);
4585 }
4586 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004587 if (thumbs.numSubThumbbails > 0) {
4588 thumbs.retriever = new IThumbnailRetriever.Stub() {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004589 @Override
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004590 public Bitmap getThumbnail(int index) {
4591 if (index < 0 || index >= thumbs.subtasks.size()) {
4592 return null;
4593 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07004594 TaskAccessInfo.SubTask sub = thumbs.subtasks.get(index);
4595 ActivityRecord resumed = mResumedActivity;
4596 if (resumed != null && resumed.thumbHolder == sub.holder) {
Craig Mautnerd2328952013-03-05 12:46:26 -08004597 return screenshotActivities(resumed);
Dianne Hackborn15491c62012-09-19 10:59:14 -07004598 }
4599 return sub.holder.lastThumbnail;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004600 }
4601 };
4602 }
4603 return thumbs;
4604 }
4605
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004606 private final void logStartActivity(int tag, ActivityRecord r,
4607 TaskRecord task) {
4608 EventLog.writeEvent(tag,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004609 r.userId, System.identityHashCode(r), task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004610 r.shortComponentName, r.intent.getAction(),
4611 r.intent.getType(), r.intent.getDataString(),
4612 r.intent.getFlags());
4613 }
4614
4615 /**
4616 * Make sure the given activity matches the current configuration. Returns
4617 * false if the activity had to be destroyed. Returns true if the
4618 * configuration is the same, or the activity will remain running as-is
4619 * for whatever reason. Ensures the HistoryRecord is updated with the
4620 * correct configuration and all other bookkeeping is handled.
4621 */
4622 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
4623 int globalChanges) {
4624 if (mConfigWillChange) {
4625 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4626 "Skipping config check (will change): " + r);
4627 return true;
4628 }
4629
4630 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4631 "Ensuring correct configuration: " + r);
4632
4633 // Short circuit: if the two configurations are the exact same
4634 // object (the common case), then there is nothing to do.
4635 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004636 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004637 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4638 "Configuration unchanged in " + r);
4639 return true;
4640 }
4641
4642 // We don't worry about activities that are finishing.
4643 if (r.finishing) {
4644 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4645 "Configuration doesn't matter in finishing " + r);
4646 r.stopFreezingScreenLocked(false);
4647 return true;
4648 }
4649
4650 // Okay we now are going to make this activity have the new config.
4651 // But then we need to figure out how it needs to deal with that.
4652 Configuration oldConfig = r.configuration;
4653 r.configuration = newConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004654
4655 // Determine what has changed. May be nothing, if this is a config
4656 // that has come back from the app after going idle. In that case
4657 // we just want to leave the official config object now in the
4658 // activity and do nothing else.
4659 final int changes = oldConfig.diff(newConfig);
4660 if (changes == 0 && !r.forceNewConfig) {
4661 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4662 "Configuration no differences in " + r);
4663 return true;
4664 }
4665
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004666 // If the activity isn't currently running, just leave the new
4667 // configuration and it will pick that up next time it starts.
4668 if (r.app == null || r.app.thread == null) {
4669 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4670 "Configuration doesn't matter not running " + r);
4671 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004672 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004673 return true;
4674 }
4675
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004676 // Figure out how to handle the changes between the configurations.
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004677 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4678 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
4679 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07004680 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004681 + ", newConfig=" + newConfig);
4682 }
Dianne Hackborne6676352011-06-01 16:51:20 -07004683 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004684 // Aha, the activity isn't handling the change, so DIE DIE DIE.
4685 r.configChangeFlags |= changes;
4686 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004687 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004688 if (r.app == null || r.app.thread == null) {
4689 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004690 "Config is destroying non-running " + r);
Dianne Hackborn28695e02011-11-02 21:59:51 -07004691 destroyActivityLocked(r, true, false, "config");
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004692 } else if (r.state == ActivityState.PAUSING) {
4693 // A little annoying: we are waiting for this activity to
4694 // finish pausing. Let's not do anything now, but just
4695 // flag that it needs to be restarted when done pausing.
4696 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004697 "Config is skipping already pausing " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004698 r.configDestroy = true;
4699 return true;
4700 } else if (r.state == ActivityState.RESUMED) {
4701 // Try to optimize this case: the configuration is changing
4702 // and we need to restart the top, resumed activity.
4703 // Instead of doing the normal handshaking, just say
4704 // "restart!".
4705 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004706 "Config is relaunching resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004707 relaunchActivityLocked(r, r.configChangeFlags, true);
4708 r.configChangeFlags = 0;
4709 } else {
4710 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004711 "Config is relaunching non-resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004712 relaunchActivityLocked(r, r.configChangeFlags, false);
4713 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004714 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004715
4716 // All done... tell the caller we weren't able to keep this
4717 // activity around.
4718 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004719 }
4720
4721 // Default case: the activity can handle this new configuration, so
4722 // hand it over. Note that we don't need to give it the new
4723 // configuration, since we always send configuration changes to all
4724 // process when they happen so it can just use whatever configuration
4725 // it last got.
4726 if (r.app != null && r.app.thread != null) {
4727 try {
4728 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004729 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004730 } catch (RemoteException e) {
4731 // If process died, whatever.
4732 }
4733 }
4734 r.stopFreezingScreenLocked(false);
4735
4736 return true;
4737 }
4738
4739 private final boolean relaunchActivityLocked(ActivityRecord r,
4740 int changes, boolean andResume) {
4741 List<ResultInfo> results = null;
4742 List<Intent> newIntents = null;
4743 if (andResume) {
4744 results = r.results;
4745 newIntents = r.newIntents;
4746 }
4747 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4748 + " with results=" + results + " newIntents=" + newIntents
4749 + " andResume=" + andResume);
4750 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004751 : EventLogTags.AM_RELAUNCH_ACTIVITY, r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004752 r.task.taskId, r.shortComponentName);
4753
4754 r.startFreezingScreenLocked(r.app, 0);
4755
4756 try {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004757 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG,
4758 (andResume ? "Relaunching to RESUMED " : "Relaunching to PAUSED ")
4759 + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004760 r.forceNewConfig = false;
Dianne Hackbornbe707852011-11-11 14:32:10 -08004761 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004762 changes, !andResume, new Configuration(mService.mConfiguration));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004763 // Note: don't need to call pauseIfSleepingLocked() here, because
4764 // the caller will only pass in 'andResume' if this activity is
4765 // currently resumed, which implies we aren't sleeping.
4766 } catch (RemoteException e) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004767 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, "Relaunch failed", e);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004768 }
4769
4770 if (andResume) {
4771 r.results = null;
4772 r.newIntents = null;
4773 if (mMainStack) {
4774 mService.reportResumedActivityLocked(r);
4775 }
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004776 r.state = ActivityState.RESUMED;
4777 } else {
4778 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
4779 r.state = ActivityState.PAUSED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004780 }
4781
4782 return true;
4783 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004784
4785 boolean willActivityBeVisibleLocked(IBinder token) {
Craig Mautnerd44711d2013-02-23 11:24:36 -08004786 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4787 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4788 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4789 final ActivityRecord r = activities.get(activityNdx);
4790 if (r.appToken == token) {
4791 return true;
4792 }
4793 if (r.fullscreen && !r.finishing) {
4794 return false;
4795 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004796 }
4797 }
4798 return true;
4799 }
4800
4801 void closeSystemDialogsLocked() {
Craig Mautnerd44711d2013-02-23 11:24:36 -08004802 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4803 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4804 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4805 final ActivityRecord r = activities.get(activityNdx);
4806 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Craig Mautnerd2328952013-03-05 12:46:26 -08004807 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "close-sys", true);
Craig Mautnerd44711d2013-02-23 11:24:36 -08004808 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004809 }
4810 }
4811 }
4812
4813 boolean forceStopPackageLocked(String name, boolean doit, boolean evenPersistent, int userId) {
4814 boolean didSomething = false;
4815 TaskRecord lastTask = null;
Craig Mautner56f52db2013-02-25 10:03:01 -08004816 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4817 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4818 int numActivities = activities.size();
4819 for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) {
4820 ActivityRecord r = activities.get(activityNdx);
4821 final boolean samePackage = r.packageName.equals(name)
4822 || (name == null && r.userId == userId);
4823 if ((userId == UserHandle.USER_ALL || r.userId == userId)
4824 && (samePackage || r.task == lastTask)
4825 && (r.app == null || evenPersistent || !r.app.persistent)) {
4826 if (!doit) {
4827 if (r.finishing) {
4828 // If this activity is just finishing, then it is not
4829 // interesting as far as something to stop.
4830 continue;
4831 }
4832 return true;
Craig Mautnercae015f2013-02-08 14:31:27 -08004833 }
Craig Mautner56f52db2013-02-25 10:03:01 -08004834 didSomething = true;
4835 Slog.i(TAG, " Force finishing activity " + r);
4836 if (samePackage) {
4837 if (r.app != null) {
4838 r.app.removed = true;
4839 }
4840 r.app = null;
Craig Mautnercae015f2013-02-08 14:31:27 -08004841 }
Craig Mautner56f52db2013-02-25 10:03:01 -08004842 lastTask = r.task;
Craig Mautnerd2328952013-03-05 12:46:26 -08004843 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "force-stop", true);
Craig Mautnercae015f2013-02-08 14:31:27 -08004844 }
4845 }
4846 }
4847 return didSomething;
4848 }
4849
4850 ActivityRecord getTasksLocked(int maxNum, IThumbnailReceiver receiver,
Craig Mautneraab647e2013-02-28 16:31:36 -08004851 PendingThumbnailsRecord pending, List<RunningTaskInfo> list) {
Craig Mautnercae015f2013-02-08 14:31:27 -08004852 ActivityRecord topRecord = null;
Craig Mautneraab647e2013-02-28 16:31:36 -08004853 for (int taskNdx = mTaskHistory.size() - 1; maxNum > 0 && taskNdx >= 0;
4854 --maxNum, --taskNdx) {
4855 final TaskRecord task = mTaskHistory.get(taskNdx);
4856 ActivityRecord r = null;
4857 ActivityRecord top = null;
4858 int numActivities = 0;
4859 int numRunning = 0;
4860 final ArrayList<ActivityRecord> activities = task.mActivities;
4861 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4862 r = activities.get(activityNdx);
Craig Mautnercae015f2013-02-08 14:31:27 -08004863
Craig Mautneraab647e2013-02-28 16:31:36 -08004864 // Initialize state for next task if needed.
4865 if (top == null || (top.state == ActivityState.INITIALIZING)) {
4866 top = r;
4867 numActivities = numRunning = 0;
Craig Mautnercae015f2013-02-08 14:31:27 -08004868 }
Craig Mautneraab647e2013-02-28 16:31:36 -08004869
4870 // Add 'r' into the current task.
4871 numActivities++;
4872 if (r.app != null && r.app.thread != null) {
4873 numRunning++;
4874 }
4875
4876 if (localLOGV) Slog.v(
4877 TAG, r.intent.getComponent().flattenToShortString()
4878 + ": task=" + r.task);
4879 }
4880
4881 RunningTaskInfo ci = new RunningTaskInfo();
4882 ci.id = task.taskId;
4883 ci.baseActivity = r.intent.getComponent();
4884 ci.topActivity = top.intent.getComponent();
4885 if (top.thumbHolder != null) {
4886 ci.description = top.thumbHolder.lastDescription;
4887 }
4888 ci.numActivities = numActivities;
4889 ci.numRunning = numRunning;
4890 //System.out.println(
4891 // "#" + maxNum + ": " + " descr=" + ci.description);
4892 if (receiver != null) {
4893 if (localLOGV) Slog.v(
4894 TAG, "State=" + top.state + "Idle=" + top.idle
4895 + " app=" + top.app
4896 + " thr=" + (top.app != null ? top.app.thread : null));
4897 if (top.state == ActivityState.RESUMED || top.state == ActivityState.PAUSING) {
4898 if (top.idle && top.app != null && top.app.thread != null) {
4899 topRecord = top;
4900 } else {
4901 top.thumbnailNeeded = true;
Craig Mautnercae015f2013-02-08 14:31:27 -08004902 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004903 }
Craig Mautneraab647e2013-02-28 16:31:36 -08004904 pending.pendingRecords.add(top);
Craig Mautnercae015f2013-02-08 14:31:27 -08004905 }
Craig Mautneraab647e2013-02-28 16:31:36 -08004906 list.add(ci);
Craig Mautnercae015f2013-02-08 14:31:27 -08004907 }
4908 return topRecord;
4909 }
4910
4911 public void unhandledBackLocked() {
Craig Mautneraab647e2013-02-28 16:31:36 -08004912 final int top = mTaskHistory.size() - 1;
Craig Mautnercae015f2013-02-08 14:31:27 -08004913 if (DEBUG_SWITCH) Slog.d(
4914 TAG, "Performing unhandledBack(): top activity at " + top);
Craig Mautneraab647e2013-02-28 16:31:36 -08004915 if (top >= 0) {
4916 final ArrayList<ActivityRecord> activities = mTaskHistory.get(top).mActivities;
4917 int activityTop = activities.size() - 1;
4918 if (activityTop > 0) {
4919 finishActivityLocked(activities.get(activityTop), Activity.RESULT_CANCELED, null,
4920 "unhandled-back", true);
4921 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004922 }
4923 }
4924
4925 void handleAppCrashLocked(ProcessRecord app) {
Craig Mautnerd44711d2013-02-23 11:24:36 -08004926 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4927 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4928 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4929 final ActivityRecord r = activities.get(activityNdx);
4930 if (r.app == app) {
4931 Slog.w(TAG, " Force finishing activity "
4932 + r.intent.getComponent().flattenToShortString());
Craig Mautnerd2328952013-03-05 12:46:26 -08004933 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false);
Craig Mautnerd44711d2013-02-23 11:24:36 -08004934 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004935 }
4936 }
4937 }
4938
4939 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
4940 boolean dumpClient, String dumpPackage) {
Craig Mautneraab647e2013-02-28 16:31:36 -08004941 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4942 final TaskRecord task = mTaskHistory.get(taskNdx);
4943 pw.print(" Task "); pw.print(taskNdx); pw.print(": id #"); pw.println(task.taskId);
4944 ActivityManagerService.dumpHistoryList(fd, pw, mTaskHistory.get(taskNdx).mActivities,
4945 " ", "Hist", true, !dumpAll, dumpClient, dumpPackage);
4946 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004947 }
4948
4949 ArrayList<ActivityRecord> getDumpActivitiesLocked(String name) {
4950 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
4951
4952 if ("all".equals(name)) {
Craig Mautneraab647e2013-02-28 16:31:36 -08004953 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4954 activities.addAll(mTaskHistory.get(taskNdx).mActivities);
Craig Mautnercae015f2013-02-08 14:31:27 -08004955 }
4956 } else if ("top".equals(name)) {
Craig Mautneraab647e2013-02-28 16:31:36 -08004957 final int top = mTaskHistory.size() - 1;
4958 if (top >= 0) {
4959 final ArrayList<ActivityRecord> list = mTaskHistory.get(top).mActivities;
4960 int listTop = list.size() - 1;
4961 if (listTop >= 0) {
4962 activities.add(list.get(listTop));
4963 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004964 }
4965 } else {
4966 ItemMatcher matcher = new ItemMatcher();
4967 matcher.build(name);
4968
Craig Mautneraab647e2013-02-28 16:31:36 -08004969 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4970 for (ActivityRecord r1 : mTaskHistory.get(taskNdx).mActivities) {
4971 if (matcher.match(r1, r1.intent.getComponent())) {
4972 activities.add(r1);
4973 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004974 }
4975 }
4976 }
4977
4978 return activities;
4979 }
4980
4981 ActivityRecord restartPackage(String packageName) {
4982 ActivityRecord starting = topRunningActivityLocked(null);
4983
4984 // All activities that came from the package must be
4985 // restarted as if there was a config change.
Craig Mautneraab647e2013-02-28 16:31:36 -08004986 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4987 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4988 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4989 final ActivityRecord a = activities.get(activityNdx);
4990 if (a.info.packageName.equals(packageName)) {
4991 a.forceNewConfig = true;
4992 if (starting != null && a == starting && a.visible) {
4993 a.startFreezingScreenLocked(starting.app,
4994 ActivityInfo.CONFIG_SCREEN_LAYOUT);
4995 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004996 }
4997 }
4998 }
4999
5000 return starting;
5001 }
Craig Mautner5d9c7be2013-02-15 14:02:56 -08005002
Craig Mautner0247fc82013-02-28 14:32:06 -08005003 private void removeActivity(ActivityRecord r) {
5004 final TaskRecord task = r.task;
Craig Mautnerd2328952013-03-05 12:46:26 -08005005 // TODO: use ActivityManagerService.removeTask to do this.
Craig Mautner0247fc82013-02-28 14:32:06 -08005006 if (task.removeActivity(r)) {
5007 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "removeActivity: Removing from history, task="
5008 + task);
5009 mTaskHistory.remove(task);
Craig Mautner0247fc82013-02-28 14:32:06 -08005010 }
5011 }
5012
5013 private void setTask(ActivityRecord r, TaskRecord newTask, ThumbnailHolder newThumbHolder,
5014 boolean isRoot) {
5015 if (r.task != null) {
5016 removeActivity(r);
5017 }
5018 r.setTask(newTask, newThumbHolder, isRoot);
5019 }
5020
Craig Mautner5d9c7be2013-02-15 14:02:56 -08005021 private TaskRecord createTaskRecord(int taskId, ActivityInfo info, Intent intent,
5022 boolean toTop) {
Craig Mautnerd2328952013-03-05 12:46:26 -08005023 TaskRecord task = new TaskRecord(taskId, info, intent, this);
Craig Mautner5d9c7be2013-02-15 14:02:56 -08005024 if (toTop) {
5025 mTaskHistory.add(task);
5026 } else {
5027 mTaskHistory.add(0, task);
5028 }
5029 return task;
5030 }
Craig Mautnerc00204b2013-03-05 15:02:14 -08005031
5032 ArrayList<TaskRecord> getAllTasks() {
5033 return new ArrayList<TaskRecord>(mTaskHistory);
5034 }
5035
5036 void moveTask(int taskId, boolean toTop) {
5037 final TaskRecord task = mService.anyTaskForIdLocked(taskId);
5038 if (task == null) {
5039 return;
5040 }
5041 task.stack.mTaskHistory.remove(task);
5042 task.stack = this;
5043 if (toTop) {
5044 mTaskHistory.add(task);
5045 } else {
5046 mTaskHistory.add(0, task);
5047 }
5048 }
5049
5050 public int getStackId() {
5051 return mStackId;
5052 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005053}