blob: dd3a186dd64f84a9dfeca713c76c3138740cf471 [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;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800155
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700156 final Context mContext;
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800157
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700158 /**
159 * The back history of all previous (and possibly still
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800160 * running) activities. It contains #TaskRecord objects.
161 */
162 private ArrayList<TaskRecord> mTaskHistory = new ArrayList<TaskRecord>();
163
164 /**
Dianne Hackbornbe707852011-11-11 14:32:10 -0800165 * Used for validating app tokens with window manager.
166 */
Craig Mautnerb1fd65c02013-02-05 13:34:57 -0800167 final ArrayList<TaskGroup> mValidateAppTokens = new ArrayList<TaskGroup>();
Dianne Hackbornbe707852011-11-11 14:32:10 -0800168
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700169 /**
170 * List of running activities, sorted by recent usage.
171 * The first entry in the list is the least recently used.
172 * It contains HistoryRecord objects.
173 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700174 final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700175
176 /**
177 * List of activities that are waiting for a new activity
178 * to become visible before completing whatever operation they are
179 * supposed to do.
180 */
181 final ArrayList<ActivityRecord> mWaitingVisibleActivities
182 = new ArrayList<ActivityRecord>();
183
184 /**
185 * List of activities that are ready to be stopped, but waiting
186 * for the next activity to settle down before doing so. It contains
187 * HistoryRecord objects.
188 */
189 final ArrayList<ActivityRecord> mStoppingActivities
190 = new ArrayList<ActivityRecord>();
191
192 /**
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800193 * List of activities that are in the process of going to sleep.
194 */
195 final ArrayList<ActivityRecord> mGoingToSleepActivities
196 = new ArrayList<ActivityRecord>();
197
198 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700199 * Animations that for the current transition have requested not to
200 * be considered for the transition animation.
201 */
202 final ArrayList<ActivityRecord> mNoAnimActivities
203 = new ArrayList<ActivityRecord>();
204
205 /**
206 * List of activities that are ready to be finished, but waiting
207 * for the previous activity to settle down before doing so. It contains
208 * HistoryRecord objects.
209 */
210 final ArrayList<ActivityRecord> mFinishingActivities
211 = new ArrayList<ActivityRecord>();
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800212
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700213 /**
214 * List of people waiting to find out about the next launched activity.
215 */
216 final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched
217 = new ArrayList<IActivityManager.WaitResult>();
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800218
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700219 /**
220 * List of people waiting to find out about the next visible activity.
221 */
222 final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible
223 = new ArrayList<IActivityManager.WaitResult>();
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700224
225 final ArrayList<UserStartedState> mStartingUsers
226 = new ArrayList<UserStartedState>();
227
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700228 /**
229 * Set when the system is going to sleep, until we have
230 * successfully paused the current activity and released our wake lock.
231 * At that point the system is allowed to actually sleep.
232 */
233 final PowerManager.WakeLock mGoingToSleep;
234
235 /**
236 * We don't want to allow the device to go to sleep while in the process
237 * of launching an activity. This is primarily to allow alarm intent
238 * receivers to launch an activity and get that to run before the device
239 * goes back to sleep.
240 */
241 final PowerManager.WakeLock mLaunchingActivity;
242
243 /**
244 * When we are in the process of pausing an activity, before starting the
245 * next one, this variable holds the activity that is currently being paused.
246 */
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800247 ActivityRecord mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700248
249 /**
250 * This is the last activity that we put into the paused state. This is
251 * used to determine if we need to do an activity transition while sleeping,
252 * when we normally hold the top activity paused.
253 */
254 ActivityRecord mLastPausedActivity = null;
255
256 /**
257 * Current activity that is resumed, or null if there is none.
258 */
259 ActivityRecord mResumedActivity = null;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800260
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700261 /**
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700262 * This is the last activity that has been started. It is only used to
263 * identify when multiple activities are started at once so that the user
264 * can be warned they may not be in the activity they think they are.
265 */
266 ActivityRecord mLastStartedActivity = null;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800267
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700268 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700269 * Set when we know we are going to be calling updateConfiguration()
270 * soon, so want to skip intermediate config checks.
271 */
272 boolean mConfigWillChange;
273
274 /**
275 * Set to indicate whether to issue an onUserLeaving callback when a
276 * newly launched activity is being brought in front of us.
277 */
278 boolean mUserLeaving = false;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800279
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700280 long mInitialStartTime = 0;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800281
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800282 /**
283 * Set when we have taken too long waiting to go to sleep.
284 */
285 boolean mSleepTimeout = false;
286
Dianne Hackborn90c52de2011-09-23 12:57:44 -0700287 /**
Craig Mautnerb12428a2012-12-20 16:07:06 -0800288 * Save the most recent screenshot for reuse. This keeps Recents from taking two identical
289 * screenshots, one for the Recents thumbnail and one for the pauseActivity thumbnail.
290 */
291 private ActivityRecord mLastScreenshotActivity = null;
292 private Bitmap mLastScreenshotBitmap = null;
293
Craig Mautnercae015f2013-02-08 14:31:27 -0800294 /**
295 * List of ActivityRecord objects that have been finished and must
296 * still report back to a pending thumbnail receiver.
297 */
298 private final ArrayList<ActivityRecord> mCancelledThumbnails = new ArrayList<ActivityRecord>();
299
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800300 int mThumbnailWidth = -1;
301 int mThumbnailHeight = -1;
302
Amith Yamasani742a6712011-05-04 14:49:28 -0700303 private int mCurrentUser;
304
Craig Mautnerc00204b2013-03-05 15:02:14 -0800305 final int mStackId;
306
Craig Mautner27084302013-03-25 08:05:25 -0700307 /** Run all ActivityStacks through this */
308 final ActivityStackSupervisor mStackSupervisor;
309
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800310 static final int SLEEP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG;
311 static final int PAUSE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 1;
312 static final int IDLE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 2;
313 static final int IDLE_NOW_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 3;
314 static final int LAUNCH_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 4;
315 static final int DESTROY_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 5;
316 static final int RESUME_TOP_ACTIVITY_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 6;
Dianne Hackborn29ba7e62012-03-16 15:03:36 -0700317 static final int LAUNCH_TICK_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 7;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700318 static final int STOP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 8;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700319 static final int DESTROY_ACTIVITIES_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 9;
320
321 static class ScheduleDestroyArgs {
322 final ProcessRecord mOwner;
323 final boolean mOomAdj;
324 final String mReason;
325 ScheduleDestroyArgs(ProcessRecord owner, boolean oomAdj, String reason) {
326 mOwner = owner;
327 mOomAdj = oomAdj;
328 mReason = reason;
329 }
330 }
331
Zoran Marcetaf958b322012-08-09 20:27:12 +0900332 final Handler mHandler;
333
334 final class ActivityStackHandler extends Handler {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700335 //public Handler() {
336 // if (localLOGV) Slog.v(TAG, "Handler started!");
337 //}
Zoran Marcetaf958b322012-08-09 20:27:12 +0900338 public ActivityStackHandler(Looper looper) {
339 super(looper);
340 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700341
Zoran Marcetaf958b322012-08-09 20:27:12 +0900342 @Override
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700343 public void handleMessage(Message msg) {
344 switch (msg.what) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800345 case SLEEP_TIMEOUT_MSG: {
Dianne Hackborn8e8d65f2011-08-11 19:36:18 -0700346 synchronized (mService) {
347 if (mService.isSleeping()) {
348 Slog.w(TAG, "Sleep timeout! Sleeping now.");
349 mSleepTimeout = true;
350 checkReadyForSleepLocked();
351 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800352 }
353 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700354 case PAUSE_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800355 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700356 // We don't at this point know if the activity is fullscreen,
357 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800358 Slog.w(TAG, "Activity pause timeout for " + r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700359 synchronized (mService) {
360 if (r.app != null) {
361 mService.logAppTooSlow(r.app, r.pauseTime,
362 "pausing " + r);
363 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700364
Craig Mautnerd2328952013-03-05 12:46:26 -0800365 activityPausedLocked(r != null ? r.appToken : null, true);
366 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700367 } break;
368 case IDLE_TIMEOUT_MSG: {
369 if (mService.mDidDexOpt) {
370 mService.mDidDexOpt = false;
371 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
372 nmsg.obj = msg.obj;
373 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
374 return;
375 }
376 // We don't at this point know if the activity is fullscreen,
377 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800378 ActivityRecord r = (ActivityRecord)msg.obj;
379 Slog.w(TAG, "Activity idle timeout for " + r);
380 activityIdleInternal(r != null ? r.appToken : null, true, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700381 } break;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700382 case LAUNCH_TICK_MSG: {
383 ActivityRecord r = (ActivityRecord)msg.obj;
384 synchronized (mService) {
385 if (r.continueLaunchTickingLocked()) {
386 mService.logAppTooSlow(r.app, r.launchTickTime,
387 "launching " + r);
388 }
389 }
390 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700391 case DESTROY_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800392 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700393 // We don't at this point know if the activity is fullscreen,
394 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800395 Slog.w(TAG, "Activity destroy timeout for " + r);
Craig Mautnerd2328952013-03-05 12:46:26 -0800396 synchronized (mService) {
397 activityDestroyedLocked(r != null ? r.appToken : null);
398 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700399 } break;
400 case IDLE_NOW_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800401 ActivityRecord r = (ActivityRecord)msg.obj;
402 activityIdleInternal(r != null ? r.appToken : null, false, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700403 } break;
404 case LAUNCH_TIMEOUT_MSG: {
405 if (mService.mDidDexOpt) {
406 mService.mDidDexOpt = false;
407 Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
408 mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
409 return;
410 }
411 synchronized (mService) {
412 if (mLaunchingActivity.isHeld()) {
413 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
414 mLaunchingActivity.release();
415 }
416 }
417 } break;
418 case RESUME_TOP_ACTIVITY_MSG: {
419 synchronized (mService) {
420 resumeTopActivityLocked(null);
421 }
422 } break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700423 case STOP_TIMEOUT_MSG: {
424 ActivityRecord r = (ActivityRecord)msg.obj;
425 // We don't at this point know if the activity is fullscreen,
426 // so we need to be conservative and assume it isn't.
427 Slog.w(TAG, "Activity stop timeout for " + r);
428 synchronized (mService) {
429 if (r.isInHistory()) {
430 activityStoppedLocked(r, null, null, null);
431 }
432 }
433 } break;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700434 case DESTROY_ACTIVITIES_MSG: {
435 ScheduleDestroyArgs args = (ScheduleDestroyArgs)msg.obj;
436 synchronized (mService) {
437 destroyActivitiesLocked(args.mOwner, args.mOomAdj, args.mReason);
438 }
439 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700440 }
441 }
Craig Mautner4b71aa12012-12-27 17:20:01 -0800442 }
443
Craig Mautner000f0022013-02-26 15:04:29 -0800444 private int numActivities() {
445 int count = 0;
446 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
447 count += mTaskHistory.get(taskNdx).mActivities.size();
448 }
449 return count;
450 }
451
Craig Mautner2219a1b2013-03-25 09:44:30 -0700452 ActivityStack(ActivityManagerService service, Context context, Looper looper, int stackId,
453 ActivityStackSupervisor supervisor) {
Zoran Marcetaf958b322012-08-09 20:27:12 +0900454 mHandler = new ActivityStackHandler(looper);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700455 mService = service;
456 mContext = context;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700457 PowerManager pm =
458 (PowerManager)context.getSystemService(Context.POWER_SERVICE);
459 mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
460 mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
461 mLaunchingActivity.setReferenceCounted(false);
Craig Mautnerc00204b2013-03-05 15:02:14 -0800462 mStackId = stackId;
Craig Mautner27084302013-03-25 08:05:25 -0700463 mStackSupervisor = supervisor;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700464 }
Craig Mautner5962b122012-10-05 14:45:52 -0700465
466 private boolean okToShow(ActivityRecord r) {
467 return r.userId == mCurrentUser
468 || (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0;
469 }
470
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700471 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800472 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
473 final TaskRecord task = mTaskHistory.get(taskNdx);
Craig Mautner11bf9a52013-02-19 14:08:51 -0800474 final ArrayList<ActivityRecord> activities = task.mActivities;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800475 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
476 ActivityRecord r = activities.get(activityNdx);
Craig Mautner11bf9a52013-02-19 14:08:51 -0800477 if (!r.finishing && r != notTop && okToShow(r)) {
478 return r;
479 }
480 }
481 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700482 return null;
483 }
484
485 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800486 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
487 final TaskRecord task = mTaskHistory.get(taskNdx);
Craig Mautner11bf9a52013-02-19 14:08:51 -0800488 final ArrayList<ActivityRecord> activities = task.mActivities;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800489 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
490 ActivityRecord r = activities.get(activityNdx);
Craig Mautner11bf9a52013-02-19 14:08:51 -0800491 if (!r.finishing && !r.delayedResume && r != notTop && okToShow(r)) {
492 return r;
493 }
494 }
495 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700496 return null;
497 }
498
499 /**
500 * This is a simplified version of topRunningActivityLocked that provides a number of
501 * optional skip-over modes. It is intended for use with the ActivityController hook only.
Craig Mautner9658b312013-02-28 10:55:59 -0800502 *
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700503 * @param token If non-null, any history records matching this token will be skipped.
504 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
Craig Mautner9658b312013-02-28 10:55:59 -0800505 *
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700506 * @return Returns the HistoryRecord of the next activity on the stack.
507 */
508 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
Craig Mautner11bf9a52013-02-19 14:08:51 -0800509 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
510 TaskRecord task = mTaskHistory.get(taskNdx);
511 if (task.taskId == taskId) {
512 continue;
513 }
514 ArrayList<ActivityRecord> activities = task.mActivities;
515 for (int i = activities.size() - 1; i >= 0; --i) {
516 final ActivityRecord r = activities.get(i);
517 // Note: the taskId check depends on real taskId fields being non-zero
518 if (!r.finishing && (token != r.appToken) && okToShow(r)) {
519 return r;
520 }
521 }
522 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700523 return null;
524 }
525
Craig Mautnerd2328952013-03-05 12:46:26 -0800526 TaskRecord taskForIdLocked(int id) {
527 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
528 final TaskRecord task = mTaskHistory.get(taskNdx);
529 if (task.taskId == id) {
530 return task;
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800531 }
532 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700533 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700534 }
535
Craig Mautnerd2328952013-03-05 12:46:26 -0800536 ActivityRecord isInStackLocked(IBinder token) {
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800537 final ActivityRecord r = ActivityRecord.forToken(token);
Craig Mautnerd2328952013-03-05 12:46:26 -0800538 if (r != null) {
539 final TaskRecord task = r.task;
540 if (task.mActivities.contains(r) && mTaskHistory.contains(task)) {
541 if (task.stack != this) Slog.w(TAG,
542 "Illegal state! task does not point to stack it is in.");
543 return r;
544 }
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800545 }
Craig Mautnerd2328952013-03-05 12:46:26 -0800546 return null;
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800547 }
548
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700549 private final boolean updateLRUListLocked(ActivityRecord r) {
550 final boolean hadit = mLRUActivities.remove(r);
551 mLRUActivities.add(r);
552 return hadit;
553 }
554
555 /**
556 * Returns the top activity in any existing task matching the given
557 * Intent. Returns null if no such task is found.
558 */
559 private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
560 ComponentName cls = intent.getComponent();
561 if (info.targetActivity != null) {
562 cls = new ComponentName(info.packageName, info.targetActivity);
563 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700564 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Craig Mautner000f0022013-02-26 15:04:29 -0800565
566 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
567 final TaskRecord task = mTaskHistory.get(taskNdx);
568 final ActivityRecord r = task.getTopActivity();
569 if (r == null || r.finishing || r.userId != userId ||
570 r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
571 continue;
572 }
573
574 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
575 // + "/aff=" + r.task.affinity + " to new cls="
576 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
577 if (task.affinity != null) {
578 if (task.affinity.equals(info.taskAffinity)) {
579 //Slog.i(TAG, "Found matching affinity!");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700580 return r;
581 }
Craig Mautner000f0022013-02-26 15:04:29 -0800582 } else if (task.intent != null && task.intent.getComponent().equals(cls)) {
583 //Slog.i(TAG, "Found matching class!");
584 //dump();
585 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
586 return r;
587 } else if (task.affinityIntent != null
588 && task.affinityIntent.getComponent().equals(cls)) {
589 //Slog.i(TAG, "Found matching class!");
590 //dump();
591 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
592 return r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700593 }
594 }
595
596 return null;
597 }
598
599 /**
600 * Returns the first activity (starting from the top of the stack) that
601 * is the same as the given activity. Returns null if no such activity
602 * is found.
603 */
604 private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
605 ComponentName cls = intent.getComponent();
606 if (info.targetActivity != null) {
607 cls = new ComponentName(info.packageName, info.targetActivity);
608 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700609 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700610
Craig Mautner000f0022013-02-26 15:04:29 -0800611 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
612 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
613 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
614 ActivityRecord r = activities.get(activityNdx);
615 if (!r.finishing && r.intent.getComponent().equals(cls) && r.userId == userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700616 //Slog.i(TAG, "Found matching class!");
617 //dump();
618 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
619 return r;
620 }
621 }
622 }
623
624 return null;
625 }
626
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700627 final void showAskCompatModeDialogLocked(ActivityRecord r) {
628 Message msg = Message.obtain();
629 msg.what = ActivityManagerService.SHOW_COMPAT_MODE_DIALOG_MSG;
630 msg.obj = r.task.askedCompatMode ? null : r;
631 mService.mHandler.sendMessage(msg);
632 }
633
Amith Yamasani742a6712011-05-04 14:49:28 -0700634 /*
635 * Move the activities around in the stack to bring a user to the foreground.
636 * @return whether there are any activities for the specified user.
637 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700638 final boolean switchUserLocked(int userId, UserStartedState uss) {
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800639 if (VALIDATE_TOKENS) {
640 validateAppTokensLocked();
641 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700642 mStartingUsers.add(uss);
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800643 if (mCurrentUser == userId) {
644 return true;
645 }
646 mCurrentUser = userId;
647
648 // Move userId's tasks to the top.
649 boolean haveActivities = false;
650 TaskRecord task = null;
651 int index = mTaskHistory.size();
652 for (int i = 0; i < index; ++i) {
653 task = mTaskHistory.get(i);
654 if (task.userId == userId) {
655 haveActivities = true;
656 mTaskHistory.remove(i);
657 mTaskHistory.add(task);
658 --index;
659 }
660 }
661
662 // task is now the original topmost TaskRecord. Transition from the old top to the new top.
663 ActivityRecord top = task != null ? task.getTopActivity() : null;
Craig Mautner000f0022013-02-26 15:04:29 -0800664 resumeTopActivityLocked(top);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700665 return haveActivities;
Amith Yamasani742a6712011-05-04 14:49:28 -0700666 }
667
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700668 final boolean realStartActivityLocked(ActivityRecord r,
669 ProcessRecord app, boolean andResume, boolean checkConfig)
670 throws RemoteException {
671
672 r.startFreezingScreenLocked(app, 0);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800673 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700674
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700675 // schedule launch ticks to collect information about slow apps.
676 r.startLaunchTickingLocked();
677
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700678 // Have the window manager re-evaluate the orientation of
679 // the screen based on the new activity order. Note that
680 // as a result of this, it can call back into the activity
681 // manager with a new orientation. We don't care about that,
682 // because the activity is not currently running so we are
683 // just restarting it anyway.
684 if (checkConfig) {
685 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
686 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -0800687 r.mayFreezeScreenLocked(app) ? r.appToken : null);
Dianne Hackborn813075a62011-11-14 17:45:19 -0800688 mService.updateConfigurationLocked(config, r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700689 }
690
691 r.app = app;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700692 app.waitingToKill = null;
Dianne Hackborn07981492013-01-28 11:36:23 -0800693 r.launchCount++;
694 r.lastLaunchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700695
696 if (localLOGV) Slog.v(TAG, "Launching: " + r);
697
698 int idx = app.activities.indexOf(r);
699 if (idx < 0) {
700 app.activities.add(r);
701 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -0700702 mService.updateLruProcessLocked(app, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700703
704 try {
705 if (app.thread == null) {
706 throw new RemoteException();
707 }
708 List<ResultInfo> results = null;
709 List<Intent> newIntents = null;
710 if (andResume) {
711 results = r.results;
712 newIntents = r.newIntents;
713 }
714 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
715 + " icicle=" + r.icicle
716 + " with results=" + results + " newIntents=" + newIntents
717 + " andResume=" + andResume);
718 if (andResume) {
719 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -0700720 r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700721 r.task.taskId, r.shortComponentName);
722 }
723 if (r.isHomeActivity) {
724 mService.mHomeProcess = app;
725 }
726 mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800727 r.sleeping = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400728 r.forceNewConfig = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700729 showAskCompatModeDialogLocked(r);
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700730 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700731 String profileFile = null;
732 ParcelFileDescriptor profileFd = null;
733 boolean profileAutoStop = false;
734 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
735 if (mService.mProfileProc == null || mService.mProfileProc == app) {
736 mService.mProfileProc = app;
737 profileFile = mService.mProfileFile;
738 profileFd = mService.mProfileFd;
739 profileAutoStop = mService.mAutoStopProfiler;
740 }
741 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -0700742 app.hasShownUi = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700743 app.pendingUiClean = true;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700744 if (profileFd != null) {
745 try {
746 profileFd = profileFd.dup();
747 } catch (IOException e) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -0800748 if (profileFd != null) {
749 try {
750 profileFd.close();
751 } catch (IOException o) {
752 }
753 profileFd = null;
754 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700755 }
756 }
Dianne Hackbornbe707852011-11-11 14:32:10 -0800757 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
Dianne Hackborn813075a62011-11-14 17:45:19 -0800758 System.identityHashCode(r), r.info,
759 new Configuration(mService.mConfiguration),
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700760 r.compat, r.icicle, results, newIntents, !andResume,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700761 mService.isNextTransitionForward(), profileFile, profileFd,
762 profileAutoStop);
Craig Mautner9658b312013-02-28 10:55:59 -0800763
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700764 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700765 // This may be a heavy-weight process! Note that the package
766 // manager will ensure that only activity can run in the main
767 // process of the .apk, which is the only thing that will be
768 // considered heavy-weight.
769 if (app.processName.equals(app.info.packageName)) {
770 if (mService.mHeavyWeightProcess != null
771 && mService.mHeavyWeightProcess != app) {
772 Log.w(TAG, "Starting new heavy weight process " + app
773 + " when already running "
774 + mService.mHeavyWeightProcess);
775 }
776 mService.mHeavyWeightProcess = app;
777 Message msg = mService.mHandler.obtainMessage(
778 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
779 msg.obj = r;
780 mService.mHandler.sendMessage(msg);
781 }
782 }
Craig Mautner9658b312013-02-28 10:55:59 -0800783
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700784 } catch (RemoteException e) {
785 if (r.launchFailed) {
786 // This is the second time we failed -- finish activity
787 // and give up.
788 Slog.e(TAG, "Second failure launching "
789 + r.intent.getComponent().flattenToShortString()
790 + ", giving up", e);
791 mService.appDiedLocked(app, app.pid, app.thread);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800792 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700793 "2nd-crash", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700794 return false;
795 }
796
797 // This is the first time we failed -- restart process and
798 // retry.
799 app.activities.remove(r);
800 throw e;
801 }
802
803 r.launchFailed = false;
804 if (updateLRUListLocked(r)) {
805 Slog.w(TAG, "Activity " + r
806 + " being launched, but already in LRU list");
807 }
808
809 if (andResume) {
810 // As part of the process of launching, ActivityThread also performs
811 // a resume.
812 r.state = ActivityState.RESUMED;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700813 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
814 + " (starting new instance)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700815 r.stopped = false;
816 mResumedActivity = r;
817 r.task.touchActiveTime();
Craig Mautnerd2328952013-03-05 12:46:26 -0800818 mService.addRecentTaskLocked(r.task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700819 completeResumeLocked(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800820 checkReadyForSleepLocked();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700821 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Launch completed; removing icicle of " + r.icicle);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700822 } else {
823 // This activity is not starting in the resumed state... which
824 // should look like we asked it to pause+stop (but remain visible),
825 // and it has done so and reported back the current icicle and
826 // other state.
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700827 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
828 + " (starting in stopped state)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700829 r.state = ActivityState.STOPPED;
830 r.stopped = true;
831 }
832
833 // Launch the new version setup screen if needed. We do this -after-
834 // launching the initial activity (that is, home), so that it can have
835 // a chance to initialize itself while in the background, making the
836 // switch back to it faster and look better.
Craig Mautner2219a1b2013-03-25 09:44:30 -0700837 if (mStackSupervisor.isMainStack(this)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700838 mService.startSetupActivityLocked();
839 }
Craig Mautner9658b312013-02-28 10:55:59 -0800840
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700841 return true;
842 }
843
844 private final void startSpecificActivityLocked(ActivityRecord r,
845 boolean andResume, boolean checkConfig) {
846 // Is this activity's application already running?
847 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
848 r.info.applicationInfo.uid);
Dianne Hackborn07981492013-01-28 11:36:23 -0800849
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700850 if (r.launchTime == 0) {
851 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700852 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700853 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700854 }
855 } else if (mInitialStartTime == 0) {
856 mInitialStartTime = SystemClock.uptimeMillis();
857 }
Craig Mautneraab647e2013-02-28 16:31:36 -0800858
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700859 if (app != null && app.thread != null) {
860 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700861 app.addPackage(r.info.packageName);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700862 realStartActivityLocked(r, app, andResume, checkConfig);
863 return;
864 } catch (RemoteException e) {
865 Slog.w(TAG, "Exception when starting activity "
866 + r.intent.getComponent().flattenToShortString(), e);
867 }
868
869 // If a dead object exception was thrown -- fall through to
870 // restart the application.
871 }
872
873 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800874 "activity", r.intent.getComponent(), false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700875 }
Craig Mautneraab647e2013-02-28 16:31:36 -0800876
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800877 void stopIfSleepingLocked() {
878 if (mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700879 if (!mGoingToSleep.isHeld()) {
880 mGoingToSleep.acquire();
881 if (mLaunchingActivity.isHeld()) {
882 mLaunchingActivity.release();
883 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
884 }
885 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800886 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
887 Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
888 mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
889 checkReadyForSleepLocked();
890 }
891 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700892
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800893 void awakeFromSleepingLocked() {
894 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
895 mSleepTimeout = false;
896 if (mGoingToSleep.isHeld()) {
897 mGoingToSleep.release();
898 }
899 // Ensure activities are no longer sleeping.
Craig Mautnerd44711d2013-02-23 11:24:36 -0800900 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
901 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
902 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
903 activities.get(activityNdx).setSleeping(false);
904 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800905 }
906 mGoingToSleepActivities.clear();
907 }
908
909 void activitySleptLocked(ActivityRecord r) {
910 mGoingToSleepActivities.remove(r);
911 checkReadyForSleepLocked();
912 }
913
914 void checkReadyForSleepLocked() {
915 if (!mService.isSleeping()) {
916 // Do not care.
917 return;
918 }
919
920 if (!mSleepTimeout) {
921 if (mResumedActivity != null) {
922 // Still have something resumed; can't sleep until it is paused.
923 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700924 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
925 startPausingLocked(false, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800926 return;
927 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800928 if (mPausingActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800929 // Still waiting for something to pause; can't sleep yet.
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800930 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800931 return;
932 }
933
934 if (mStoppingActivities.size() > 0) {
935 // Still need to tell some activities to stop; can't sleep yet.
936 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
937 + mStoppingActivities.size() + " activities");
Dianne Hackborn80a7ac12011-09-22 18:32:52 -0700938 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800939 return;
940 }
941
942 ensureActivitiesVisibleLocked(null, 0);
943
944 // Make sure any stopped but visible activities are now sleeping.
945 // This ensures that the activity's onStop() is called.
Craig Mautnerd44711d2013-02-23 11:24:36 -0800946 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
947 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
948 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
949 final ActivityRecord r = activities.get(activityNdx);
950 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
951 r.setSleeping(true);
952 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800953 }
954 }
955
956 if (mGoingToSleepActivities.size() > 0) {
957 // Still need to tell some activities to sleep; can't sleep yet.
958 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
959 + mGoingToSleepActivities.size() + " activities");
960 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700961 }
962 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800963
964 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
965
966 if (mGoingToSleep.isHeld()) {
967 mGoingToSleep.release();
968 }
969 if (mService.mShuttingDown) {
970 mService.notifyAll();
971 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700972 }
Craig Mautner59c00972012-07-30 12:10:24 -0700973
Dianne Hackbornd2835932010-12-13 16:28:46 -0800974 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -0800975 if (who.noDisplay) {
976 return null;
977 }
Craig Mautneraab647e2013-02-28 16:31:36 -0800978
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800979 Resources res = mService.mContext.getResources();
980 int w = mThumbnailWidth;
981 int h = mThumbnailHeight;
982 if (w < 0) {
983 mThumbnailWidth = w =
984 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
985 mThumbnailHeight = h =
986 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
987 }
988
989 if (w > 0) {
Craig Mautnerb12428a2012-12-20 16:07:06 -0800990 if (who != mLastScreenshotActivity || mLastScreenshotBitmap == null
991 || mLastScreenshotBitmap.getWidth() != w
992 || mLastScreenshotBitmap.getHeight() != h) {
993 mLastScreenshotActivity = who;
994 mLastScreenshotBitmap = mService.mWindowManager.screenshotApplications(
995 who.appToken, Display.DEFAULT_DISPLAY, w, h);
996 }
997 if (mLastScreenshotBitmap != null) {
998 return mLastScreenshotBitmap.copy(Config.ARGB_8888, true);
999 }
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001000 }
1001 return null;
1002 }
1003
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001004 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001005 if (mPausingActivity != null) {
1006 RuntimeException e = new RuntimeException();
1007 Slog.e(TAG, "Trying to pause when pause is already pending for "
1008 + mPausingActivity, e);
1009 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001010 ActivityRecord prev = mResumedActivity;
1011 if (prev == null) {
1012 RuntimeException e = new RuntimeException();
1013 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
1014 resumeTopActivityLocked(null);
1015 return;
1016 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001017 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
1018 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001019 mResumedActivity = null;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001020 mPausingActivity = prev;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001021 mLastPausedActivity = prev;
1022 prev.state = ActivityState.PAUSING;
1023 prev.task.touchActiveTime();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001024 prev.updateThumbnail(screenshotActivities(prev), null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001025
1026 mService.updateCpuStats();
Craig Mautneraab647e2013-02-28 16:31:36 -08001027
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001028 if (prev.app != null && prev.app.thread != null) {
1029 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
1030 try {
1031 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001032 prev.userId, System.identityHashCode(prev),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001033 prev.shortComponentName);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001034 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
1035 userLeaving, prev.configChangeFlags);
Craig Mautner2219a1b2013-03-25 09:44:30 -07001036 if (mStackSupervisor.isMainStack(this)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001037 mService.updateUsageStats(prev, false);
1038 }
1039 } catch (Exception e) {
1040 // Ignore exception, if process died other code will cleanup.
1041 Slog.w(TAG, "Exception thrown during pause", e);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001042 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001043 mLastPausedActivity = null;
1044 }
1045 } else {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001046 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001047 mLastPausedActivity = null;
1048 }
1049
1050 // If we are not going to sleep, we want to ensure the device is
1051 // awake until the next activity is started.
1052 if (!mService.mSleeping && !mService.mShuttingDown) {
1053 mLaunchingActivity.acquire();
1054 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
1055 // To be safe, don't allow the wake lock to be held for too long.
1056 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
1057 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
1058 }
1059 }
1060
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001061
1062 if (mPausingActivity != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001063 // Have the window manager pause its key dispatching until the new
1064 // activity has started. If we're pausing the activity just because
1065 // the screen is being turned off and the UI is sleeping, don't interrupt
1066 // key dispatch; the same activity will pick it up again on wakeup.
1067 if (!uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001068 prev.pauseKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001069 } else {
1070 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
1071 }
1072
1073 // Schedule a pause timeout in case the app doesn't respond.
1074 // We don't give it much time because this directly impacts the
1075 // responsiveness seen by the user.
1076 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
1077 msg.obj = prev;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001078 prev.pauseTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001079 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
1080 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
1081 } else {
1082 // This activity failed to schedule the
1083 // pause, so just treat it as being paused now.
1084 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001085 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001086 }
1087 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001088
Craig Mautnerd2328952013-03-05 12:46:26 -08001089 final void activityResumedLocked(IBinder token) {
1090 final ActivityRecord r = ActivityRecord.forToken(token);
1091 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Resumed activity; dropping state of: " + r);
1092 r.icicle = null;
1093 r.haveState = false;
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001094 }
1095
Craig Mautnerd2328952013-03-05 12:46:26 -08001096 final void activityPausedLocked(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001097 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001098 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001099
Craig Mautnerd2328952013-03-05 12:46:26 -08001100 final ActivityRecord r = isInStackLocked(token);
1101 if (r != null) {
1102 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
1103 if (mPausingActivity == r) {
1104 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
1105 + (timeout ? " (due to timeout)" : " (pause complete)"));
1106 r.state = ActivityState.PAUSED;
1107 completePauseLocked();
1108 } else {
1109 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
1110 r.userId, System.identityHashCode(r), r.shortComponentName,
1111 mPausingActivity != null
1112 ? mPausingActivity.shortComponentName : "(none)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001113 }
1114 }
1115 }
1116
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001117 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
1118 CharSequence description) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07001119 if (r.state != ActivityState.STOPPING) {
1120 Slog.i(TAG, "Activity reported stop, but no longer stopping: " + r);
1121 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1122 return;
1123 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001124 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Saving icicle of " + r + ": " + icicle);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001125 if (icicle != null) {
1126 // If icicle is null, this is happening due to a timeout, so we
1127 // haven't really saved the state.
1128 r.icicle = icicle;
1129 r.haveState = true;
Dianne Hackborn07981492013-01-28 11:36:23 -08001130 r.launchCount = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001131 r.updateThumbnail(thumbnail, description);
1132 }
1133 if (!r.stopped) {
1134 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
1135 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1136 r.stopped = true;
1137 r.state = ActivityState.STOPPED;
Dianne Hackborn6e3d6da2012-06-15 12:05:27 -07001138 if (r.finishing) {
1139 r.clearOptionsLocked();
1140 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001141 if (r.configDestroy) {
1142 destroyActivityLocked(r, true, false, "stop-config");
1143 resumeTopActivityLocked(null);
1144 } else {
1145 // Now that this process has stopped, we may want to consider
1146 // it to be the previous app to try to keep around in case
1147 // the user wants to return to it.
1148 ProcessRecord fgApp = null;
1149 if (mResumedActivity != null) {
1150 fgApp = mResumedActivity.app;
1151 } else if (mPausingActivity != null) {
1152 fgApp = mPausingActivity.app;
1153 }
1154 if (r.app != null && fgApp != null && r.app != fgApp
1155 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
1156 && r.app != mService.mHomeProcess) {
1157 mService.mPreviousProcess = r.app;
1158 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
1159 }
Dianne Hackborn50685602011-12-01 12:23:37 -08001160 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001161 }
1162 }
1163 }
1164
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001165 private final void completePauseLocked() {
1166 ActivityRecord prev = mPausingActivity;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001167 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
Craig Mautneraab647e2013-02-28 16:31:36 -08001168
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001169 if (prev != null) {
1170 if (prev.finishing) {
1171 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001172 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001173 } else if (prev.app != null) {
1174 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
1175 if (prev.waitingVisible) {
1176 prev.waitingVisible = false;
1177 mWaitingVisibleActivities.remove(prev);
1178 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
1179 TAG, "Complete pause, no longer waiting: " + prev);
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001180 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001181 if (prev.configDestroy) {
1182 // The previous is being paused because the configuration
1183 // is changing, which means it is actually stopping...
1184 // To juggle the fact that we are also starting a new
1185 // instance right now, we need to first completely stop
1186 // the current instance before starting the new one.
1187 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
1188 destroyActivityLocked(prev, true, false, "pause-config");
1189 } else {
1190 mStoppingActivities.add(prev);
1191 if (mStoppingActivities.size() > 3) {
1192 // If we already have a few activities waiting to stop,
1193 // then give up on things going idle and start clearing
1194 // them out.
1195 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
1196 scheduleIdleLocked();
1197 } else {
1198 checkReadyForSleepLocked();
1199 }
1200 }
1201 } else {
1202 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
1203 prev = null;
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001204 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001205 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001206 }
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001207
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001208 if (!mService.isSleeping()) {
1209 resumeTopActivityLocked(prev);
1210 } else {
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001211 checkReadyForSleepLocked();
Dianne Hackborncc5a0552012-10-01 16:32:39 -07001212 ActivityRecord top = topRunningActivityLocked(null);
1213 if (top == null || (prev != null && top != prev)) {
1214 // If there are no more activities available to run,
1215 // do resume anyway to start something. Also if the top
1216 // activity on the stack is not the just paused activity,
1217 // we need to go ahead and resume it to ensure we complete
1218 // an in-flight app switch.
Dianne Hackborn42e620c2012-06-24 13:20:51 -07001219 resumeTopActivityLocked(null);
1220 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001221 }
Craig Mautneraab647e2013-02-28 16:31:36 -08001222
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001223 if (prev != null) {
1224 prev.resumeKeyDispatchingLocked();
1225 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001226
1227 if (prev.app != null && prev.cpuTimeAtResume > 0
1228 && mService.mBatteryStatsService.isOnBattery()) {
1229 long diff = 0;
1230 synchronized (mService.mProcessStatsThread) {
1231 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
1232 - prev.cpuTimeAtResume;
1233 }
1234 if (diff > 0) {
1235 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
1236 synchronized (bsi) {
1237 BatteryStatsImpl.Uid.Proc ps =
1238 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
1239 prev.info.packageName);
1240 if (ps != null) {
1241 ps.addForegroundTimeLocked(diff);
1242 }
1243 }
1244 }
1245 }
1246 prev.cpuTimeAtResume = 0; // reset it
1247 }
1248
1249 /**
1250 * Once we know that we have asked an application to put an activity in
1251 * the resumed state (either by launching it or explicitly telling it),
1252 * this function updates the rest of our state to match that fact.
1253 */
1254 private final void completeResumeLocked(ActivityRecord next) {
1255 next.idle = false;
1256 next.results = null;
1257 next.newIntents = null;
1258
1259 // schedule an idle timeout in case the app doesn't do it for us.
1260 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1261 msg.obj = next;
1262 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
1263
1264 if (false) {
1265 // The activity was never told to pause, so just keep
1266 // things going as-is. To maintain our own state,
1267 // we need to emulate it coming back and saying it is
1268 // idle.
1269 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
1270 msg.obj = next;
1271 mHandler.sendMessage(msg);
1272 }
1273
Craig Mautner2219a1b2013-03-25 09:44:30 -07001274 if (mStackSupervisor.isMainStack(this)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001275 mService.reportResumedActivityLocked(next);
1276 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07001277
Craig Mautner2219a1b2013-03-25 09:44:30 -07001278 if (mStackSupervisor.isMainStack(this)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001279 mService.setFocusedActivityLocked(next);
1280 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001281 next.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001282 ensureActivitiesVisibleLocked(null, 0);
1283 mService.mWindowManager.executeAppTransition();
1284 mNoAnimActivities.clear();
1285
1286 // Mark the point when the activity is resuming
1287 // TODO: To be more accurate, the mark should be before the onCreate,
1288 // not after the onResume. But for subsequent starts, onResume is fine.
1289 if (next.app != null) {
1290 synchronized (mService.mProcessStatsThread) {
1291 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1292 }
1293 } else {
1294 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1295 }
1296 }
1297
1298 /**
1299 * Make sure that all activities that need to be visible (that is, they
1300 * currently can be seen by the user) actually are.
1301 */
1302 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1303 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1304 if (DEBUG_VISBILITY) Slog.v(
1305 TAG, "ensureActivitiesVisible behind " + top
1306 + " configChanges=0x" + Integer.toHexString(configChanges));
1307
1308 // If the top activity is not fullscreen, then we need to
1309 // make sure any activities under it are now visible.
Craig Mautnerd44711d2013-02-23 11:24:36 -08001310 boolean aboveTop = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001311 boolean behindFullscreen = false;
Craig Mautnerd44711d2013-02-23 11:24:36 -08001312 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
1313 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
1314 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
1315 final ActivityRecord r = activities.get(activityNdx);
1316 if (r.finishing) {
1317 continue;
1318 }
1319 if (aboveTop && r != top) {
1320 continue;
1321 }
1322 aboveTop = false;
1323 if (!behindFullscreen) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001324 if (DEBUG_VISBILITY) Slog.v(
Craig Mautnerd44711d2013-02-23 11:24:36 -08001325 TAG, "Make visible? " + r + " finishing=" + r.finishing
1326 + " state=" + r.state);
Craig Mautner58547802013-03-05 08:23:53 -08001327
Craig Mautnerd44711d2013-02-23 11:24:36 -08001328 final boolean doThisProcess = onlyThisProcess == null
1329 || onlyThisProcess.equals(r.processName);
1330
1331 // First: if this is not the current activity being started, make
1332 // sure it matches the current configuration.
1333 if (r != starting && doThisProcess) {
1334 ensureActivityConfigurationLocked(r, 0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001335 }
Craig Mautnerd44711d2013-02-23 11:24:36 -08001336
1337 if (r.app == null || r.app.thread == null) {
1338 if (onlyThisProcess == null
1339 || onlyThisProcess.equals(r.processName)) {
1340 // This activity needs to be visible, but isn't even
1341 // running... get it started, but don't resume it
1342 // at this point.
1343 if (DEBUG_VISBILITY) Slog.v(
1344 TAG, "Start and freeze screen for " + r);
1345 if (r != starting) {
1346 r.startFreezingScreenLocked(r.app, configChanges);
1347 }
1348 if (!r.visible) {
1349 if (DEBUG_VISBILITY) Slog.v(
1350 TAG, "Starting and making visible: " + r);
1351 mService.mWindowManager.setAppVisibility(r.appToken, true);
1352 }
1353 if (r != starting) {
1354 startSpecificActivityLocked(r, false, false);
1355 }
1356 }
1357
1358 } else if (r.visible) {
1359 // If this activity is already visible, then there is nothing
1360 // else to do here.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001361 if (DEBUG_VISBILITY) Slog.v(
Craig Mautnerd44711d2013-02-23 11:24:36 -08001362 TAG, "Skipping: already visible at " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001363 r.stopFreezingScreenLocked(false);
Craig Mautnerd44711d2013-02-23 11:24:36 -08001364
1365 } else if (onlyThisProcess == null) {
1366 // This activity is not currently visible, but is running.
1367 // Tell it to become visible.
1368 r.visible = true;
1369 if (r.state != ActivityState.RESUMED && r != starting) {
1370 // If this activity is paused, tell it
1371 // to now show its window.
1372 if (DEBUG_VISBILITY) Slog.v(
1373 TAG, "Making visible and scheduling visibility: " + r);
1374 try {
1375 mService.mWindowManager.setAppVisibility(r.appToken, true);
1376 r.sleeping = false;
1377 r.app.pendingUiClean = true;
1378 r.app.thread.scheduleWindowVisibility(r.appToken, true);
1379 r.stopFreezingScreenLocked(false);
1380 } catch (Exception e) {
1381 // Just skip on any failure; we'll make it
1382 // visible when it next restarts.
1383 Slog.w(TAG, "Exception thrown making visibile: "
1384 + r.intent.getComponent(), e);
1385 }
1386 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001387 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001388
Craig Mautnerd44711d2013-02-23 11:24:36 -08001389 // Aggregate current change flags.
1390 configChanges |= r.configChangeFlags;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001391
Craig Mautnerd44711d2013-02-23 11:24:36 -08001392 if (r.fullscreen) {
1393 // At this point, nothing else needs to be shown
1394 if (DEBUG_VISBILITY) Slog.v(
1395 TAG, "Stopping: fullscreen at " + r);
1396 behindFullscreen = true;
1397 }
1398 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001399 if (r.visible) {
1400 if (DEBUG_VISBILITY) Slog.v(
1401 TAG, "Making invisible: " + r);
1402 r.visible = false;
1403 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001404 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001405 if ((r.state == ActivityState.STOPPING
1406 || r.state == ActivityState.STOPPED)
1407 && r.app != null && r.app.thread != null) {
1408 if (DEBUG_VISBILITY) Slog.v(
1409 TAG, "Scheduling invisibility: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001410 r.app.thread.scheduleWindowVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001411 }
1412 } catch (Exception e) {
1413 // Just skip on any failure; we'll make it
1414 // visible when it next restarts.
1415 Slog.w(TAG, "Exception thrown making hidden: "
1416 + r.intent.getComponent(), e);
1417 }
1418 } else {
1419 if (DEBUG_VISBILITY) Slog.v(
1420 TAG, "Already invisible: " + r);
1421 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001422 }
1423 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001424 }
1425 }
1426
1427 /**
1428 * Version of ensureActivitiesVisible that can easily be called anywhere.
1429 */
1430 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1431 int configChanges) {
1432 ActivityRecord r = topRunningActivityLocked(null);
1433 if (r != null) {
1434 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1435 }
1436 }
Craig Mautner58547802013-03-05 08:23:53 -08001437
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001438 /**
1439 * Ensure that the top activity in the stack is resumed.
1440 *
1441 * @param prev The previously resumed activity, for when in the process
1442 * of pausing; can be null to call from elsewhere.
1443 *
1444 * @return Returns true if something is being resumed, or false if
1445 * nothing happened.
1446 */
1447 final boolean resumeTopActivityLocked(ActivityRecord prev) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001448 return resumeTopActivityLocked(prev, null);
1449 }
1450
1451 final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001452 // Find the first activity that is not finishing.
1453 ActivityRecord next = topRunningActivityLocked(null);
1454
1455 // Remember how we'll process this pause/resume situation, and ensure
1456 // that the state is reset however we wind up proceeding.
1457 final boolean userLeaving = mUserLeaving;
1458 mUserLeaving = false;
1459
1460 if (next == null) {
1461 // There are no more activities! Let's just start up the
1462 // Launcher...
Craig Mautner2219a1b2013-03-25 09:44:30 -07001463 if (mStackSupervisor.isMainStack(this)) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001464 ActivityOptions.abort(options);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001465 return mService.startHomeActivityLocked(mCurrentUser);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001466 }
1467 }
1468
1469 next.delayedResume = false;
Craig Mautner58547802013-03-05 08:23:53 -08001470
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001471 // If the top activity is the resumed one, nothing to do.
1472 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1473 // Make sure we have executed any pending transitions, since there
1474 // should be nothing left to do at this point.
1475 mService.mWindowManager.executeAppTransition();
1476 mNoAnimActivities.clear();
Dianne Hackborn84375872012-06-01 19:03:50 -07001477 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001478 return false;
1479 }
1480
1481 // If we are sleeping, and there is no resumed activity, and the top
1482 // activity is paused, well that is the state we want.
1483 if ((mService.mSleeping || mService.mShuttingDown)
p13451dbad2872012-04-18 11:39:23 +09001484 && mLastPausedActivity == next
1485 && (next.state == ActivityState.PAUSED
1486 || next.state == ActivityState.STOPPED
1487 || next.state == ActivityState.STOPPING)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001488 // Make sure we have executed any pending transitions, since there
1489 // should be nothing left to do at this point.
1490 mService.mWindowManager.executeAppTransition();
1491 mNoAnimActivities.clear();
Dianne Hackborn84375872012-06-01 19:03:50 -07001492 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001493 return false;
1494 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001495
1496 // Make sure that the user who owns this activity is started. If not,
1497 // we will just leave it as is because someone should be bringing
1498 // another user's activities to the top of the stack.
1499 if (mService.mStartedUsers.get(next.userId) == null) {
1500 Slog.w(TAG, "Skipping resume of top activity " + next
1501 + ": user " + next.userId + " is stopped");
1502 return false;
1503 }
1504
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001505 // The activity may be waiting for stop, but that is no longer
1506 // appropriate for it.
1507 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001508 mGoingToSleepActivities.remove(next);
1509 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001510 mWaitingVisibleActivities.remove(next);
1511
Dianne Hackborn84375872012-06-01 19:03:50 -07001512 next.updateOptionsLocked(options);
1513
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001514 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1515
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001516 // If we are currently pausing an activity, then don't do anything
1517 // until that is done.
1518 if (mPausingActivity != null) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07001519 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(TAG,
1520 "Skip resume: pausing=" + mPausingActivity);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001521 return false;
1522 }
1523
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001524 // Okay we are now going to start a switch, to 'next'. We may first
1525 // have to pause the current activity, but this is an important point
1526 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001527 // XXX "App Redirected" dialog is getting too many false positives
1528 // at this point, so turn off for now.
1529 if (false) {
1530 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1531 long now = SystemClock.uptimeMillis();
1532 final boolean inTime = mLastStartedActivity.startTime != 0
1533 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1534 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1535 final int nextUid = next.info.applicationInfo.uid;
1536 if (inTime && lastUid != nextUid
1537 && lastUid != next.launchedFromUid
1538 && mService.checkPermission(
1539 android.Manifest.permission.STOP_APP_SWITCHES,
1540 -1, next.launchedFromUid)
1541 != PackageManager.PERMISSION_GRANTED) {
1542 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1543 } else {
1544 next.startTime = now;
1545 mLastStartedActivity = next;
1546 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001547 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001548 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001549 mLastStartedActivity = next;
1550 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001551 }
Craig Mautner58547802013-03-05 08:23:53 -08001552
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001553 // We need to start pausing the current activity so the top one
1554 // can be resumed...
1555 if (mResumedActivity != null) {
1556 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001557 // At this point we want to put the upcoming activity's process
1558 // at the top of the LRU list, since we know we will be needing it
1559 // very soon and it would be a waste to let it get killed if it
1560 // happens to be sitting towards the end.
1561 if (next.app != null && next.app.thread != null) {
1562 // No reason to do full oom adj update here; we'll let that
1563 // happen whenever it needs to later.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001564 mService.updateLruProcessLocked(next.app, false);
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001565 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001566 startPausingLocked(userLeaving, false);
1567 return true;
1568 }
1569
Christopher Tated3f175c2012-06-14 14:16:54 -07001570 // If the most recent activity was noHistory but was only stopped rather
1571 // than stopped+finished because the device went to sleep, we need to make
1572 // sure to finish it as we're making a new activity topmost.
1573 final ActivityRecord last = mLastPausedActivity;
1574 if (mService.mSleeping && last != null && !last.finishing) {
1575 if ((last.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
1576 || (last.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
1577 if (DEBUG_STATES) {
1578 Slog.d(TAG, "no-history finish of " + last + " on new resume");
1579 }
1580 requestFinishActivityLocked(last.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001581 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07001582 }
1583 }
1584
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001585 if (prev != null && prev != next) {
1586 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1587 prev.waitingVisible = true;
1588 mWaitingVisibleActivities.add(prev);
1589 if (DEBUG_SWITCH) Slog.v(
1590 TAG, "Resuming top, waiting visible to hide: " + prev);
1591 } else {
1592 // The next activity is already visible, so hide the previous
1593 // activity's windows right now so we can show the new one ASAP.
1594 // We only do this if the previous is finishing, which should mean
1595 // it is on top of the one being resumed so hiding it quickly
1596 // is good. Otherwise, we want to do the normal route of allowing
1597 // the resumed activity to be shown so we can decide if the
1598 // previous should actually be hidden depending on whether the
1599 // new one is found to be full-screen or not.
1600 if (prev.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001601 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001602 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1603 + prev + ", waitingVisible="
1604 + (prev != null ? prev.waitingVisible : null)
1605 + ", nowVisible=" + next.nowVisible);
1606 } else {
1607 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1608 + prev + ", waitingVisible="
1609 + (prev != null ? prev.waitingVisible : null)
1610 + ", nowVisible=" + next.nowVisible);
1611 }
1612 }
1613 }
1614
Dianne Hackborne7f97212011-02-24 14:40:20 -08001615 // Launching this app's activity, make sure the app is no longer
1616 // considered stopped.
1617 try {
1618 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001619 next.packageName, false, next.userId); /* TODO: Verify if correct userid */
Dianne Hackborne7f97212011-02-24 14:40:20 -08001620 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001621 } catch (IllegalArgumentException e) {
1622 Slog.w(TAG, "Failed trying to unstop package "
1623 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001624 }
1625
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001626 // We are starting up the next activity, so tell the window manager
1627 // that the previous one will be hidden soon. This way it can know
1628 // to ignore it when computing the desired screen orientation.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001629 boolean noAnim = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001630 if (prev != null) {
1631 if (prev.finishing) {
1632 if (DEBUG_TRANSITION) Slog.v(TAG,
1633 "Prepare close transition: prev=" + prev);
1634 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001635 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001636 AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001637 } else {
1638 mService.mWindowManager.prepareAppTransition(prev.task == next.task
Craig Mautner4b71aa12012-12-27 17:20:01 -08001639 ? AppTransition.TRANSIT_ACTIVITY_CLOSE
1640 : AppTransition.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001641 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001642 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1643 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001644 } else {
1645 if (DEBUG_TRANSITION) Slog.v(TAG,
1646 "Prepare open transition: prev=" + prev);
1647 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001648 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001649 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001650 AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001651 } else {
1652 mService.mWindowManager.prepareAppTransition(prev.task == next.task
Craig Mautner4b71aa12012-12-27 17:20:01 -08001653 ? AppTransition.TRANSIT_ACTIVITY_OPEN
1654 : AppTransition.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001655 }
1656 }
1657 if (false) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001658 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1659 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001660 }
Craig Mautner000f0022013-02-26 15:04:29 -08001661 } else if (numActivities() > 1) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001662 if (DEBUG_TRANSITION) Slog.v(TAG,
1663 "Prepare open transition: no previous");
1664 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001665 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001666 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001667 AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001668 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001669 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001670 AppTransition.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001671 }
1672 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001673 if (!noAnim) {
1674 next.applyOptionsLocked();
1675 } else {
1676 next.clearOptionsLocked();
1677 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001678
1679 if (next.app != null && next.app.thread != null) {
1680 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1681
1682 // This activity is now becoming visible.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001683 mService.mWindowManager.setAppVisibility(next.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001684
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001685 // schedule launch ticks to collect information about slow apps.
1686 next.startLaunchTickingLocked();
1687
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001688 ActivityRecord lastResumedActivity = mResumedActivity;
1689 ActivityState lastState = next.state;
1690
1691 mService.updateCpuStats();
Craig Mautner58547802013-03-05 08:23:53 -08001692
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001693 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001694 next.state = ActivityState.RESUMED;
1695 mResumedActivity = next;
1696 next.task.touchActiveTime();
Craig Mautnerd2328952013-03-05 12:46:26 -08001697 mService.addRecentTaskLocked(next.task);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001698 mService.updateLruProcessLocked(next.app, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001699 updateLRUListLocked(next);
1700
1701 // Have the window manager re-evaluate the orientation of
1702 // the screen based on the new activity order.
1703 boolean updated = false;
Craig Mautner2219a1b2013-03-25 09:44:30 -07001704 if (mStackSupervisor.isMainStack(this)) {
Craig Mautner8d341ef2013-03-26 09:03:27 -07001705 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1706 mService.mConfiguration,
1707 next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
1708 if (config != null) {
1709 next.frozenBeforeDestroy = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001710 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07001711 updated = mService.updateConfigurationLocked(config, next, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001712 }
Craig Mautner8d341ef2013-03-26 09:03:27 -07001713
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001714 if (!updated) {
1715 // The configuration update wasn't able to keep the existing
1716 // instance of the activity, and instead started a new one.
1717 // We should be all done, but let's just make sure our activity
1718 // is still at the top and schedule another run if something
1719 // weird happened.
1720 ActivityRecord nextNext = topRunningActivityLocked(null);
1721 if (DEBUG_SWITCH) Slog.i(TAG,
1722 "Activity config changed during resume: " + next
1723 + ", new next: " + nextNext);
1724 if (nextNext != next) {
1725 // Do over!
1726 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1727 }
Craig Mautner2219a1b2013-03-25 09:44:30 -07001728 if (mStackSupervisor.isMainStack(this)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001729 mService.setFocusedActivityLocked(next);
1730 }
1731 ensureActivitiesVisibleLocked(null, 0);
1732 mService.mWindowManager.executeAppTransition();
1733 mNoAnimActivities.clear();
1734 return true;
1735 }
Craig Mautner58547802013-03-05 08:23:53 -08001736
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001737 try {
1738 // Deliver all pending results.
Craig Mautner05d6272ba2013-02-11 09:39:27 -08001739 ArrayList<ResultInfo> a = next.results;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001740 if (a != null) {
1741 final int N = a.size();
1742 if (!next.finishing && N > 0) {
1743 if (DEBUG_RESULTS) Slog.v(
1744 TAG, "Delivering results to " + next
1745 + ": " + a);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001746 next.app.thread.scheduleSendResult(next.appToken, a);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001747 }
1748 }
1749
1750 if (next.newIntents != null) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001751 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001752 }
1753
1754 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001755 next.userId, System.identityHashCode(next),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001756 next.task.taskId, next.shortComponentName);
Craig Mautner58547802013-03-05 08:23:53 -08001757
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001758 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001759 showAskCompatModeDialogLocked(next);
Dianne Hackborn905577f2011-09-07 18:31:28 -07001760 next.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001761 next.app.thread.scheduleResumeActivity(next.appToken,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001762 mService.isNextTransitionForward());
Craig Mautner58547802013-03-05 08:23:53 -08001763
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001764 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001765
1766 } catch (Exception e) {
1767 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001768 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1769 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001770 next.state = lastState;
1771 mResumedActivity = lastResumedActivity;
1772 Slog.i(TAG, "Restarting because process died: " + next);
1773 if (!next.hasBeenLaunched) {
1774 next.hasBeenLaunched = true;
1775 } else {
Craig Mautner2219a1b2013-03-25 09:44:30 -07001776 if (SHOW_APP_STARTING_PREVIEW && mStackSupervisor.isMainStack(this)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001777 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001778 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001779 mService.compatibilityInfoForPackageLocked(
1780 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001781 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001782 next.labelRes, next.icon, next.windowFlags,
1783 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001784 }
1785 }
1786 startSpecificActivityLocked(next, true, false);
1787 return true;
1788 }
1789
1790 // From this point on, if something goes wrong there is no way
1791 // to recover the activity.
1792 try {
1793 next.visible = true;
1794 completeResumeLocked(next);
1795 } catch (Exception e) {
1796 // If any exception gets thrown, toss away this
1797 // activity and try the next one.
1798 Slog.w(TAG, "Exception thrown during resume of " + next, e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001799 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001800 "resume-exception", true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001801 return true;
1802 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001803 next.stopped = false;
1804
1805 } else {
1806 // Whoops, need to restart this activity!
1807 if (!next.hasBeenLaunched) {
1808 next.hasBeenLaunched = true;
1809 } else {
1810 if (SHOW_APP_STARTING_PREVIEW) {
1811 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001812 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001813 mService.compatibilityInfoForPackageLocked(
1814 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001815 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001816 next.labelRes, next.icon, next.windowFlags,
1817 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001818 }
1819 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1820 }
1821 startSpecificActivityLocked(next, true, true);
1822 }
1823
1824 return true;
1825 }
1826
Craig Mautner11bf9a52013-02-19 14:08:51 -08001827
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001828 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001829 boolean doResume, boolean keepCurTransition, Bundle options) {
Craig Mautner70a86932013-02-28 22:37:44 -08001830 TaskRecord task = null;
Craig Mautnerd2328952013-03-05 12:46:26 -08001831 TaskRecord rTask = r.task;
1832 final int taskId = rTask.taskId;
1833 if (taskForIdLocked(taskId) == null || newTask) {
Craig Mautner77878772013-03-04 19:46:24 -08001834 // Last activity in task had been removed or ActivityManagerService is reusing task.
1835 // Insert or replace.
Craig Mautner77878772013-03-04 19:46:24 -08001836 // Might not even be in.
Craig Mautnerd2328952013-03-05 12:46:26 -08001837 mTaskHistory.remove(rTask);
Craig Mautner77878772013-03-04 19:46:24 -08001838 // Now put task at top.
Craig Mautnerd2328952013-03-05 12:46:26 -08001839 mTaskHistory.add(rTask);
1840 mService.mWindowManager.moveTaskToTop(taskId);
Craig Mautner77878772013-03-04 19:46:24 -08001841 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001842 if (!newTask) {
1843 // If starting in an existing task, find where that is...
Craig Mautner70a86932013-02-28 22:37:44 -08001844 boolean startIt = true;
1845 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
1846 task = mTaskHistory.get(taskNdx);
1847 if (task == r.task) {
1848 // Here it is! Now, if this is not yet visible to the
1849 // user, then just add it without starting; it will
1850 // get started when the user navigates back to it.
Craig Mautner70a86932013-02-28 22:37:44 -08001851 if (!startIt) {
1852 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to task "
1853 + task, new RuntimeException("here").fillInStackTrace());
1854 task.addActivityToTop(r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001855 r.putInHistory();
Craig Mautner70a86932013-02-28 22:37:44 -08001856 mService.mWindowManager.addAppToken(task.mActivities.indexOf(r),
Craig Mautnerc00204b2013-03-05 15:02:14 -08001857 r.appToken, r.task.taskId, mStackId, r.info.screenOrientation,
1858 r.fullscreen,
Craig Mautner5962b122012-10-05 14:45:52 -07001859 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001860 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001861 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001862 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001863 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001864 return;
1865 }
1866 break;
Craig Mautner70a86932013-02-28 22:37:44 -08001867 } else if (task.numFullscreen > 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001868 startIt = false;
1869 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001870 }
1871 }
1872
1873 // Place a new activity at top of stack, so it is next to interact
1874 // with the user.
Craig Mautner70a86932013-02-28 22:37:44 -08001875
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001876 // If we are not placing the new activity frontmost, we do not want
1877 // to deliver the onUserLeaving callback to the actual frontmost
1878 // activity
Craig Mautner70a86932013-02-28 22:37:44 -08001879 if (task == r.task && mTaskHistory.indexOf(task) != (mTaskHistory.size() - 1)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001880 mUserLeaving = false;
Craig Mautner70a86932013-02-28 22:37:44 -08001881 if (DEBUG_USER_LEAVING) Slog.v(TAG,
1882 "startActivity() behind front, mUserLeaving=false");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001883 }
Craig Mautner70a86932013-02-28 22:37:44 -08001884
1885 task = r.task;
1886
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001887 // Slot the activity into the history stack and proceed
Craig Mautner70a86932013-02-28 22:37:44 -08001888 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to stack to task " + task,
Craig Mautner56f52db2013-02-25 10:03:01 -08001889 new RuntimeException("here").fillInStackTrace());
Craig Mautner70a86932013-02-28 22:37:44 -08001890 task.addActivityToTop(r);
1891
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001892 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001893 r.frontOfTask = newTask;
Craig Mautner70a86932013-02-28 22:37:44 -08001894 if (numActivities() > 1) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001895 // We want to show the starting preview window if we are
1896 // switching to a new task, or the next activity's process is
1897 // not currently running.
1898 boolean showStartingIcon = newTask;
1899 ProcessRecord proc = r.app;
1900 if (proc == null) {
1901 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1902 }
1903 if (proc == null || proc.thread == null) {
1904 showStartingIcon = true;
1905 }
1906 if (DEBUG_TRANSITION) Slog.v(TAG,
1907 "Prepare open transition: starting " + r);
1908 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001909 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001910 AppTransition.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001911 mNoAnimActivities.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001912 } else {
1913 mService.mWindowManager.prepareAppTransition(newTask
Craig Mautner4b71aa12012-12-27 17:20:01 -08001914 ? AppTransition.TRANSIT_TASK_OPEN
1915 : AppTransition.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001916 mNoAnimActivities.remove(r);
1917 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001918 r.updateOptionsLocked(options);
Craig Mautner70a86932013-02-28 22:37:44 -08001919 mService.mWindowManager.addAppToken(task.mActivities.indexOf(r),
Craig Mautnerc00204b2013-03-05 15:02:14 -08001920 r.appToken, r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,
Craig Mautner5962b122012-10-05 14:45:52 -07001921 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001922 boolean doShow = true;
1923 if (newTask) {
1924 // Even though this activity is starting fresh, we still need
1925 // to reset it to make sure we apply affinities to move any
1926 // existing activities from other tasks in to it.
1927 // If the caller has requested that the target task be
1928 // reset, then do so.
1929 if ((r.intent.getFlags()
1930 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1931 resetTaskIfNeededLocked(r, r);
1932 doShow = topRunningNonDelayedActivityLocked(null) == r;
1933 }
1934 }
1935 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1936 // Figure out if we are transitioning from another activity that is
1937 // "has the same starting icon" as the next one. This allows the
1938 // window manager to keep the previous window it had previously
1939 // created, if it still had one.
1940 ActivityRecord prev = mResumedActivity;
1941 if (prev != null) {
1942 // We don't want to reuse the previous starting preview if:
1943 // (1) The current activity is in a different task.
1944 if (prev.task != r.task) prev = null;
1945 // (2) The current activity is already displayed.
1946 else if (prev.nowVisible) prev = null;
1947 }
1948 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001949 r.appToken, r.packageName, r.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001950 mService.compatibilityInfoForPackageLocked(
1951 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001952 r.labelRes, r.icon, r.windowFlags,
1953 prev != null ? prev.appToken : null, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001954 }
1955 } else {
1956 // If this is the first activity, don't do any fancy animations,
1957 // because there is nothing for it to animate on top of.
Craig Mautner70a86932013-02-28 22:37:44 -08001958 mService.mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken,
Craig Mautnerc00204b2013-03-05 15:02:14 -08001959 r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,
Craig Mautner5962b122012-10-05 14:45:52 -07001960 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001961 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001962 }
1963 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001964 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001965 }
1966
1967 if (doResume) {
1968 resumeTopActivityLocked(null);
1969 }
1970 }
1971
Dianne Hackbornbe707852011-11-11 14:32:10 -08001972 final void validateAppTokensLocked() {
1973 mValidateAppTokens.clear();
Craig Mautner000f0022013-02-26 15:04:29 -08001974 mValidateAppTokens.ensureCapacity(numActivities());
1975 final int numTasks = mTaskHistory.size();
1976 for (int taskNdx = 0; taskNdx < numTasks; ++taskNdx) {
1977 TaskRecord task = mTaskHistory.get(taskNdx);
1978 final ArrayList<ActivityRecord> activities = task.mActivities;
1979 if (activities.size() == 0) {
1980 continue;
Craig Mautnerb1fd65c02013-02-05 13:34:57 -08001981 }
Craig Mautner000f0022013-02-26 15:04:29 -08001982 TaskGroup group = new TaskGroup();
1983 group.taskId = task.taskId;
1984 mValidateAppTokens.add(group);
1985 final int numActivities = activities.size();
1986 for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) {
1987 final ActivityRecord r = activities.get(activityNdx);
1988 group.tokens.add(r.appToken);
1989 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001990 }
Craig Mautner00af9fe2013-03-25 09:13:41 -07001991 mService.mWindowManager.validateAppTokens(mStackId, mValidateAppTokens);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001992 }
1993
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001994 /**
1995 * Perform a reset of the given task, if needed as part of launching it.
1996 * Returns the new HistoryRecord at the top of the task.
1997 */
Craig Mautnere3a74d52013-02-22 14:14:58 -08001998 /**
1999 * Helper method for #resetTaskIfNeededLocked.
2000 * We are inside of the task being reset... we'll either finish this activity, push it out
2001 * for another task, or leave it as-is.
2002 * @param task The task containing the Activity (taskTop) that might be reset.
2003 * @param forceReset
2004 * @return An ActivityOptions that needs to be processed.
2005 */
2006 private final ActivityOptions resetTargetTaskIfNeededLocked(TaskRecord task,
2007 boolean forceReset) {
2008 ActivityOptions topOptions = null;
2009
2010 int replyChainEnd = -1;
2011 boolean canMoveOptions = true;
2012
2013 // We only do this for activities that are not the root of the task (since if we finish
2014 // the root, we may no longer have the task!).
2015 final ArrayList<ActivityRecord> activities = task.mActivities;
2016 final int numActivities = activities.size();
2017 for (int i = numActivities - 1; i > 0; --i ) {
2018 ActivityRecord target = activities.get(i);
2019
2020 final int flags = target.info.flags;
2021 final boolean finishOnTaskLaunch =
2022 (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
2023 final boolean allowTaskReparenting =
2024 (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
2025 final boolean clearWhenTaskReset =
2026 (target.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
2027
2028 if (!finishOnTaskLaunch
2029 && !clearWhenTaskReset
2030 && target.resultTo != null) {
2031 // If this activity is sending a reply to a previous
2032 // activity, we can't do anything with it now until
2033 // we reach the start of the reply chain.
2034 // XXX note that we are assuming the result is always
2035 // to the previous activity, which is almost always
2036 // the case but we really shouldn't count on.
2037 if (replyChainEnd < 0) {
2038 replyChainEnd = i;
2039 }
2040 } else if (!finishOnTaskLaunch
2041 && !clearWhenTaskReset
2042 && allowTaskReparenting
2043 && target.taskAffinity != null
2044 && !target.taskAffinity.equals(task.affinity)) {
2045 // If this activity has an affinity for another
2046 // task, then we need to move it out of here. We will
2047 // move it as far out of the way as possible, to the
2048 // bottom of the activity stack. This also keeps it
2049 // correctly ordered with any activities we previously
2050 // moved.
2051 TaskRecord bottomTask = mTaskHistory.get(0);
2052 ActivityRecord p = bottomTask.mActivities.get(0);
2053 if (target.taskAffinity != null
2054 && target.taskAffinity.equals(p.task.affinity)) {
2055 // If the activity currently at the bottom has the
2056 // same task affinity as the one we are moving,
2057 // then merge it into the same task.
Craig Mautner0247fc82013-02-28 14:32:06 -08002058 setTask(target, p.task, p.thumbHolder, false);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002059 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2060 + " out to bottom task " + p.task);
2061 } else {
Craig Mautner8d341ef2013-03-26 09:03:27 -07002062 setTask(target, createTaskRecord(mStackSupervisor.getNextTaskId(), target.info,
2063 null, false), null, false);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002064 target.task.affinityIntent = target.intent;
2065 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2066 + " out to new task " + target.task);
2067 }
2068
2069 final TaskRecord targetTask = target.task;
2070 final int targetTaskId = targetTask.taskId;
2071 mService.mWindowManager.setAppGroupId(target.appToken, targetTaskId);
2072
2073 ThumbnailHolder curThumbHolder = target.thumbHolder;
2074 boolean gotOptions = !canMoveOptions;
2075
2076 final int start = replyChainEnd < 0 ? i : replyChainEnd;
2077 for (int srcPos = start; srcPos >= i; --srcPos) {
2078 p = activities.get(srcPos);
2079 if (p.finishing) {
2080 continue;
2081 }
2082
2083 curThumbHolder = p.thumbHolder;
2084 canMoveOptions = false;
2085 if (!gotOptions && topOptions == null) {
2086 topOptions = p.takeOptionsLocked();
2087 if (topOptions != null) {
2088 gotOptions = true;
2089 }
2090 }
2091 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Removing activity " + p + " from task="
2092 + task + " adding to task=" + targetTask,
2093 new RuntimeException("here").fillInStackTrace());
2094 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
2095 + " out to target's task " + target.task);
Craig Mautner0247fc82013-02-28 14:32:06 -08002096 setTask(p, targetTask, curThumbHolder, false);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002097 targetTask.addActivityAtBottom(p);
Craig Mautner0247fc82013-02-28 14:32:06 -08002098
Craig Mautnere3a74d52013-02-22 14:14:58 -08002099 mService.mWindowManager.setAppGroupId(p.appToken, targetTaskId);
2100 }
2101
2102 mService.mWindowManager.moveTaskToBottom(targetTaskId);
2103 if (VALIDATE_TOKENS) {
2104 validateAppTokensLocked();
2105 }
2106
2107 replyChainEnd = -1;
2108 } else if (forceReset || finishOnTaskLaunch || clearWhenTaskReset) {
2109 // If the activity should just be removed -- either
2110 // because it asks for it, or the task should be
2111 // cleared -- then finish it and anything that is
2112 // part of its reply chain.
2113 int end;
2114 if (clearWhenTaskReset) {
2115 // In this case, we want to finish this activity
2116 // and everything above it, so be sneaky and pretend
2117 // like these are all in the reply chain.
2118 end = numActivities - 1;
2119 } else if (replyChainEnd < 0) {
2120 end = i;
2121 } else {
2122 end = replyChainEnd;
2123 }
2124 ActivityRecord p = null;
2125 boolean gotOptions = !canMoveOptions;
2126 for (int srcPos = i; srcPos <= end; srcPos++) {
2127 p = activities.get(srcPos);
2128 if (p.finishing) {
2129 continue;
2130 }
2131 canMoveOptions = false;
2132 if (!gotOptions && topOptions == null) {
2133 topOptions = p.takeOptionsLocked();
2134 if (topOptions != null) {
2135 gotOptions = true;
2136 }
2137 }
Craig Mautner58547802013-03-05 08:23:53 -08002138 if (DEBUG_TASKS) Slog.w(TAG,
2139 "resetTaskIntendedTask: calling finishActivity on " + p);
Craig Mautnerd44711d2013-02-23 11:24:36 -08002140 if (finishActivityLocked(p, Activity.RESULT_CANCELED, null, "reset", false)) {
Craig Mautnere3a74d52013-02-22 14:14:58 -08002141 end--;
2142 srcPos--;
2143 }
2144 }
2145 replyChainEnd = -1;
2146 } else {
2147 // If we were in the middle of a chain, well the
2148 // activity that started it all doesn't want anything
2149 // special, so leave it all as-is.
2150 replyChainEnd = -1;
2151 }
2152 }
2153
2154 return topOptions;
2155 }
2156
2157 /**
2158 * Helper method for #resetTaskIfNeededLocked. Processes all of the activities in a given
2159 * TaskRecord looking for an affinity with the task of resetTaskIfNeededLocked.taskTop.
2160 * @param affinityTask The task we are looking for an affinity to.
2161 * @param task Task that resetTaskIfNeededLocked.taskTop belongs to.
2162 * @param topTaskIsHigher True if #task has already been processed by resetTaskIfNeededLocked.
2163 * @param forceReset Flag passed in to resetTaskIfNeededLocked.
2164 */
Craig Mautner77878772013-03-04 19:46:24 -08002165 private final int resetAffinityTaskIfNeededLocked(TaskRecord affinityTask, TaskRecord task,
2166 boolean topTaskIsHigher, boolean forceReset, int taskInsertionPoint) {
Craig Mautnere3a74d52013-02-22 14:14:58 -08002167 int replyChainEnd = -1;
2168 final int taskId = task.taskId;
2169 final String taskAffinity = task.affinity;
2170
2171 final ArrayList<ActivityRecord> activities = affinityTask.mActivities;
2172 final int numActivities = activities.size();
2173 // Do not operate on the root Activity.
2174 for (int i = numActivities - 1; i > 0; --i) {
2175 ActivityRecord target = activities.get(i);
2176
2177 final int flags = target.info.flags;
2178 boolean finishOnTaskLaunch = (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
2179 boolean allowTaskReparenting = (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
2180
2181 if (target.resultTo != null) {
2182 // If this activity is sending a reply to a previous
2183 // activity, we can't do anything with it now until
2184 // we reach the start of the reply chain.
2185 // XXX note that we are assuming the result is always
2186 // to the previous activity, which is almost always
2187 // the case but we really shouldn't count on.
2188 if (replyChainEnd < 0) {
2189 replyChainEnd = i;
2190 }
2191 } else if (topTaskIsHigher
2192 && allowTaskReparenting
2193 && taskAffinity != null
2194 && taskAffinity.equals(target.taskAffinity)) {
2195 // This activity has an affinity for our task. Either remove it if we are
2196 // clearing or move it over to our task. Note that
2197 // we currently punt on the case where we are resetting a
2198 // task that is not at the top but who has activities above
2199 // with an affinity to it... this is really not a normal
2200 // case, and we will need to later pull that task to the front
2201 // and usually at that point we will do the reset and pick
2202 // up those remaining activities. (This only happens if
2203 // someone starts an activity in a new task from an activity
2204 // in a task that is not currently on top.)
2205 if (forceReset || finishOnTaskLaunch) {
2206 final int start = replyChainEnd >= 0 ? replyChainEnd : i;
2207 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index " + start + " to " + i);
2208 for (int srcPos = start; srcPos >= i; --srcPos) {
2209 final ActivityRecord p = activities.get(srcPos);
2210 if (p.finishing) {
2211 continue;
2212 }
Craig Mautnerd44711d2013-02-23 11:24:36 -08002213 finishActivityLocked(p, Activity.RESULT_CANCELED, null, "reset", false);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002214 }
2215 } else {
Craig Mautner77878772013-03-04 19:46:24 -08002216 if (taskInsertionPoint < 0) {
2217 taskInsertionPoint = task.mActivities.size();
Craig Mautnerd2328952013-03-05 12:46:26 -08002218
Craig Mautner77878772013-03-04 19:46:24 -08002219 }
Craig Mautner77878772013-03-04 19:46:24 -08002220
2221 final int start = replyChainEnd >= 0 ? replyChainEnd : i;
2222 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting from task=" + affinityTask + ":"
2223 + start + "-" + i + " to task=" + task + ":" + taskInsertionPoint);
2224 for (int srcPos = start; srcPos >= i; --srcPos) {
Craig Mautnere3a74d52013-02-22 14:14:58 -08002225 final ActivityRecord p = activities.get(srcPos);
Craig Mautner0247fc82013-02-28 14:32:06 -08002226 setTask(p, task, null, false);
Craig Mautner77878772013-03-04 19:46:24 -08002227 task.addActivityAtIndex(taskInsertionPoint, p);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002228
Craig Mautnere3a74d52013-02-22 14:14:58 -08002229 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Removing and adding activity " + p
2230 + " to stack at " + task,
2231 new RuntimeException("here").fillInStackTrace());
2232 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p + " from " + srcPos
2233 + " in to resetting task " + task);
2234 mService.mWindowManager.setAppGroupId(p.appToken, taskId);
2235 }
2236 mService.mWindowManager.moveTaskToTop(taskId);
Craig Mautner9658b312013-02-28 10:55:59 -08002237 if (VALIDATE_TOKENS) {
2238 validateAppTokensLocked();
2239 }
Craig Mautnere3a74d52013-02-22 14:14:58 -08002240
2241 // Now we've moved it in to place... but what if this is
2242 // a singleTop activity and we have put it on top of another
2243 // instance of the same activity? Then we drop the instance
2244 // below so it remains singleTop.
2245 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2246 ArrayList<ActivityRecord> taskActivities = task.mActivities;
2247 boolean found = false;
2248 int targetNdx = taskActivities.indexOf(target);
2249 if (targetNdx > 0) {
2250 ActivityRecord p = taskActivities.get(targetNdx - 1);
2251 if (p.intent.getComponent().equals(target.intent.getComponent())) {
Craig Mautner58547802013-03-05 08:23:53 -08002252 finishActivityLocked(p, Activity.RESULT_CANCELED, null, "replace",
2253 false);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002254 }
2255 }
2256 }
2257 }
2258
2259 replyChainEnd = -1;
2260 }
2261 }
Craig Mautner77878772013-03-04 19:46:24 -08002262 return taskInsertionPoint;
Craig Mautnere3a74d52013-02-22 14:14:58 -08002263 }
2264
2265 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
2266 ActivityRecord newActivity) {
2267 boolean forceReset =
2268 (newActivity.info.flags & ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
2269 if (ACTIVITY_INACTIVE_RESET_TIME > 0
2270 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
2271 if ((newActivity.info.flags & ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
2272 forceReset = true;
2273 }
2274 }
2275
2276 final TaskRecord task = taskTop.task;
2277
2278 /** False until we evaluate the TaskRecord associated with taskTop. Switches to true
2279 * for remaining tasks. Used for later tasks to reparent to task. */
2280 boolean taskFound = false;
2281
2282 /** If ActivityOptions are moved out and need to be aborted or moved to taskTop. */
2283 ActivityOptions topOptions = null;
2284
Craig Mautner77878772013-03-04 19:46:24 -08002285 // Preserve the location for reparenting in the new task.
2286 int reparentInsertionPoint = -1;
2287
Craig Mautnere3a74d52013-02-22 14:14:58 -08002288 for (int i = mTaskHistory.size() - 1; i >= 0; --i) {
2289 final TaskRecord targetTask = mTaskHistory.get(i);
2290
2291 if (targetTask == task) {
2292 topOptions = resetTargetTaskIfNeededLocked(task, forceReset);
2293 taskFound = true;
2294 } else {
Craig Mautner77878772013-03-04 19:46:24 -08002295 reparentInsertionPoint = resetAffinityTaskIfNeededLocked(targetTask, task,
2296 taskFound, forceReset, reparentInsertionPoint);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002297 }
2298 }
2299
Craig Mautner70a86932013-02-28 22:37:44 -08002300 int taskNdx = mTaskHistory.indexOf(task);
2301 do {
2302 taskTop = mTaskHistory.get(taskNdx--).getTopActivity();
2303 } while (taskTop == null && taskNdx >= 0);
2304
Craig Mautnere3a74d52013-02-22 14:14:58 -08002305 if (topOptions != null) {
2306 // If we got some ActivityOptions from an activity on top that
2307 // was removed from the task, propagate them to the new real top.
2308 if (taskTop != null) {
Craig Mautnere3a74d52013-02-22 14:14:58 -08002309 taskTop.updateOptionsLocked(topOptions);
2310 } else {
Craig Mautnere3a74d52013-02-22 14:14:58 -08002311 topOptions.abort();
2312 }
2313 }
2314
2315 return taskTop;
2316 }
2317
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002318 /**
2319 * Perform clear operation as requested by
2320 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2321 * stack to the given task, then look for
2322 * an instance of that activity in the stack and, if found, finish all
2323 * activities on top of it and return the instance.
2324 *
2325 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002326 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002327 * or null if none was found.
2328 */
Craig Mautner16030772013-02-26 16:05:47 -08002329 private final ActivityRecord performClearTaskLocked(TaskRecord task,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002330 ActivityRecord newR, int launchFlags) {
Craig Mautner16030772013-02-26 16:05:47 -08002331
2332 final ArrayList<ActivityRecord> activities = task.mActivities;
2333 int numActivities = activities.size();
2334 for (int activityNdx = numActivities - 1; activityNdx >= 0; --activityNdx) {
2335 ActivityRecord r = activities.get(activityNdx);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002336 if (r.finishing) {
2337 continue;
2338 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002339 if (r.realActivity.equals(newR.realActivity)) {
2340 // Here it is! Now finish everything in front...
2341 ActivityRecord ret = r;
Craig Mautner16030772013-02-26 16:05:47 -08002342
2343 for (++activityNdx; activityNdx < numActivities; ++activityNdx) {
2344 r = activities.get(activityNdx);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002345 if (r.finishing) {
2346 continue;
2347 }
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002348 ActivityOptions opts = r.takeOptionsLocked();
2349 if (opts != null) {
2350 ret.updateOptionsLocked(opts);
2351 }
Craig Mautner16030772013-02-26 16:05:47 -08002352 if (finishActivityLocked(r, Activity.RESULT_CANCELED, null, "clear", false)) {
Craig Mautner9658b312013-02-28 10:55:59 -08002353 --activityNdx;
Craig Mautner16030772013-02-26 16:05:47 -08002354 --numActivities;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002355 }
2356 }
Craig Mautner16030772013-02-26 16:05:47 -08002357
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002358 // Finally, if this is a normal launch mode (that is, not
2359 // expecting onNewIntent()), then we will finish the current
2360 // instance of the activity so a new fresh one can be started.
2361 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
Craig Mautner16030772013-02-26 16:05:47 -08002362 && (launchFlags & Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002363 if (!ret.finishing) {
Craig Mautner16030772013-02-26 16:05:47 -08002364 if (activities.contains(ret)) {
Craig Mautnerd44711d2013-02-23 11:24:36 -08002365 finishActivityLocked(ret, Activity.RESULT_CANCELED, null,
2366 "clear", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002367 }
2368 return null;
2369 }
2370 }
Craig Mautner16030772013-02-26 16:05:47 -08002371
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002372 return ret;
2373 }
2374 }
2375
2376 return null;
2377 }
2378
2379 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002380 * Completely remove all activities associated with an existing
2381 * task starting at a specified index.
2382 */
Craig Mautner16030772013-02-26 16:05:47 -08002383 private final void performClearTaskAtIndexLocked(TaskRecord task, int activityNdx) {
2384 final ArrayList<ActivityRecord> activities = task.mActivities;
2385 int numActivities = activities.size();
2386 for ( ; activityNdx < numActivities; ++activityNdx) {
2387 final ActivityRecord r = activities.get(activityNdx);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002388 if (r.finishing) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002389 continue;
2390 }
Craig Mautner16030772013-02-26 16:05:47 -08002391 if (finishActivityLocked(r, Activity.RESULT_CANCELED, null, "clear", false)) {
2392 --activityNdx;
2393 --numActivities;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002394 }
2395 }
2396 }
2397
2398 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002399 * Completely remove all activities associated with an existing task.
2400 */
Craig Mautner16030772013-02-26 16:05:47 -08002401 private final void performClearTaskLocked(TaskRecord task) {
2402 performClearTaskAtIndexLocked(task, 0);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002403 }
2404
2405 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002406 * Find the activity in the history stack within the given task. Returns
2407 * the index within the history at which it's found, or < 0 if not found.
2408 */
Craig Mautner56f52db2013-02-25 10:03:01 -08002409 private final ActivityRecord findActivityInHistoryLocked(ActivityRecord r, TaskRecord task) {
2410 final ComponentName realActivity = r.realActivity;
2411 ArrayList<ActivityRecord> activities = task.mActivities;
2412 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2413 ActivityRecord candidate = activities.get(activityNdx);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07002414 if (candidate.finishing) {
2415 continue;
2416 }
Craig Mautner56f52db2013-02-25 10:03:01 -08002417 if (candidate.realActivity.equals(realActivity)) {
2418 return candidate;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002419 }
2420 }
Craig Mautner56f52db2013-02-25 10:03:01 -08002421 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002422 }
2423
2424 /**
2425 * Reorder the history stack so that the activity at the given index is
2426 * brought to the front.
2427 */
Craig Mautner56f52db2013-02-25 10:03:01 -08002428 private final void moveActivityToFrontLocked(ActivityRecord newTop) {
2429 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Removing and adding activity " + newTop
2430 + " to stack at top", new RuntimeException("here").fillInStackTrace());
2431
2432 final TaskRecord task = newTop.task;
2433 task.getTopActivity().frontOfTask = false;
2434 task.mActivities.remove(newTop);
2435 task.mActivities.add(newTop);
2436 newTop.frontOfTask = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002437 }
2438
2439 final int startActivityLocked(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002440 Intent intent, String resolvedType, ActivityInfo aInfo, IBinder resultTo,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002441 String resultWho, int requestCode,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002442 int callingPid, int callingUid, String callingPackage, int startFlags, Bundle options,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002443 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackborna4972e92012-03-14 10:38:05 -07002444 int err = ActivityManager.START_SUCCESS;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002445
2446 ProcessRecord callerApp = null;
2447 if (caller != null) {
2448 callerApp = mService.getRecordForAppLocked(caller);
2449 if (callerApp != null) {
2450 callingPid = callerApp.pid;
2451 callingUid = callerApp.info.uid;
2452 } else {
2453 Slog.w(TAG, "Unable to find app for caller " + caller
2454 + " (pid=" + callingPid + ") when starting: "
2455 + intent.toString());
Dianne Hackborna4972e92012-03-14 10:38:05 -07002456 err = ActivityManager.START_PERMISSION_DENIED;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002457 }
2458 }
2459
Dianne Hackborna4972e92012-03-14 10:38:05 -07002460 if (err == ActivityManager.START_SUCCESS) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002461 final int userId = aInfo != null ? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0;
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07002462 Slog.i(TAG, "START u" + userId + " {" + intent.toShortString(true, true, true, false)
2463 + "} from pid " + (callerApp != null ? callerApp.pid : callingPid));
Dianne Hackbornefb58102010-10-14 16:47:34 -07002464 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002465
2466 ActivityRecord sourceRecord = null;
2467 ActivityRecord resultRecord = null;
2468 if (resultTo != null) {
Craig Mautner56f52db2013-02-25 10:03:01 -08002469 sourceRecord = isInStackLocked(resultTo);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002470 if (DEBUG_RESULTS) Slog.v(
Craig Mautner56f52db2013-02-25 10:03:01 -08002471 TAG, "Will send result to " + resultTo + " " + sourceRecord);
2472 if (sourceRecord != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002473 if (requestCode >= 0 && !sourceRecord.finishing) {
2474 resultRecord = sourceRecord;
2475 }
2476 }
2477 }
2478
2479 int launchFlags = intent.getFlags();
2480
2481 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2482 && sourceRecord != null) {
2483 // Transfer the result target from the source activity to the new
2484 // one being started, including any failures.
2485 if (requestCode >= 0) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002486 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002487 return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002488 }
2489 resultRecord = sourceRecord.resultTo;
2490 resultWho = sourceRecord.resultWho;
2491 requestCode = sourceRecord.requestCode;
2492 sourceRecord.resultTo = null;
2493 if (resultRecord != null) {
2494 resultRecord.removeResultsLocked(
2495 sourceRecord, resultWho, requestCode);
2496 }
2497 }
2498
Dianne Hackborna4972e92012-03-14 10:38:05 -07002499 if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002500 // We couldn't find a class that can handle the given Intent.
2501 // That's the end of that!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002502 err = ActivityManager.START_INTENT_NOT_RESOLVED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002503 }
2504
Dianne Hackborna4972e92012-03-14 10:38:05 -07002505 if (err == ActivityManager.START_SUCCESS && aInfo == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002506 // We couldn't find the specific class specified in the Intent.
2507 // Also the end of the line.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002508 err = ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002509 }
2510
Dianne Hackborna4972e92012-03-14 10:38:05 -07002511 if (err != ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002512 if (resultRecord != null) {
2513 sendActivityResultLocked(-1,
2514 resultRecord, resultWho, requestCode,
2515 Activity.RESULT_CANCELED, null);
2516 }
Craig Mautner27084302013-03-25 08:05:25 -07002517 mStackSupervisor.setDismissKeyguard(false);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002518 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002519 return err;
2520 }
2521
Jeff Sharkey35be7562012-04-18 19:16:15 -07002522 final int startAnyPerm = mService.checkPermission(
2523 START_ANY_ACTIVITY, callingPid, callingUid);
2524 final int componentPerm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002525 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Jeff Sharkey35be7562012-04-18 19:16:15 -07002526 if (startAnyPerm != PERMISSION_GRANTED && componentPerm != PERMISSION_GRANTED) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002527 if (resultRecord != null) {
2528 sendActivityResultLocked(-1,
2529 resultRecord, resultWho, requestCode,
2530 Activity.RESULT_CANCELED, null);
2531 }
Craig Mautner27084302013-03-25 08:05:25 -07002532 mStackSupervisor.setDismissKeyguard(false);
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002533 String msg;
2534 if (!aInfo.exported) {
2535 msg = "Permission Denial: starting " + intent.toString()
2536 + " from " + callerApp + " (pid=" + callingPid
2537 + ", uid=" + callingUid + ")"
2538 + " not exported from uid " + aInfo.applicationInfo.uid;
2539 } else {
2540 msg = "Permission Denial: starting " + intent.toString()
2541 + " from " + callerApp + " (pid=" + callingPid
2542 + ", uid=" + callingUid + ")"
2543 + " requires " + aInfo.permission;
2544 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002545 Slog.w(TAG, msg);
2546 throw new SecurityException(msg);
2547 }
2548
Craig Mautner2219a1b2013-03-25 09:44:30 -07002549 if (mStackSupervisor.isMainStack(this)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002550 if (mService.mController != null) {
2551 boolean abort = false;
2552 try {
2553 // The Intent we give to the watcher has the extra data
2554 // stripped off, since it can contain private information.
2555 Intent watchIntent = intent.cloneFilter();
2556 abort = !mService.mController.activityStarting(watchIntent,
2557 aInfo.applicationInfo.packageName);
2558 } catch (RemoteException e) {
2559 mService.mController = null;
2560 }
Craig Mautnerd2328952013-03-05 12:46:26 -08002561
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002562 if (abort) {
2563 if (resultRecord != null) {
Craig Mautner8d341ef2013-03-26 09:03:27 -07002564 sendActivityResultLocked(-1, resultRecord, resultWho, requestCode,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002565 Activity.RESULT_CANCELED, null);
2566 }
2567 // We pretend to the caller that it was really started, but
2568 // they will just get a cancel result.
Craig Mautner27084302013-03-25 08:05:25 -07002569 mStackSupervisor.setDismissKeyguard(false);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002570 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002571 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002572 }
2573 }
2574 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002575
Craig Mautnerd2328952013-03-05 12:46:26 -08002576 ActivityRecord r = new ActivityRecord(mService, callerApp, callingUid, callingPackage,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002577 intent, resolvedType, aInfo, mService.mConfiguration,
2578 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002579 if (outActivity != null) {
2580 outActivity[0] = r;
2581 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002582
Craig Mautner2219a1b2013-03-25 09:44:30 -07002583 if (mStackSupervisor.isMainStack(this)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002584 if (mResumedActivity == null
2585 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2586 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
Craig Mautner64f2b172013-03-11 11:40:31 -07002587 PendingActivityLaunch pal =
2588 new PendingActivityLaunch(r, sourceRecord, startFlags, this);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002589 mService.mPendingActivityLaunches.add(pal);
Craig Mautner27084302013-03-25 08:05:25 -07002590 mStackSupervisor.setDismissKeyguard(false);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002591 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002592 return ActivityManager.START_SWITCHES_CANCELED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002593 }
2594 }
Craig Mautnerd2328952013-03-05 12:46:26 -08002595
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002596 if (mService.mDidAppSwitch) {
2597 // This is the second allowed switch since we stopped switches,
2598 // so now just generally allow switches. Use case: user presses
2599 // home (switches disabled, switch to home, mDidAppSwitch now true);
2600 // user taps a home icon (coming from home so allowed, we hit here
2601 // and now allow anyone to switch again).
2602 mService.mAppSwitchesAllowedTime = 0;
2603 } else {
2604 mService.mDidAppSwitch = true;
2605 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002606 }
Craig Mautnerd2328952013-03-05 12:46:26 -08002607
Craig Mautner8d341ef2013-03-26 09:03:27 -07002608 mService.doPendingActivityLaunchesLocked(false);
2609
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002610 err = startActivityUncheckedLocked(r, sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002611 startFlags, true, options);
Craig Mautner27084302013-03-25 08:05:25 -07002612 if (mPausingActivity == null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002613 // Someone asked to have the keyguard dismissed on the next
2614 // activity start, but we are not actually doing an activity
2615 // switch... just dismiss the keyguard now, because we
2616 // probably want to see whatever is behind it.
Craig Mautner27084302013-03-25 08:05:25 -07002617 mStackSupervisor.dismissKeyguard();
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002618 }
2619 return err;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002620 }
Craig Mautnerd2328952013-03-05 12:46:26 -08002621
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002622 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2623 if ((launchFlags &
2624 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2625 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2626 // Caller wants to appear on home activity, so before starting
2627 // their own activity we will bring home to the front.
2628 moveHomeToFrontLocked();
2629 }
2630 }
2631
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002632 final int startActivityUncheckedLocked(ActivityRecord r,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002633 ActivityRecord sourceRecord, int startFlags, boolean doResume,
2634 Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002635 final Intent intent = r.intent;
2636 final int callingUid = r.launchedFromUid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002637
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002638 int launchFlags = intent.getFlags();
Craig Mautnerd2328952013-03-05 12:46:26 -08002639
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002640 // We'll invoke onUserLeaving before onPause only if the launching
2641 // activity did not explicitly state that this is an automated launch.
2642 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2643 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2644 "startActivity() => mUserLeaving=" + mUserLeaving);
Craig Mautnerd2328952013-03-05 12:46:26 -08002645
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002646 // If the caller has asked not to resume at this point, we make note
2647 // of this in the record so that we can skip it when trying to find
2648 // the top running activity.
2649 if (!doResume) {
2650 r.delayedResume = true;
2651 }
Craig Mautnerd2328952013-03-05 12:46:26 -08002652
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002653 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2654 != 0 ? r : null;
2655
2656 // If the onlyIfNeeded flag is set, then we can do this if the activity
2657 // being launched is the same as the one making the call... or, as
2658 // a special case, if we do not know the caller then we count the
2659 // current top activity as the caller.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002660 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002661 ActivityRecord checkedCaller = sourceRecord;
2662 if (checkedCaller == null) {
2663 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2664 }
2665 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2666 // Caller is not the same as launcher, so always needed.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002667 startFlags &= ~ActivityManager.START_FLAG_ONLY_IF_NEEDED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002668 }
2669 }
2670
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002671 if (sourceRecord == null) {
2672 // This activity is not being started from another... in this
2673 // case we -always- start a new task.
2674 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2675 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2676 + intent);
2677 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2678 }
2679 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2680 // The original activity who is starting us is running as a single
2681 // instance... this new activity it is starting must go on its
2682 // own task.
2683 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2684 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2685 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2686 // The activity being started is a single instance... it always
2687 // gets launched into its own task.
2688 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2689 }
2690
2691 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2692 // For whatever reason this activity is being launched into a new
2693 // task... yet the caller has requested a result back. Well, that
2694 // is pretty messed up, so instead immediately send back a cancel
2695 // and let the new task continue launched as normal without a
2696 // dependency on its originator.
2697 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2698 sendActivityResultLocked(-1,
2699 r.resultTo, r.resultWho, r.requestCode,
2700 Activity.RESULT_CANCELED, null);
2701 r.resultTo = null;
2702 }
2703
2704 boolean addingToTask = false;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002705 boolean movedHome = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002706 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002707 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2708 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2709 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2710 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2711 // If bring to front is requested, and no result is requested, and
2712 // we can find a task that was started with this same
2713 // component, then instead of launching bring that one to the front.
2714 if (r.resultTo == null) {
2715 // See if there is a task to bring to the front. If this is
2716 // a SINGLE_INSTANCE activity, there can be one and only one
2717 // instance of it in the history, and it is always in its own
2718 // unique task, so we do a special search.
2719 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2720 ? findTaskLocked(intent, r.info)
2721 : findActivityLocked(intent, r.info);
2722 if (taskTop != null) {
2723 if (taskTop.task.intent == null) {
2724 // This task was started because of movement of
2725 // the activity based on affinity... now that we
2726 // are actually launching it, we can assign the
2727 // base intent.
2728 taskTop.task.setIntent(intent, r.info);
2729 }
2730 // If the target task is not in the front, then we need
2731 // to bring it to the front... except... well, with
2732 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2733 // to have the same behavior as if a new instance was
2734 // being started, which means not bringing it to the front
2735 // if the caller is not itself in the front.
2736 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002737 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002738 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2739 boolean callerAtFront = sourceRecord == null
2740 || curTop.task == sourceRecord.task;
2741 if (callerAtFront) {
2742 // We really do want to push this one into the
2743 // user's face, right now.
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002744 movedHome = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002745 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002746 moveTaskToFrontLocked(taskTop.task, r, options);
Dianne Hackborn84375872012-06-01 19:03:50 -07002747 options = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002748 }
2749 }
2750 // If the caller has requested that the target task be
2751 // reset, then do so.
2752 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2753 taskTop = resetTaskIfNeededLocked(taskTop, r);
2754 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002755 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002756 // We don't need to start a new activity, and
2757 // the client said not to do anything if that
2758 // is the case, so this is it! And for paranoia, make
2759 // sure we have correctly resumed the top activity.
2760 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07002761 resumeTopActivityLocked(null, options);
2762 } else {
2763 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002764 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002765 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002766 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002767 if ((launchFlags &
2768 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2769 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2770 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002771 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002772 // not be too hard...
2773 reuseTask = taskTop.task;
Craig Mautner16030772013-02-26 16:05:47 -08002774 performClearTaskLocked(taskTop.task);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002775 reuseTask.setIntent(r.intent, r.info);
2776 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002777 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2778 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2779 // In this situation we want to remove all activities
2780 // from the task up to the one being started. In most
2781 // cases this means we are resetting the task to its
2782 // initial state.
Craig Mautner16030772013-02-26 16:05:47 -08002783 ActivityRecord top = performClearTaskLocked(taskTop.task, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002784 if (top != null) {
2785 if (top.frontOfTask) {
2786 // Activity aliases may mean we use different
2787 // intents for the top activity, so make sure
2788 // the task now has the identity of the new
2789 // intent.
2790 top.task.setIntent(r.intent, r.info);
2791 }
2792 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002793 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002794 } else {
2795 // A special case: we need to
2796 // start the activity because it is not currently
2797 // running, and the caller has asked to clear the
2798 // current task to have this activity at the top.
2799 addingToTask = true;
2800 // Now pretend like this activity is being started
2801 // by the top of its task, so it is put in the
2802 // right place.
2803 sourceRecord = taskTop;
2804 }
2805 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2806 // In this case the top activity on the task is the
2807 // same as the one being launched, so we take that
2808 // as a request to bring the task to the foreground.
2809 // If the top activity in the task is the root
2810 // activity, deliver this new intent to it if it
2811 // desires.
Johan Viktorssonf363dfd2012-02-16 17:05:16 +01002812 if (((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2813 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP)
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002814 && taskTop.realActivity.equals(r.realActivity)) {
2815 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2816 if (taskTop.frontOfTask) {
2817 taskTop.task.setIntent(r.intent, r.info);
2818 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002819 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002820 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2821 // In this case we are launching the root activity
2822 // of the task, but with a different intent. We
2823 // should start a new instance on top.
2824 addingToTask = true;
2825 sourceRecord = taskTop;
2826 }
2827 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2828 // In this case an activity is being launched in to an
2829 // existing task, without resetting that task. This
2830 // is typically the situation of launching an activity
2831 // from a notification or shortcut. We want to place
2832 // the new activity on top of the current task.
2833 addingToTask = true;
2834 sourceRecord = taskTop;
2835 } else if (!taskTop.task.rootWasReset) {
2836 // In this case we are launching in to an existing task
2837 // that has not yet been started from its front door.
2838 // The current task has been brought to the front.
2839 // Ideally, we'd probably like to place this new task
2840 // at the bottom of its stack, but that's a little hard
2841 // to do with the current organization of the code so
2842 // for now we'll just drop it.
2843 taskTop.task.setIntent(r.intent, r.info);
2844 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002845 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002846 // We didn't do anything... but it was needed (a.k.a., client
2847 // don't use that intent!) And for paranoia, make
2848 // sure we have correctly resumed the top activity.
2849 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07002850 resumeTopActivityLocked(null, options);
2851 } else {
2852 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002853 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002854 return ActivityManager.START_TASK_TO_FRONT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002855 }
2856 }
2857 }
2858 }
2859
2860 //String uri = r.intent.toURI();
2861 //Intent intent2 = new Intent(uri);
2862 //Slog.i(TAG, "Given intent: " + r.intent);
2863 //Slog.i(TAG, "URI is: " + uri);
2864 //Slog.i(TAG, "To intent: " + intent2);
2865
2866 if (r.packageName != null) {
2867 // If the activity being launched is the same as the one currently
2868 // at the top, then we need to check if it should only be launched
2869 // once.
2870 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2871 if (top != null && r.resultTo == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002872 if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002873 if (top.app != null && top.app.thread != null) {
2874 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2875 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2876 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2877 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2878 // For paranoia, make sure we have correctly
2879 // resumed the top activity.
2880 if (doResume) {
2881 resumeTopActivityLocked(null);
2882 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002883 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002884 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002885 // We don't need to start a new activity, and
2886 // the client said not to do anything if that
2887 // is the case, so this is it!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002888 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002889 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002890 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002891 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002892 }
2893 }
2894 }
2895 }
2896
2897 } else {
2898 if (r.resultTo != null) {
2899 sendActivityResultLocked(-1,
2900 r.resultTo, r.resultWho, r.requestCode,
2901 Activity.RESULT_CANCELED, null);
2902 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002903 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002904 return ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002905 }
2906
2907 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002908 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002909
2910 // Should this be considered a new task?
2911 if (r.resultTo == null && !addingToTask
2912 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002913 if (reuseTask == null) {
Craig Mautner8d341ef2013-03-26 09:03:27 -07002914 setTask(r, createTaskRecord(mStackSupervisor.getNextTaskId(), r.info, intent,
2915 true), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002916 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2917 + " in new task " + r.task);
2918 } else {
Craig Mautner0247fc82013-02-28 14:32:06 -08002919 setTask(r, reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002920 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002921 newTask = true;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002922 if (!movedHome) {
2923 moveHomeToFrontFromLaunchLocked(launchFlags);
2924 }
Craig Mautnerd2328952013-03-05 12:46:26 -08002925
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002926 } else if (sourceRecord != null) {
2927 if (!addingToTask &&
2928 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2929 // In this case, we are adding the activity to an existing
2930 // task, but the caller has asked to clear that task if the
2931 // activity is already running.
Craig Mautner16030772013-02-26 16:05:47 -08002932 ActivityRecord top = performClearTaskLocked(sourceRecord.task, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002933 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002934 if (top != null) {
2935 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002936 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002937 // For paranoia, make sure we have correctly
2938 // resumed the top activity.
2939 if (doResume) {
2940 resumeTopActivityLocked(null);
2941 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002942 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002943 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002944 }
2945 } else if (!addingToTask &&
2946 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2947 // In this case, we are launching an activity in our own task
2948 // that may already be running somewhere in the history, and
2949 // we want to shuffle it to the front of the stack if so.
Craig Mautner56f52db2013-02-25 10:03:01 -08002950 final ActivityRecord top = findActivityInHistoryLocked(r, sourceRecord.task);
2951 if (top != null) {
2952 moveActivityToFrontLocked(top);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002953 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002954 top.updateOptionsLocked(options);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002955 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002956 if (doResume) {
2957 resumeTopActivityLocked(null);
2958 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002959 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002960 }
2961 }
2962 // An existing activity is starting this new activity, so we want
2963 // to keep the new one in the same task as the one that is starting
2964 // it.
Craig Mautner0247fc82013-02-28 14:32:06 -08002965 setTask(r, sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002966 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2967 + " in existing task " + r.task);
2968
2969 } else {
2970 // This not being started from an existing activity, and not part
2971 // of a new task... just put it in the top task, though these days
2972 // this case should never happen.
Craig Mautner9658b312013-02-28 10:55:59 -08002973 ActivityRecord prev = null;
2974 // Iterate to find the first non-empty task stack. Note that this code can
2975 // go away once we stop storing tasks with empty mActivities lists.
2976 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
2977 ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
2978 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2979 prev = activities.get(activityNdx);
2980 break;
2981 }
2982 }
Craig Mautner0247fc82013-02-28 14:32:06 -08002983 setTask(r, prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002984 ? prev.task
Craig Mautner8d341ef2013-03-26 09:03:27 -07002985 : createTaskRecord(mStackSupervisor.getNextTaskId(), r.info, intent, true),
2986 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002987 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2988 + " in new guessed " + r.task);
2989 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002990
Dianne Hackborn39792d22010-08-19 18:01:52 -07002991 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002992 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002993
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002994 if (newTask) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002995 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.userId, r.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002996 }
2997 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002998 startActivityLocked(r, newTask, doResume, keepCurTransition, options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002999 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003000 }
3001
Dianne Hackborna4972e92012-03-14 10:38:05 -07003002 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003003 String profileFile, ParcelFileDescriptor profileFd, int userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003004 // Collect information about the target of the Intent.
3005 ActivityInfo aInfo;
3006 try {
3007 ResolveInfo rInfo =
3008 AppGlobals.getPackageManager().resolveIntent(
3009 intent, resolvedType,
3010 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07003011 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003012 aInfo = rInfo != null ? rInfo.activityInfo : null;
3013 } catch (RemoteException e) {
3014 aInfo = null;
3015 }
3016
3017 if (aInfo != null) {
3018 // Store the found target back into the intent, because now that
3019 // we have it we never want to do this again. For example, if the
3020 // user navigates back to this point in the history, we should
3021 // always restart the exact same activity.
3022 intent.setComponent(new ComponentName(
3023 aInfo.applicationInfo.packageName, aInfo.name));
3024
3025 // Don't debug things in the system process
Dianne Hackborna4972e92012-03-14 10:38:05 -07003026 if ((startFlags&ActivityManager.START_FLAG_DEBUG) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003027 if (!aInfo.processName.equals("system")) {
3028 mService.setDebugApp(aInfo.processName, true, false);
3029 }
3030 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003031
Dianne Hackborna4972e92012-03-14 10:38:05 -07003032 if ((startFlags&ActivityManager.START_FLAG_OPENGL_TRACES) != 0) {
Siva Velusamy92a8b222012-03-09 16:24:04 -08003033 if (!aInfo.processName.equals("system")) {
3034 mService.setOpenGlTraceApp(aInfo.applicationInfo, aInfo.processName);
3035 }
3036 }
3037
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003038 if (profileFile != null) {
3039 if (!aInfo.processName.equals("system")) {
3040 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003041 profileFile, profileFd,
3042 (startFlags&ActivityManager.START_FLAG_AUTO_STOP_PROFILER) != 0);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003043 }
3044 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003045 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003046 return aInfo;
3047 }
3048
3049 final int startActivityMayWait(IApplicationThread caller, int callingUid,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003050 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003051 String resultWho, int requestCode, int startFlags, String profileFile,
3052 ParcelFileDescriptor profileFd, WaitResult outResult, Configuration config,
3053 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003054 // Refuse possible leaked file descriptors
3055 if (intent != null && intent.hasFileDescriptors()) {
3056 throw new IllegalArgumentException("File descriptors passed in Intent");
3057 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003058 boolean componentSpecified = intent.getComponent() != null;
3059
3060 // Don't modify the client's object!
3061 intent = new Intent(intent);
3062
3063 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003064 ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003065 profileFile, profileFd, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003066
3067 synchronized (mService) {
3068 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003069 if (callingUid >= 0) {
3070 callingPid = -1;
3071 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003072 callingPid = Binder.getCallingPid();
3073 callingUid = Binder.getCallingUid();
3074 } else {
3075 callingPid = callingUid = -1;
3076 }
Craig Mautner27084302013-03-25 08:05:25 -07003077
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003078 mConfigWillChange = config != null
3079 && mService.mConfiguration.diff(config) != 0;
3080 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3081 "Starting activity when config will change = " + mConfigWillChange);
Craig Mautner27084302013-03-25 08:05:25 -07003082
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003083 final long origId = Binder.clearCallingIdentity();
Craig Mautner27084302013-03-25 08:05:25 -07003084
Craig Mautner2219a1b2013-03-25 09:44:30 -07003085 if (mStackSupervisor.isMainStack(this) && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07003086 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003087 // This may be a heavy-weight process! Check to see if we already
3088 // have another, different heavy-weight process running.
3089 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
3090 if (mService.mHeavyWeightProcess != null &&
3091 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
3092 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
3093 int realCallingPid = callingPid;
3094 int realCallingUid = callingUid;
3095 if (caller != null) {
3096 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
3097 if (callerApp != null) {
3098 realCallingPid = callerApp.pid;
3099 realCallingUid = callerApp.info.uid;
3100 } else {
3101 Slog.w(TAG, "Unable to find app for caller " + caller
3102 + " (pid=" + realCallingPid + ") when starting: "
3103 + intent.toString());
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003104 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003105 return ActivityManager.START_PERMISSION_DENIED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003106 }
3107 }
Craig Mautner27084302013-03-25 08:05:25 -07003108
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003109 IIntentSender target = mService.getIntentSenderLocked(
Dianne Hackborna4972e92012-03-14 10:38:05 -07003110 ActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn41203752012-08-31 14:05:51 -07003111 realCallingUid, userId, null, null, 0, new Intent[] { intent },
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003112 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003113 | PendingIntent.FLAG_ONE_SHOT, null);
Craig Mautner27084302013-03-25 08:05:25 -07003114
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003115 Intent newIntent = new Intent();
3116 if (requestCode >= 0) {
3117 // Caller is requesting a result.
3118 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
3119 }
3120 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
3121 new IntentSender(target));
3122 if (mService.mHeavyWeightProcess.activities.size() > 0) {
3123 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
3124 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
3125 hist.packageName);
3126 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
3127 hist.task.taskId);
3128 }
3129 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
3130 aInfo.packageName);
3131 newIntent.setFlags(intent.getFlags());
3132 newIntent.setClassName("android",
3133 HeavyWeightSwitcherActivity.class.getName());
3134 intent = newIntent;
3135 resolvedType = null;
3136 caller = null;
3137 callingUid = Binder.getCallingUid();
3138 callingPid = Binder.getCallingPid();
3139 componentSpecified = true;
3140 try {
3141 ResolveInfo rInfo =
3142 AppGlobals.getPackageManager().resolveIntent(
3143 intent, null,
3144 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07003145 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003146 aInfo = rInfo != null ? rInfo.activityInfo : null;
Amith Yamasani742a6712011-05-04 14:49:28 -07003147 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003148 } catch (RemoteException e) {
3149 aInfo = null;
3150 }
3151 }
3152 }
3153 }
Craig Mautner27084302013-03-25 08:05:25 -07003154
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003155 int res = startActivityLocked(caller, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003156 aInfo, resultTo, resultWho, requestCode, callingPid, callingUid,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003157 callingPackage, startFlags, options, componentSpecified, null);
Craig Mautner27084302013-03-25 08:05:25 -07003158
Craig Mautner2219a1b2013-03-25 09:44:30 -07003159 if (mConfigWillChange && mStackSupervisor.isMainStack(this)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003160 // If the caller also wants to switch to a new configuration,
3161 // do so now. This allows a clean switch, as we are waiting
3162 // for the current activity to pause (so we will not destroy
3163 // it), and have not yet started the next activity.
3164 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
3165 "updateConfiguration()");
3166 mConfigWillChange = false;
3167 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3168 "Updating to new configuration after starting activity.");
Dianne Hackborn813075a62011-11-14 17:45:19 -08003169 mService.updateConfigurationLocked(config, null, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003170 }
Craig Mautner27084302013-03-25 08:05:25 -07003171
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003172 Binder.restoreCallingIdentity(origId);
Craig Mautner27084302013-03-25 08:05:25 -07003173
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003174 if (outResult != null) {
3175 outResult.result = res;
Dianne Hackborna4972e92012-03-14 10:38:05 -07003176 if (res == ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003177 mWaitingActivityLaunched.add(outResult);
3178 do {
3179 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003180 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003181 } catch (InterruptedException e) {
3182 }
3183 } while (!outResult.timeout && outResult.who == null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003184 } else if (res == ActivityManager.START_TASK_TO_FRONT) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003185 ActivityRecord r = this.topRunningActivityLocked(null);
3186 if (r.nowVisible) {
3187 outResult.timeout = false;
3188 outResult.who = new ComponentName(r.info.packageName, r.info.name);
3189 outResult.totalTime = 0;
3190 outResult.thisTime = 0;
3191 } else {
3192 outResult.thisTime = SystemClock.uptimeMillis();
3193 mWaitingActivityVisible.add(outResult);
3194 do {
3195 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003196 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003197 } catch (InterruptedException e) {
3198 }
3199 } while (!outResult.timeout && outResult.who == null);
3200 }
3201 }
3202 }
Craig Mautner27084302013-03-25 08:05:25 -07003203
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003204 return res;
3205 }
3206 }
Craig Mautner27084302013-03-25 08:05:25 -07003207
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003208 final int startActivities(IApplicationThread caller, int callingUid, String callingPackage,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003209 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
3210 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003211 if (intents == null) {
3212 throw new NullPointerException("intents is null");
3213 }
3214 if (resolvedTypes == null) {
3215 throw new NullPointerException("resolvedTypes is null");
3216 }
3217 if (intents.length != resolvedTypes.length) {
3218 throw new IllegalArgumentException("intents are length different than resolvedTypes");
3219 }
3220
3221 ActivityRecord[] outActivity = new ActivityRecord[1];
3222
3223 int callingPid;
3224 if (callingUid >= 0) {
3225 callingPid = -1;
3226 } else if (caller == null) {
3227 callingPid = Binder.getCallingPid();
3228 callingUid = Binder.getCallingUid();
3229 } else {
3230 callingPid = callingUid = -1;
3231 }
3232 final long origId = Binder.clearCallingIdentity();
3233 try {
3234 synchronized (mService) {
3235
3236 for (int i=0; i<intents.length; i++) {
3237 Intent intent = intents[i];
3238 if (intent == null) {
3239 continue;
3240 }
3241
3242 // Refuse possible leaked file descriptors
3243 if (intent != null && intent.hasFileDescriptors()) {
3244 throw new IllegalArgumentException("File descriptors passed in Intent");
3245 }
3246
3247 boolean componentSpecified = intent.getComponent() != null;
3248
3249 // Don't modify the client's object!
3250 intent = new Intent(intent);
3251
3252 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003253 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i],
Amith Yamasani483f3b02012-03-13 16:08:00 -07003254 0, null, null, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07003255 // TODO: New, check if this is correct
3256 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003257
Craig Mautner8d341ef2013-03-26 09:03:27 -07003258 if (mStackSupervisor.isMainStack(this) && aInfo != null &&
3259 (aInfo.applicationInfo.flags & ApplicationInfo.FLAG_CANT_SAVE_STATE)
3260 != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003261 throw new IllegalArgumentException(
3262 "FLAG_CANT_SAVE_STATE not supported here");
3263 }
3264
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003265 Bundle theseOptions;
3266 if (options != null && i == intents.length-1) {
3267 theseOptions = options;
3268 } else {
3269 theseOptions = null;
3270 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003271 int res = startActivityLocked(caller, intent, resolvedTypes[i],
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003272 aInfo, resultTo, null, -1, callingPid, callingUid, callingPackage,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003273 0, theseOptions, componentSpecified, outActivity);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003274 if (res < 0) {
3275 return res;
3276 }
3277
Dianne Hackbornbe707852011-11-11 14:32:10 -08003278 resultTo = outActivity[0] != null ? outActivity[0].appToken : null;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003279 }
3280 }
3281 } finally {
3282 Binder.restoreCallingIdentity(origId);
3283 }
3284
Dianne Hackborna4972e92012-03-14 10:38:05 -07003285 return ActivityManager.START_SUCCESS;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003286 }
3287
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003288 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
3289 long thisTime, long totalTime) {
3290 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
3291 WaitResult w = mWaitingActivityLaunched.get(i);
3292 w.timeout = timeout;
3293 if (r != null) {
3294 w.who = new ComponentName(r.info.packageName, r.info.name);
3295 }
3296 w.thisTime = thisTime;
3297 w.totalTime = totalTime;
3298 }
3299 mService.notifyAll();
3300 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003301
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003302 void reportActivityVisibleLocked(ActivityRecord r) {
3303 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
3304 WaitResult w = mWaitingActivityVisible.get(i);
3305 w.timeout = false;
3306 if (r != null) {
3307 w.who = new ComponentName(r.info.packageName, r.info.name);
3308 }
3309 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
3310 w.thisTime = w.totalTime;
3311 }
3312 mService.notifyAll();
Craig Mautner27084302013-03-25 08:05:25 -07003313 mStackSupervisor.dismissKeyguard();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003314 }
3315
3316 void sendActivityResultLocked(int callingUid, ActivityRecord r,
3317 String resultWho, int requestCode, int resultCode, Intent data) {
3318
3319 if (callingUid > 0) {
3320 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003321 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003322 }
3323
3324 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3325 + " : who=" + resultWho + " req=" + requestCode
3326 + " res=" + resultCode + " data=" + data);
3327 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3328 try {
3329 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3330 list.add(new ResultInfo(resultWho, requestCode,
3331 resultCode, data));
Dianne Hackbornbe707852011-11-11 14:32:10 -08003332 r.app.thread.scheduleSendResult(r.appToken, list);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003333 return;
3334 } catch (Exception e) {
3335 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3336 }
3337 }
3338
3339 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3340 }
3341
3342 private final void stopActivityLocked(ActivityRecord r) {
3343 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3344 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3345 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3346 if (!r.finishing) {
Christopher Tated3f175c2012-06-14 14:16:54 -07003347 if (!mService.mSleeping) {
3348 if (DEBUG_STATES) {
3349 Slog.d(TAG, "no-history finish of " + r);
3350 }
3351 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003352 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07003353 } else {
3354 if (DEBUG_STATES) Slog.d(TAG, "Not finishing noHistory " + r
3355 + " on stop because we're just sleeping");
3356 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003357 }
Christopher Tate5007ddd2012-06-12 13:08:18 -07003358 }
3359
3360 if (r.app != null && r.app.thread != null) {
Craig Mautner2219a1b2013-03-25 09:44:30 -07003361 if (mStackSupervisor.isMainStack(this)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003362 if (mService.mFocusedActivity == r) {
3363 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3364 }
3365 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003366 r.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003367 try {
3368 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003369 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3370 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003371 r.state = ActivityState.STOPPING;
3372 if (DEBUG_VISBILITY) Slog.v(
3373 TAG, "Stopping visible=" + r.visible + " for " + r);
3374 if (!r.visible) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003375 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003376 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003377 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003378 if (mService.isSleeping()) {
3379 r.setSleeping(true);
3380 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003381 Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG);
3382 msg.obj = r;
3383 mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003384 } catch (Exception e) {
3385 // Maybe just ignore exceptions here... if the process
3386 // has crashed, our death notification will clean things
3387 // up.
3388 Slog.w(TAG, "Exception thrown during pause", e);
3389 // Just in case, assume it to be stopped.
3390 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003391 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003392 r.state = ActivityState.STOPPED;
3393 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003394 destroyActivityLocked(r, true, false, "stop-except");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003395 }
3396 }
3397 }
3398 }
3399
3400 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3401 boolean remove) {
3402 int N = mStoppingActivities.size();
3403 if (N <= 0) return null;
3404
3405 ArrayList<ActivityRecord> stops = null;
3406
3407 final boolean nowVisible = mResumedActivity != null
3408 && mResumedActivity.nowVisible
3409 && !mResumedActivity.waitingVisible;
3410 for (int i=0; i<N; i++) {
3411 ActivityRecord s = mStoppingActivities.get(i);
3412 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3413 + nowVisible + " waitingVisible=" + s.waitingVisible
3414 + " finishing=" + s.finishing);
3415 if (s.waitingVisible && nowVisible) {
3416 mWaitingVisibleActivities.remove(s);
3417 s.waitingVisible = false;
3418 if (s.finishing) {
3419 // If this activity is finishing, it is sitting on top of
3420 // everyone else but we now know it is no longer needed...
3421 // so get rid of it. Otherwise, we need to go through the
3422 // normal flow and hide it once we determine that it is
3423 // hidden by the activities in front of it.
3424 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003425 mService.mWindowManager.setAppVisibility(s.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003426 }
3427 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003428 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003429 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3430 if (stops == null) {
3431 stops = new ArrayList<ActivityRecord>();
3432 }
3433 stops.add(s);
3434 mStoppingActivities.remove(i);
3435 N--;
3436 i--;
3437 }
3438 }
3439
3440 return stops;
3441 }
3442
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003443 final void scheduleIdleLocked() {
3444 Message msg = Message.obtain();
3445 msg.what = IDLE_NOW_MSG;
3446 mHandler.sendMessage(msg);
3447 }
3448
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003449 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003450 Configuration config) {
3451 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3452
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003453 ActivityRecord res = null;
3454
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003455 ArrayList<ActivityRecord> stops = null;
3456 ArrayList<ActivityRecord> finishes = null;
3457 ArrayList<ActivityRecord> thumbnails = null;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003458 ArrayList<UserStartedState> startingUsers = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003459 int NS = 0;
3460 int NF = 0;
3461 int NT = 0;
3462 IApplicationThread sendThumbnail = null;
3463 boolean booting = false;
3464 boolean enableScreen = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003465 boolean activityRemoved = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003466
3467 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003468 ActivityRecord r = ActivityRecord.forToken(token);
3469 if (r != null) {
3470 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003471 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003472 }
3473
3474 // Get the activity record.
Craig Mautnerd44711d2013-02-23 11:24:36 -08003475 if (isInStackLocked(token) != null) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003476 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003477
3478 if (fromTimeout) {
3479 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3480 }
3481
3482 // This is a hack to semi-deal with a race condition
3483 // in the client where it can be constructed with a
3484 // newer configuration from when we asked it to launch.
3485 // We'll update with whatever configuration it now says
3486 // it used to launch.
3487 if (config != null) {
3488 r.configuration = config;
3489 }
3490
3491 // No longer need to keep the device awake.
3492 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3493 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3494 mLaunchingActivity.release();
3495 }
3496
3497 // We are now idle. If someone is waiting for a thumbnail from
3498 // us, we can now deliver.
3499 r.idle = true;
3500 mService.scheduleAppGcsLocked();
3501 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3502 sendThumbnail = r.app.thread;
3503 r.thumbnailNeeded = false;
3504 }
3505
3506 // If this activity is fullscreen, set up to hide those under it.
3507
3508 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3509 ensureActivitiesVisibleLocked(null, 0);
3510
3511 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
Craig Mautner2219a1b2013-03-25 09:44:30 -07003512 if (mStackSupervisor.isMainStack(this)) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003513 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003514 mService.mBooted = true;
3515 enableScreen = true;
3516 }
3517 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003518 } else if (fromTimeout) {
3519 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3520 }
3521
3522 // Atomically retrieve all of the other things to do.
3523 stops = processStoppingActivitiesLocked(true);
3524 NS = stops != null ? stops.size() : 0;
3525 if ((NF=mFinishingActivities.size()) > 0) {
3526 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3527 mFinishingActivities.clear();
3528 }
Craig Mautnercae015f2013-02-08 14:31:27 -08003529 if ((NT=mCancelledThumbnails.size()) > 0) {
3530 thumbnails = new ArrayList<ActivityRecord>(mCancelledThumbnails);
3531 mCancelledThumbnails.clear();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003532 }
3533
Craig Mautner2219a1b2013-03-25 09:44:30 -07003534 if (mStackSupervisor.isMainStack(this)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003535 booting = mService.mBooting;
3536 mService.mBooting = false;
3537 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003538 if (mStartingUsers.size() > 0) {
3539 startingUsers = new ArrayList<UserStartedState>(mStartingUsers);
3540 mStartingUsers.clear();
3541 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003542 }
3543
3544 int i;
3545
3546 // Send thumbnail if requested.
3547 if (sendThumbnail != null) {
3548 try {
3549 sendThumbnail.requestThumbnail(token);
3550 } catch (Exception e) {
3551 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3552 mService.sendPendingThumbnail(null, token, null, null, true);
3553 }
3554 }
3555
3556 // Stop any activities that are scheduled to do so but have been
3557 // waiting for the next one to start.
3558 for (i=0; i<NS; i++) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003559 ActivityRecord r = stops.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003560 synchronized (mService) {
3561 if (r.finishing) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003562 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003563 } else {
3564 stopActivityLocked(r);
3565 }
3566 }
3567 }
3568
3569 // Finish any activities that are scheduled to do so but have been
3570 // waiting for the next one to start.
3571 for (i=0; i<NF; i++) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003572 ActivityRecord r = finishes.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003573 synchronized (mService) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003574 activityRemoved = destroyActivityLocked(r, true, false, "finish-idle");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003575 }
3576 }
3577
3578 // Report back to any thumbnail receivers.
3579 for (i=0; i<NT; i++) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003580 ActivityRecord r = thumbnails.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003581 mService.sendPendingThumbnail(r, null, null, null, true);
3582 }
3583
3584 if (booting) {
3585 mService.finishBooting();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003586 } else if (startingUsers != null) {
3587 for (i=0; i<startingUsers.size(); i++) {
3588 mService.finishUserSwitch(startingUsers.get(i));
3589 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003590 }
3591
3592 mService.trimApplications();
3593 //dump();
3594 //mWindowManager.dump();
3595
3596 if (enableScreen) {
3597 mService.enableScreenAfterBoot();
3598 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003599
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003600 if (activityRemoved) {
3601 resumeTopActivityLocked(null);
3602 }
3603
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003604 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003605 }
3606
3607 /**
3608 * @return Returns true if the activity is being finished, false if for
3609 * some reason it is being left as-is.
3610 */
3611 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003612 Intent resultData, String reason, boolean oomAdj) {
Craig Mautnerd74f7d72013-02-26 13:41:02 -08003613 ActivityRecord r = isInStackLocked(token);
Christopher Tated3f175c2012-06-14 14:16:54 -07003614 if (DEBUG_RESULTS || DEBUG_STATES) Slog.v(
Craig Mautnerd74f7d72013-02-26 13:41:02 -08003615 TAG, "Finishing activity token=" + token + " r="
Christopher Tated3f175c2012-06-14 14:16:54 -07003616 + ", result=" + resultCode + ", data=" + resultData
3617 + ", reason=" + reason);
Craig Mautnerd74f7d72013-02-26 13:41:02 -08003618 if (r == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003619 return false;
3620 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003621
Craig Mautnerd44711d2013-02-23 11:24:36 -08003622 finishActivityLocked(r, resultCode, resultData, reason, oomAdj);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003623 return true;
3624 }
3625
Craig Mautnerd2328952013-03-05 12:46:26 -08003626 final void finishSubActivityLocked(ActivityRecord self, String resultWho, int requestCode) {
Craig Mautner9658b312013-02-28 10:55:59 -08003627 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3628 ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3629 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3630 ActivityRecord r = activities.get(activityNdx);
3631 if (r.resultTo == self && r.requestCode == requestCode) {
3632 if ((r.resultWho == null && resultWho == null) ||
3633 (r.resultWho != null && r.resultWho.equals(resultWho))) {
3634 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "request-sub",
3635 false);
3636 }
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003637 }
3638 }
3639 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003640 mService.updateOomAdjLocked();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003641 }
3642
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003643 final void finishTopRunningActivityLocked(ProcessRecord app) {
3644 ActivityRecord r = topRunningActivityLocked(null);
3645 if (r != null && r.app == app) {
3646 // If the top running activity is from this crashing
3647 // process, then terminate it to avoid getting in a loop.
3648 Slog.w(TAG, " Force finishing activity "
3649 + r.intent.getComponent().flattenToShortString());
Craig Mautner9658b312013-02-28 10:55:59 -08003650 int taskNdx = mTaskHistory.indexOf(r.task);
3651 int activityNdx = r.task.mActivities.indexOf(r);
Craig Mautnerd2328952013-03-05 12:46:26 -08003652 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003653 // Also terminate any activities below it that aren't yet
3654 // stopped, to avoid a situation where one will get
3655 // re-start our crashing activity once it gets resumed again.
Craig Mautner9658b312013-02-28 10:55:59 -08003656 --activityNdx;
3657 if (activityNdx < 0) {
3658 do {
3659 --taskNdx;
3660 if (taskNdx < 0) {
3661 break;
3662 }
3663 activityNdx = mTaskHistory.get(taskNdx).mActivities.size() - 1;
3664 } while (activityNdx < 0);
3665 }
3666 if (activityNdx >= 0) {
3667 r = mTaskHistory.get(taskNdx).mActivities.get(activityNdx);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003668 if (r.state == ActivityState.RESUMED
3669 || r.state == ActivityState.PAUSING
3670 || r.state == ActivityState.PAUSED) {
3671 if (!r.isHomeActivity || mService.mHomeProcess != r.app) {
3672 Slog.w(TAG, " Force finishing activity "
3673 + r.intent.getComponent().flattenToShortString());
Craig Mautnerd2328952013-03-05 12:46:26 -08003674 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003675 }
3676 }
3677 }
3678 }
3679 }
3680
Craig Mautnerd2328952013-03-05 12:46:26 -08003681 final boolean finishActivityAffinityLocked(ActivityRecord r) {
Craig Mautnerd74f7d72013-02-26 13:41:02 -08003682 ArrayList<ActivityRecord> activities = r.task.mActivities;
3683 for (int index = activities.indexOf(r); index >= 0; --index) {
3684 ActivityRecord cur = activities.get(index);
3685 if (!Objects.equal(cur.taskAffinity, r.taskAffinity)) {
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003686 break;
3687 }
Craig Mautnerd44711d2013-02-23 11:24:36 -08003688 finishActivityLocked(cur, Activity.RESULT_CANCELED, null, "request-affinity",
3689 true);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003690 }
3691 return true;
3692 }
3693
Dianne Hackborn5c607432012-02-28 14:44:19 -08003694 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
3695 // send the result
3696 ActivityRecord resultTo = r.resultTo;
3697 if (resultTo != null) {
3698 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3699 + " who=" + r.resultWho + " req=" + r.requestCode
3700 + " res=" + resultCode + " data=" + resultData);
3701 if (r.info.applicationInfo.uid > 0) {
3702 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3703 resultTo.packageName, resultData,
3704 resultTo.getUriPermissionsLocked());
3705 }
3706 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3707 resultData);
3708 r.resultTo = null;
3709 }
3710 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3711
3712 // Make sure this HistoryRecord is not holding on to other resources,
3713 // because clients have remote IPC references to this object so we
3714 // can't assume that will go away and want to avoid circular IPC refs.
3715 r.results = null;
3716 r.pendingResults = null;
3717 r.newIntents = null;
3718 r.icicle = null;
3719 }
3720
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003721 /**
3722 * @return Returns true if this activity has been removed from the history
3723 * list, or false if it is still in the list and will be removed later.
3724 */
Craig Mautnerd44711d2013-02-23 11:24:36 -08003725 final boolean finishActivityLocked(ActivityRecord r, int resultCode,
3726 Intent resultData, String reason, boolean oomAdj) {
3727 return finishActivityLocked(r, resultCode, resultData, reason, false, oomAdj);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003728 }
3729
3730 /**
3731 * @return Returns true if this activity has been removed from the history
3732 * list, or false if it is still in the list and will be removed later.
3733 */
Craig Mautnerd44711d2013-02-23 11:24:36 -08003734 final boolean finishActivityLocked(ActivityRecord r, int resultCode, Intent resultData,
3735 String reason, boolean immediate, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003736 if (r.finishing) {
3737 Slog.w(TAG, "Duplicate finish request for " + r);
3738 return false;
3739 }
3740
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003741 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003742 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003743 r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003744 r.task.taskId, r.shortComponentName, reason);
Craig Mautnerd44711d2013-02-23 11:24:36 -08003745 final ArrayList<ActivityRecord> activities = r.task.mActivities;
3746 final int index = activities.indexOf(r);
3747 if (index < (activities.size() - 1)) {
3748 ActivityRecord next = activities.get(index+1);
3749 if (r.frontOfTask) {
3750 // The next activity is now the front of the task.
3751 next.frontOfTask = true;
3752 }
3753 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3754 // If the caller asked that this activity (and all above it)
3755 // be cleared when the task is reset, don't lose that information,
3756 // but propagate it up to the next activity.
3757 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003758 }
3759 }
3760
3761 r.pauseKeyDispatchingLocked();
Craig Mautner2219a1b2013-03-25 09:44:30 -07003762 if (mStackSupervisor.isMainStack(this)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003763 if (mService.mFocusedActivity == r) {
3764 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3765 }
3766 }
3767
Dianne Hackborn5c607432012-02-28 14:44:19 -08003768 finishActivityResultsLocked(r, resultCode, resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003769
3770 if (mService.mPendingThumbnails.size() > 0) {
3771 // There are clients waiting to receive thumbnails so, in case
3772 // this is an activity that someone is waiting for, add it
3773 // to the pending list so we can correctly update the clients.
Craig Mautnercae015f2013-02-08 14:31:27 -08003774 mCancelledThumbnails.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003775 }
3776
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003777 if (immediate) {
Craig Mautnerd44711d2013-02-23 11:24:36 -08003778 return finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, oomAdj) == null;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003779 } else if (mResumedActivity == r) {
Craig Mautner0247fc82013-02-28 14:32:06 -08003780 boolean endTask = index <= 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003781 if (DEBUG_TRANSITION) Slog.v(TAG,
3782 "Prepare close transition: finishing " + r);
3783 mService.mWindowManager.prepareAppTransition(endTask
Craig Mautner4b71aa12012-12-27 17:20:01 -08003784 ? AppTransition.TRANSIT_TASK_CLOSE
3785 : AppTransition.TRANSIT_ACTIVITY_CLOSE, false);
Craig Mautner0247fc82013-02-28 14:32:06 -08003786
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003787 // Tell window manager to prepare for this one to be removed.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003788 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003789
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003790 if (mPausingActivity == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003791 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3792 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3793 startPausingLocked(false, false);
3794 }
3795
3796 } else if (r.state != ActivityState.PAUSING) {
3797 // If the activity is PAUSING, we will complete the finish once
3798 // it is done pausing; else we can just directly finish it here.
3799 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
Craig Mautnerd44711d2013-02-23 11:24:36 -08003800 return finishCurrentActivityLocked(r, FINISH_AFTER_PAUSE, oomAdj) == null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003801 } else {
3802 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3803 }
3804
3805 return false;
3806 }
3807
3808 private static final int FINISH_IMMEDIATELY = 0;
3809 private static final int FINISH_AFTER_PAUSE = 1;
3810 private static final int FINISH_AFTER_VISIBLE = 2;
3811
Craig Mautnerd44711d2013-02-23 11:24:36 -08003812
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003813 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003814 int mode, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003815 // First things first: if this activity is currently visible,
3816 // and the resumed activity is not yet visible, then hold off on
3817 // finishing until the resumed one becomes visible.
3818 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3819 if (!mStoppingActivities.contains(r)) {
3820 mStoppingActivities.add(r);
3821 if (mStoppingActivities.size() > 3) {
3822 // If we already have a few activities waiting to stop,
3823 // then give up on things going idle and start clearing
3824 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003825 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003826 } else {
3827 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003828 }
3829 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003830 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3831 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003832 r.state = ActivityState.STOPPING;
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003833 if (oomAdj) {
3834 mService.updateOomAdjLocked();
3835 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003836 return r;
3837 }
3838
3839 // make sure the record is cleaned out of other places.
3840 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003841 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003842 mWaitingVisibleActivities.remove(r);
3843 if (mResumedActivity == r) {
3844 mResumedActivity = null;
3845 }
3846 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003847 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003848 r.state = ActivityState.FINISHING;
3849
3850 if (mode == FINISH_IMMEDIATELY
3851 || prevState == ActivityState.STOPPED
3852 || prevState == ActivityState.INITIALIZING) {
3853 // If this activity is already stopped, we can just finish
3854 // it right now.
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003855 boolean activityRemoved = destroyActivityLocked(r, true,
3856 oomAdj, "finish-imm");
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003857 if (activityRemoved) {
3858 resumeTopActivityLocked(null);
3859 }
3860 return activityRemoved ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003861 }
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003862
3863 // Need to go through the full pause cycle to get this
3864 // activity into the stopped state and then finish it.
3865 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3866 mFinishingActivities.add(r);
3867 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003868 return r;
3869 }
3870
Craig Mautnerd2328952013-03-05 12:46:26 -08003871 final boolean navigateUpToLocked(IBinder token, Intent destIntent, int resultCode,
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003872 Intent resultData) {
Craig Mautnerd2328952013-03-05 12:46:26 -08003873 final ActivityRecord srec = ActivityRecord.forToken(token);
Craig Mautner0247fc82013-02-28 14:32:06 -08003874 final TaskRecord task = srec.task;
3875 final ArrayList<ActivityRecord> activities = task.mActivities;
3876 final int start = activities.indexOf(srec);
3877 if (!mTaskHistory.contains(task) || (start < 0)) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003878 return false;
3879 }
3880 int finishTo = start - 1;
Craig Mautner0247fc82013-02-28 14:32:06 -08003881 ActivityRecord parent = finishTo < 0 ? null : activities.get(finishTo);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003882 boolean foundParentInTask = false;
Craig Mautner0247fc82013-02-28 14:32:06 -08003883 final ComponentName dest = destIntent.getComponent();
3884 if (start > 0 && dest != null) {
3885 for (int i = finishTo; i >= 0; i--) {
3886 ActivityRecord r = activities.get(i);
3887 if (r.info.packageName.equals(dest.getPackageName()) &&
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003888 r.info.name.equals(dest.getClassName())) {
3889 finishTo = i;
3890 parent = r;
3891 foundParentInTask = true;
3892 break;
3893 }
3894 }
3895 }
3896
3897 IActivityController controller = mService.mController;
3898 if (controller != null) {
3899 ActivityRecord next = topRunningActivityLocked(srec.appToken, 0);
3900 if (next != null) {
3901 // ask watcher if this is allowed
3902 boolean resumeOK = true;
3903 try {
3904 resumeOK = controller.activityResuming(next.packageName);
3905 } catch (RemoteException e) {
3906 mService.mController = null;
3907 }
3908
3909 if (!resumeOK) {
3910 return false;
3911 }
3912 }
3913 }
3914 final long origId = Binder.clearCallingIdentity();
3915 for (int i = start; i > finishTo; i--) {
Craig Mautner0247fc82013-02-28 14:32:06 -08003916 ActivityRecord r = activities.get(i);
3917 requestFinishActivityLocked(r.appToken, resultCode, resultData, "navigate-up", true);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003918 // Only return the supplied result for the first activity finished
3919 resultCode = Activity.RESULT_CANCELED;
3920 resultData = null;
3921 }
3922
3923 if (parent != null && foundParentInTask) {
3924 final int parentLaunchMode = parent.info.launchMode;
3925 final int destIntentFlags = destIntent.getFlags();
3926 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
3927 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
3928 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
3929 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
3930 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
3931 } else {
3932 try {
3933 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
3934 destIntent.getComponent(), 0, srec.userId);
3935 int res = startActivityLocked(srec.app.thread, destIntent,
3936 null, aInfo, parent.appToken, null,
3937 0, -1, parent.launchedFromUid, parent.launchedFromPackage,
3938 0, null, true, null);
3939 foundParentInTask = res == ActivityManager.START_SUCCESS;
3940 } catch (RemoteException e) {
3941 foundParentInTask = false;
3942 }
3943 requestFinishActivityLocked(parent.appToken, resultCode,
3944 resultData, "navigate-up", true);
3945 }
3946 }
3947 Binder.restoreCallingIdentity(origId);
3948 return foundParentInTask;
3949 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003950 /**
3951 * Perform the common clean-up of an activity record. This is called both
3952 * as part of destroyActivityLocked() (when destroying the client-side
3953 * representation) and cleaning things up as a result of its hosting
3954 * processing going away, in which case there is no remaining client-side
3955 * state to destroy so only the cleanup here is needed.
3956 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003957 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3958 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003959 if (mResumedActivity == r) {
3960 mResumedActivity = null;
3961 }
3962 if (mService.mFocusedActivity == r) {
3963 mService.mFocusedActivity = null;
3964 }
3965
3966 r.configDestroy = false;
3967 r.frozenBeforeDestroy = false;
3968
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003969 if (setState) {
3970 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3971 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08003972 if (DEBUG_APP) Slog.v(TAG, "Clearing app during cleanUp for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003973 r.app = null;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003974 }
3975
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003976 // Make sure this record is no longer in the pending finishes list.
3977 // This could happen, for example, if we are trimming activities
3978 // down to the max limit while they are still waiting to finish.
3979 mFinishingActivities.remove(r);
3980 mWaitingVisibleActivities.remove(r);
3981
3982 // Remove any pending results.
3983 if (r.finishing && r.pendingResults != null) {
3984 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3985 PendingIntentRecord rec = apr.get();
3986 if (rec != null) {
3987 mService.cancelIntentSenderLocked(rec, false);
3988 }
3989 }
3990 r.pendingResults = null;
3991 }
3992
3993 if (cleanServices) {
3994 cleanUpActivityServicesLocked(r);
3995 }
3996
3997 if (mService.mPendingThumbnails.size() > 0) {
3998 // There are clients waiting to receive thumbnails so, in case
3999 // this is an activity that someone is waiting for, add it
4000 // to the pending list so we can correctly update the clients.
Craig Mautnercae015f2013-02-08 14:31:27 -08004001 mCancelledThumbnails.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004002 }
4003
4004 // Get rid of any pending idle timeouts.
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004005 removeTimeoutsForActivityLocked(r);
4006 }
4007
4008 private void removeTimeoutsForActivityLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004009 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07004010 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004011 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004012 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07004013 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004014 }
4015
Dianne Hackborn5c607432012-02-28 14:44:19 -08004016 final void removeActivityFromHistoryLocked(ActivityRecord r) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004017 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
4018 r.makeFinishing();
4019 if (DEBUG_ADD_REMOVE) {
4020 RuntimeException here = new RuntimeException("here");
4021 here.fillInStackTrace();
4022 Slog.i(TAG, "Removing activity " + r + " from stack");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004023 }
Craig Mautner0247fc82013-02-28 14:32:06 -08004024 if (r.task != null) {
4025 removeActivity(r);
Craig Mautner5d9c7be2013-02-15 14:02:56 -08004026 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004027 r.takeFromHistory();
4028 removeTimeoutsForActivityLocked(r);
Craig Mautner0247fc82013-02-28 14:32:06 -08004029 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (removed from history)");
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004030 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08004031 if (DEBUG_APP) Slog.v(TAG, "Clearing app during remove for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004032 r.app = null;
4033 mService.mWindowManager.removeAppToken(r.appToken);
4034 if (VALIDATE_TOKENS) {
4035 validateAppTokensLocked();
4036 }
4037 cleanUpActivityServicesLocked(r);
4038 r.removeUriPermissionsLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004039 }
4040
4041 /**
4042 * Perform clean-up of service connections in an activity record.
4043 */
4044 final void cleanUpActivityServicesLocked(ActivityRecord r) {
4045 // Throw away any services that have been bound by this activity.
4046 if (r.connections != null) {
4047 Iterator<ConnectionRecord> it = r.connections.iterator();
4048 while (it.hasNext()) {
4049 ConnectionRecord c = it.next();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004050 mService.mServices.removeConnectionLocked(c, null, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004051 }
4052 r.connections = null;
4053 }
4054 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004055
4056 final void scheduleDestroyActivities(ProcessRecord owner, boolean oomAdj, String reason) {
4057 Message msg = mHandler.obtainMessage(DESTROY_ACTIVITIES_MSG);
4058 msg.obj = new ScheduleDestroyArgs(owner, oomAdj, reason);
4059 mHandler.sendMessage(msg);
4060 }
4061
Dianne Hackborn28695e02011-11-02 21:59:51 -07004062 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004063 boolean lastIsOpaque = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004064 boolean activityRemoved = false;
Craig Mautnerd44711d2013-02-23 11:24:36 -08004065 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4066 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4067 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4068 final ActivityRecord r = activities.get(activityNdx);
4069 if (r.finishing) {
4070 continue;
4071 }
4072 if (r.fullscreen) {
4073 lastIsOpaque = true;
4074 }
4075 if (owner != null && r.app != owner) {
4076 continue;
4077 }
4078 if (!lastIsOpaque) {
4079 continue;
4080 }
4081 // We can destroy this one if we have its icicle saved and
4082 // it is not in the process of pausing/stopping/finishing.
4083 if (r.app != null && r != mResumedActivity && r != mPausingActivity
4084 && r.haveState && !r.visible && r.stopped
4085 && r.state != ActivityState.DESTROYING
4086 && r.state != ActivityState.DESTROYED) {
4087 if (DEBUG_SWITCH) Slog.v(TAG, "Destroying " + r + " in state " + r.state
4088 + " resumed=" + mResumedActivity
4089 + " pausing=" + mPausingActivity);
4090 if (destroyActivityLocked(r, true, oomAdj, reason)) {
4091 activityRemoved = true;
4092 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004093 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004094 }
4095 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004096 if (activityRemoved) {
4097 resumeTopActivityLocked(null);
4098 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004099 }
4100
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004101 /**
4102 * Destroy the current CLIENT SIDE instance of an activity. This may be
4103 * called both when actually finishing an activity, or when performing
4104 * a configuration switch where we destroy the current client-side object
4105 * but then create a new client-side object for this same HistoryRecord.
4106 */
4107 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackborn28695e02011-11-02 21:59:51 -07004108 boolean removeFromApp, boolean oomAdj, String reason) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004109 if (DEBUG_SWITCH || DEBUG_CLEANUP) Slog.v(
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004110 TAG, "Removing activity from " + reason + ": token=" + r
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004111 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
4112 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004113 r.userId, System.identityHashCode(r),
Dianne Hackborn28695e02011-11-02 21:59:51 -07004114 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004115
4116 boolean removedFromHistory = false;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004117
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004118 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004119
4120 final boolean hadApp = r.app != null;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004121
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004122 if (hadApp) {
4123 if (removeFromApp) {
Craig Mautnerd2328952013-03-05 12:46:26 -08004124 r.app.activities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004125 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
4126 mService.mHeavyWeightProcess = null;
4127 mService.mHandler.sendEmptyMessage(
4128 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
4129 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004130 if (r.app.activities.size() == 0) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07004131 // No longer have activities, so update oom adj.
4132 mService.updateOomAdjLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004133 }
4134 }
4135
4136 boolean skipDestroy = false;
4137
4138 try {
4139 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004140 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004141 r.configChangeFlags);
4142 } catch (Exception e) {
4143 // We can just ignore exceptions here... if the process
4144 // has crashed, our death notification will clean things
4145 // up.
4146 //Slog.w(TAG, "Exception thrown during finish", e);
4147 if (r.finishing) {
4148 removeActivityFromHistoryLocked(r);
4149 removedFromHistory = true;
4150 skipDestroy = true;
4151 }
4152 }
4153
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004154 r.nowVisible = false;
4155
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004156 // If the activity is finishing, we need to wait on removing it
4157 // from the list to give it a chance to do its cleanup. During
4158 // that time it may make calls back with its token so we need to
4159 // be able to find it on the list and so we don't want to remove
4160 // it from the list yet. Otherwise, we can just immediately put
4161 // it in the destroyed state since we are not removing it from the
4162 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004163 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004164 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
4165 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004166 r.state = ActivityState.DESTROYING;
4167 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
4168 msg.obj = r;
4169 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
4170 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004171 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4172 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004173 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08004174 if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004175 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004176 }
4177 } else {
4178 // remove this record from the history.
4179 if (r.finishing) {
4180 removeActivityFromHistoryLocked(r);
4181 removedFromHistory = true;
4182 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004183 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4184 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004185 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08004186 if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004187 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004188 }
4189 }
4190
4191 r.configChangeFlags = 0;
4192
4193 if (!mLRUActivities.remove(r) && hadApp) {
4194 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
4195 }
4196
4197 return removedFromHistory;
4198 }
4199
Craig Mautnerd2328952013-03-05 12:46:26 -08004200 final void activityDestroyedLocked(IBinder token) {
4201 final long origId = Binder.clearCallingIdentity();
4202 try {
4203 ActivityRecord r = ActivityRecord.forToken(token);
4204 if (r != null) {
4205 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004206 }
Craig Mautnerd2328952013-03-05 12:46:26 -08004207
4208 if (isInStackLocked(token) != null) {
4209 if (r.state == ActivityState.DESTROYING) {
4210 cleanUpActivityLocked(r, true, false);
4211 removeActivityFromHistoryLocked(r);
4212 }
4213 }
4214 resumeTopActivityLocked(null);
4215 } finally {
4216 Binder.restoreCallingIdentity(origId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004217 }
4218 }
4219
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004220 private void removeHistoryRecordsForAppLocked(ArrayList<ActivityRecord> list,
4221 ProcessRecord app, String listName) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004222 int i = list.size();
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004223 if (DEBUG_CLEANUP) Slog.v(
4224 TAG, "Removing app " + app + " from list " + listName
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004225 + " with " + i + " entries");
4226 while (i > 0) {
4227 i--;
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004228 ActivityRecord r = list.get(i);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004229 if (DEBUG_CLEANUP) Slog.v(TAG, "Record #" + i + " " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004230 if (r.app == app) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004231 if (DEBUG_CLEANUP) Slog.v(TAG, "---> REMOVING this entry!");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004232 list.remove(i);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004233 removeTimeoutsForActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004234 }
4235 }
4236 }
4237
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004238 boolean removeHistoryRecordsForAppLocked(ProcessRecord app) {
4239 removeHistoryRecordsForAppLocked(mLRUActivities, app, "mLRUActivities");
4240 removeHistoryRecordsForAppLocked(mStoppingActivities, app, "mStoppingActivities");
4241 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app, "mGoingToSleepActivities");
4242 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app,
4243 "mWaitingVisibleActivities");
4244 removeHistoryRecordsForAppLocked(mFinishingActivities, app, "mFinishingActivities");
4245
4246 boolean hasVisibleActivities = false;
4247
4248 // Clean out the history list.
Craig Mautner0247fc82013-02-28 14:32:06 -08004249 int i = numActivities();
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004250 if (DEBUG_CLEANUP) Slog.v(
4251 TAG, "Removing app " + app + " from history with " + i + " entries");
Craig Mautner0247fc82013-02-28 14:32:06 -08004252 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4253 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4254 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4255 final ActivityRecord r = activities.get(activityNdx);
4256 --i;
4257 if (DEBUG_CLEANUP) Slog.v(
4258 TAG, "Record #" + i + " " + r + ": app=" + r.app);
4259 if (r.app == app) {
4260 boolean remove;
4261 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
4262 // Don't currently have state for the activity, or
4263 // it is finishing -- always remove it.
4264 remove = true;
4265 } else if (r.launchCount > 2 &&
4266 r.lastLaunchTime > (SystemClock.uptimeMillis()-60000)) {
4267 // We have launched this activity too many times since it was
4268 // able to run, so give up and remove it.
4269 remove = true;
4270 } else {
4271 // The process may be gone, but the activity lives on!
4272 remove = false;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004273 }
Craig Mautner0247fc82013-02-28 14:32:06 -08004274 if (remove) {
4275 if (ActivityStack.DEBUG_ADD_REMOVE || DEBUG_CLEANUP) {
4276 RuntimeException here = new RuntimeException("here");
4277 here.fillInStackTrace();
4278 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
4279 + ": haveState=" + r.haveState
4280 + " stateNotNeeded=" + r.stateNotNeeded
4281 + " finishing=" + r.finishing
4282 + " state=" + r.state, here);
4283 }
4284 if (!r.finishing) {
4285 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
4286 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
4287 r.userId, System.identityHashCode(r),
4288 r.task.taskId, r.shortComponentName,
4289 "proc died without state saved");
4290 }
4291 removeActivityFromHistoryLocked(r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004292
Craig Mautner0247fc82013-02-28 14:32:06 -08004293 } else {
4294 // We have the current state for this activity, so
4295 // it can be restarted later when needed.
4296 if (localLOGV) Slog.v(
4297 TAG, "Keeping entry, setting app to null");
4298 if (r.visible) {
4299 hasVisibleActivities = true;
4300 }
4301 if (DEBUG_APP) Slog.v(TAG, "Clearing app during removeHistory for activity "
4302 + r);
4303 r.app = null;
4304 r.nowVisible = false;
4305 if (!r.haveState) {
4306 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
4307 "App died, clearing saved state of " + r);
4308 r.icicle = null;
4309 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004310 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004311
Craig Mautnerd2328952013-03-05 12:46:26 -08004312 cleanUpActivityLocked(r, true, true);
Craig Mautner0247fc82013-02-28 14:32:06 -08004313 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004314 }
4315 }
4316
4317 return hasVisibleActivities;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004318 }
Craig Mautner0247fc82013-02-28 14:32:06 -08004319
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004320 /**
4321 * Move the current home activity's task (if one exists) to the front
4322 * of the stack.
4323 */
4324 final void moveHomeToFrontLocked() {
Craig Mautner0247fc82013-02-28 14:32:06 -08004325 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4326 final TaskRecord task = mTaskHistory.get(taskNdx);
4327 final ArrayList<ActivityRecord> activities = task.mActivities;
Craig Mautner11bf9a52013-02-19 14:08:51 -08004328 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4329 final ActivityRecord r = activities.get(activityNdx);
4330 if (r.isHomeActivity) {
Craig Mautner0247fc82013-02-28 14:32:06 -08004331 moveTaskToFrontLocked(task, null, null);
4332 return;
Craig Mautner11bf9a52013-02-19 14:08:51 -08004333 }
4334 }
4335 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004336 }
4337
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004338 final void updateTransitLocked(int transit, Bundle options) {
4339 if (options != null) {
4340 ActivityRecord r = topRunningActivityLocked(null);
4341 if (r != null && r.state != ActivityState.RESUMED) {
4342 r.updateOptionsLocked(options);
4343 } else {
4344 ActivityOptions.abort(options);
4345 }
4346 }
4347 mService.mWindowManager.prepareAppTransition(transit, false);
4348 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004349
Craig Mautnercae015f2013-02-08 14:31:27 -08004350 final boolean findTaskToMoveToFrontLocked(int taskId, int flags, Bundle options) {
Craig Mautnerd2328952013-03-05 12:46:26 -08004351 final TaskRecord task = taskForIdLocked(taskId);
4352 if (task != null) {
Craig Mautneraab647e2013-02-28 16:31:36 -08004353 if ((flags & ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
4354 mUserLeaving = true;
Craig Mautnercae015f2013-02-08 14:31:27 -08004355 }
Craig Mautneraab647e2013-02-28 16:31:36 -08004356 if ((flags & ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
4357 // Caller wants the home activity moved with it. To accomplish this,
4358 // we'll just move the home task to the top first.
4359 moveHomeToFrontLocked();
4360 }
4361 moveTaskToFrontLocked(task, null, options);
4362 return true;
Craig Mautnercae015f2013-02-08 14:31:27 -08004363 }
4364 return false;
4365 }
4366
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004367 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason, Bundle options) {
Craig Mautner11bf9a52013-02-19 14:08:51 -08004368 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004369
Craig Mautner11bf9a52013-02-19 14:08:51 -08004370 final int numTasks = mTaskHistory.size();
4371 final int index = mTaskHistory.indexOf(tr);
4372 if (numTasks == 0 || index < 0 || index == numTasks - 1) {
4373 // nothing to do!
4374 if (reason != null &&
4375 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
4376 ActivityOptions.abort(options);
4377 } else {
4378 updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options);
4379 }
4380 return;
4381 }
4382
4383 // Shift all activities with this task up to the top
4384 // of the stack, keeping them in the same internal order.
4385 mTaskHistory.remove(tr);
4386 mTaskHistory.add(tr);
4387
4388 if (DEBUG_TRANSITION) Slog.v(TAG, "Prepare to front transition: task=" + tr);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004389 if (reason != null &&
4390 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Craig Mautner11bf9a52013-02-19 14:08:51 -08004391 mService.mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004392 ActivityRecord r = topRunningActivityLocked(null);
4393 if (r != null) {
4394 mNoAnimActivities.add(r);
4395 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004396 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004397 } else {
Craig Mautner4b71aa12012-12-27 17:20:01 -08004398 updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004399 }
Craig Mautner30e2d722013-02-12 11:30:16 -08004400
Craig Mautner58547802013-03-05 08:23:53 -08004401 mService.mWindowManager.moveTaskToTop(tr.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004402
Craig Mautner58547802013-03-05 08:23:53 -08004403 resumeTopActivityLocked(null);
4404 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, tr.userId, tr.taskId);
Craig Mautner11bf9a52013-02-19 14:08:51 -08004405
4406 if (VALIDATE_TOKENS) {
4407 validateAppTokensLocked();
4408 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004409 }
4410
4411 /**
4412 * Worker method for rearranging history stack. Implements the function of moving all
4413 * activities for a specific task (gathering them if disjoint) into a single group at the
4414 * bottom of the stack.
4415 *
4416 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
4417 * to premeptively cancel the move.
4418 *
4419 * @param task The taskId to collect and move to the bottom.
4420 * @return Returns true if the move completed, false if not.
4421 */
4422 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
4423 Slog.i(TAG, "moveTaskToBack: " + task);
Craig Mautnerb44de0d2013-02-21 20:00:58 -08004424
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004425 // If we have a watcher, preflight the move before committing to it. First check
4426 // for *other* available tasks, but if none are available, then try again allowing the
4427 // current task to be selected.
Craig Mautner2219a1b2013-03-25 09:44:30 -07004428 if (mStackSupervisor.isMainStack(this) && mService.mController != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004429 ActivityRecord next = topRunningActivityLocked(null, task);
4430 if (next == null) {
4431 next = topRunningActivityLocked(null, 0);
4432 }
4433 if (next != null) {
4434 // ask watcher if this is allowed
4435 boolean moveOK = true;
4436 try {
4437 moveOK = mService.mController.activityResuming(next.packageName);
4438 } catch (RemoteException e) {
4439 mService.mController = null;
4440 }
4441 if (!moveOK) {
4442 return false;
4443 }
4444 }
4445 }
4446
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004447 if (DEBUG_TRANSITION) Slog.v(TAG,
4448 "Prepare to back transition: task=" + task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004449
Craig Mautnerd2328952013-03-05 12:46:26 -08004450 final TaskRecord tr = taskForIdLocked(task);
4451 if (tr == null) {
4452 return false;
4453 }
Craig Mautner11bf9a52013-02-19 14:08:51 -08004454 mTaskHistory.remove(tr);
4455 mTaskHistory.add(0, tr);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004456
4457 if (reason != null &&
4458 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Craig Mautner11bf9a52013-02-19 14:08:51 -08004459 mService.mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004460 ActivityRecord r = topRunningActivityLocked(null);
4461 if (r != null) {
4462 mNoAnimActivities.add(r);
4463 }
4464 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004465 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08004466 AppTransition.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004467 }
Craig Mautner30e2d722013-02-12 11:30:16 -08004468 mService.mWindowManager.moveTaskToBottom(task);
Craig Mautnerb44de0d2013-02-21 20:00:58 -08004469
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004470 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004471 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004472 }
4473
Craig Mautner58547802013-03-05 08:23:53 -08004474 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004475 return true;
4476 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07004477
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004478 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
Craig Mautner16030772013-02-26 16:05:47 -08004479 TaskAccessInfo info = getTaskAccessInfoLocked(tr, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004480 ActivityRecord resumed = mResumedActivity;
4481 if (resumed != null && resumed.thumbHolder == tr) {
Craig Mautnerd2328952013-03-05 12:46:26 -08004482 info.mainThumbnail = screenshotActivities(resumed);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004483 }
Dianne Hackborn6a864952012-09-21 18:46:11 -07004484 if (info.mainThumbnail == null) {
4485 info.mainThumbnail = tr.lastThumbnail;
4486 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004487 return info;
4488 }
4489
Dianne Hackborn15491c62012-09-19 10:59:14 -07004490 public Bitmap getTaskTopThumbnailLocked(TaskRecord tr) {
4491 ActivityRecord resumed = mResumedActivity;
4492 if (resumed != null && resumed.task == tr) {
4493 // This task is the current resumed task, we just need to take
4494 // a screenshot of it and return that.
Craig Mautnerd2328952013-03-05 12:46:26 -08004495 return screenshotActivities(resumed);
Dianne Hackborn15491c62012-09-19 10:59:14 -07004496 }
4497 // Return the information about the task, to figure out the top
4498 // thumbnail to return.
Craig Mautner16030772013-02-26 16:05:47 -08004499 TaskAccessInfo info = getTaskAccessInfoLocked(tr, true);
Dianne Hackborn15491c62012-09-19 10:59:14 -07004500 if (info.numSubThumbbails <= 0) {
Dianne Hackborn6a864952012-09-21 18:46:11 -07004501 return info.mainThumbnail != null ? info.mainThumbnail : tr.lastThumbnail;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004502 }
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004503 return info.subtasks.get(info.numSubThumbbails-1).holder.lastThumbnail;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004504 }
4505
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004506 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex,
4507 boolean taskRequired) {
Craig Mautnerd2328952013-03-05 12:46:26 -08004508 final TaskRecord task = taskForIdLocked(taskId);
4509 if (task == null) {
4510 return null;
4511 }
Craig Mautner16030772013-02-26 16:05:47 -08004512 TaskAccessInfo info = getTaskAccessInfoLocked(task, false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004513 if (info.root == null) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004514 if (taskRequired) {
4515 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
4516 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004517 return null;
4518 }
4519
4520 if (subTaskIndex < 0) {
4521 // Just remove the entire task.
Craig Mautner16030772013-02-26 16:05:47 -08004522 performClearTaskAtIndexLocked(task, info.rootIndex);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004523 return info.root;
4524 }
4525
4526 if (subTaskIndex >= info.subtasks.size()) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004527 if (taskRequired) {
4528 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
4529 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004530 return null;
4531 }
4532
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004533 // Remove all of this task's activities starting at the sub task.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004534 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
Craig Mautner16030772013-02-26 16:05:47 -08004535 performClearTaskAtIndexLocked(task, subtask.index);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004536 return subtask.activity;
4537 }
4538
Craig Mautner16030772013-02-26 16:05:47 -08004539 public TaskAccessInfo getTaskAccessInfoLocked(TaskRecord task, boolean inclThumbs) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004540 final TaskAccessInfo thumbs = new TaskAccessInfo();
4541 // How many different sub-thumbnails?
Craig Mautner16030772013-02-26 16:05:47 -08004542 final ArrayList<ActivityRecord> activities = task.mActivities;
4543 final int NA = activities.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004544 int j = 0;
4545 ThumbnailHolder holder = null;
4546 while (j < NA) {
Craig Mautner16030772013-02-26 16:05:47 -08004547 ActivityRecord ar = activities.get(j);
4548 if (!ar.finishing) {
Dianne Hackborn8da429e2012-09-23 12:52:19 -07004549 thumbs.root = ar;
4550 thumbs.rootIndex = j;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004551 holder = ar.thumbHolder;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004552 if (holder != null) {
4553 thumbs.mainThumbnail = holder.lastThumbnail;
4554 }
4555 j++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004556 break;
4557 }
4558 j++;
4559 }
4560
4561 if (j >= NA) {
4562 return thumbs;
4563 }
4564
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004565 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
4566 thumbs.subtasks = subtasks;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004567 while (j < NA) {
Craig Mautner16030772013-02-26 16:05:47 -08004568 ActivityRecord ar = activities.get(j);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004569 j++;
4570 if (ar.finishing) {
4571 continue;
4572 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004573 if (ar.thumbHolder != holder && holder != null) {
4574 thumbs.numSubThumbbails++;
4575 holder = ar.thumbHolder;
4576 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
Dianne Hackborn15491c62012-09-19 10:59:14 -07004577 sub.holder = holder;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004578 sub.activity = ar;
4579 sub.index = j-1;
4580 subtasks.add(sub);
4581 }
4582 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004583 if (thumbs.numSubThumbbails > 0) {
4584 thumbs.retriever = new IThumbnailRetriever.Stub() {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004585 @Override
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004586 public Bitmap getThumbnail(int index) {
4587 if (index < 0 || index >= thumbs.subtasks.size()) {
4588 return null;
4589 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07004590 TaskAccessInfo.SubTask sub = thumbs.subtasks.get(index);
4591 ActivityRecord resumed = mResumedActivity;
4592 if (resumed != null && resumed.thumbHolder == sub.holder) {
Craig Mautnerd2328952013-03-05 12:46:26 -08004593 return screenshotActivities(resumed);
Dianne Hackborn15491c62012-09-19 10:59:14 -07004594 }
4595 return sub.holder.lastThumbnail;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004596 }
4597 };
4598 }
4599 return thumbs;
4600 }
4601
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004602 private final void logStartActivity(int tag, ActivityRecord r,
4603 TaskRecord task) {
4604 EventLog.writeEvent(tag,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004605 r.userId, System.identityHashCode(r), task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004606 r.shortComponentName, r.intent.getAction(),
4607 r.intent.getType(), r.intent.getDataString(),
4608 r.intent.getFlags());
4609 }
4610
4611 /**
4612 * Make sure the given activity matches the current configuration. Returns
4613 * false if the activity had to be destroyed. Returns true if the
4614 * configuration is the same, or the activity will remain running as-is
4615 * for whatever reason. Ensures the HistoryRecord is updated with the
4616 * correct configuration and all other bookkeeping is handled.
4617 */
4618 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
4619 int globalChanges) {
4620 if (mConfigWillChange) {
4621 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4622 "Skipping config check (will change): " + r);
4623 return true;
4624 }
4625
4626 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4627 "Ensuring correct configuration: " + r);
4628
4629 // Short circuit: if the two configurations are the exact same
4630 // object (the common case), then there is nothing to do.
4631 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004632 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004633 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4634 "Configuration unchanged in " + r);
4635 return true;
4636 }
4637
4638 // We don't worry about activities that are finishing.
4639 if (r.finishing) {
4640 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4641 "Configuration doesn't matter in finishing " + r);
4642 r.stopFreezingScreenLocked(false);
4643 return true;
4644 }
4645
4646 // Okay we now are going to make this activity have the new config.
4647 // But then we need to figure out how it needs to deal with that.
4648 Configuration oldConfig = r.configuration;
4649 r.configuration = newConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004650
4651 // Determine what has changed. May be nothing, if this is a config
4652 // that has come back from the app after going idle. In that case
4653 // we just want to leave the official config object now in the
4654 // activity and do nothing else.
4655 final int changes = oldConfig.diff(newConfig);
4656 if (changes == 0 && !r.forceNewConfig) {
4657 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4658 "Configuration no differences in " + r);
4659 return true;
4660 }
4661
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004662 // If the activity isn't currently running, just leave the new
4663 // configuration and it will pick that up next time it starts.
4664 if (r.app == null || r.app.thread == null) {
4665 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4666 "Configuration doesn't matter not running " + r);
4667 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004668 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004669 return true;
4670 }
4671
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004672 // Figure out how to handle the changes between the configurations.
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004673 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4674 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
4675 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07004676 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004677 + ", newConfig=" + newConfig);
4678 }
Dianne Hackborne6676352011-06-01 16:51:20 -07004679 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004680 // Aha, the activity isn't handling the change, so DIE DIE DIE.
4681 r.configChangeFlags |= changes;
4682 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004683 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004684 if (r.app == null || r.app.thread == null) {
4685 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004686 "Config is destroying non-running " + r);
Dianne Hackborn28695e02011-11-02 21:59:51 -07004687 destroyActivityLocked(r, true, false, "config");
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004688 } else if (r.state == ActivityState.PAUSING) {
4689 // A little annoying: we are waiting for this activity to
4690 // finish pausing. Let's not do anything now, but just
4691 // flag that it needs to be restarted when done pausing.
4692 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004693 "Config is skipping already pausing " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004694 r.configDestroy = true;
4695 return true;
4696 } else if (r.state == ActivityState.RESUMED) {
4697 // Try to optimize this case: the configuration is changing
4698 // and we need to restart the top, resumed activity.
4699 // Instead of doing the normal handshaking, just say
4700 // "restart!".
4701 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004702 "Config is relaunching resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004703 relaunchActivityLocked(r, r.configChangeFlags, true);
4704 r.configChangeFlags = 0;
4705 } else {
4706 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004707 "Config is relaunching non-resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004708 relaunchActivityLocked(r, r.configChangeFlags, false);
4709 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004710 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004711
4712 // All done... tell the caller we weren't able to keep this
4713 // activity around.
4714 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004715 }
4716
4717 // Default case: the activity can handle this new configuration, so
4718 // hand it over. Note that we don't need to give it the new
4719 // configuration, since we always send configuration changes to all
4720 // process when they happen so it can just use whatever configuration
4721 // it last got.
4722 if (r.app != null && r.app.thread != null) {
4723 try {
4724 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004725 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004726 } catch (RemoteException e) {
4727 // If process died, whatever.
4728 }
4729 }
4730 r.stopFreezingScreenLocked(false);
4731
4732 return true;
4733 }
4734
4735 private final boolean relaunchActivityLocked(ActivityRecord r,
4736 int changes, boolean andResume) {
4737 List<ResultInfo> results = null;
4738 List<Intent> newIntents = null;
4739 if (andResume) {
4740 results = r.results;
4741 newIntents = r.newIntents;
4742 }
4743 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4744 + " with results=" + results + " newIntents=" + newIntents
4745 + " andResume=" + andResume);
4746 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004747 : EventLogTags.AM_RELAUNCH_ACTIVITY, r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004748 r.task.taskId, r.shortComponentName);
4749
4750 r.startFreezingScreenLocked(r.app, 0);
4751
4752 try {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004753 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG,
4754 (andResume ? "Relaunching to RESUMED " : "Relaunching to PAUSED ")
4755 + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004756 r.forceNewConfig = false;
Dianne Hackbornbe707852011-11-11 14:32:10 -08004757 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004758 changes, !andResume, new Configuration(mService.mConfiguration));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004759 // Note: don't need to call pauseIfSleepingLocked() here, because
4760 // the caller will only pass in 'andResume' if this activity is
4761 // currently resumed, which implies we aren't sleeping.
4762 } catch (RemoteException e) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004763 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, "Relaunch failed", e);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004764 }
4765
4766 if (andResume) {
4767 r.results = null;
4768 r.newIntents = null;
Craig Mautner2219a1b2013-03-25 09:44:30 -07004769 if (mStackSupervisor.isMainStack(this)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004770 mService.reportResumedActivityLocked(r);
4771 }
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004772 r.state = ActivityState.RESUMED;
4773 } else {
4774 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
4775 r.state = ActivityState.PAUSED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004776 }
4777
4778 return true;
4779 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004780
4781 boolean willActivityBeVisibleLocked(IBinder token) {
Craig Mautnerd44711d2013-02-23 11:24:36 -08004782 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4783 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4784 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4785 final ActivityRecord r = activities.get(activityNdx);
4786 if (r.appToken == token) {
4787 return true;
4788 }
4789 if (r.fullscreen && !r.finishing) {
4790 return false;
4791 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004792 }
4793 }
4794 return true;
4795 }
4796
4797 void closeSystemDialogsLocked() {
Craig Mautnerd44711d2013-02-23 11:24:36 -08004798 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4799 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4800 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4801 final ActivityRecord r = activities.get(activityNdx);
4802 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Craig Mautnerd2328952013-03-05 12:46:26 -08004803 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "close-sys", true);
Craig Mautnerd44711d2013-02-23 11:24:36 -08004804 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004805 }
4806 }
4807 }
4808
4809 boolean forceStopPackageLocked(String name, boolean doit, boolean evenPersistent, int userId) {
4810 boolean didSomething = false;
4811 TaskRecord lastTask = null;
Craig Mautner56f52db2013-02-25 10:03:01 -08004812 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4813 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4814 int numActivities = activities.size();
4815 for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) {
4816 ActivityRecord r = activities.get(activityNdx);
4817 final boolean samePackage = r.packageName.equals(name)
4818 || (name == null && r.userId == userId);
4819 if ((userId == UserHandle.USER_ALL || r.userId == userId)
4820 && (samePackage || r.task == lastTask)
4821 && (r.app == null || evenPersistent || !r.app.persistent)) {
4822 if (!doit) {
4823 if (r.finishing) {
4824 // If this activity is just finishing, then it is not
4825 // interesting as far as something to stop.
4826 continue;
4827 }
4828 return true;
Craig Mautnercae015f2013-02-08 14:31:27 -08004829 }
Craig Mautner56f52db2013-02-25 10:03:01 -08004830 didSomething = true;
4831 Slog.i(TAG, " Force finishing activity " + r);
4832 if (samePackage) {
4833 if (r.app != null) {
4834 r.app.removed = true;
4835 }
4836 r.app = null;
Craig Mautnercae015f2013-02-08 14:31:27 -08004837 }
Craig Mautner56f52db2013-02-25 10:03:01 -08004838 lastTask = r.task;
Craig Mautnerd2328952013-03-05 12:46:26 -08004839 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "force-stop", true);
Craig Mautnercae015f2013-02-08 14:31:27 -08004840 }
4841 }
4842 }
4843 return didSomething;
4844 }
4845
4846 ActivityRecord getTasksLocked(int maxNum, IThumbnailReceiver receiver,
Craig Mautneraab647e2013-02-28 16:31:36 -08004847 PendingThumbnailsRecord pending, List<RunningTaskInfo> list) {
Craig Mautnercae015f2013-02-08 14:31:27 -08004848 ActivityRecord topRecord = null;
Craig Mautneraab647e2013-02-28 16:31:36 -08004849 for (int taskNdx = mTaskHistory.size() - 1; maxNum > 0 && taskNdx >= 0;
4850 --maxNum, --taskNdx) {
4851 final TaskRecord task = mTaskHistory.get(taskNdx);
4852 ActivityRecord r = null;
4853 ActivityRecord top = null;
4854 int numActivities = 0;
4855 int numRunning = 0;
4856 final ArrayList<ActivityRecord> activities = task.mActivities;
4857 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4858 r = activities.get(activityNdx);
Craig Mautnercae015f2013-02-08 14:31:27 -08004859
Craig Mautneraab647e2013-02-28 16:31:36 -08004860 // Initialize state for next task if needed.
4861 if (top == null || (top.state == ActivityState.INITIALIZING)) {
4862 top = r;
4863 numActivities = numRunning = 0;
Craig Mautnercae015f2013-02-08 14:31:27 -08004864 }
Craig Mautneraab647e2013-02-28 16:31:36 -08004865
4866 // Add 'r' into the current task.
4867 numActivities++;
4868 if (r.app != null && r.app.thread != null) {
4869 numRunning++;
4870 }
4871
4872 if (localLOGV) Slog.v(
4873 TAG, r.intent.getComponent().flattenToShortString()
4874 + ": task=" + r.task);
4875 }
4876
4877 RunningTaskInfo ci = new RunningTaskInfo();
4878 ci.id = task.taskId;
4879 ci.baseActivity = r.intent.getComponent();
4880 ci.topActivity = top.intent.getComponent();
4881 if (top.thumbHolder != null) {
4882 ci.description = top.thumbHolder.lastDescription;
4883 }
4884 ci.numActivities = numActivities;
4885 ci.numRunning = numRunning;
4886 //System.out.println(
4887 // "#" + maxNum + ": " + " descr=" + ci.description);
4888 if (receiver != null) {
4889 if (localLOGV) Slog.v(
4890 TAG, "State=" + top.state + "Idle=" + top.idle
4891 + " app=" + top.app
4892 + " thr=" + (top.app != null ? top.app.thread : null));
4893 if (top.state == ActivityState.RESUMED || top.state == ActivityState.PAUSING) {
4894 if (top.idle && top.app != null && top.app.thread != null) {
4895 topRecord = top;
4896 } else {
4897 top.thumbnailNeeded = true;
Craig Mautnercae015f2013-02-08 14:31:27 -08004898 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004899 }
Craig Mautneraab647e2013-02-28 16:31:36 -08004900 pending.pendingRecords.add(top);
Craig Mautnercae015f2013-02-08 14:31:27 -08004901 }
Craig Mautneraab647e2013-02-28 16:31:36 -08004902 list.add(ci);
Craig Mautnercae015f2013-02-08 14:31:27 -08004903 }
4904 return topRecord;
4905 }
4906
4907 public void unhandledBackLocked() {
Craig Mautneraab647e2013-02-28 16:31:36 -08004908 final int top = mTaskHistory.size() - 1;
Craig Mautnercae015f2013-02-08 14:31:27 -08004909 if (DEBUG_SWITCH) Slog.d(
4910 TAG, "Performing unhandledBack(): top activity at " + top);
Craig Mautneraab647e2013-02-28 16:31:36 -08004911 if (top >= 0) {
4912 final ArrayList<ActivityRecord> activities = mTaskHistory.get(top).mActivities;
4913 int activityTop = activities.size() - 1;
4914 if (activityTop > 0) {
4915 finishActivityLocked(activities.get(activityTop), Activity.RESULT_CANCELED, null,
4916 "unhandled-back", true);
4917 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004918 }
4919 }
4920
4921 void handleAppCrashLocked(ProcessRecord app) {
Craig Mautnerd44711d2013-02-23 11:24:36 -08004922 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4923 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4924 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4925 final ActivityRecord r = activities.get(activityNdx);
4926 if (r.app == app) {
4927 Slog.w(TAG, " Force finishing activity "
4928 + r.intent.getComponent().flattenToShortString());
Craig Mautnerd2328952013-03-05 12:46:26 -08004929 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed", false);
Craig Mautnerd44711d2013-02-23 11:24:36 -08004930 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004931 }
4932 }
4933 }
4934
4935 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
4936 boolean dumpClient, String dumpPackage) {
Craig Mautneraab647e2013-02-28 16:31:36 -08004937 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4938 final TaskRecord task = mTaskHistory.get(taskNdx);
4939 pw.print(" Task "); pw.print(taskNdx); pw.print(": id #"); pw.println(task.taskId);
Craig Mautner8d341ef2013-03-26 09:03:27 -07004940 ActivityStackSupervisor.dumpHistoryList(fd, pw, mTaskHistory.get(taskNdx).mActivities,
Craig Mautneraab647e2013-02-28 16:31:36 -08004941 " ", "Hist", true, !dumpAll, dumpClient, dumpPackage);
4942 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004943 }
4944
4945 ArrayList<ActivityRecord> getDumpActivitiesLocked(String name) {
4946 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
4947
4948 if ("all".equals(name)) {
Craig Mautneraab647e2013-02-28 16:31:36 -08004949 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4950 activities.addAll(mTaskHistory.get(taskNdx).mActivities);
Craig Mautnercae015f2013-02-08 14:31:27 -08004951 }
4952 } else if ("top".equals(name)) {
Craig Mautneraab647e2013-02-28 16:31:36 -08004953 final int top = mTaskHistory.size() - 1;
4954 if (top >= 0) {
4955 final ArrayList<ActivityRecord> list = mTaskHistory.get(top).mActivities;
4956 int listTop = list.size() - 1;
4957 if (listTop >= 0) {
4958 activities.add(list.get(listTop));
4959 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004960 }
4961 } else {
4962 ItemMatcher matcher = new ItemMatcher();
4963 matcher.build(name);
4964
Craig Mautneraab647e2013-02-28 16:31:36 -08004965 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4966 for (ActivityRecord r1 : mTaskHistory.get(taskNdx).mActivities) {
4967 if (matcher.match(r1, r1.intent.getComponent())) {
4968 activities.add(r1);
4969 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004970 }
4971 }
4972 }
4973
4974 return activities;
4975 }
4976
4977 ActivityRecord restartPackage(String packageName) {
4978 ActivityRecord starting = topRunningActivityLocked(null);
4979
4980 // All activities that came from the package must be
4981 // restarted as if there was a config change.
Craig Mautneraab647e2013-02-28 16:31:36 -08004982 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4983 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4984 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4985 final ActivityRecord a = activities.get(activityNdx);
4986 if (a.info.packageName.equals(packageName)) {
4987 a.forceNewConfig = true;
4988 if (starting != null && a == starting && a.visible) {
4989 a.startFreezingScreenLocked(starting.app,
4990 ActivityInfo.CONFIG_SCREEN_LAYOUT);
4991 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004992 }
4993 }
4994 }
4995
4996 return starting;
4997 }
Craig Mautner5d9c7be2013-02-15 14:02:56 -08004998
Craig Mautner0247fc82013-02-28 14:32:06 -08004999 private void removeActivity(ActivityRecord r) {
5000 final TaskRecord task = r.task;
Craig Mautnerd2328952013-03-05 12:46:26 -08005001 // TODO: use ActivityManagerService.removeTask to do this.
Craig Mautner0247fc82013-02-28 14:32:06 -08005002 if (task.removeActivity(r)) {
5003 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "removeActivity: Removing from history, task="
5004 + task);
5005 mTaskHistory.remove(task);
Craig Mautner0247fc82013-02-28 14:32:06 -08005006 }
5007 }
5008
5009 private void setTask(ActivityRecord r, TaskRecord newTask, ThumbnailHolder newThumbHolder,
5010 boolean isRoot) {
5011 if (r.task != null) {
5012 removeActivity(r);
5013 }
5014 r.setTask(newTask, newThumbHolder, isRoot);
5015 }
5016
Craig Mautner5d9c7be2013-02-15 14:02:56 -08005017 private TaskRecord createTaskRecord(int taskId, ActivityInfo info, Intent intent,
5018 boolean toTop) {
Craig Mautnerd2328952013-03-05 12:46:26 -08005019 TaskRecord task = new TaskRecord(taskId, info, intent, this);
Craig Mautner5d9c7be2013-02-15 14:02:56 -08005020 if (toTop) {
5021 mTaskHistory.add(task);
5022 } else {
5023 mTaskHistory.add(0, task);
5024 }
5025 return task;
5026 }
Craig Mautnerc00204b2013-03-05 15:02:14 -08005027
5028 ArrayList<TaskRecord> getAllTasks() {
5029 return new ArrayList<TaskRecord>(mTaskHistory);
5030 }
5031
5032 void moveTask(int taskId, boolean toTop) {
Craig Mautner8d341ef2013-03-26 09:03:27 -07005033 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
Craig Mautnerc00204b2013-03-05 15:02:14 -08005034 if (task == null) {
5035 return;
5036 }
5037 task.stack.mTaskHistory.remove(task);
5038 task.stack = this;
5039 if (toTop) {
5040 mTaskHistory.add(task);
5041 } else {
5042 mTaskHistory.add(0, task);
5043 }
5044 }
5045
5046 public int getStackId() {
5047 return mStackId;
5048 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005049}