blob: bc835b68be297ebf5a3ddd1d20df3e92ada7dc7a [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;
24import com.android.server.am.ActivityManagerService.PendingActivityLaunch;
25
26import android.app.Activity;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070027import android.app.ActivityManager;
Dianne Hackborn7a2195c2012-03-19 17:38:00 -070028import android.app.ActivityOptions;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070029import android.app.AppGlobals;
30import android.app.IActivityManager;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070031import android.app.IThumbnailRetriever;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070032import android.app.IApplicationThread;
33import android.app.PendingIntent;
34import android.app.ResultInfo;
35import android.app.IActivityManager.WaitResult;
36import android.content.ComponentName;
37import android.content.Context;
38import android.content.IIntentSender;
39import android.content.Intent;
40import android.content.IntentSender;
41import android.content.pm.ActivityInfo;
42import android.content.pm.ApplicationInfo;
43import android.content.pm.PackageManager;
44import android.content.pm.ResolveInfo;
45import android.content.res.Configuration;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -080046import android.content.res.Resources;
47import android.graphics.Bitmap;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070048import android.os.Binder;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070049import android.os.Bundle;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070050import android.os.Handler;
51import android.os.IBinder;
52import android.os.Message;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070053import android.os.ParcelFileDescriptor;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070054import android.os.PowerManager;
Dianne Hackborne302a162012-05-15 14:58:32 -070055import android.os.Process;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070056import android.os.RemoteException;
57import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070058import android.os.UserHandle;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070059import android.util.EventLog;
60import android.util.Log;
61import android.util.Slog;
Craig Mautner59c00972012-07-30 12:10:24 -070062import android.view.Display;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070063import android.view.WindowManagerPolicy;
64
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070065import java.io.IOException;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070066import java.lang.ref.WeakReference;
67import java.util.ArrayList;
68import java.util.Iterator;
69import java.util.List;
70
71/**
72 * State and management of a single stack of activities.
73 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070074final class ActivityStack {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070075 static final String TAG = ActivityManagerService.TAG;
Dianne Hackbornb961cd22011-06-21 12:13:37 -070076 static final boolean localLOGV = ActivityManagerService.localLOGV;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070077 static final boolean DEBUG_SWITCH = ActivityManagerService.DEBUG_SWITCH;
78 static final boolean DEBUG_PAUSE = ActivityManagerService.DEBUG_PAUSE;
79 static final boolean DEBUG_VISBILITY = ActivityManagerService.DEBUG_VISBILITY;
80 static final boolean DEBUG_USER_LEAVING = ActivityManagerService.DEBUG_USER_LEAVING;
81 static final boolean DEBUG_TRANSITION = ActivityManagerService.DEBUG_TRANSITION;
82 static final boolean DEBUG_RESULTS = ActivityManagerService.DEBUG_RESULTS;
83 static final boolean DEBUG_CONFIGURATION = ActivityManagerService.DEBUG_CONFIGURATION;
84 static final boolean DEBUG_TASKS = ActivityManagerService.DEBUG_TASKS;
85
Dianne Hackbornce86ba82011-07-13 19:33:41 -070086 static final boolean DEBUG_STATES = false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070087 static final boolean DEBUG_ADD_REMOVE = false;
88 static final boolean DEBUG_SAVED_STATE = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070089
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070090 static final boolean VALIDATE_TOKENS = ActivityManagerService.VALIDATE_TOKENS;
91
92 // How long we wait until giving up on the last activity telling us it
93 // is idle.
94 static final int IDLE_TIMEOUT = 10*1000;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -070095
96 // Ticks during which we check progress while waiting for an app to launch.
97 static final int LAUNCH_TICK = 500;
98
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070099 // How long we wait until giving up on the last activity to pause. This
100 // is short because it directly impacts the responsiveness of starting the
101 // next activity.
102 static final int PAUSE_TIMEOUT = 500;
103
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700104 // How long we wait for the activity to tell us it has stopped before
105 // giving up. This is a good amount of time because we really need this
106 // from the application in order to get its saved state.
107 static final int STOP_TIMEOUT = 10*1000;
108
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800109 // How long we can hold the sleep wake lock before giving up.
110 static final int SLEEP_TIMEOUT = 5*1000;
111
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700112 // How long we can hold the launch wake lock before giving up.
113 static final int LAUNCH_TIMEOUT = 10*1000;
114
115 // How long we wait until giving up on an activity telling us it has
116 // finished destroying itself.
117 static final int DESTROY_TIMEOUT = 10*1000;
118
119 // How long until we reset a task when the user returns to it. Currently
Dianne Hackborn621e17d2010-11-22 15:59:56 -0800120 // disabled.
121 static final long ACTIVITY_INACTIVE_RESET_TIME = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700122
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700123 // How long between activity launches that we consider safe to not warn
124 // the user about an unexpected activity being launched on top.
125 static final long START_WARN_TIME = 5*1000;
126
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700127 // Set to false to disable the preview that is shown while a new activity
128 // is being started.
129 static final boolean SHOW_APP_STARTING_PREVIEW = true;
130
131 enum ActivityState {
132 INITIALIZING,
133 RESUMED,
134 PAUSING,
135 PAUSED,
136 STOPPING,
137 STOPPED,
138 FINISHING,
139 DESTROYING,
140 DESTROYED
141 }
142
143 final ActivityManagerService mService;
144 final boolean mMainStack;
145
146 final Context mContext;
147
148 /**
149 * The back history of all previous (and possibly still
150 * running) activities. It contains HistoryRecord objects.
151 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700152 final ArrayList<ActivityRecord> mHistory = new ArrayList<ActivityRecord>();
Dianne Hackbornbe707852011-11-11 14:32:10 -0800153
154 /**
155 * Used for validating app tokens with window manager.
156 */
157 final ArrayList<IBinder> mValidateAppTokens = new ArrayList<IBinder>();
158
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700159 /**
160 * List of running activities, sorted by recent usage.
161 * The first entry in the list is the least recently used.
162 * It contains HistoryRecord objects.
163 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700164 final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700165
166 /**
167 * List of activities that are waiting for a new activity
168 * to become visible before completing whatever operation they are
169 * supposed to do.
170 */
171 final ArrayList<ActivityRecord> mWaitingVisibleActivities
172 = new ArrayList<ActivityRecord>();
173
174 /**
175 * List of activities that are ready to be stopped, but waiting
176 * for the next activity to settle down before doing so. It contains
177 * HistoryRecord objects.
178 */
179 final ArrayList<ActivityRecord> mStoppingActivities
180 = new ArrayList<ActivityRecord>();
181
182 /**
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800183 * List of activities that are in the process of going to sleep.
184 */
185 final ArrayList<ActivityRecord> mGoingToSleepActivities
186 = new ArrayList<ActivityRecord>();
187
188 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700189 * Animations that for the current transition have requested not to
190 * be considered for the transition animation.
191 */
192 final ArrayList<ActivityRecord> mNoAnimActivities
193 = new ArrayList<ActivityRecord>();
194
195 /**
196 * List of activities that are ready to be finished, but waiting
197 * for the previous activity to settle down before doing so. It contains
198 * HistoryRecord objects.
199 */
200 final ArrayList<ActivityRecord> mFinishingActivities
201 = new ArrayList<ActivityRecord>();
202
203 /**
204 * List of people waiting to find out about the next launched activity.
205 */
206 final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched
207 = new ArrayList<IActivityManager.WaitResult>();
208
209 /**
210 * List of people waiting to find out about the next visible activity.
211 */
212 final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible
213 = new ArrayList<IActivityManager.WaitResult>();
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700214
215 final ArrayList<UserStartedState> mStartingUsers
216 = new ArrayList<UserStartedState>();
217
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700218 /**
219 * Set when the system is going to sleep, until we have
220 * successfully paused the current activity and released our wake lock.
221 * At that point the system is allowed to actually sleep.
222 */
223 final PowerManager.WakeLock mGoingToSleep;
224
225 /**
226 * We don't want to allow the device to go to sleep while in the process
227 * of launching an activity. This is primarily to allow alarm intent
228 * receivers to launch an activity and get that to run before the device
229 * goes back to sleep.
230 */
231 final PowerManager.WakeLock mLaunchingActivity;
232
233 /**
234 * When we are in the process of pausing an activity, before starting the
235 * next one, this variable holds the activity that is currently being paused.
236 */
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800237 ActivityRecord mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700238
239 /**
240 * This is the last activity that we put into the paused state. This is
241 * used to determine if we need to do an activity transition while sleeping,
242 * when we normally hold the top activity paused.
243 */
244 ActivityRecord mLastPausedActivity = null;
245
246 /**
247 * Current activity that is resumed, or null if there is none.
248 */
249 ActivityRecord mResumedActivity = null;
250
251 /**
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700252 * This is the last activity that has been started. It is only used to
253 * identify when multiple activities are started at once so that the user
254 * can be warned they may not be in the activity they think they are.
255 */
256 ActivityRecord mLastStartedActivity = null;
257
258 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700259 * Set when we know we are going to be calling updateConfiguration()
260 * soon, so want to skip intermediate config checks.
261 */
262 boolean mConfigWillChange;
263
264 /**
265 * Set to indicate whether to issue an onUserLeaving callback when a
266 * newly launched activity is being brought in front of us.
267 */
268 boolean mUserLeaving = false;
269
270 long mInitialStartTime = 0;
271
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800272 /**
273 * Set when we have taken too long waiting to go to sleep.
274 */
275 boolean mSleepTimeout = false;
276
Dianne Hackborn90c52de2011-09-23 12:57:44 -0700277 /**
278 * Dismiss the keyguard after the next activity is displayed?
279 */
280 boolean mDismissKeyguardOnNextActivity = false;
281
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800282 int mThumbnailWidth = -1;
283 int mThumbnailHeight = -1;
284
Amith Yamasani742a6712011-05-04 14:49:28 -0700285 private int mCurrentUser;
286
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800287 static final int SLEEP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG;
288 static final int PAUSE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 1;
289 static final int IDLE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 2;
290 static final int IDLE_NOW_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 3;
291 static final int LAUNCH_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 4;
292 static final int DESTROY_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 5;
293 static final int RESUME_TOP_ACTIVITY_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 6;
Dianne Hackborn29ba7e62012-03-16 15:03:36 -0700294 static final int LAUNCH_TICK_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 7;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700295 static final int STOP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 8;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700296 static final int DESTROY_ACTIVITIES_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 9;
297
298 static class ScheduleDestroyArgs {
299 final ProcessRecord mOwner;
300 final boolean mOomAdj;
301 final String mReason;
302 ScheduleDestroyArgs(ProcessRecord owner, boolean oomAdj, String reason) {
303 mOwner = owner;
304 mOomAdj = oomAdj;
305 mReason = reason;
306 }
307 }
308
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700309 final Handler mHandler = new Handler() {
310 //public Handler() {
311 // if (localLOGV) Slog.v(TAG, "Handler started!");
312 //}
313
314 public void handleMessage(Message msg) {
315 switch (msg.what) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800316 case SLEEP_TIMEOUT_MSG: {
Dianne Hackborn8e8d65f2011-08-11 19:36:18 -0700317 synchronized (mService) {
318 if (mService.isSleeping()) {
319 Slog.w(TAG, "Sleep timeout! Sleeping now.");
320 mSleepTimeout = true;
321 checkReadyForSleepLocked();
322 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800323 }
324 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700325 case PAUSE_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800326 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700327 // We don't at this point know if the activity is fullscreen,
328 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800329 Slog.w(TAG, "Activity pause timeout for " + r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700330 synchronized (mService) {
331 if (r.app != null) {
332 mService.logAppTooSlow(r.app, r.pauseTime,
333 "pausing " + r);
334 }
335 }
336
Dianne Hackbornbe707852011-11-11 14:32:10 -0800337 activityPaused(r != null ? r.appToken : null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700338 } break;
339 case IDLE_TIMEOUT_MSG: {
340 if (mService.mDidDexOpt) {
341 mService.mDidDexOpt = false;
342 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
343 nmsg.obj = msg.obj;
344 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
345 return;
346 }
347 // We don't at this point know if the activity is fullscreen,
348 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800349 ActivityRecord r = (ActivityRecord)msg.obj;
350 Slog.w(TAG, "Activity idle timeout for " + r);
351 activityIdleInternal(r != null ? r.appToken : null, true, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700352 } break;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700353 case LAUNCH_TICK_MSG: {
354 ActivityRecord r = (ActivityRecord)msg.obj;
355 synchronized (mService) {
356 if (r.continueLaunchTickingLocked()) {
357 mService.logAppTooSlow(r.app, r.launchTickTime,
358 "launching " + r);
359 }
360 }
361 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700362 case DESTROY_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800363 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700364 // We don't at this point know if the activity is fullscreen,
365 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800366 Slog.w(TAG, "Activity destroy timeout for " + r);
367 activityDestroyed(r != null ? r.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700368 } break;
369 case IDLE_NOW_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800370 ActivityRecord r = (ActivityRecord)msg.obj;
371 activityIdleInternal(r != null ? r.appToken : null, false, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700372 } break;
373 case LAUNCH_TIMEOUT_MSG: {
374 if (mService.mDidDexOpt) {
375 mService.mDidDexOpt = false;
376 Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
377 mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
378 return;
379 }
380 synchronized (mService) {
381 if (mLaunchingActivity.isHeld()) {
382 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
383 mLaunchingActivity.release();
384 }
385 }
386 } break;
387 case RESUME_TOP_ACTIVITY_MSG: {
388 synchronized (mService) {
389 resumeTopActivityLocked(null);
390 }
391 } break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700392 case STOP_TIMEOUT_MSG: {
393 ActivityRecord r = (ActivityRecord)msg.obj;
394 // We don't at this point know if the activity is fullscreen,
395 // so we need to be conservative and assume it isn't.
396 Slog.w(TAG, "Activity stop timeout for " + r);
397 synchronized (mService) {
398 if (r.isInHistory()) {
399 activityStoppedLocked(r, null, null, null);
400 }
401 }
402 } break;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700403 case DESTROY_ACTIVITIES_MSG: {
404 ScheduleDestroyArgs args = (ScheduleDestroyArgs)msg.obj;
405 synchronized (mService) {
406 destroyActivitiesLocked(args.mOwner, args.mOomAdj, args.mReason);
407 }
408 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700409 }
410 }
411 };
412
413 ActivityStack(ActivityManagerService service, Context context, boolean mainStack) {
414 mService = service;
415 mContext = context;
416 mMainStack = mainStack;
417 PowerManager pm =
418 (PowerManager)context.getSystemService(Context.POWER_SERVICE);
419 mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
420 mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
421 mLaunchingActivity.setReferenceCounted(false);
422 }
423
424 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
425 int i = mHistory.size()-1;
426 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700427 ActivityRecord r = mHistory.get(i);
Amith Yamasani259d5e52012-08-31 15:11:01 -0700428 if (!r.finishing && r != notTop && r.userId == mCurrentUser) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700429 return r;
430 }
431 i--;
432 }
433 return null;
434 }
435
436 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
437 int i = mHistory.size()-1;
438 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700439 ActivityRecord r = mHistory.get(i);
Amith Yamasani259d5e52012-08-31 15:11:01 -0700440 if (!r.finishing && !r.delayedResume && r != notTop && r.userId == mCurrentUser) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700441 return r;
442 }
443 i--;
444 }
445 return null;
446 }
447
448 /**
449 * This is a simplified version of topRunningActivityLocked that provides a number of
450 * optional skip-over modes. It is intended for use with the ActivityController hook only.
451 *
452 * @param token If non-null, any history records matching this token will be skipped.
453 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
454 *
455 * @return Returns the HistoryRecord of the next activity on the stack.
456 */
457 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
458 int i = mHistory.size()-1;
459 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700460 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700461 // Note: the taskId check depends on real taskId fields being non-zero
Amith Yamasani259d5e52012-08-31 15:11:01 -0700462 if (!r.finishing && (token != r.appToken) && (taskId != r.task.taskId)
463 && r.userId == mCurrentUser) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700464 return r;
465 }
466 i--;
467 }
468 return null;
469 }
470
471 final int indexOfTokenLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800472 return mHistory.indexOf(ActivityRecord.forToken(token));
473 }
474
475 final int indexOfActivityLocked(ActivityRecord r) {
476 return mHistory.indexOf(r);
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700477 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700478
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700479 final ActivityRecord isInStackLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800480 ActivityRecord r = ActivityRecord.forToken(token);
481 if (mHistory.contains(r)) {
482 return r;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700483 }
484 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700485 }
486
487 private final boolean updateLRUListLocked(ActivityRecord r) {
488 final boolean hadit = mLRUActivities.remove(r);
489 mLRUActivities.add(r);
490 return hadit;
491 }
492
493 /**
494 * Returns the top activity in any existing task matching the given
495 * Intent. Returns null if no such task is found.
496 */
497 private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
498 ComponentName cls = intent.getComponent();
499 if (info.targetActivity != null) {
500 cls = new ComponentName(info.packageName, info.targetActivity);
501 }
502
503 TaskRecord cp = null;
504
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700505 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700506 final int N = mHistory.size();
507 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700508 ActivityRecord r = mHistory.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -0700509 if (!r.finishing && r.task != cp && r.userId == userId
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700510 && r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
511 cp = r.task;
512 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
513 // + "/aff=" + r.task.affinity + " to new cls="
514 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
515 if (r.task.affinity != null) {
516 if (r.task.affinity.equals(info.taskAffinity)) {
517 //Slog.i(TAG, "Found matching affinity!");
518 return r;
519 }
520 } else if (r.task.intent != null
521 && r.task.intent.getComponent().equals(cls)) {
522 //Slog.i(TAG, "Found matching class!");
523 //dump();
524 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
525 return r;
526 } else if (r.task.affinityIntent != null
527 && r.task.affinityIntent.getComponent().equals(cls)) {
528 //Slog.i(TAG, "Found matching class!");
529 //dump();
530 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
531 return r;
532 }
533 }
534 }
535
536 return null;
537 }
538
539 /**
540 * Returns the first activity (starting from the top of the stack) that
541 * is the same as the given activity. Returns null if no such activity
542 * is found.
543 */
544 private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
545 ComponentName cls = intent.getComponent();
546 if (info.targetActivity != null) {
547 cls = new ComponentName(info.packageName, info.targetActivity);
548 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700549 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700550
551 final int N = mHistory.size();
552 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700553 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700554 if (!r.finishing) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700555 if (r.intent.getComponent().equals(cls) && r.userId == userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700556 //Slog.i(TAG, "Found matching class!");
557 //dump();
558 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
559 return r;
560 }
561 }
562 }
563
564 return null;
565 }
566
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700567 final void showAskCompatModeDialogLocked(ActivityRecord r) {
568 Message msg = Message.obtain();
569 msg.what = ActivityManagerService.SHOW_COMPAT_MODE_DIALOG_MSG;
570 msg.obj = r.task.askedCompatMode ? null : r;
571 mService.mHandler.sendMessage(msg);
572 }
573
Amith Yamasani742a6712011-05-04 14:49:28 -0700574 /*
575 * Move the activities around in the stack to bring a user to the foreground.
576 * @return whether there are any activities for the specified user.
577 */
578 final boolean switchUser(int userId) {
579 synchronized (mService) {
580 mCurrentUser = userId;
581
582 // Only one activity? Nothing to do...
583 if (mHistory.size() < 2)
584 return false;
585
586 boolean haveActivities = false;
587 // Check if the top activity is from the new user.
588 ActivityRecord top = mHistory.get(mHistory.size() - 1);
589 if (top.userId == userId) return true;
590 // Otherwise, move the user's activities to the top.
591 int N = mHistory.size();
592 int i = 0;
593 while (i < N) {
594 ActivityRecord r = mHistory.get(i);
595 if (r.userId == userId) {
596 ActivityRecord moveToTop = mHistory.remove(i);
597 mHistory.add(moveToTop);
598 // No need to check the top one now
599 N--;
600 haveActivities = true;
601 } else {
602 i++;
603 }
604 }
605 // Transition from the old top to the new top
606 resumeTopActivityLocked(top);
607 return haveActivities;
608 }
609 }
610
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700611 final boolean realStartActivityLocked(ActivityRecord r,
612 ProcessRecord app, boolean andResume, boolean checkConfig)
613 throws RemoteException {
614
615 r.startFreezingScreenLocked(app, 0);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800616 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700617
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700618 // schedule launch ticks to collect information about slow apps.
619 r.startLaunchTickingLocked();
620
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700621 // Have the window manager re-evaluate the orientation of
622 // the screen based on the new activity order. Note that
623 // as a result of this, it can call back into the activity
624 // manager with a new orientation. We don't care about that,
625 // because the activity is not currently running so we are
626 // just restarting it anyway.
627 if (checkConfig) {
628 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
629 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -0800630 r.mayFreezeScreenLocked(app) ? r.appToken : null);
Dianne Hackborn813075a62011-11-14 17:45:19 -0800631 mService.updateConfigurationLocked(config, r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700632 }
633
634 r.app = app;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700635 app.waitingToKill = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700636
637 if (localLOGV) Slog.v(TAG, "Launching: " + r);
638
639 int idx = app.activities.indexOf(r);
640 if (idx < 0) {
641 app.activities.add(r);
642 }
643 mService.updateLruProcessLocked(app, true, true);
644
645 try {
646 if (app.thread == null) {
647 throw new RemoteException();
648 }
649 List<ResultInfo> results = null;
650 List<Intent> newIntents = null;
651 if (andResume) {
652 results = r.results;
653 newIntents = r.newIntents;
654 }
655 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
656 + " icicle=" + r.icicle
657 + " with results=" + results + " newIntents=" + newIntents
658 + " andResume=" + andResume);
659 if (andResume) {
660 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
661 System.identityHashCode(r),
662 r.task.taskId, r.shortComponentName);
663 }
664 if (r.isHomeActivity) {
665 mService.mHomeProcess = app;
666 }
667 mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800668 r.sleeping = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400669 r.forceNewConfig = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700670 showAskCompatModeDialogLocked(r);
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700671 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700672 String profileFile = null;
673 ParcelFileDescriptor profileFd = null;
674 boolean profileAutoStop = false;
675 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
676 if (mService.mProfileProc == null || mService.mProfileProc == app) {
677 mService.mProfileProc = app;
678 profileFile = mService.mProfileFile;
679 profileFd = mService.mProfileFd;
680 profileAutoStop = mService.mAutoStopProfiler;
681 }
682 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -0700683 app.hasShownUi = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700684 app.pendingUiClean = true;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700685 if (profileFd != null) {
686 try {
687 profileFd = profileFd.dup();
688 } catch (IOException e) {
689 profileFd = null;
690 }
691 }
Dianne Hackbornbe707852011-11-11 14:32:10 -0800692 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
Dianne Hackborn813075a62011-11-14 17:45:19 -0800693 System.identityHashCode(r), r.info,
694 new Configuration(mService.mConfiguration),
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700695 r.compat, r.icicle, results, newIntents, !andResume,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700696 mService.isNextTransitionForward(), profileFile, profileFd,
697 profileAutoStop);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700698
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700699 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700700 // This may be a heavy-weight process! Note that the package
701 // manager will ensure that only activity can run in the main
702 // process of the .apk, which is the only thing that will be
703 // considered heavy-weight.
704 if (app.processName.equals(app.info.packageName)) {
705 if (mService.mHeavyWeightProcess != null
706 && mService.mHeavyWeightProcess != app) {
707 Log.w(TAG, "Starting new heavy weight process " + app
708 + " when already running "
709 + mService.mHeavyWeightProcess);
710 }
711 mService.mHeavyWeightProcess = app;
712 Message msg = mService.mHandler.obtainMessage(
713 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
714 msg.obj = r;
715 mService.mHandler.sendMessage(msg);
716 }
717 }
718
719 } catch (RemoteException e) {
720 if (r.launchFailed) {
721 // This is the second time we failed -- finish activity
722 // and give up.
723 Slog.e(TAG, "Second failure launching "
724 + r.intent.getComponent().flattenToShortString()
725 + ", giving up", e);
726 mService.appDiedLocked(app, app.pid, app.thread);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800727 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700728 "2nd-crash", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700729 return false;
730 }
731
732 // This is the first time we failed -- restart process and
733 // retry.
734 app.activities.remove(r);
735 throw e;
736 }
737
738 r.launchFailed = false;
739 if (updateLRUListLocked(r)) {
740 Slog.w(TAG, "Activity " + r
741 + " being launched, but already in LRU list");
742 }
743
744 if (andResume) {
745 // As part of the process of launching, ActivityThread also performs
746 // a resume.
747 r.state = ActivityState.RESUMED;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700748 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
749 + " (starting new instance)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700750 r.stopped = false;
751 mResumedActivity = r;
752 r.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -0800753 if (mMainStack) {
754 mService.addRecentTaskLocked(r.task);
755 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700756 completeResumeLocked(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800757 checkReadyForSleepLocked();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700758 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Launch completed; removing icicle of " + r.icicle);
759 r.icicle = null;
760 r.haveState = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700761 } else {
762 // This activity is not starting in the resumed state... which
763 // should look like we asked it to pause+stop (but remain visible),
764 // and it has done so and reported back the current icicle and
765 // other state.
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700766 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
767 + " (starting in stopped state)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700768 r.state = ActivityState.STOPPED;
769 r.stopped = true;
770 }
771
772 // Launch the new version setup screen if needed. We do this -after-
773 // launching the initial activity (that is, home), so that it can have
774 // a chance to initialize itself while in the background, making the
775 // switch back to it faster and look better.
776 if (mMainStack) {
777 mService.startSetupActivityLocked();
778 }
779
780 return true;
781 }
782
783 private final void startSpecificActivityLocked(ActivityRecord r,
784 boolean andResume, boolean checkConfig) {
785 // Is this activity's application already running?
786 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
787 r.info.applicationInfo.uid);
788
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700789 if (r.launchTime == 0) {
790 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700791 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700792 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700793 }
794 } else if (mInitialStartTime == 0) {
795 mInitialStartTime = SystemClock.uptimeMillis();
796 }
797
798 if (app != null && app.thread != null) {
799 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700800 app.addPackage(r.info.packageName);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700801 realStartActivityLocked(r, app, andResume, checkConfig);
802 return;
803 } catch (RemoteException e) {
804 Slog.w(TAG, "Exception when starting activity "
805 + r.intent.getComponent().flattenToShortString(), e);
806 }
807
808 // If a dead object exception was thrown -- fall through to
809 // restart the application.
810 }
811
812 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800813 "activity", r.intent.getComponent(), false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700814 }
815
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800816 void stopIfSleepingLocked() {
817 if (mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700818 if (!mGoingToSleep.isHeld()) {
819 mGoingToSleep.acquire();
820 if (mLaunchingActivity.isHeld()) {
821 mLaunchingActivity.release();
822 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
823 }
824 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800825 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
826 Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
827 mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
828 checkReadyForSleepLocked();
829 }
830 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700831
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800832 void awakeFromSleepingLocked() {
833 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
834 mSleepTimeout = false;
835 if (mGoingToSleep.isHeld()) {
836 mGoingToSleep.release();
837 }
838 // Ensure activities are no longer sleeping.
839 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700840 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800841 r.setSleeping(false);
842 }
843 mGoingToSleepActivities.clear();
844 }
845
846 void activitySleptLocked(ActivityRecord r) {
847 mGoingToSleepActivities.remove(r);
848 checkReadyForSleepLocked();
849 }
850
851 void checkReadyForSleepLocked() {
852 if (!mService.isSleeping()) {
853 // Do not care.
854 return;
855 }
856
857 if (!mSleepTimeout) {
858 if (mResumedActivity != null) {
859 // Still have something resumed; can't sleep until it is paused.
860 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700861 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
862 startPausingLocked(false, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800863 return;
864 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800865 if (mPausingActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800866 // Still waiting for something to pause; can't sleep yet.
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800867 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800868 return;
869 }
870
871 if (mStoppingActivities.size() > 0) {
872 // Still need to tell some activities to stop; can't sleep yet.
873 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
874 + mStoppingActivities.size() + " activities");
Dianne Hackborn80a7ac12011-09-22 18:32:52 -0700875 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800876 return;
877 }
878
879 ensureActivitiesVisibleLocked(null, 0);
880
881 // Make sure any stopped but visible activities are now sleeping.
882 // This ensures that the activity's onStop() is called.
883 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700884 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800885 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
886 r.setSleeping(true);
887 }
888 }
889
890 if (mGoingToSleepActivities.size() > 0) {
891 // Still need to tell some activities to sleep; can't sleep yet.
892 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
893 + mGoingToSleepActivities.size() + " activities");
894 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700895 }
896 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800897
898 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
899
900 if (mGoingToSleep.isHeld()) {
901 mGoingToSleep.release();
902 }
903 if (mService.mShuttingDown) {
904 mService.notifyAll();
905 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700906 }
Craig Mautner59c00972012-07-30 12:10:24 -0700907
Dianne Hackbornd2835932010-12-13 16:28:46 -0800908 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -0800909 if (who.noDisplay) {
910 return null;
911 }
912
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800913 Resources res = mService.mContext.getResources();
914 int w = mThumbnailWidth;
915 int h = mThumbnailHeight;
916 if (w < 0) {
917 mThumbnailWidth = w =
918 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
919 mThumbnailHeight = h =
920 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
921 }
922
923 if (w > 0) {
Craig Mautner59c00972012-07-30 12:10:24 -0700924 return mService.mWindowManager.screenshotApplications(who.appToken,
925 Display.DEFAULT_DISPLAY, w, h);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800926 }
927 return null;
928 }
929
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700930 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800931 if (mPausingActivity != null) {
932 RuntimeException e = new RuntimeException();
933 Slog.e(TAG, "Trying to pause when pause is already pending for "
934 + mPausingActivity, e);
935 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700936 ActivityRecord prev = mResumedActivity;
937 if (prev == null) {
938 RuntimeException e = new RuntimeException();
939 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
940 resumeTopActivityLocked(null);
941 return;
942 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700943 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
944 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700945 mResumedActivity = null;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800946 mPausingActivity = prev;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700947 mLastPausedActivity = prev;
948 prev.state = ActivityState.PAUSING;
949 prev.task.touchActiveTime();
Dianne Hackbornf26fd992011-04-08 18:14:09 -0700950 prev.updateThumbnail(screenshotActivities(prev), null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700951
952 mService.updateCpuStats();
953
954 if (prev.app != null && prev.app.thread != null) {
955 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
956 try {
957 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
958 System.identityHashCode(prev),
959 prev.shortComponentName);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800960 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
961 userLeaving, prev.configChangeFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700962 if (mMainStack) {
963 mService.updateUsageStats(prev, false);
964 }
965 } catch (Exception e) {
966 // Ignore exception, if process died other code will cleanup.
967 Slog.w(TAG, "Exception thrown during pause", e);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800968 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700969 mLastPausedActivity = null;
970 }
971 } else {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800972 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700973 mLastPausedActivity = null;
974 }
975
976 // If we are not going to sleep, we want to ensure the device is
977 // awake until the next activity is started.
978 if (!mService.mSleeping && !mService.mShuttingDown) {
979 mLaunchingActivity.acquire();
980 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
981 // To be safe, don't allow the wake lock to be held for too long.
982 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
983 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
984 }
985 }
986
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800987
988 if (mPausingActivity != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700989 // Have the window manager pause its key dispatching until the new
990 // activity has started. If we're pausing the activity just because
991 // the screen is being turned off and the UI is sleeping, don't interrupt
992 // key dispatch; the same activity will pick it up again on wakeup.
993 if (!uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800994 prev.pauseKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700995 } else {
996 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
997 }
998
999 // Schedule a pause timeout in case the app doesn't respond.
1000 // We don't give it much time because this directly impacts the
1001 // responsiveness seen by the user.
1002 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
1003 msg.obj = prev;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001004 prev.pauseTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001005 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
1006 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
1007 } else {
1008 // This activity failed to schedule the
1009 // pause, so just treat it as being paused now.
1010 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001011 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001012 }
1013 }
1014
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001015 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001016 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001017 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001018
1019 ActivityRecord r = null;
1020
1021 synchronized (mService) {
1022 int index = indexOfTokenLocked(token);
1023 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001024 r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001025 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001026 if (mPausingActivity == r) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001027 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
1028 + (timeout ? " (due to timeout)" : " (pause complete)"));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001029 r.state = ActivityState.PAUSED;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001030 completePauseLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001031 } else {
1032 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
1033 System.identityHashCode(r), r.shortComponentName,
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001034 mPausingActivity != null
1035 ? mPausingActivity.shortComponentName : "(none)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001036 }
1037 }
1038 }
1039 }
1040
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001041 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
1042 CharSequence description) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07001043 if (r.state != ActivityState.STOPPING) {
1044 Slog.i(TAG, "Activity reported stop, but no longer stopping: " + r);
1045 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1046 return;
1047 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001048 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Saving icicle of " + r + ": " + icicle);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001049 if (icicle != null) {
1050 // If icicle is null, this is happening due to a timeout, so we
1051 // haven't really saved the state.
1052 r.icicle = icicle;
1053 r.haveState = true;
1054 r.updateThumbnail(thumbnail, description);
1055 }
1056 if (!r.stopped) {
1057 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
1058 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1059 r.stopped = true;
1060 r.state = ActivityState.STOPPED;
Dianne Hackborn6e3d6da2012-06-15 12:05:27 -07001061 if (r.finishing) {
1062 r.clearOptionsLocked();
1063 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001064 if (r.configDestroy) {
1065 destroyActivityLocked(r, true, false, "stop-config");
1066 resumeTopActivityLocked(null);
1067 } else {
1068 // Now that this process has stopped, we may want to consider
1069 // it to be the previous app to try to keep around in case
1070 // the user wants to return to it.
1071 ProcessRecord fgApp = null;
1072 if (mResumedActivity != null) {
1073 fgApp = mResumedActivity.app;
1074 } else if (mPausingActivity != null) {
1075 fgApp = mPausingActivity.app;
1076 }
1077 if (r.app != null && fgApp != null && r.app != fgApp
1078 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
1079 && r.app != mService.mHomeProcess) {
1080 mService.mPreviousProcess = r.app;
1081 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
1082 }
Dianne Hackborn50685602011-12-01 12:23:37 -08001083 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001084 }
1085 }
1086 }
1087
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001088 private final void completePauseLocked() {
1089 ActivityRecord prev = mPausingActivity;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001090 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
1091
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001092 if (prev != null) {
1093 if (prev.finishing) {
1094 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001095 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001096 } else if (prev.app != null) {
1097 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
1098 if (prev.waitingVisible) {
1099 prev.waitingVisible = false;
1100 mWaitingVisibleActivities.remove(prev);
1101 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
1102 TAG, "Complete pause, no longer waiting: " + prev);
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001103 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001104 if (prev.configDestroy) {
1105 // The previous is being paused because the configuration
1106 // is changing, which means it is actually stopping...
1107 // To juggle the fact that we are also starting a new
1108 // instance right now, we need to first completely stop
1109 // the current instance before starting the new one.
1110 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
1111 destroyActivityLocked(prev, true, false, "pause-config");
1112 } else {
1113 mStoppingActivities.add(prev);
1114 if (mStoppingActivities.size() > 3) {
1115 // If we already have a few activities waiting to stop,
1116 // then give up on things going idle and start clearing
1117 // them out.
1118 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
1119 scheduleIdleLocked();
1120 } else {
1121 checkReadyForSleepLocked();
1122 }
1123 }
1124 } else {
1125 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
1126 prev = null;
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001127 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001128 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001129 }
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001130
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001131 if (!mService.isSleeping()) {
1132 resumeTopActivityLocked(prev);
1133 } else {
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001134 checkReadyForSleepLocked();
Dianne Hackborn42e620c2012-06-24 13:20:51 -07001135 if (topRunningActivityLocked(null) == null) {
1136 // If there are no more activities available to run, then
1137 // do resume anyway to start something.
1138 resumeTopActivityLocked(null);
1139 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001140 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001141
1142 if (prev != null) {
1143 prev.resumeKeyDispatchingLocked();
1144 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001145
1146 if (prev.app != null && prev.cpuTimeAtResume > 0
1147 && mService.mBatteryStatsService.isOnBattery()) {
1148 long diff = 0;
1149 synchronized (mService.mProcessStatsThread) {
1150 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
1151 - prev.cpuTimeAtResume;
1152 }
1153 if (diff > 0) {
1154 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
1155 synchronized (bsi) {
1156 BatteryStatsImpl.Uid.Proc ps =
1157 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
1158 prev.info.packageName);
1159 if (ps != null) {
1160 ps.addForegroundTimeLocked(diff);
1161 }
1162 }
1163 }
1164 }
1165 prev.cpuTimeAtResume = 0; // reset it
1166 }
1167
1168 /**
1169 * Once we know that we have asked an application to put an activity in
1170 * the resumed state (either by launching it or explicitly telling it),
1171 * this function updates the rest of our state to match that fact.
1172 */
1173 private final void completeResumeLocked(ActivityRecord next) {
1174 next.idle = false;
1175 next.results = null;
1176 next.newIntents = null;
1177
1178 // schedule an idle timeout in case the app doesn't do it for us.
1179 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1180 msg.obj = next;
1181 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
1182
1183 if (false) {
1184 // The activity was never told to pause, so just keep
1185 // things going as-is. To maintain our own state,
1186 // we need to emulate it coming back and saying it is
1187 // idle.
1188 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
1189 msg.obj = next;
1190 mHandler.sendMessage(msg);
1191 }
1192
1193 if (mMainStack) {
1194 mService.reportResumedActivityLocked(next);
1195 }
1196
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001197 next.clearThumbnail();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001198 if (mMainStack) {
1199 mService.setFocusedActivityLocked(next);
1200 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001201 next.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001202 ensureActivitiesVisibleLocked(null, 0);
1203 mService.mWindowManager.executeAppTransition();
1204 mNoAnimActivities.clear();
1205
1206 // Mark the point when the activity is resuming
1207 // TODO: To be more accurate, the mark should be before the onCreate,
1208 // not after the onResume. But for subsequent starts, onResume is fine.
1209 if (next.app != null) {
1210 synchronized (mService.mProcessStatsThread) {
1211 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1212 }
1213 } else {
1214 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1215 }
1216 }
1217
1218 /**
1219 * Make sure that all activities that need to be visible (that is, they
1220 * currently can be seen by the user) actually are.
1221 */
1222 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1223 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1224 if (DEBUG_VISBILITY) Slog.v(
1225 TAG, "ensureActivitiesVisible behind " + top
1226 + " configChanges=0x" + Integer.toHexString(configChanges));
1227
1228 // If the top activity is not fullscreen, then we need to
1229 // make sure any activities under it are now visible.
1230 final int count = mHistory.size();
1231 int i = count-1;
1232 while (mHistory.get(i) != top) {
1233 i--;
1234 }
1235 ActivityRecord r;
1236 boolean behindFullscreen = false;
1237 for (; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001238 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001239 if (DEBUG_VISBILITY) Slog.v(
1240 TAG, "Make visible? " + r + " finishing=" + r.finishing
1241 + " state=" + r.state);
1242 if (r.finishing) {
1243 continue;
1244 }
1245
1246 final boolean doThisProcess = onlyThisProcess == null
1247 || onlyThisProcess.equals(r.processName);
1248
1249 // First: if this is not the current activity being started, make
1250 // sure it matches the current configuration.
1251 if (r != starting && doThisProcess) {
1252 ensureActivityConfigurationLocked(r, 0);
1253 }
1254
1255 if (r.app == null || r.app.thread == null) {
1256 if (onlyThisProcess == null
1257 || onlyThisProcess.equals(r.processName)) {
1258 // This activity needs to be visible, but isn't even
1259 // running... get it started, but don't resume it
1260 // at this point.
1261 if (DEBUG_VISBILITY) Slog.v(
1262 TAG, "Start and freeze screen for " + r);
1263 if (r != starting) {
1264 r.startFreezingScreenLocked(r.app, configChanges);
1265 }
1266 if (!r.visible) {
1267 if (DEBUG_VISBILITY) Slog.v(
1268 TAG, "Starting and making visible: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001269 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001270 }
1271 if (r != starting) {
1272 startSpecificActivityLocked(r, false, false);
1273 }
1274 }
1275
1276 } else if (r.visible) {
1277 // If this activity is already visible, then there is nothing
1278 // else to do here.
1279 if (DEBUG_VISBILITY) Slog.v(
1280 TAG, "Skipping: already visible at " + r);
1281 r.stopFreezingScreenLocked(false);
1282
1283 } else if (onlyThisProcess == null) {
1284 // This activity is not currently visible, but is running.
1285 // Tell it to become visible.
1286 r.visible = true;
1287 if (r.state != ActivityState.RESUMED && r != starting) {
1288 // If this activity is paused, tell it
1289 // to now show its window.
1290 if (DEBUG_VISBILITY) Slog.v(
1291 TAG, "Making visible and scheduling visibility: " + r);
1292 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001293 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001294 r.sleeping = false;
Dianne Hackborn905577f2011-09-07 18:31:28 -07001295 r.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001296 r.app.thread.scheduleWindowVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001297 r.stopFreezingScreenLocked(false);
1298 } catch (Exception e) {
1299 // Just skip on any failure; we'll make it
1300 // visible when it next restarts.
1301 Slog.w(TAG, "Exception thrown making visibile: "
1302 + r.intent.getComponent(), e);
1303 }
1304 }
1305 }
1306
1307 // Aggregate current change flags.
1308 configChanges |= r.configChangeFlags;
1309
1310 if (r.fullscreen) {
1311 // At this point, nothing else needs to be shown
1312 if (DEBUG_VISBILITY) Slog.v(
1313 TAG, "Stopping: fullscreen at " + r);
1314 behindFullscreen = true;
1315 i--;
1316 break;
1317 }
1318 }
1319
1320 // Now for any activities that aren't visible to the user, make
1321 // sure they no longer are keeping the screen frozen.
1322 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001323 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001324 if (DEBUG_VISBILITY) Slog.v(
1325 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1326 + " state=" + r.state
1327 + " behindFullscreen=" + behindFullscreen);
1328 if (!r.finishing) {
1329 if (behindFullscreen) {
1330 if (r.visible) {
1331 if (DEBUG_VISBILITY) Slog.v(
1332 TAG, "Making invisible: " + r);
1333 r.visible = false;
1334 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001335 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001336 if ((r.state == ActivityState.STOPPING
1337 || r.state == ActivityState.STOPPED)
1338 && r.app != null && r.app.thread != null) {
1339 if (DEBUG_VISBILITY) Slog.v(
1340 TAG, "Scheduling invisibility: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001341 r.app.thread.scheduleWindowVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001342 }
1343 } catch (Exception e) {
1344 // Just skip on any failure; we'll make it
1345 // visible when it next restarts.
1346 Slog.w(TAG, "Exception thrown making hidden: "
1347 + r.intent.getComponent(), e);
1348 }
1349 } else {
1350 if (DEBUG_VISBILITY) Slog.v(
1351 TAG, "Already invisible: " + r);
1352 }
1353 } else if (r.fullscreen) {
1354 if (DEBUG_VISBILITY) Slog.v(
1355 TAG, "Now behindFullscreen: " + r);
1356 behindFullscreen = true;
1357 }
1358 }
1359 i--;
1360 }
1361 }
1362
1363 /**
1364 * Version of ensureActivitiesVisible that can easily be called anywhere.
1365 */
1366 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1367 int configChanges) {
1368 ActivityRecord r = topRunningActivityLocked(null);
1369 if (r != null) {
1370 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1371 }
1372 }
1373
1374 /**
1375 * Ensure that the top activity in the stack is resumed.
1376 *
1377 * @param prev The previously resumed activity, for when in the process
1378 * of pausing; can be null to call from elsewhere.
1379 *
1380 * @return Returns true if something is being resumed, or false if
1381 * nothing happened.
1382 */
1383 final boolean resumeTopActivityLocked(ActivityRecord prev) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001384 return resumeTopActivityLocked(prev, null);
1385 }
1386
1387 final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001388 // Find the first activity that is not finishing.
1389 ActivityRecord next = topRunningActivityLocked(null);
1390
1391 // Remember how we'll process this pause/resume situation, and ensure
1392 // that the state is reset however we wind up proceeding.
1393 final boolean userLeaving = mUserLeaving;
1394 mUserLeaving = false;
1395
1396 if (next == null) {
1397 // There are no more activities! Let's just start up the
1398 // Launcher...
1399 if (mMainStack) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001400 ActivityOptions.abort(options);
Amith Yamasani259d5e52012-08-31 15:11:01 -07001401 return mService.startHomeActivityLocked(mCurrentUser, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001402 }
1403 }
1404
1405 next.delayedResume = false;
1406
1407 // If the top activity is the resumed one, nothing to do.
1408 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1409 // Make sure we have executed any pending transitions, since there
1410 // should be nothing left to do at this point.
1411 mService.mWindowManager.executeAppTransition();
1412 mNoAnimActivities.clear();
Dianne Hackborn84375872012-06-01 19:03:50 -07001413 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001414 return false;
1415 }
1416
1417 // If we are sleeping, and there is no resumed activity, and the top
1418 // activity is paused, well that is the state we want.
1419 if ((mService.mSleeping || mService.mShuttingDown)
p13451dbad2872012-04-18 11:39:23 +09001420 && mLastPausedActivity == next
1421 && (next.state == ActivityState.PAUSED
1422 || next.state == ActivityState.STOPPED
1423 || next.state == ActivityState.STOPPING)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001424 // Make sure we have executed any pending transitions, since there
1425 // should be nothing left to do at this point.
1426 mService.mWindowManager.executeAppTransition();
1427 mNoAnimActivities.clear();
Dianne Hackborn84375872012-06-01 19:03:50 -07001428 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001429 return false;
1430 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001431
1432 // Make sure that the user who owns this activity is started. If not,
1433 // we will just leave it as is because someone should be bringing
1434 // another user's activities to the top of the stack.
1435 if (mService.mStartedUsers.get(next.userId) == null) {
1436 Slog.w(TAG, "Skipping resume of top activity " + next
1437 + ": user " + next.userId + " is stopped");
1438 return false;
1439 }
1440
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001441 // The activity may be waiting for stop, but that is no longer
1442 // appropriate for it.
1443 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001444 mGoingToSleepActivities.remove(next);
1445 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001446 mWaitingVisibleActivities.remove(next);
1447
Dianne Hackborn84375872012-06-01 19:03:50 -07001448 next.updateOptionsLocked(options);
1449
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001450 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1451
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001452 // If we are currently pausing an activity, then don't do anything
1453 // until that is done.
1454 if (mPausingActivity != null) {
1455 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
1456 return false;
1457 }
1458
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001459 // Okay we are now going to start a switch, to 'next'. We may first
1460 // have to pause the current activity, but this is an important point
1461 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001462 // XXX "App Redirected" dialog is getting too many false positives
1463 // at this point, so turn off for now.
1464 if (false) {
1465 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1466 long now = SystemClock.uptimeMillis();
1467 final boolean inTime = mLastStartedActivity.startTime != 0
1468 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1469 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1470 final int nextUid = next.info.applicationInfo.uid;
1471 if (inTime && lastUid != nextUid
1472 && lastUid != next.launchedFromUid
1473 && mService.checkPermission(
1474 android.Manifest.permission.STOP_APP_SWITCHES,
1475 -1, next.launchedFromUid)
1476 != PackageManager.PERMISSION_GRANTED) {
1477 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1478 } else {
1479 next.startTime = now;
1480 mLastStartedActivity = next;
1481 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001482 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001483 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001484 mLastStartedActivity = next;
1485 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001486 }
1487
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001488 // We need to start pausing the current activity so the top one
1489 // can be resumed...
1490 if (mResumedActivity != null) {
1491 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
1492 startPausingLocked(userLeaving, false);
1493 return true;
1494 }
1495
Christopher Tated3f175c2012-06-14 14:16:54 -07001496 // If the most recent activity was noHistory but was only stopped rather
1497 // than stopped+finished because the device went to sleep, we need to make
1498 // sure to finish it as we're making a new activity topmost.
1499 final ActivityRecord last = mLastPausedActivity;
1500 if (mService.mSleeping && last != null && !last.finishing) {
1501 if ((last.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
1502 || (last.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
1503 if (DEBUG_STATES) {
1504 Slog.d(TAG, "no-history finish of " + last + " on new resume");
1505 }
1506 requestFinishActivityLocked(last.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001507 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07001508 }
1509 }
1510
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001511 if (prev != null && prev != next) {
1512 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1513 prev.waitingVisible = true;
1514 mWaitingVisibleActivities.add(prev);
1515 if (DEBUG_SWITCH) Slog.v(
1516 TAG, "Resuming top, waiting visible to hide: " + prev);
1517 } else {
1518 // The next activity is already visible, so hide the previous
1519 // activity's windows right now so we can show the new one ASAP.
1520 // We only do this if the previous is finishing, which should mean
1521 // it is on top of the one being resumed so hiding it quickly
1522 // is good. Otherwise, we want to do the normal route of allowing
1523 // the resumed activity to be shown so we can decide if the
1524 // previous should actually be hidden depending on whether the
1525 // new one is found to be full-screen or not.
1526 if (prev.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001527 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001528 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1529 + prev + ", waitingVisible="
1530 + (prev != null ? prev.waitingVisible : null)
1531 + ", nowVisible=" + next.nowVisible);
1532 } else {
1533 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1534 + prev + ", waitingVisible="
1535 + (prev != null ? prev.waitingVisible : null)
1536 + ", nowVisible=" + next.nowVisible);
1537 }
1538 }
1539 }
1540
Dianne Hackborne7f97212011-02-24 14:40:20 -08001541 // Launching this app's activity, make sure the app is no longer
1542 // considered stopped.
1543 try {
1544 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001545 next.packageName, false, next.userId); /* TODO: Verify if correct userid */
Dianne Hackborne7f97212011-02-24 14:40:20 -08001546 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001547 } catch (IllegalArgumentException e) {
1548 Slog.w(TAG, "Failed trying to unstop package "
1549 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001550 }
1551
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001552 // We are starting up the next activity, so tell the window manager
1553 // that the previous one will be hidden soon. This way it can know
1554 // to ignore it when computing the desired screen orientation.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001555 boolean noAnim = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001556 if (prev != null) {
1557 if (prev.finishing) {
1558 if (DEBUG_TRANSITION) Slog.v(TAG,
1559 "Prepare close transition: prev=" + prev);
1560 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001561 mService.mWindowManager.prepareAppTransition(
1562 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001563 } else {
1564 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1565 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001566 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001567 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001568 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1569 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001570 } else {
1571 if (DEBUG_TRANSITION) Slog.v(TAG,
1572 "Prepare open transition: prev=" + prev);
1573 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001574 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001575 mService.mWindowManager.prepareAppTransition(
1576 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001577 } else {
1578 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1579 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001580 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001581 }
1582 }
1583 if (false) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001584 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1585 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001586 }
1587 } else if (mHistory.size() > 1) {
1588 if (DEBUG_TRANSITION) Slog.v(TAG,
1589 "Prepare open transition: no previous");
1590 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001591 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001592 mService.mWindowManager.prepareAppTransition(
1593 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001594 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001595 mService.mWindowManager.prepareAppTransition(
1596 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001597 }
1598 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001599 if (!noAnim) {
1600 next.applyOptionsLocked();
1601 } else {
1602 next.clearOptionsLocked();
1603 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001604
1605 if (next.app != null && next.app.thread != null) {
1606 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1607
1608 // This activity is now becoming visible.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001609 mService.mWindowManager.setAppVisibility(next.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001610
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001611 // schedule launch ticks to collect information about slow apps.
1612 next.startLaunchTickingLocked();
1613
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001614 ActivityRecord lastResumedActivity = mResumedActivity;
1615 ActivityState lastState = next.state;
1616
1617 mService.updateCpuStats();
1618
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001619 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001620 next.state = ActivityState.RESUMED;
1621 mResumedActivity = next;
1622 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001623 if (mMainStack) {
1624 mService.addRecentTaskLocked(next.task);
1625 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001626 mService.updateLruProcessLocked(next.app, true, true);
1627 updateLRUListLocked(next);
1628
1629 // Have the window manager re-evaluate the orientation of
1630 // the screen based on the new activity order.
1631 boolean updated = false;
1632 if (mMainStack) {
1633 synchronized (mService) {
1634 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1635 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001636 next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001637 if (config != null) {
1638 next.frozenBeforeDestroy = true;
1639 }
Dianne Hackborn813075a62011-11-14 17:45:19 -08001640 updated = mService.updateConfigurationLocked(config, next, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001641 }
1642 }
1643 if (!updated) {
1644 // The configuration update wasn't able to keep the existing
1645 // instance of the activity, and instead started a new one.
1646 // We should be all done, but let's just make sure our activity
1647 // is still at the top and schedule another run if something
1648 // weird happened.
1649 ActivityRecord nextNext = topRunningActivityLocked(null);
1650 if (DEBUG_SWITCH) Slog.i(TAG,
1651 "Activity config changed during resume: " + next
1652 + ", new next: " + nextNext);
1653 if (nextNext != next) {
1654 // Do over!
1655 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1656 }
1657 if (mMainStack) {
1658 mService.setFocusedActivityLocked(next);
1659 }
1660 ensureActivitiesVisibleLocked(null, 0);
1661 mService.mWindowManager.executeAppTransition();
1662 mNoAnimActivities.clear();
1663 return true;
1664 }
1665
1666 try {
1667 // Deliver all pending results.
1668 ArrayList a = next.results;
1669 if (a != null) {
1670 final int N = a.size();
1671 if (!next.finishing && N > 0) {
1672 if (DEBUG_RESULTS) Slog.v(
1673 TAG, "Delivering results to " + next
1674 + ": " + a);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001675 next.app.thread.scheduleSendResult(next.appToken, a);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001676 }
1677 }
1678
1679 if (next.newIntents != null) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001680 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001681 }
1682
1683 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
1684 System.identityHashCode(next),
1685 next.task.taskId, next.shortComponentName);
1686
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001687 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001688 showAskCompatModeDialogLocked(next);
Dianne Hackborn905577f2011-09-07 18:31:28 -07001689 next.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001690 next.app.thread.scheduleResumeActivity(next.appToken,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001691 mService.isNextTransitionForward());
1692
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001693 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001694
1695 } catch (Exception e) {
1696 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001697 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1698 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001699 next.state = lastState;
1700 mResumedActivity = lastResumedActivity;
1701 Slog.i(TAG, "Restarting because process died: " + next);
1702 if (!next.hasBeenLaunched) {
1703 next.hasBeenLaunched = true;
1704 } else {
1705 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1706 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001707 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001708 mService.compatibilityInfoForPackageLocked(
1709 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001710 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001711 next.labelRes, next.icon, next.windowFlags,
1712 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001713 }
1714 }
1715 startSpecificActivityLocked(next, true, false);
1716 return true;
1717 }
1718
1719 // From this point on, if something goes wrong there is no way
1720 // to recover the activity.
1721 try {
1722 next.visible = true;
1723 completeResumeLocked(next);
1724 } catch (Exception e) {
1725 // If any exception gets thrown, toss away this
1726 // activity and try the next one.
1727 Slog.w(TAG, "Exception thrown during resume of " + next, e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001728 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001729 "resume-exception", true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001730 return true;
1731 }
1732
1733 // Didn't need to use the icicle, and it is now out of date.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001734 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Resumed activity; didn't need icicle of: " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001735 next.icicle = null;
1736 next.haveState = false;
1737 next.stopped = false;
1738
1739 } else {
1740 // Whoops, need to restart this activity!
1741 if (!next.hasBeenLaunched) {
1742 next.hasBeenLaunched = true;
1743 } else {
1744 if (SHOW_APP_STARTING_PREVIEW) {
1745 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001746 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001747 mService.compatibilityInfoForPackageLocked(
1748 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001749 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001750 next.labelRes, next.icon, next.windowFlags,
1751 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001752 }
1753 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1754 }
1755 startSpecificActivityLocked(next, true, true);
1756 }
1757
1758 return true;
1759 }
1760
1761 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001762 boolean doResume, boolean keepCurTransition, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001763 final int NH = mHistory.size();
1764
1765 int addPos = -1;
1766
1767 if (!newTask) {
1768 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001769 boolean startIt = true;
1770 for (int i = NH-1; i >= 0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001771 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001772 if (p.finishing) {
1773 continue;
1774 }
1775 if (p.task == r.task) {
1776 // Here it is! Now, if this is not yet visible to the
1777 // user, then just add it without starting; it will
1778 // get started when the user navigates back to it.
1779 addPos = i+1;
1780 if (!startIt) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001781 if (DEBUG_ADD_REMOVE) {
1782 RuntimeException here = new RuntimeException("here");
1783 here.fillInStackTrace();
1784 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos,
1785 here);
1786 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001787 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001788 r.putInHistory();
Dianne Hackbornbe707852011-11-11 14:32:10 -08001789 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001790 r.info.screenOrientation, r.fullscreen);
1791 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001792 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001793 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001794 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001795 return;
1796 }
1797 break;
1798 }
1799 if (p.fullscreen) {
1800 startIt = false;
1801 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001802 }
1803 }
1804
1805 // Place a new activity at top of stack, so it is next to interact
1806 // with the user.
1807 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001808 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001809 }
1810
1811 // If we are not placing the new activity frontmost, we do not want
1812 // to deliver the onUserLeaving callback to the actual frontmost
1813 // activity
1814 if (addPos < NH) {
1815 mUserLeaving = false;
1816 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1817 }
1818
1819 // Slot the activity into the history stack and proceed
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001820 if (DEBUG_ADD_REMOVE) {
1821 RuntimeException here = new RuntimeException("here");
1822 here.fillInStackTrace();
1823 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos, here);
1824 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001825 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001826 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001827 r.frontOfTask = newTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001828 if (NH > 0) {
1829 // We want to show the starting preview window if we are
1830 // switching to a new task, or the next activity's process is
1831 // not currently running.
1832 boolean showStartingIcon = newTask;
1833 ProcessRecord proc = r.app;
1834 if (proc == null) {
1835 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1836 }
1837 if (proc == null || proc.thread == null) {
1838 showStartingIcon = true;
1839 }
1840 if (DEBUG_TRANSITION) Slog.v(TAG,
1841 "Prepare open transition: starting " + r);
1842 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001843 mService.mWindowManager.prepareAppTransition(
1844 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001845 mNoAnimActivities.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001846 } else {
1847 mService.mWindowManager.prepareAppTransition(newTask
1848 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001849 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001850 mNoAnimActivities.remove(r);
1851 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001852 r.updateOptionsLocked(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001853 mService.mWindowManager.addAppToken(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001854 addPos, r.appToken, r.task.taskId, r.info.screenOrientation, r.fullscreen);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001855 boolean doShow = true;
1856 if (newTask) {
1857 // Even though this activity is starting fresh, we still need
1858 // to reset it to make sure we apply affinities to move any
1859 // existing activities from other tasks in to it.
1860 // If the caller has requested that the target task be
1861 // reset, then do so.
1862 if ((r.intent.getFlags()
1863 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1864 resetTaskIfNeededLocked(r, r);
1865 doShow = topRunningNonDelayedActivityLocked(null) == r;
1866 }
1867 }
1868 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1869 // Figure out if we are transitioning from another activity that is
1870 // "has the same starting icon" as the next one. This allows the
1871 // window manager to keep the previous window it had previously
1872 // created, if it still had one.
1873 ActivityRecord prev = mResumedActivity;
1874 if (prev != null) {
1875 // We don't want to reuse the previous starting preview if:
1876 // (1) The current activity is in a different task.
1877 if (prev.task != r.task) prev = null;
1878 // (2) The current activity is already displayed.
1879 else if (prev.nowVisible) prev = null;
1880 }
1881 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001882 r.appToken, r.packageName, r.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001883 mService.compatibilityInfoForPackageLocked(
1884 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001885 r.labelRes, r.icon, r.windowFlags,
1886 prev != null ? prev.appToken : null, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001887 }
1888 } else {
1889 // If this is the first activity, don't do any fancy animations,
1890 // because there is nothing for it to animate on top of.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001891 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001892 r.info.screenOrientation, r.fullscreen);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001893 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001894 }
1895 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001896 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001897 }
1898
1899 if (doResume) {
1900 resumeTopActivityLocked(null);
1901 }
1902 }
1903
Dianne Hackbornbe707852011-11-11 14:32:10 -08001904 final void validateAppTokensLocked() {
1905 mValidateAppTokens.clear();
1906 mValidateAppTokens.ensureCapacity(mHistory.size());
1907 for (int i=0; i<mHistory.size(); i++) {
1908 mValidateAppTokens.add(mHistory.get(i).appToken);
1909 }
1910 mService.mWindowManager.validateAppTokens(mValidateAppTokens);
1911 }
1912
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001913 /**
1914 * Perform a reset of the given task, if needed as part of launching it.
1915 * Returns the new HistoryRecord at the top of the task.
1916 */
1917 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1918 ActivityRecord newActivity) {
1919 boolean forceReset = (newActivity.info.flags
1920 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001921 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1922 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001923 if ((newActivity.info.flags
1924 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1925 forceReset = true;
1926 }
1927 }
1928
1929 final TaskRecord task = taskTop.task;
1930
1931 // We are going to move through the history list so that we can look
1932 // at each activity 'target' with 'below' either the interesting
1933 // activity immediately below it in the stack or null.
1934 ActivityRecord target = null;
1935 int targetI = 0;
1936 int taskTopI = -1;
1937 int replyChainEnd = -1;
1938 int lastReparentPos = -1;
1939 for (int i=mHistory.size()-1; i>=-1; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001940 ActivityRecord below = i >= 0 ? mHistory.get(i) : null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001941
1942 if (below != null && below.finishing) {
1943 continue;
1944 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001945 // Don't check any lower in the stack if we're crossing a user boundary.
1946 if (below != null && below.userId != taskTop.userId) {
1947 break;
1948 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001949 if (target == null) {
1950 target = below;
1951 targetI = i;
1952 // If we were in the middle of a reply chain before this
1953 // task, it doesn't appear like the root of the chain wants
1954 // anything interesting, so drop it.
1955 replyChainEnd = -1;
1956 continue;
1957 }
1958
1959 final int flags = target.info.flags;
1960
1961 final boolean finishOnTaskLaunch =
1962 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1963 final boolean allowTaskReparenting =
1964 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1965
1966 if (target.task == task) {
1967 // We are inside of the task being reset... we'll either
1968 // finish this activity, push it out for another task,
1969 // or leave it as-is. We only do this
1970 // for activities that are not the root of the task (since
1971 // if we finish the root, we may no longer have the task!).
1972 if (taskTopI < 0) {
1973 taskTopI = targetI;
1974 }
1975 if (below != null && below.task == task) {
1976 final boolean clearWhenTaskReset =
1977 (target.intent.getFlags()
1978 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
1979 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
1980 // If this activity is sending a reply to a previous
1981 // activity, we can't do anything with it now until
1982 // we reach the start of the reply chain.
1983 // XXX note that we are assuming the result is always
1984 // to the previous activity, which is almost always
1985 // the case but we really shouldn't count on.
1986 if (replyChainEnd < 0) {
1987 replyChainEnd = targetI;
1988 }
1989 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
1990 && target.taskAffinity != null
1991 && !target.taskAffinity.equals(task.affinity)) {
1992 // If this activity has an affinity for another
1993 // task, then we need to move it out of here. We will
1994 // move it as far out of the way as possible, to the
1995 // bottom of the activity stack. This also keeps it
1996 // correctly ordered with any activities we previously
1997 // moved.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001998 ActivityRecord p = mHistory.get(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001999 if (target.taskAffinity != null
2000 && target.taskAffinity.equals(p.task.affinity)) {
2001 // If the activity currently at the bottom has the
2002 // same task affinity as the one we are moving,
2003 // then merge it into the same task.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002004 target.setTask(p.task, p.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002005 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2006 + " out to bottom task " + p.task);
2007 } else {
2008 mService.mCurTask++;
2009 if (mService.mCurTask <= 0) {
2010 mService.mCurTask = 1;
2011 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002012 target.setTask(new TaskRecord(mService.mCurTask, target.info, null),
2013 null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002014 target.task.affinityIntent = target.intent;
2015 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2016 + " out to new task " + target.task);
2017 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002018 mService.mWindowManager.setAppGroupId(target.appToken, task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002019 if (replyChainEnd < 0) {
2020 replyChainEnd = targetI;
2021 }
2022 int dstPos = 0;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002023 ThumbnailHolder curThumbHolder = target.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002024 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002025 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002026 if (p.finishing) {
2027 continue;
2028 }
2029 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
2030 + " out to target's task " + target.task);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002031 p.setTask(target.task, curThumbHolder, false);
2032 curThumbHolder = p.thumbHolder;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002033 if (DEBUG_ADD_REMOVE) {
2034 RuntimeException here = new RuntimeException("here");
2035 here.fillInStackTrace();
2036 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2037 + dstPos, here);
2038 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002039 mHistory.remove(srcPos);
2040 mHistory.add(dstPos, p);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002041 mService.mWindowManager.moveAppToken(dstPos, p.appToken);
2042 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002043 dstPos++;
2044 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002045 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002046 }
2047 i++;
2048 }
2049 if (taskTop == p) {
2050 taskTop = below;
2051 }
2052 if (taskTopI == replyChainEnd) {
2053 taskTopI = -1;
2054 }
2055 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002056 } else if (forceReset || finishOnTaskLaunch
2057 || clearWhenTaskReset) {
2058 // If the activity should just be removed -- either
2059 // because it asks for it, or the task should be
2060 // cleared -- then finish it and anything that is
2061 // part of its reply chain.
2062 if (clearWhenTaskReset) {
2063 // In this case, we want to finish this activity
2064 // and everything above it, so be sneaky and pretend
2065 // like these are all in the reply chain.
2066 replyChainEnd = targetI+1;
2067 while (replyChainEnd < mHistory.size() &&
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002068 (mHistory.get(
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002069 replyChainEnd)).task == task) {
2070 replyChainEnd++;
2071 }
2072 replyChainEnd--;
2073 } else if (replyChainEnd < 0) {
2074 replyChainEnd = targetI;
2075 }
2076 ActivityRecord p = null;
2077 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002078 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002079 if (p.finishing) {
2080 continue;
2081 }
2082 if (finishActivityLocked(p, srcPos,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002083 Activity.RESULT_CANCELED, null, "reset", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002084 replyChainEnd--;
2085 srcPos--;
2086 }
2087 }
2088 if (taskTop == p) {
2089 taskTop = below;
2090 }
2091 if (taskTopI == replyChainEnd) {
2092 taskTopI = -1;
2093 }
2094 replyChainEnd = -1;
2095 } else {
2096 // If we were in the middle of a chain, well the
2097 // activity that started it all doesn't want anything
2098 // special, so leave it all as-is.
2099 replyChainEnd = -1;
2100 }
2101 } else {
2102 // Reached the bottom of the task -- any reply chain
2103 // should be left as-is.
2104 replyChainEnd = -1;
2105 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002106
2107 } else if (target.resultTo != null && (below == null
2108 || below.task == target.task)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002109 // If this activity is sending a reply to a previous
2110 // activity, we can't do anything with it now until
2111 // we reach the start of the reply chain.
2112 // XXX note that we are assuming the result is always
2113 // to the previous activity, which is almost always
2114 // the case but we really shouldn't count on.
2115 if (replyChainEnd < 0) {
2116 replyChainEnd = targetI;
2117 }
2118
2119 } else if (taskTopI >= 0 && allowTaskReparenting
2120 && task.affinity != null
2121 && task.affinity.equals(target.taskAffinity)) {
2122 // We are inside of another task... if this activity has
2123 // an affinity for our task, then either remove it if we are
2124 // clearing or move it over to our task. Note that
2125 // we currently punt on the case where we are resetting a
2126 // task that is not at the top but who has activities above
2127 // with an affinity to it... this is really not a normal
2128 // case, and we will need to later pull that task to the front
2129 // and usually at that point we will do the reset and pick
2130 // up those remaining activities. (This only happens if
2131 // someone starts an activity in a new task from an activity
2132 // in a task that is not currently on top.)
2133 if (forceReset || finishOnTaskLaunch) {
2134 if (replyChainEnd < 0) {
2135 replyChainEnd = targetI;
2136 }
2137 ActivityRecord p = null;
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002138 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index "
2139 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002140 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002141 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002142 if (p.finishing) {
2143 continue;
2144 }
2145 if (finishActivityLocked(p, srcPos,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002146 Activity.RESULT_CANCELED, null, "reset", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002147 taskTopI--;
2148 lastReparentPos--;
2149 replyChainEnd--;
2150 srcPos--;
2151 }
2152 }
2153 replyChainEnd = -1;
2154 } else {
2155 if (replyChainEnd < 0) {
2156 replyChainEnd = targetI;
2157 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002158 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting task at index "
2159 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002160 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002161 ActivityRecord p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002162 if (p.finishing) {
2163 continue;
2164 }
2165 if (lastReparentPos < 0) {
2166 lastReparentPos = taskTopI;
2167 taskTop = p;
2168 } else {
2169 lastReparentPos--;
2170 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002171 if (DEBUG_ADD_REMOVE) {
2172 RuntimeException here = new RuntimeException("here");
2173 here.fillInStackTrace();
2174 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2175 + lastReparentPos, here);
2176 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002177 mHistory.remove(srcPos);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002178 p.setTask(task, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002179 mHistory.add(lastReparentPos, p);
2180 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002181 + " from " + srcPos + " to " + lastReparentPos
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002182 + " in to resetting task " + task);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002183 mService.mWindowManager.moveAppToken(lastReparentPos, p.appToken);
2184 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002185 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002186 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002187 }
2188 }
2189 replyChainEnd = -1;
2190
2191 // Now we've moved it in to place... but what if this is
2192 // a singleTop activity and we have put it on top of another
2193 // instance of the same activity? Then we drop the instance
2194 // below so it remains singleTop.
2195 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2196 for (int j=lastReparentPos-1; j>=0; j--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002197 ActivityRecord p = mHistory.get(j);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002198 if (p.finishing) {
2199 continue;
2200 }
2201 if (p.intent.getComponent().equals(target.intent.getComponent())) {
2202 if (finishActivityLocked(p, j,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002203 Activity.RESULT_CANCELED, null, "replace", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002204 taskTopI--;
2205 lastReparentPos--;
2206 }
2207 }
2208 }
2209 }
2210 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002211
2212 } else if (below != null && below.task != target.task) {
2213 // We hit the botton of a task; the reply chain can't
2214 // pass through it.
2215 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002216 }
2217
2218 target = below;
2219 targetI = i;
2220 }
2221
2222 return taskTop;
2223 }
2224
2225 /**
2226 * Perform clear operation as requested by
2227 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2228 * stack to the given task, then look for
2229 * an instance of that activity in the stack and, if found, finish all
2230 * activities on top of it and return the instance.
2231 *
2232 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002233 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002234 * or null if none was found.
2235 */
2236 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002237 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002238 int i = mHistory.size();
2239
2240 // First find the requested task.
2241 while (i > 0) {
2242 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002243 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002244 if (r.task.taskId == taskId) {
2245 i++;
2246 break;
2247 }
2248 }
2249
2250 // Now clear it.
2251 while (i > 0) {
2252 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002253 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002254 if (r.finishing) {
2255 continue;
2256 }
2257 if (r.task.taskId != taskId) {
2258 return null;
2259 }
2260 if (r.realActivity.equals(newR.realActivity)) {
2261 // Here it is! Now finish everything in front...
2262 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002263 while (i < (mHistory.size()-1)) {
2264 i++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002265 r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002266 if (r.task.taskId != taskId) {
2267 break;
2268 }
2269 if (r.finishing) {
2270 continue;
2271 }
2272 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002273 null, "clear", false)) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002274 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002275 }
2276 }
2277
2278 // Finally, if this is a normal launch mode (that is, not
2279 // expecting onNewIntent()), then we will finish the current
2280 // instance of the activity so a new fresh one can be started.
2281 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2282 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
2283 if (!ret.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002284 int index = indexOfTokenLocked(ret.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002285 if (index >= 0) {
2286 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002287 null, "clear", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002288 }
2289 return null;
2290 }
2291 }
2292
2293 return ret;
2294 }
2295 }
2296
2297 return null;
2298 }
2299
2300 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002301 * Completely remove all activities associated with an existing
2302 * task starting at a specified index.
2303 */
2304 private final void performClearTaskAtIndexLocked(int taskId, int i) {
Dianne Hackborneabd3282011-10-13 16:26:49 -07002305 while (i < mHistory.size()) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002306 ActivityRecord r = mHistory.get(i);
2307 if (r.task.taskId != taskId) {
2308 // Whoops hit the end.
2309 return;
2310 }
2311 if (r.finishing) {
2312 i++;
2313 continue;
2314 }
2315 if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002316 null, "clear", false)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002317 i++;
2318 }
2319 }
2320 }
2321
2322 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002323 * Completely remove all activities associated with an existing task.
2324 */
2325 private final void performClearTaskLocked(int taskId) {
2326 int i = mHistory.size();
2327
2328 // First find the requested task.
2329 while (i > 0) {
2330 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002331 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002332 if (r.task.taskId == taskId) {
2333 i++;
2334 break;
2335 }
2336 }
2337
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002338 // Now find the start and clear it.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002339 while (i > 0) {
2340 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002341 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002342 if (r.finishing) {
2343 continue;
2344 }
2345 if (r.task.taskId != taskId) {
2346 // We hit the bottom. Now finish it all...
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002347 performClearTaskAtIndexLocked(taskId, i+1);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002348 return;
2349 }
2350 }
2351 }
2352
2353 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002354 * Find the activity in the history stack within the given task. Returns
2355 * the index within the history at which it's found, or < 0 if not found.
2356 */
2357 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2358 int i = mHistory.size();
2359 while (i > 0) {
2360 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002361 ActivityRecord candidate = mHistory.get(i);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07002362 if (candidate.finishing) {
2363 continue;
2364 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002365 if (candidate.task.taskId != task) {
2366 break;
2367 }
2368 if (candidate.realActivity.equals(r.realActivity)) {
2369 return i;
2370 }
2371 }
2372
2373 return -1;
2374 }
2375
2376 /**
2377 * Reorder the history stack so that the activity at the given index is
2378 * brought to the front.
2379 */
2380 private final ActivityRecord moveActivityToFrontLocked(int where) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002381 ActivityRecord newTop = mHistory.remove(where);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002382 int top = mHistory.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002383 ActivityRecord oldTop = mHistory.get(top-1);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002384 if (DEBUG_ADD_REMOVE) {
2385 RuntimeException here = new RuntimeException("here");
2386 here.fillInStackTrace();
2387 Slog.i(TAG, "Removing and adding activity " + newTop + " to stack at "
2388 + top, here);
2389 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002390 mHistory.add(top, newTop);
2391 oldTop.frontOfTask = false;
2392 newTop.frontOfTask = true;
2393 return newTop;
2394 }
2395
2396 final int startActivityLocked(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002397 Intent intent, String resolvedType, ActivityInfo aInfo, IBinder resultTo,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002398 String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002399 int callingPid, int callingUid, int startFlags, Bundle options,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002400 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002401
Dianne Hackborna4972e92012-03-14 10:38:05 -07002402 int err = ActivityManager.START_SUCCESS;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002403
2404 ProcessRecord callerApp = null;
2405 if (caller != null) {
2406 callerApp = mService.getRecordForAppLocked(caller);
2407 if (callerApp != null) {
2408 callingPid = callerApp.pid;
2409 callingUid = callerApp.info.uid;
2410 } else {
2411 Slog.w(TAG, "Unable to find app for caller " + caller
2412 + " (pid=" + callingPid + ") when starting: "
2413 + intent.toString());
Dianne Hackborna4972e92012-03-14 10:38:05 -07002414 err = ActivityManager.START_PERMISSION_DENIED;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002415 }
2416 }
2417
Dianne Hackborna4972e92012-03-14 10:38:05 -07002418 if (err == ActivityManager.START_SUCCESS) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002419 final int userId = aInfo != null ? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0;
Dianne Hackborn21c241e2012-03-08 13:57:23 -08002420 Slog.i(TAG, "START {" + intent.toShortString(true, true, true, false)
Amith Yamasania4a54e22012-04-16 15:44:19 -07002421 + " u=" + userId + "} from pid " + (callerApp != null ? callerApp.pid : callingPid));
Dianne Hackbornefb58102010-10-14 16:47:34 -07002422 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002423
2424 ActivityRecord sourceRecord = null;
2425 ActivityRecord resultRecord = null;
2426 if (resultTo != null) {
2427 int index = indexOfTokenLocked(resultTo);
2428 if (DEBUG_RESULTS) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002429 TAG, "Will send result to " + resultTo + " (index " + index + ")");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002430 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002431 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002432 if (requestCode >= 0 && !sourceRecord.finishing) {
2433 resultRecord = sourceRecord;
2434 }
2435 }
2436 }
2437
2438 int launchFlags = intent.getFlags();
2439
2440 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2441 && sourceRecord != null) {
2442 // Transfer the result target from the source activity to the new
2443 // one being started, including any failures.
2444 if (requestCode >= 0) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002445 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002446 return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002447 }
2448 resultRecord = sourceRecord.resultTo;
2449 resultWho = sourceRecord.resultWho;
2450 requestCode = sourceRecord.requestCode;
2451 sourceRecord.resultTo = null;
2452 if (resultRecord != null) {
2453 resultRecord.removeResultsLocked(
2454 sourceRecord, resultWho, requestCode);
2455 }
2456 }
2457
Dianne Hackborna4972e92012-03-14 10:38:05 -07002458 if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002459 // We couldn't find a class that can handle the given Intent.
2460 // That's the end of that!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002461 err = ActivityManager.START_INTENT_NOT_RESOLVED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002462 }
2463
Dianne Hackborna4972e92012-03-14 10:38:05 -07002464 if (err == ActivityManager.START_SUCCESS && aInfo == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002465 // We couldn't find the specific class specified in the Intent.
2466 // Also the end of the line.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002467 err = ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002468 }
2469
Dianne Hackborna4972e92012-03-14 10:38:05 -07002470 if (err != ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002471 if (resultRecord != null) {
2472 sendActivityResultLocked(-1,
2473 resultRecord, resultWho, requestCode,
2474 Activity.RESULT_CANCELED, null);
2475 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002476 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002477 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002478 return err;
2479 }
2480
Jeff Sharkey35be7562012-04-18 19:16:15 -07002481 final int startAnyPerm = mService.checkPermission(
2482 START_ANY_ACTIVITY, callingPid, callingUid);
2483 final int componentPerm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002484 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Jeff Sharkey35be7562012-04-18 19:16:15 -07002485 if (startAnyPerm != PERMISSION_GRANTED && componentPerm != PERMISSION_GRANTED) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002486 if (resultRecord != null) {
2487 sendActivityResultLocked(-1,
2488 resultRecord, resultWho, requestCode,
2489 Activity.RESULT_CANCELED, null);
2490 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002491 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002492 String msg;
2493 if (!aInfo.exported) {
2494 msg = "Permission Denial: starting " + intent.toString()
2495 + " from " + callerApp + " (pid=" + callingPid
2496 + ", uid=" + callingUid + ")"
2497 + " not exported from uid " + aInfo.applicationInfo.uid;
2498 } else {
2499 msg = "Permission Denial: starting " + intent.toString()
2500 + " from " + callerApp + " (pid=" + callingPid
2501 + ", uid=" + callingUid + ")"
2502 + " requires " + aInfo.permission;
2503 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002504 Slog.w(TAG, msg);
2505 throw new SecurityException(msg);
2506 }
2507
2508 if (mMainStack) {
2509 if (mService.mController != null) {
2510 boolean abort = false;
2511 try {
2512 // The Intent we give to the watcher has the extra data
2513 // stripped off, since it can contain private information.
2514 Intent watchIntent = intent.cloneFilter();
2515 abort = !mService.mController.activityStarting(watchIntent,
2516 aInfo.applicationInfo.packageName);
2517 } catch (RemoteException e) {
2518 mService.mController = null;
2519 }
2520
2521 if (abort) {
2522 if (resultRecord != null) {
2523 sendActivityResultLocked(-1,
2524 resultRecord, resultWho, requestCode,
2525 Activity.RESULT_CANCELED, null);
2526 }
2527 // We pretend to the caller that it was really started, but
2528 // they will just get a cancel result.
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002529 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002530 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002531 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002532 }
2533 }
2534 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002535
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002536 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2537 intent, resolvedType, aInfo, mService.mConfiguration,
2538 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002539 if (outActivity != null) {
2540 outActivity[0] = r;
2541 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002542
2543 if (mMainStack) {
2544 if (mResumedActivity == null
2545 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2546 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2547 PendingActivityLaunch pal = new PendingActivityLaunch();
2548 pal.r = r;
2549 pal.sourceRecord = sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002550 pal.startFlags = startFlags;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002551 mService.mPendingActivityLaunches.add(pal);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002552 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002553 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002554 return ActivityManager.START_SWITCHES_CANCELED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002555 }
2556 }
2557
2558 if (mService.mDidAppSwitch) {
2559 // This is the second allowed switch since we stopped switches,
2560 // so now just generally allow switches. Use case: user presses
2561 // home (switches disabled, switch to home, mDidAppSwitch now true);
2562 // user taps a home icon (coming from home so allowed, we hit here
2563 // and now allow anyone to switch again).
2564 mService.mAppSwitchesAllowedTime = 0;
2565 } else {
2566 mService.mDidAppSwitch = true;
2567 }
2568
2569 mService.doPendingActivityLaunchesLocked(false);
2570 }
2571
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002572 err = startActivityUncheckedLocked(r, sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002573 startFlags, true, options);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002574 if (mDismissKeyguardOnNextActivity && mPausingActivity == null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002575 // Someone asked to have the keyguard dismissed on the next
2576 // activity start, but we are not actually doing an activity
2577 // switch... just dismiss the keyguard now, because we
2578 // probably want to see whatever is behind it.
2579 mDismissKeyguardOnNextActivity = false;
2580 mService.mWindowManager.dismissKeyguard();
2581 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002582 Slog.i(TAG, "DONE STARTING!");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002583 return err;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002584 }
2585
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002586 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2587 if ((launchFlags &
2588 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2589 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2590 // Caller wants to appear on home activity, so before starting
2591 // their own activity we will bring home to the front.
2592 moveHomeToFrontLocked();
2593 }
2594 }
2595
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002596 final int startActivityUncheckedLocked(ActivityRecord r,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002597 ActivityRecord sourceRecord, int startFlags, boolean doResume,
2598 Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002599 final Intent intent = r.intent;
2600 final int callingUid = r.launchedFromUid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002601 final int userId = r.userId;
2602
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002603 int launchFlags = intent.getFlags();
2604
2605 // We'll invoke onUserLeaving before onPause only if the launching
2606 // activity did not explicitly state that this is an automated launch.
2607 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2608 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2609 "startActivity() => mUserLeaving=" + mUserLeaving);
2610
2611 // If the caller has asked not to resume at this point, we make note
2612 // of this in the record so that we can skip it when trying to find
2613 // the top running activity.
2614 if (!doResume) {
2615 r.delayedResume = true;
2616 }
2617
2618 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2619 != 0 ? r : null;
2620
2621 // If the onlyIfNeeded flag is set, then we can do this if the activity
2622 // being launched is the same as the one making the call... or, as
2623 // a special case, if we do not know the caller then we count the
2624 // current top activity as the caller.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002625 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002626 ActivityRecord checkedCaller = sourceRecord;
2627 if (checkedCaller == null) {
2628 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2629 }
2630 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2631 // Caller is not the same as launcher, so always needed.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002632 startFlags &= ~ActivityManager.START_FLAG_ONLY_IF_NEEDED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002633 }
2634 }
2635
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002636 if (sourceRecord == null) {
2637 // This activity is not being started from another... in this
2638 // case we -always- start a new task.
2639 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2640 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2641 + intent);
2642 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2643 }
2644 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2645 // The original activity who is starting us is running as a single
2646 // instance... this new activity it is starting must go on its
2647 // own task.
2648 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2649 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2650 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2651 // The activity being started is a single instance... it always
2652 // gets launched into its own task.
2653 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2654 }
2655
2656 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2657 // For whatever reason this activity is being launched into a new
2658 // task... yet the caller has requested a result back. Well, that
2659 // is pretty messed up, so instead immediately send back a cancel
2660 // and let the new task continue launched as normal without a
2661 // dependency on its originator.
2662 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2663 sendActivityResultLocked(-1,
2664 r.resultTo, r.resultWho, r.requestCode,
2665 Activity.RESULT_CANCELED, null);
2666 r.resultTo = null;
2667 }
2668
2669 boolean addingToTask = false;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002670 boolean movedHome = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002671 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002672 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2673 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2674 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2675 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2676 // If bring to front is requested, and no result is requested, and
2677 // we can find a task that was started with this same
2678 // component, then instead of launching bring that one to the front.
2679 if (r.resultTo == null) {
2680 // See if there is a task to bring to the front. If this is
2681 // a SINGLE_INSTANCE activity, there can be one and only one
2682 // instance of it in the history, and it is always in its own
2683 // unique task, so we do a special search.
2684 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2685 ? findTaskLocked(intent, r.info)
2686 : findActivityLocked(intent, r.info);
2687 if (taskTop != null) {
2688 if (taskTop.task.intent == null) {
2689 // This task was started because of movement of
2690 // the activity based on affinity... now that we
2691 // are actually launching it, we can assign the
2692 // base intent.
2693 taskTop.task.setIntent(intent, r.info);
2694 }
2695 // If the target task is not in the front, then we need
2696 // to bring it to the front... except... well, with
2697 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2698 // to have the same behavior as if a new instance was
2699 // being started, which means not bringing it to the front
2700 // if the caller is not itself in the front.
2701 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002702 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002703 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2704 boolean callerAtFront = sourceRecord == null
2705 || curTop.task == sourceRecord.task;
2706 if (callerAtFront) {
2707 // We really do want to push this one into the
2708 // user's face, right now.
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002709 movedHome = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002710 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002711 moveTaskToFrontLocked(taskTop.task, r, options);
Dianne Hackborn84375872012-06-01 19:03:50 -07002712 options = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002713 }
2714 }
2715 // If the caller has requested that the target task be
2716 // reset, then do so.
2717 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2718 taskTop = resetTaskIfNeededLocked(taskTop, r);
2719 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002720 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002721 // We don't need to start a new activity, and
2722 // the client said not to do anything if that
2723 // is the case, so this is it! And for paranoia, make
2724 // sure we have correctly resumed the top activity.
2725 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07002726 resumeTopActivityLocked(null, options);
2727 } else {
2728 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002729 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002730 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002731 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002732 if ((launchFlags &
2733 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2734 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2735 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002736 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002737 // not be too hard...
2738 reuseTask = taskTop.task;
2739 performClearTaskLocked(taskTop.task.taskId);
2740 reuseTask.setIntent(r.intent, r.info);
2741 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002742 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2743 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2744 // In this situation we want to remove all activities
2745 // from the task up to the one being started. In most
2746 // cases this means we are resetting the task to its
2747 // initial state.
2748 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002749 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002750 if (top != null) {
2751 if (top.frontOfTask) {
2752 // Activity aliases may mean we use different
2753 // intents for the top activity, so make sure
2754 // the task now has the identity of the new
2755 // intent.
2756 top.task.setIntent(r.intent, r.info);
2757 }
2758 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002759 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002760 } else {
2761 // A special case: we need to
2762 // start the activity because it is not currently
2763 // running, and the caller has asked to clear the
2764 // current task to have this activity at the top.
2765 addingToTask = true;
2766 // Now pretend like this activity is being started
2767 // by the top of its task, so it is put in the
2768 // right place.
2769 sourceRecord = taskTop;
2770 }
2771 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2772 // In this case the top activity on the task is the
2773 // same as the one being launched, so we take that
2774 // as a request to bring the task to the foreground.
2775 // If the top activity in the task is the root
2776 // activity, deliver this new intent to it if it
2777 // desires.
Johan Viktorssonf363dfd2012-02-16 17:05:16 +01002778 if (((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2779 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP)
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002780 && taskTop.realActivity.equals(r.realActivity)) {
2781 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2782 if (taskTop.frontOfTask) {
2783 taskTop.task.setIntent(r.intent, r.info);
2784 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002785 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002786 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2787 // In this case we are launching the root activity
2788 // of the task, but with a different intent. We
2789 // should start a new instance on top.
2790 addingToTask = true;
2791 sourceRecord = taskTop;
2792 }
2793 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2794 // In this case an activity is being launched in to an
2795 // existing task, without resetting that task. This
2796 // is typically the situation of launching an activity
2797 // from a notification or shortcut. We want to place
2798 // the new activity on top of the current task.
2799 addingToTask = true;
2800 sourceRecord = taskTop;
2801 } else if (!taskTop.task.rootWasReset) {
2802 // In this case we are launching in to an existing task
2803 // that has not yet been started from its front door.
2804 // The current task has been brought to the front.
2805 // Ideally, we'd probably like to place this new task
2806 // at the bottom of its stack, but that's a little hard
2807 // to do with the current organization of the code so
2808 // for now we'll just drop it.
2809 taskTop.task.setIntent(r.intent, r.info);
2810 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002811 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002812 // We didn't do anything... but it was needed (a.k.a., client
2813 // don't use that intent!) And for paranoia, make
2814 // sure we have correctly resumed the top activity.
2815 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07002816 resumeTopActivityLocked(null, options);
2817 } else {
2818 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002819 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002820 return ActivityManager.START_TASK_TO_FRONT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002821 }
2822 }
2823 }
2824 }
2825
2826 //String uri = r.intent.toURI();
2827 //Intent intent2 = new Intent(uri);
2828 //Slog.i(TAG, "Given intent: " + r.intent);
2829 //Slog.i(TAG, "URI is: " + uri);
2830 //Slog.i(TAG, "To intent: " + intent2);
2831
2832 if (r.packageName != null) {
2833 // If the activity being launched is the same as the one currently
2834 // at the top, then we need to check if it should only be launched
2835 // once.
2836 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2837 if (top != null && r.resultTo == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002838 if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002839 if (top.app != null && top.app.thread != null) {
2840 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2841 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2842 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2843 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2844 // For paranoia, make sure we have correctly
2845 // resumed the top activity.
2846 if (doResume) {
2847 resumeTopActivityLocked(null);
2848 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002849 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002850 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002851 // We don't need to start a new activity, and
2852 // the client said not to do anything if that
2853 // is the case, so this is it!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002854 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002855 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002856 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002857 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002858 }
2859 }
2860 }
2861 }
2862
2863 } else {
2864 if (r.resultTo != null) {
2865 sendActivityResultLocked(-1,
2866 r.resultTo, r.resultWho, r.requestCode,
2867 Activity.RESULT_CANCELED, null);
2868 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002869 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002870 return ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002871 }
2872
2873 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002874 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002875
2876 // Should this be considered a new task?
2877 if (r.resultTo == null && !addingToTask
2878 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002879 if (reuseTask == null) {
2880 // todo: should do better management of integers.
2881 mService.mCurTask++;
2882 if (mService.mCurTask <= 0) {
2883 mService.mCurTask = 1;
2884 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002885 r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002886 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2887 + " in new task " + r.task);
2888 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002889 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002890 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002891 newTask = true;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002892 if (!movedHome) {
2893 moveHomeToFrontFromLaunchLocked(launchFlags);
2894 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002895
2896 } else if (sourceRecord != null) {
2897 if (!addingToTask &&
2898 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2899 // In this case, we are adding the activity to an existing
2900 // task, but the caller has asked to clear that task if the
2901 // activity is already running.
2902 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002903 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002904 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002905 if (top != null) {
2906 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002907 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002908 // For paranoia, make sure we have correctly
2909 // resumed the top activity.
2910 if (doResume) {
2911 resumeTopActivityLocked(null);
2912 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002913 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002914 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002915 }
2916 } else if (!addingToTask &&
2917 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2918 // In this case, we are launching an activity in our own task
2919 // that may already be running somewhere in the history, and
2920 // we want to shuffle it to the front of the stack if so.
2921 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2922 if (where >= 0) {
2923 ActivityRecord top = moveActivityToFrontLocked(where);
2924 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002925 top.updateOptionsLocked(options);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002926 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002927 if (doResume) {
2928 resumeTopActivityLocked(null);
2929 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002930 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002931 }
2932 }
2933 // An existing activity is starting this new activity, so we want
2934 // to keep the new one in the same task as the one that is starting
2935 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002936 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002937 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2938 + " in existing task " + r.task);
2939
2940 } else {
2941 // This not being started from an existing activity, and not part
2942 // of a new task... just put it in the top task, though these days
2943 // this case should never happen.
2944 final int N = mHistory.size();
2945 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002946 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002947 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002948 ? prev.task
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002949 : new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002950 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2951 + " in new guessed " + r.task);
2952 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002953
Dianne Hackborn39792d22010-08-19 18:01:52 -07002954 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002955 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002956
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002957 if (newTask) {
2958 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
2959 }
2960 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002961 startActivityLocked(r, newTask, doResume, keepCurTransition, options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002962 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002963 }
2964
Dianne Hackborna4972e92012-03-14 10:38:05 -07002965 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002966 String profileFile, ParcelFileDescriptor profileFd, int userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002967 // Collect information about the target of the Intent.
2968 ActivityInfo aInfo;
2969 try {
2970 ResolveInfo rInfo =
2971 AppGlobals.getPackageManager().resolveIntent(
2972 intent, resolvedType,
2973 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07002974 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002975 aInfo = rInfo != null ? rInfo.activityInfo : null;
2976 } catch (RemoteException e) {
2977 aInfo = null;
2978 }
2979
2980 if (aInfo != null) {
2981 // Store the found target back into the intent, because now that
2982 // we have it we never want to do this again. For example, if the
2983 // user navigates back to this point in the history, we should
2984 // always restart the exact same activity.
2985 intent.setComponent(new ComponentName(
2986 aInfo.applicationInfo.packageName, aInfo.name));
2987
2988 // Don't debug things in the system process
Dianne Hackborna4972e92012-03-14 10:38:05 -07002989 if ((startFlags&ActivityManager.START_FLAG_DEBUG) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002990 if (!aInfo.processName.equals("system")) {
2991 mService.setDebugApp(aInfo.processName, true, false);
2992 }
2993 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002994
Dianne Hackborna4972e92012-03-14 10:38:05 -07002995 if ((startFlags&ActivityManager.START_FLAG_OPENGL_TRACES) != 0) {
Siva Velusamy92a8b222012-03-09 16:24:04 -08002996 if (!aInfo.processName.equals("system")) {
2997 mService.setOpenGlTraceApp(aInfo.applicationInfo, aInfo.processName);
2998 }
2999 }
3000
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003001 if (profileFile != null) {
3002 if (!aInfo.processName.equals("system")) {
3003 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003004 profileFile, profileFd,
3005 (startFlags&ActivityManager.START_FLAG_AUTO_STOP_PROFILER) != 0);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003006 }
3007 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003008 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003009 return aInfo;
3010 }
3011
3012 final int startActivityMayWait(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003013 Intent intent, String resolvedType, IBinder resultTo,
3014 String resultWho, int requestCode, int startFlags, String profileFile,
3015 ParcelFileDescriptor profileFd, WaitResult outResult, Configuration config,
3016 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003017 // Refuse possible leaked file descriptors
3018 if (intent != null && intent.hasFileDescriptors()) {
3019 throw new IllegalArgumentException("File descriptors passed in Intent");
3020 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003021 boolean componentSpecified = intent.getComponent() != null;
3022
3023 // Don't modify the client's object!
3024 intent = new Intent(intent);
3025
3026 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003027 ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003028 profileFile, profileFd, userId);
Amith Yamasania10d1aa2012-08-21 09:49:53 -07003029 if (aInfo != null && (aInfo.flags & ActivityInfo.FLAG_MULTIPROCESS) == 0
3030 && mService.isSingleton(aInfo.processName, aInfo.applicationInfo, null, 0)) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07003031 userId = 0;
3032 }
Amith Yamasani742a6712011-05-04 14:49:28 -07003033 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003034
3035 synchronized (mService) {
3036 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003037 if (callingUid >= 0) {
3038 callingPid = -1;
3039 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003040 callingPid = Binder.getCallingPid();
3041 callingUid = Binder.getCallingUid();
3042 } else {
3043 callingPid = callingUid = -1;
3044 }
3045
3046 mConfigWillChange = config != null
3047 && mService.mConfiguration.diff(config) != 0;
3048 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3049 "Starting activity when config will change = " + mConfigWillChange);
3050
3051 final long origId = Binder.clearCallingIdentity();
3052
3053 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07003054 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003055 // This may be a heavy-weight process! Check to see if we already
3056 // have another, different heavy-weight process running.
3057 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
3058 if (mService.mHeavyWeightProcess != null &&
3059 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
3060 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
3061 int realCallingPid = callingPid;
3062 int realCallingUid = callingUid;
3063 if (caller != null) {
3064 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
3065 if (callerApp != null) {
3066 realCallingPid = callerApp.pid;
3067 realCallingUid = callerApp.info.uid;
3068 } else {
3069 Slog.w(TAG, "Unable to find app for caller " + caller
3070 + " (pid=" + realCallingPid + ") when starting: "
3071 + intent.toString());
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003072 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003073 return ActivityManager.START_PERMISSION_DENIED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003074 }
3075 }
3076
3077 IIntentSender target = mService.getIntentSenderLocked(
Dianne Hackborna4972e92012-03-14 10:38:05 -07003078 ActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn41203752012-08-31 14:05:51 -07003079 realCallingUid, userId, null, null, 0, new Intent[] { intent },
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003080 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003081 | PendingIntent.FLAG_ONE_SHOT, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003082
3083 Intent newIntent = new Intent();
3084 if (requestCode >= 0) {
3085 // Caller is requesting a result.
3086 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
3087 }
3088 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
3089 new IntentSender(target));
3090 if (mService.mHeavyWeightProcess.activities.size() > 0) {
3091 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
3092 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
3093 hist.packageName);
3094 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
3095 hist.task.taskId);
3096 }
3097 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
3098 aInfo.packageName);
3099 newIntent.setFlags(intent.getFlags());
3100 newIntent.setClassName("android",
3101 HeavyWeightSwitcherActivity.class.getName());
3102 intent = newIntent;
3103 resolvedType = null;
3104 caller = null;
3105 callingUid = Binder.getCallingUid();
3106 callingPid = Binder.getCallingPid();
3107 componentSpecified = true;
3108 try {
3109 ResolveInfo rInfo =
3110 AppGlobals.getPackageManager().resolveIntent(
3111 intent, null,
3112 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07003113 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003114 aInfo = rInfo != null ? rInfo.activityInfo : null;
Amith Yamasani742a6712011-05-04 14:49:28 -07003115 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003116 } catch (RemoteException e) {
3117 aInfo = null;
3118 }
3119 }
3120 }
3121 }
3122
3123 int res = startActivityLocked(caller, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003124 aInfo, resultTo, resultWho, requestCode, callingPid, callingUid,
3125 startFlags, options, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003126
3127 if (mConfigWillChange && mMainStack) {
3128 // If the caller also wants to switch to a new configuration,
3129 // do so now. This allows a clean switch, as we are waiting
3130 // for the current activity to pause (so we will not destroy
3131 // it), and have not yet started the next activity.
3132 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
3133 "updateConfiguration()");
3134 mConfigWillChange = false;
3135 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3136 "Updating to new configuration after starting activity.");
Dianne Hackborn813075a62011-11-14 17:45:19 -08003137 mService.updateConfigurationLocked(config, null, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003138 }
3139
3140 Binder.restoreCallingIdentity(origId);
3141
3142 if (outResult != null) {
3143 outResult.result = res;
Dianne Hackborna4972e92012-03-14 10:38:05 -07003144 if (res == ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003145 mWaitingActivityLaunched.add(outResult);
3146 do {
3147 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003148 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003149 } catch (InterruptedException e) {
3150 }
3151 } while (!outResult.timeout && outResult.who == null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003152 } else if (res == ActivityManager.START_TASK_TO_FRONT) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003153 ActivityRecord r = this.topRunningActivityLocked(null);
3154 if (r.nowVisible) {
3155 outResult.timeout = false;
3156 outResult.who = new ComponentName(r.info.packageName, r.info.name);
3157 outResult.totalTime = 0;
3158 outResult.thisTime = 0;
3159 } else {
3160 outResult.thisTime = SystemClock.uptimeMillis();
3161 mWaitingActivityVisible.add(outResult);
3162 do {
3163 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003164 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003165 } catch (InterruptedException e) {
3166 }
3167 } while (!outResult.timeout && outResult.who == null);
3168 }
3169 }
3170 }
3171
3172 return res;
3173 }
3174 }
3175
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003176 final int startActivities(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003177 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
3178 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003179 if (intents == null) {
3180 throw new NullPointerException("intents is null");
3181 }
3182 if (resolvedTypes == null) {
3183 throw new NullPointerException("resolvedTypes is null");
3184 }
3185 if (intents.length != resolvedTypes.length) {
3186 throw new IllegalArgumentException("intents are length different than resolvedTypes");
3187 }
3188
3189 ActivityRecord[] outActivity = new ActivityRecord[1];
3190
3191 int callingPid;
3192 if (callingUid >= 0) {
3193 callingPid = -1;
3194 } else if (caller == null) {
3195 callingPid = Binder.getCallingPid();
3196 callingUid = Binder.getCallingUid();
3197 } else {
3198 callingPid = callingUid = -1;
3199 }
3200 final long origId = Binder.clearCallingIdentity();
3201 try {
3202 synchronized (mService) {
3203
3204 for (int i=0; i<intents.length; i++) {
3205 Intent intent = intents[i];
3206 if (intent == null) {
3207 continue;
3208 }
3209
3210 // Refuse possible leaked file descriptors
3211 if (intent != null && intent.hasFileDescriptors()) {
3212 throw new IllegalArgumentException("File descriptors passed in Intent");
3213 }
3214
3215 boolean componentSpecified = intent.getComponent() != null;
3216
3217 // Don't modify the client's object!
3218 intent = new Intent(intent);
3219
3220 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003221 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i],
Amith Yamasani483f3b02012-03-13 16:08:00 -07003222 0, null, null, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07003223 // TODO: New, check if this is correct
3224 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003225
3226 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
3227 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
3228 throw new IllegalArgumentException(
3229 "FLAG_CANT_SAVE_STATE not supported here");
3230 }
3231
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003232 Bundle theseOptions;
3233 if (options != null && i == intents.length-1) {
3234 theseOptions = options;
3235 } else {
3236 theseOptions = null;
3237 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003238 int res = startActivityLocked(caller, intent, resolvedTypes[i],
Dianne Hackborna4972e92012-03-14 10:38:05 -07003239 aInfo, resultTo, null, -1, callingPid, callingUid,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003240 0, theseOptions, componentSpecified, outActivity);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003241 if (res < 0) {
3242 return res;
3243 }
3244
Dianne Hackbornbe707852011-11-11 14:32:10 -08003245 resultTo = outActivity[0] != null ? outActivity[0].appToken : null;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003246 }
3247 }
3248 } finally {
3249 Binder.restoreCallingIdentity(origId);
3250 }
3251
Dianne Hackborna4972e92012-03-14 10:38:05 -07003252 return ActivityManager.START_SUCCESS;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003253 }
3254
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003255 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
3256 long thisTime, long totalTime) {
3257 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
3258 WaitResult w = mWaitingActivityLaunched.get(i);
3259 w.timeout = timeout;
3260 if (r != null) {
3261 w.who = new ComponentName(r.info.packageName, r.info.name);
3262 }
3263 w.thisTime = thisTime;
3264 w.totalTime = totalTime;
3265 }
3266 mService.notifyAll();
3267 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003268
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003269 void reportActivityVisibleLocked(ActivityRecord r) {
3270 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
3271 WaitResult w = mWaitingActivityVisible.get(i);
3272 w.timeout = false;
3273 if (r != null) {
3274 w.who = new ComponentName(r.info.packageName, r.info.name);
3275 }
3276 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
3277 w.thisTime = w.totalTime;
3278 }
3279 mService.notifyAll();
Dianne Hackborn90c52de2011-09-23 12:57:44 -07003280
3281 if (mDismissKeyguardOnNextActivity) {
3282 mDismissKeyguardOnNextActivity = false;
3283 mService.mWindowManager.dismissKeyguard();
3284 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003285 }
3286
3287 void sendActivityResultLocked(int callingUid, ActivityRecord r,
3288 String resultWho, int requestCode, int resultCode, Intent data) {
3289
3290 if (callingUid > 0) {
3291 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003292 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003293 }
3294
3295 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3296 + " : who=" + resultWho + " req=" + requestCode
3297 + " res=" + resultCode + " data=" + data);
3298 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3299 try {
3300 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3301 list.add(new ResultInfo(resultWho, requestCode,
3302 resultCode, data));
Dianne Hackbornbe707852011-11-11 14:32:10 -08003303 r.app.thread.scheduleSendResult(r.appToken, list);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003304 return;
3305 } catch (Exception e) {
3306 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3307 }
3308 }
3309
3310 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3311 }
3312
3313 private final void stopActivityLocked(ActivityRecord r) {
3314 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3315 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3316 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3317 if (!r.finishing) {
Christopher Tated3f175c2012-06-14 14:16:54 -07003318 if (!mService.mSleeping) {
3319 if (DEBUG_STATES) {
3320 Slog.d(TAG, "no-history finish of " + r);
3321 }
3322 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003323 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07003324 } else {
3325 if (DEBUG_STATES) Slog.d(TAG, "Not finishing noHistory " + r
3326 + " on stop because we're just sleeping");
3327 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003328 }
Christopher Tate5007ddd2012-06-12 13:08:18 -07003329 }
3330
3331 if (r.app != null && r.app.thread != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003332 if (mMainStack) {
3333 if (mService.mFocusedActivity == r) {
3334 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3335 }
3336 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003337 r.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003338 try {
3339 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003340 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3341 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003342 r.state = ActivityState.STOPPING;
3343 if (DEBUG_VISBILITY) Slog.v(
3344 TAG, "Stopping visible=" + r.visible + " for " + r);
3345 if (!r.visible) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003346 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003347 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003348 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003349 if (mService.isSleeping()) {
3350 r.setSleeping(true);
3351 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003352 Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG);
3353 msg.obj = r;
3354 mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003355 } catch (Exception e) {
3356 // Maybe just ignore exceptions here... if the process
3357 // has crashed, our death notification will clean things
3358 // up.
3359 Slog.w(TAG, "Exception thrown during pause", e);
3360 // Just in case, assume it to be stopped.
3361 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003362 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003363 r.state = ActivityState.STOPPED;
3364 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003365 destroyActivityLocked(r, true, false, "stop-except");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003366 }
3367 }
3368 }
3369 }
3370
3371 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3372 boolean remove) {
3373 int N = mStoppingActivities.size();
3374 if (N <= 0) return null;
3375
3376 ArrayList<ActivityRecord> stops = null;
3377
3378 final boolean nowVisible = mResumedActivity != null
3379 && mResumedActivity.nowVisible
3380 && !mResumedActivity.waitingVisible;
3381 for (int i=0; i<N; i++) {
3382 ActivityRecord s = mStoppingActivities.get(i);
3383 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3384 + nowVisible + " waitingVisible=" + s.waitingVisible
3385 + " finishing=" + s.finishing);
3386 if (s.waitingVisible && nowVisible) {
3387 mWaitingVisibleActivities.remove(s);
3388 s.waitingVisible = false;
3389 if (s.finishing) {
3390 // If this activity is finishing, it is sitting on top of
3391 // everyone else but we now know it is no longer needed...
3392 // so get rid of it. Otherwise, we need to go through the
3393 // normal flow and hide it once we determine that it is
3394 // hidden by the activities in front of it.
3395 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003396 mService.mWindowManager.setAppVisibility(s.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003397 }
3398 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003399 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003400 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3401 if (stops == null) {
3402 stops = new ArrayList<ActivityRecord>();
3403 }
3404 stops.add(s);
3405 mStoppingActivities.remove(i);
3406 N--;
3407 i--;
3408 }
3409 }
3410
3411 return stops;
3412 }
3413
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003414 final void scheduleIdleLocked() {
3415 Message msg = Message.obtain();
3416 msg.what = IDLE_NOW_MSG;
3417 mHandler.sendMessage(msg);
3418 }
3419
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003420 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003421 Configuration config) {
3422 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3423
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003424 ActivityRecord res = null;
3425
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003426 ArrayList<ActivityRecord> stops = null;
3427 ArrayList<ActivityRecord> finishes = null;
3428 ArrayList<ActivityRecord> thumbnails = null;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003429 ArrayList<UserStartedState> startingUsers = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003430 int NS = 0;
3431 int NF = 0;
3432 int NT = 0;
3433 IApplicationThread sendThumbnail = null;
3434 boolean booting = false;
3435 boolean enableScreen = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003436 boolean activityRemoved = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003437
3438 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003439 ActivityRecord r = ActivityRecord.forToken(token);
3440 if (r != null) {
3441 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003442 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003443 }
3444
3445 // Get the activity record.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003446 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003447 if (index >= 0) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003448 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003449
3450 if (fromTimeout) {
3451 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3452 }
3453
3454 // This is a hack to semi-deal with a race condition
3455 // in the client where it can be constructed with a
3456 // newer configuration from when we asked it to launch.
3457 // We'll update with whatever configuration it now says
3458 // it used to launch.
3459 if (config != null) {
3460 r.configuration = config;
3461 }
3462
3463 // No longer need to keep the device awake.
3464 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3465 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3466 mLaunchingActivity.release();
3467 }
3468
3469 // We are now idle. If someone is waiting for a thumbnail from
3470 // us, we can now deliver.
3471 r.idle = true;
3472 mService.scheduleAppGcsLocked();
3473 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3474 sendThumbnail = r.app.thread;
3475 r.thumbnailNeeded = false;
3476 }
3477
3478 // If this activity is fullscreen, set up to hide those under it.
3479
3480 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3481 ensureActivitiesVisibleLocked(null, 0);
3482
3483 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3484 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003485 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003486 mService.mBooted = true;
3487 enableScreen = true;
3488 }
3489 }
3490
3491 } else if (fromTimeout) {
3492 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3493 }
3494
3495 // Atomically retrieve all of the other things to do.
3496 stops = processStoppingActivitiesLocked(true);
3497 NS = stops != null ? stops.size() : 0;
3498 if ((NF=mFinishingActivities.size()) > 0) {
3499 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3500 mFinishingActivities.clear();
3501 }
3502 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3503 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3504 mService.mCancelledThumbnails.clear();
3505 }
3506
3507 if (mMainStack) {
3508 booting = mService.mBooting;
3509 mService.mBooting = false;
3510 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003511 if (mStartingUsers.size() > 0) {
3512 startingUsers = new ArrayList<UserStartedState>(mStartingUsers);
3513 mStartingUsers.clear();
3514 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003515 }
3516
3517 int i;
3518
3519 // Send thumbnail if requested.
3520 if (sendThumbnail != null) {
3521 try {
3522 sendThumbnail.requestThumbnail(token);
3523 } catch (Exception e) {
3524 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3525 mService.sendPendingThumbnail(null, token, null, null, true);
3526 }
3527 }
3528
3529 // Stop any activities that are scheduled to do so but have been
3530 // waiting for the next one to start.
3531 for (i=0; i<NS; i++) {
3532 ActivityRecord r = (ActivityRecord)stops.get(i);
3533 synchronized (mService) {
3534 if (r.finishing) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003535 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003536 } else {
3537 stopActivityLocked(r);
3538 }
3539 }
3540 }
3541
3542 // Finish any activities that are scheduled to do so but have been
3543 // waiting for the next one to start.
3544 for (i=0; i<NF; i++) {
3545 ActivityRecord r = (ActivityRecord)finishes.get(i);
3546 synchronized (mService) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003547 activityRemoved = destroyActivityLocked(r, true, false, "finish-idle");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003548 }
3549 }
3550
3551 // Report back to any thumbnail receivers.
3552 for (i=0; i<NT; i++) {
3553 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3554 mService.sendPendingThumbnail(r, null, null, null, true);
3555 }
3556
3557 if (booting) {
3558 mService.finishBooting();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003559 } else if (startingUsers != null) {
3560 for (i=0; i<startingUsers.size(); i++) {
3561 mService.finishUserSwitch(startingUsers.get(i));
3562 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003563 }
3564
3565 mService.trimApplications();
3566 //dump();
3567 //mWindowManager.dump();
3568
3569 if (enableScreen) {
3570 mService.enableScreenAfterBoot();
3571 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003572
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003573 if (activityRemoved) {
3574 resumeTopActivityLocked(null);
3575 }
3576
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003577 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003578 }
3579
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003580 final void addStartingUserLocked(UserStartedState uss) {
3581 mStartingUsers.add(uss);
3582 }
3583
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003584 /**
3585 * @return Returns true if the activity is being finished, false if for
3586 * some reason it is being left as-is.
3587 */
3588 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003589 Intent resultData, String reason, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003590 int index = indexOfTokenLocked(token);
Christopher Tated3f175c2012-06-14 14:16:54 -07003591 if (DEBUG_RESULTS || DEBUG_STATES) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003592 TAG, "Finishing activity @" + index + ": token=" + token
Christopher Tated3f175c2012-06-14 14:16:54 -07003593 + ", result=" + resultCode + ", data=" + resultData
3594 + ", reason=" + reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003595 if (index < 0) {
3596 return false;
3597 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003598 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003599
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003600 finishActivityLocked(r, index, resultCode, resultData, reason, oomAdj);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003601 return true;
3602 }
3603
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003604 final void finishSubActivityLocked(IBinder token, String resultWho, int requestCode) {
3605 ActivityRecord self = isInStackLocked(token);
3606 if (self == null) {
3607 return;
3608 }
3609
3610 int i;
3611 for (i=mHistory.size()-1; i>=0; i--) {
3612 ActivityRecord r = (ActivityRecord)mHistory.get(i);
3613 if (r.resultTo == self && r.requestCode == requestCode) {
3614 if ((r.resultWho == null && resultWho == null) ||
3615 (r.resultWho != null && r.resultWho.equals(resultWho))) {
3616 finishActivityLocked(r, i,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003617 Activity.RESULT_CANCELED, null, "request-sub", false);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003618 }
3619 }
3620 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003621 mService.updateOomAdjLocked();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003622 }
3623
3624 final boolean finishActivityAffinityLocked(IBinder token) {
3625 int index = indexOfTokenLocked(token);
3626 if (DEBUG_RESULTS) Slog.v(
3627 TAG, "Finishing activity affinity @" + index + ": token=" + token);
3628 if (index < 0) {
3629 return false;
3630 }
3631 ActivityRecord r = mHistory.get(index);
3632
Amith Yamasanibfc1be12012-05-15 11:12:17 -07003633 while (index >= 0) {
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003634 ActivityRecord cur = mHistory.get(index);
3635 if (cur.task != r.task) {
3636 break;
3637 }
3638 if (cur.taskAffinity == null && r.taskAffinity != null) {
3639 break;
3640 }
3641 if (cur.taskAffinity != null && !cur.taskAffinity.equals(r.taskAffinity)) {
3642 break;
3643 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003644 finishActivityLocked(cur, index, Activity.RESULT_CANCELED, null,
3645 "request-affinity", true);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003646 index--;
3647 }
3648 return true;
3649 }
3650
Dianne Hackborn5c607432012-02-28 14:44:19 -08003651 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
3652 // send the result
3653 ActivityRecord resultTo = r.resultTo;
3654 if (resultTo != null) {
3655 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3656 + " who=" + r.resultWho + " req=" + r.requestCode
3657 + " res=" + resultCode + " data=" + resultData);
3658 if (r.info.applicationInfo.uid > 0) {
3659 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3660 resultTo.packageName, resultData,
3661 resultTo.getUriPermissionsLocked());
3662 }
3663 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3664 resultData);
3665 r.resultTo = null;
3666 }
3667 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3668
3669 // Make sure this HistoryRecord is not holding on to other resources,
3670 // because clients have remote IPC references to this object so we
3671 // can't assume that will go away and want to avoid circular IPC refs.
3672 r.results = null;
3673 r.pendingResults = null;
3674 r.newIntents = null;
3675 r.icicle = null;
3676 }
3677
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003678 /**
3679 * @return Returns true if this activity has been removed from the history
3680 * list, or false if it is still in the list and will be removed later.
3681 */
3682 final boolean finishActivityLocked(ActivityRecord r, int index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003683 int resultCode, Intent resultData, String reason, boolean oomAdj) {
3684 return finishActivityLocked(r, index, resultCode, resultData, reason, false, oomAdj);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003685 }
3686
3687 /**
3688 * @return Returns true if this activity has been removed from the history
3689 * list, or false if it is still in the list and will be removed later.
3690 */
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003691 final boolean finishActivityLocked(ActivityRecord r, int index, int resultCode,
3692 Intent resultData, String reason, boolean immediate, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003693 if (r.finishing) {
3694 Slog.w(TAG, "Duplicate finish request for " + r);
3695 return false;
3696 }
3697
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003698 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003699 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3700 System.identityHashCode(r),
3701 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003702 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003703 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003704 if (next.task == r.task) {
3705 if (r.frontOfTask) {
3706 // The next activity is now the front of the task.
3707 next.frontOfTask = true;
3708 }
3709 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3710 // If the caller asked that this activity (and all above it)
3711 // be cleared when the task is reset, don't lose that information,
3712 // but propagate it up to the next activity.
3713 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3714 }
3715 }
3716 }
3717
3718 r.pauseKeyDispatchingLocked();
3719 if (mMainStack) {
3720 if (mService.mFocusedActivity == r) {
3721 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3722 }
3723 }
3724
Dianne Hackborn5c607432012-02-28 14:44:19 -08003725 finishActivityResultsLocked(r, resultCode, resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003726
3727 if (mService.mPendingThumbnails.size() > 0) {
3728 // There are clients waiting to receive thumbnails so, in case
3729 // this is an activity that someone is waiting for, add it
3730 // to the pending list so we can correctly update the clients.
3731 mService.mCancelledThumbnails.add(r);
3732 }
3733
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003734 if (immediate) {
3735 return finishCurrentActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003736 FINISH_IMMEDIATELY, oomAdj) == null;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003737 } else if (mResumedActivity == r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003738 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003739 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003740 if (DEBUG_TRANSITION) Slog.v(TAG,
3741 "Prepare close transition: finishing " + r);
3742 mService.mWindowManager.prepareAppTransition(endTask
3743 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003744 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003745
3746 // Tell window manager to prepare for this one to be removed.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003747 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003748
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003749 if (mPausingActivity == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003750 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3751 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3752 startPausingLocked(false, false);
3753 }
3754
3755 } else if (r.state != ActivityState.PAUSING) {
3756 // If the activity is PAUSING, we will complete the finish once
3757 // it is done pausing; else we can just directly finish it here.
3758 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3759 return finishCurrentActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003760 FINISH_AFTER_PAUSE, oomAdj) == null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003761 } else {
3762 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3763 }
3764
3765 return false;
3766 }
3767
3768 private static final int FINISH_IMMEDIATELY = 0;
3769 private static final int FINISH_AFTER_PAUSE = 1;
3770 private static final int FINISH_AFTER_VISIBLE = 2;
3771
3772 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003773 int mode, boolean oomAdj) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003774 final int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003775 if (index < 0) {
3776 return null;
3777 }
3778
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003779 return finishCurrentActivityLocked(r, index, mode, oomAdj);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003780 }
3781
3782 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003783 int index, int mode, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003784 // First things first: if this activity is currently visible,
3785 // and the resumed activity is not yet visible, then hold off on
3786 // finishing until the resumed one becomes visible.
3787 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3788 if (!mStoppingActivities.contains(r)) {
3789 mStoppingActivities.add(r);
3790 if (mStoppingActivities.size() > 3) {
3791 // If we already have a few activities waiting to stop,
3792 // then give up on things going idle and start clearing
3793 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003794 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003795 } else {
3796 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003797 }
3798 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003799 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3800 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003801 r.state = ActivityState.STOPPING;
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003802 if (oomAdj) {
3803 mService.updateOomAdjLocked();
3804 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003805 return r;
3806 }
3807
3808 // make sure the record is cleaned out of other places.
3809 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003810 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003811 mWaitingVisibleActivities.remove(r);
3812 if (mResumedActivity == r) {
3813 mResumedActivity = null;
3814 }
3815 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003816 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003817 r.state = ActivityState.FINISHING;
3818
3819 if (mode == FINISH_IMMEDIATELY
3820 || prevState == ActivityState.STOPPED
3821 || prevState == ActivityState.INITIALIZING) {
3822 // If this activity is already stopped, we can just finish
3823 // it right now.
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003824 boolean activityRemoved = destroyActivityLocked(r, true,
3825 oomAdj, "finish-imm");
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003826 if (activityRemoved) {
3827 resumeTopActivityLocked(null);
3828 }
3829 return activityRemoved ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003830 } else {
3831 // Need to go through the full pause cycle to get this
3832 // activity into the stopped state and then finish it.
3833 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3834 mFinishingActivities.add(r);
3835 resumeTopActivityLocked(null);
3836 }
3837 return r;
3838 }
3839
3840 /**
3841 * Perform the common clean-up of an activity record. This is called both
3842 * as part of destroyActivityLocked() (when destroying the client-side
3843 * representation) and cleaning things up as a result of its hosting
3844 * processing going away, in which case there is no remaining client-side
3845 * state to destroy so only the cleanup here is needed.
3846 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003847 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3848 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003849 if (mResumedActivity == r) {
3850 mResumedActivity = null;
3851 }
3852 if (mService.mFocusedActivity == r) {
3853 mService.mFocusedActivity = null;
3854 }
3855
3856 r.configDestroy = false;
3857 r.frozenBeforeDestroy = false;
3858
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003859 if (setState) {
3860 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3861 r.state = ActivityState.DESTROYED;
3862 }
3863
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003864 // Make sure this record is no longer in the pending finishes list.
3865 // This could happen, for example, if we are trimming activities
3866 // down to the max limit while they are still waiting to finish.
3867 mFinishingActivities.remove(r);
3868 mWaitingVisibleActivities.remove(r);
3869
3870 // Remove any pending results.
3871 if (r.finishing && r.pendingResults != null) {
3872 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3873 PendingIntentRecord rec = apr.get();
3874 if (rec != null) {
3875 mService.cancelIntentSenderLocked(rec, false);
3876 }
3877 }
3878 r.pendingResults = null;
3879 }
3880
3881 if (cleanServices) {
3882 cleanUpActivityServicesLocked(r);
3883 }
3884
3885 if (mService.mPendingThumbnails.size() > 0) {
3886 // There are clients waiting to receive thumbnails so, in case
3887 // this is an activity that someone is waiting for, add it
3888 // to the pending list so we can correctly update the clients.
3889 mService.mCancelledThumbnails.add(r);
3890 }
3891
3892 // Get rid of any pending idle timeouts.
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003893 removeTimeoutsForActivityLocked(r);
3894 }
3895
3896 private void removeTimeoutsForActivityLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003897 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003898 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003899 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003900 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003901 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003902 }
3903
Dianne Hackborn5c607432012-02-28 14:44:19 -08003904 final void removeActivityFromHistoryLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003905 if (r.state != ActivityState.DESTROYED) {
Dianne Hackborn5c607432012-02-28 14:44:19 -08003906 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003907 r.makeFinishing();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003908 if (DEBUG_ADD_REMOVE) {
3909 RuntimeException here = new RuntimeException("here");
3910 here.fillInStackTrace();
3911 Slog.i(TAG, "Removing activity " + r + " from stack");
3912 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003913 mHistory.remove(r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003914 r.takeFromHistory();
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003915 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3916 + " (removed from history)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003917 r.state = ActivityState.DESTROYED;
Dianne Hackbornbe707852011-11-11 14:32:10 -08003918 mService.mWindowManager.removeAppToken(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003919 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003920 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003921 }
3922 cleanUpActivityServicesLocked(r);
3923 r.removeUriPermissionsLocked();
3924 }
3925 }
3926
3927 /**
3928 * Perform clean-up of service connections in an activity record.
3929 */
3930 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3931 // Throw away any services that have been bound by this activity.
3932 if (r.connections != null) {
3933 Iterator<ConnectionRecord> it = r.connections.iterator();
3934 while (it.hasNext()) {
3935 ConnectionRecord c = it.next();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003936 mService.mServices.removeConnectionLocked(c, null, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003937 }
3938 r.connections = null;
3939 }
3940 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003941
3942 final void scheduleDestroyActivities(ProcessRecord owner, boolean oomAdj, String reason) {
3943 Message msg = mHandler.obtainMessage(DESTROY_ACTIVITIES_MSG);
3944 msg.obj = new ScheduleDestroyArgs(owner, oomAdj, reason);
3945 mHandler.sendMessage(msg);
3946 }
3947
Dianne Hackborn28695e02011-11-02 21:59:51 -07003948 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003949 boolean lastIsOpaque = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003950 boolean activityRemoved = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003951 for (int i=mHistory.size()-1; i>=0; i--) {
3952 ActivityRecord r = mHistory.get(i);
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003953 if (r.finishing) {
3954 continue;
3955 }
3956 if (r.fullscreen) {
3957 lastIsOpaque = true;
3958 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003959 if (owner != null && r.app != owner) {
3960 continue;
3961 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003962 if (!lastIsOpaque) {
3963 continue;
3964 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003965 // We can destroy this one if we have its icicle saved and
3966 // it is not in the process of pausing/stopping/finishing.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003967 if (r.app != null && r != mResumedActivity && r != mPausingActivity
3968 && r.haveState && !r.visible && r.stopped
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003969 && r.state != ActivityState.DESTROYING
3970 && r.state != ActivityState.DESTROYED) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003971 if (DEBUG_SWITCH) Slog.v(TAG, "Destroying " + r + " in state " + r.state
3972 + " resumed=" + mResumedActivity
3973 + " pausing=" + mPausingActivity);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003974 if (destroyActivityLocked(r, true, oomAdj, reason)) {
3975 activityRemoved = true;
3976 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003977 }
3978 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003979 if (activityRemoved) {
3980 resumeTopActivityLocked(null);
3981 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003982 }
3983
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003984 /**
3985 * Destroy the current CLIENT SIDE instance of an activity. This may be
3986 * called both when actually finishing an activity, or when performing
3987 * a configuration switch where we destroy the current client-side object
3988 * but then create a new client-side object for this same HistoryRecord.
3989 */
3990 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackborn28695e02011-11-02 21:59:51 -07003991 boolean removeFromApp, boolean oomAdj, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003992 if (DEBUG_SWITCH) Slog.v(
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003993 TAG, "Removing activity from " + reason + ": token=" + r
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003994 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3995 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3996 System.identityHashCode(r),
Dianne Hackborn28695e02011-11-02 21:59:51 -07003997 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003998
3999 boolean removedFromHistory = false;
4000
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004001 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004002
4003 final boolean hadApp = r.app != null;
4004
4005 if (hadApp) {
4006 if (removeFromApp) {
4007 int idx = r.app.activities.indexOf(r);
4008 if (idx >= 0) {
4009 r.app.activities.remove(idx);
4010 }
4011 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
4012 mService.mHeavyWeightProcess = null;
4013 mService.mHandler.sendEmptyMessage(
4014 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
4015 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004016 if (r.app.activities.size() == 0) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07004017 // No longer have activities, so update oom adj.
4018 mService.updateOomAdjLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004019 }
4020 }
4021
4022 boolean skipDestroy = false;
4023
4024 try {
4025 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004026 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004027 r.configChangeFlags);
4028 } catch (Exception e) {
4029 // We can just ignore exceptions here... if the process
4030 // has crashed, our death notification will clean things
4031 // up.
4032 //Slog.w(TAG, "Exception thrown during finish", e);
4033 if (r.finishing) {
4034 removeActivityFromHistoryLocked(r);
4035 removedFromHistory = true;
4036 skipDestroy = true;
4037 }
4038 }
4039
4040 r.app = null;
4041 r.nowVisible = false;
4042
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004043 // If the activity is finishing, we need to wait on removing it
4044 // from the list to give it a chance to do its cleanup. During
4045 // that time it may make calls back with its token so we need to
4046 // be able to find it on the list and so we don't want to remove
4047 // it from the list yet. Otherwise, we can just immediately put
4048 // it in the destroyed state since we are not removing it from the
4049 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004050 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004051 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
4052 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004053 r.state = ActivityState.DESTROYING;
4054 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
4055 msg.obj = r;
4056 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
4057 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004058 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4059 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004060 r.state = ActivityState.DESTROYED;
4061 }
4062 } else {
4063 // remove this record from the history.
4064 if (r.finishing) {
4065 removeActivityFromHistoryLocked(r);
4066 removedFromHistory = true;
4067 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004068 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4069 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004070 r.state = ActivityState.DESTROYED;
4071 }
4072 }
4073
4074 r.configChangeFlags = 0;
4075
4076 if (!mLRUActivities.remove(r) && hadApp) {
4077 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
4078 }
4079
4080 return removedFromHistory;
4081 }
4082
4083 final void activityDestroyed(IBinder token) {
4084 synchronized (mService) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004085 final long origId = Binder.clearCallingIdentity();
4086 try {
4087 ActivityRecord r = ActivityRecord.forToken(token);
4088 if (r != null) {
4089 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004090 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004091
4092 int index = indexOfActivityLocked(r);
4093 if (index >= 0) {
4094 if (r.state == ActivityState.DESTROYING) {
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07004095 cleanUpActivityLocked(r, true, false);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004096 removeActivityFromHistoryLocked(r);
4097 }
4098 }
4099 resumeTopActivityLocked(null);
4100 } finally {
4101 Binder.restoreCallingIdentity(origId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004102 }
4103 }
4104 }
4105
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004106 private void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004107 int i = list.size();
4108 if (localLOGV) Slog.v(
4109 TAG, "Removing app " + app + " from list " + list
4110 + " with " + i + " entries");
4111 while (i > 0) {
4112 i--;
4113 ActivityRecord r = (ActivityRecord)list.get(i);
4114 if (localLOGV) Slog.v(
4115 TAG, "Record #" + i + " " + r + ": app=" + r.app);
4116 if (r.app == app) {
4117 if (localLOGV) Slog.v(TAG, "Removing this entry!");
4118 list.remove(i);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004119 removeTimeoutsForActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004120 }
4121 }
4122 }
4123
4124 void removeHistoryRecordsForAppLocked(ProcessRecord app) {
4125 removeHistoryRecordsForAppLocked(mLRUActivities, app);
4126 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004127 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004128 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
4129 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
4130 }
4131
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004132 /**
4133 * Move the current home activity's task (if one exists) to the front
4134 * of the stack.
4135 */
4136 final void moveHomeToFrontLocked() {
4137 TaskRecord homeTask = null;
4138 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004139 ActivityRecord hr = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004140 if (hr.isHomeActivity) {
4141 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08004142 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004143 }
4144 }
4145 if (homeTask != null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004146 moveTaskToFrontLocked(homeTask, null, null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004147 }
4148 }
4149
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004150 final void updateTransitLocked(int transit, Bundle options) {
4151 if (options != null) {
4152 ActivityRecord r = topRunningActivityLocked(null);
4153 if (r != null && r.state != ActivityState.RESUMED) {
4154 r.updateOptionsLocked(options);
4155 } else {
4156 ActivityOptions.abort(options);
4157 }
4158 }
4159 mService.mWindowManager.prepareAppTransition(transit, false);
4160 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004161
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004162 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004163 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
4164
4165 final int task = tr.taskId;
4166 int top = mHistory.size()-1;
4167
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004168 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004169 // nothing to do!
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004170 if (reason != null &&
4171 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
4172 ActivityOptions.abort(options);
4173 } else {
4174 updateTransitLocked(WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, options);
4175 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004176 return;
4177 }
4178
Dianne Hackbornbe707852011-11-11 14:32:10 -08004179 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004180
4181 // Applying the affinities may have removed entries from the history,
4182 // so get the size again.
4183 top = mHistory.size()-1;
4184 int pos = top;
4185
4186 // Shift all activities with this task up to the top
4187 // of the stack, keeping them in the same internal order.
4188 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004189 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004190 if (localLOGV) Slog.v(
4191 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004192 if (r.task.taskId == task) {
4193 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004194 if (DEBUG_ADD_REMOVE) {
4195 RuntimeException here = new RuntimeException("here");
4196 here.fillInStackTrace();
4197 Slog.i(TAG, "Removing and adding activity " + r + " to stack at " + top, here);
4198 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004199 mHistory.remove(pos);
4200 mHistory.add(top, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004201 moved.add(0, r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004202 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004203 }
4204 pos--;
4205 }
4206
4207 if (DEBUG_TRANSITION) Slog.v(TAG,
4208 "Prepare to front transition: task=" + tr);
4209 if (reason != null &&
4210 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004211 mService.mWindowManager.prepareAppTransition(
4212 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004213 ActivityRecord r = topRunningActivityLocked(null);
4214 if (r != null) {
4215 mNoAnimActivities.add(r);
4216 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004217 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004218 } else {
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004219 updateTransitLocked(WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004220 }
4221
4222 mService.mWindowManager.moveAppTokensToTop(moved);
4223 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004224 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004225 }
4226
4227 finishTaskMoveLocked(task);
4228 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
4229 }
4230
4231 private final void finishTaskMoveLocked(int task) {
4232 resumeTopActivityLocked(null);
4233 }
4234
4235 /**
4236 * Worker method for rearranging history stack. Implements the function of moving all
4237 * activities for a specific task (gathering them if disjoint) into a single group at the
4238 * bottom of the stack.
4239 *
4240 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
4241 * to premeptively cancel the move.
4242 *
4243 * @param task The taskId to collect and move to the bottom.
4244 * @return Returns true if the move completed, false if not.
4245 */
4246 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
4247 Slog.i(TAG, "moveTaskToBack: " + task);
4248
4249 // If we have a watcher, preflight the move before committing to it. First check
4250 // for *other* available tasks, but if none are available, then try again allowing the
4251 // current task to be selected.
4252 if (mMainStack && mService.mController != null) {
4253 ActivityRecord next = topRunningActivityLocked(null, task);
4254 if (next == null) {
4255 next = topRunningActivityLocked(null, 0);
4256 }
4257 if (next != null) {
4258 // ask watcher if this is allowed
4259 boolean moveOK = true;
4260 try {
4261 moveOK = mService.mController.activityResuming(next.packageName);
4262 } catch (RemoteException e) {
4263 mService.mController = null;
4264 }
4265 if (!moveOK) {
4266 return false;
4267 }
4268 }
4269 }
4270
Dianne Hackbornbe707852011-11-11 14:32:10 -08004271 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004272
4273 if (DEBUG_TRANSITION) Slog.v(TAG,
4274 "Prepare to back transition: task=" + task);
4275
4276 final int N = mHistory.size();
4277 int bottom = 0;
4278 int pos = 0;
4279
4280 // Shift all activities with this task down to the bottom
4281 // of the stack, keeping them in the same internal order.
4282 while (pos < N) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004283 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004284 if (localLOGV) Slog.v(
4285 TAG, "At " + pos + " ckp " + r.task + ": " + r);
4286 if (r.task.taskId == task) {
4287 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004288 if (DEBUG_ADD_REMOVE) {
4289 RuntimeException here = new RuntimeException("here");
4290 here.fillInStackTrace();
4291 Slog.i(TAG, "Removing and adding activity " + r + " to stack at "
4292 + bottom, here);
4293 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004294 mHistory.remove(pos);
4295 mHistory.add(bottom, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004296 moved.add(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004297 bottom++;
4298 }
4299 pos++;
4300 }
4301
4302 if (reason != null &&
4303 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004304 mService.mWindowManager.prepareAppTransition(
4305 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004306 ActivityRecord r = topRunningActivityLocked(null);
4307 if (r != null) {
4308 mNoAnimActivities.add(r);
4309 }
4310 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004311 mService.mWindowManager.prepareAppTransition(
4312 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004313 }
4314 mService.mWindowManager.moveAppTokensToBottom(moved);
4315 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004316 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004317 }
4318
4319 finishTaskMoveLocked(task);
4320 return true;
4321 }
4322
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004323 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
4324 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4325 ActivityRecord resumed = mResumedActivity;
4326 if (resumed != null && resumed.thumbHolder == tr) {
4327 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
4328 } else {
4329 info.mainThumbnail = tr.lastThumbnail;
4330 }
4331 return info;
4332 }
4333
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004334 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex,
4335 boolean taskRequired) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004336 TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
4337 if (info.root == null) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004338 if (taskRequired) {
4339 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
4340 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004341 return null;
4342 }
4343
4344 if (subTaskIndex < 0) {
4345 // Just remove the entire task.
4346 performClearTaskAtIndexLocked(taskId, info.rootIndex);
4347 return info.root;
4348 }
4349
4350 if (subTaskIndex >= info.subtasks.size()) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004351 if (taskRequired) {
4352 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
4353 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004354 return null;
4355 }
4356
4357 // Remove all of this task's activies starting at the sub task.
4358 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
4359 performClearTaskAtIndexLocked(taskId, subtask.index);
4360 return subtask.activity;
4361 }
4362
4363 public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
4364 ActivityRecord resumed = mResumedActivity;
4365 final TaskAccessInfo thumbs = new TaskAccessInfo();
4366 // How many different sub-thumbnails?
4367 final int NA = mHistory.size();
4368 int j = 0;
4369 ThumbnailHolder holder = null;
4370 while (j < NA) {
4371 ActivityRecord ar = mHistory.get(j);
4372 if (!ar.finishing && ar.task.taskId == taskId) {
4373 holder = ar.thumbHolder;
4374 break;
4375 }
4376 j++;
4377 }
4378
4379 if (j >= NA) {
4380 return thumbs;
4381 }
4382
4383 thumbs.root = mHistory.get(j);
4384 thumbs.rootIndex = j;
4385
4386 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
4387 thumbs.subtasks = subtasks;
4388 ActivityRecord lastActivity = null;
4389 while (j < NA) {
4390 ActivityRecord ar = mHistory.get(j);
4391 j++;
4392 if (ar.finishing) {
4393 continue;
4394 }
4395 if (ar.task.taskId != taskId) {
4396 break;
4397 }
4398 lastActivity = ar;
4399 if (ar.thumbHolder != holder && holder != null) {
4400 thumbs.numSubThumbbails++;
4401 holder = ar.thumbHolder;
4402 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
4403 sub.thumbnail = holder.lastThumbnail;
4404 sub.activity = ar;
4405 sub.index = j-1;
4406 subtasks.add(sub);
4407 }
4408 }
4409 if (lastActivity != null && subtasks.size() > 0) {
4410 if (resumed == lastActivity) {
4411 TaskAccessInfo.SubTask sub = subtasks.get(subtasks.size()-1);
4412 sub.thumbnail = lastActivity.stack.screenshotActivities(lastActivity);
4413 }
4414 }
4415 if (thumbs.numSubThumbbails > 0) {
4416 thumbs.retriever = new IThumbnailRetriever.Stub() {
4417 public Bitmap getThumbnail(int index) {
4418 if (index < 0 || index >= thumbs.subtasks.size()) {
4419 return null;
4420 }
4421 return thumbs.subtasks.get(index).thumbnail;
4422 }
4423 };
4424 }
4425 return thumbs;
4426 }
4427
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004428 private final void logStartActivity(int tag, ActivityRecord r,
4429 TaskRecord task) {
4430 EventLog.writeEvent(tag,
4431 System.identityHashCode(r), task.taskId,
4432 r.shortComponentName, r.intent.getAction(),
4433 r.intent.getType(), r.intent.getDataString(),
4434 r.intent.getFlags());
4435 }
4436
4437 /**
4438 * Make sure the given activity matches the current configuration. Returns
4439 * false if the activity had to be destroyed. Returns true if the
4440 * configuration is the same, or the activity will remain running as-is
4441 * for whatever reason. Ensures the HistoryRecord is updated with the
4442 * correct configuration and all other bookkeeping is handled.
4443 */
4444 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
4445 int globalChanges) {
4446 if (mConfigWillChange) {
4447 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4448 "Skipping config check (will change): " + r);
4449 return true;
4450 }
4451
4452 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4453 "Ensuring correct configuration: " + r);
4454
4455 // Short circuit: if the two configurations are the exact same
4456 // object (the common case), then there is nothing to do.
4457 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004458 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004459 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4460 "Configuration unchanged in " + r);
4461 return true;
4462 }
4463
4464 // We don't worry about activities that are finishing.
4465 if (r.finishing) {
4466 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4467 "Configuration doesn't matter in finishing " + r);
4468 r.stopFreezingScreenLocked(false);
4469 return true;
4470 }
4471
4472 // Okay we now are going to make this activity have the new config.
4473 // But then we need to figure out how it needs to deal with that.
4474 Configuration oldConfig = r.configuration;
4475 r.configuration = newConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004476
4477 // Determine what has changed. May be nothing, if this is a config
4478 // that has come back from the app after going idle. In that case
4479 // we just want to leave the official config object now in the
4480 // activity and do nothing else.
4481 final int changes = oldConfig.diff(newConfig);
4482 if (changes == 0 && !r.forceNewConfig) {
4483 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4484 "Configuration no differences in " + r);
4485 return true;
4486 }
4487
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004488 // If the activity isn't currently running, just leave the new
4489 // configuration and it will pick that up next time it starts.
4490 if (r.app == null || r.app.thread == null) {
4491 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4492 "Configuration doesn't matter not running " + r);
4493 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004494 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004495 return true;
4496 }
4497
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004498 // Figure out how to handle the changes between the configurations.
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004499 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4500 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
4501 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07004502 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004503 + ", newConfig=" + newConfig);
4504 }
Dianne Hackborne6676352011-06-01 16:51:20 -07004505 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004506 // Aha, the activity isn't handling the change, so DIE DIE DIE.
4507 r.configChangeFlags |= changes;
4508 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004509 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004510 if (r.app == null || r.app.thread == null) {
4511 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004512 "Config is destroying non-running " + r);
Dianne Hackborn28695e02011-11-02 21:59:51 -07004513 destroyActivityLocked(r, true, false, "config");
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004514 } else if (r.state == ActivityState.PAUSING) {
4515 // A little annoying: we are waiting for this activity to
4516 // finish pausing. Let's not do anything now, but just
4517 // flag that it needs to be restarted when done pausing.
4518 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004519 "Config is skipping already pausing " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004520 r.configDestroy = true;
4521 return true;
4522 } else if (r.state == ActivityState.RESUMED) {
4523 // Try to optimize this case: the configuration is changing
4524 // and we need to restart the top, resumed activity.
4525 // Instead of doing the normal handshaking, just say
4526 // "restart!".
4527 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004528 "Config is relaunching resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004529 relaunchActivityLocked(r, r.configChangeFlags, true);
4530 r.configChangeFlags = 0;
4531 } else {
4532 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004533 "Config is relaunching non-resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004534 relaunchActivityLocked(r, r.configChangeFlags, false);
4535 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004536 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004537
4538 // All done... tell the caller we weren't able to keep this
4539 // activity around.
4540 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004541 }
4542
4543 // Default case: the activity can handle this new configuration, so
4544 // hand it over. Note that we don't need to give it the new
4545 // configuration, since we always send configuration changes to all
4546 // process when they happen so it can just use whatever configuration
4547 // it last got.
4548 if (r.app != null && r.app.thread != null) {
4549 try {
4550 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004551 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004552 } catch (RemoteException e) {
4553 // If process died, whatever.
4554 }
4555 }
4556 r.stopFreezingScreenLocked(false);
4557
4558 return true;
4559 }
4560
4561 private final boolean relaunchActivityLocked(ActivityRecord r,
4562 int changes, boolean andResume) {
4563 List<ResultInfo> results = null;
4564 List<Intent> newIntents = null;
4565 if (andResume) {
4566 results = r.results;
4567 newIntents = r.newIntents;
4568 }
4569 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4570 + " with results=" + results + " newIntents=" + newIntents
4571 + " andResume=" + andResume);
4572 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
4573 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
4574 r.task.taskId, r.shortComponentName);
4575
4576 r.startFreezingScreenLocked(r.app, 0);
4577
4578 try {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004579 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG,
4580 (andResume ? "Relaunching to RESUMED " : "Relaunching to PAUSED ")
4581 + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004582 r.forceNewConfig = false;
Dianne Hackbornbe707852011-11-11 14:32:10 -08004583 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004584 changes, !andResume, new Configuration(mService.mConfiguration));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004585 // Note: don't need to call pauseIfSleepingLocked() here, because
4586 // the caller will only pass in 'andResume' if this activity is
4587 // currently resumed, which implies we aren't sleeping.
4588 } catch (RemoteException e) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004589 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, "Relaunch failed", e);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004590 }
4591
4592 if (andResume) {
4593 r.results = null;
4594 r.newIntents = null;
4595 if (mMainStack) {
4596 mService.reportResumedActivityLocked(r);
4597 }
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004598 r.state = ActivityState.RESUMED;
4599 } else {
4600 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
4601 r.state = ActivityState.PAUSED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004602 }
4603
4604 return true;
4605 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004606
4607 public void dismissKeyguardOnNextActivityLocked() {
4608 mDismissKeyguardOnNextActivity = true;
4609 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004610}