blob: 25fae830820cc87d44ce5d1086325cae4c7f68c9 [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.net.Uri;
49import android.os.Binder;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070050import android.os.Bundle;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070051import android.os.Handler;
52import android.os.IBinder;
53import android.os.Message;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070054import android.os.ParcelFileDescriptor;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070055import android.os.PowerManager;
56import android.os.RemoteException;
57import android.os.SystemClock;
Amith Yamasani742a6712011-05-04 14:49:28 -070058import android.os.UserId;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070059import android.util.EventLog;
60import android.util.Log;
61import android.util.Slog;
62import android.view.WindowManagerPolicy;
63
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070064import java.io.IOException;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070065import java.lang.ref.WeakReference;
66import java.util.ArrayList;
67import java.util.Iterator;
68import java.util.List;
69
70/**
71 * State and management of a single stack of activities.
72 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070073final class ActivityStack {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070074 static final String TAG = ActivityManagerService.TAG;
Dianne Hackbornb961cd22011-06-21 12:13:37 -070075 static final boolean localLOGV = ActivityManagerService.localLOGV;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070076 static final boolean DEBUG_SWITCH = ActivityManagerService.DEBUG_SWITCH;
77 static final boolean DEBUG_PAUSE = ActivityManagerService.DEBUG_PAUSE;
78 static final boolean DEBUG_VISBILITY = ActivityManagerService.DEBUG_VISBILITY;
79 static final boolean DEBUG_USER_LEAVING = ActivityManagerService.DEBUG_USER_LEAVING;
80 static final boolean DEBUG_TRANSITION = ActivityManagerService.DEBUG_TRANSITION;
81 static final boolean DEBUG_RESULTS = ActivityManagerService.DEBUG_RESULTS;
82 static final boolean DEBUG_CONFIGURATION = ActivityManagerService.DEBUG_CONFIGURATION;
83 static final boolean DEBUG_TASKS = ActivityManagerService.DEBUG_TASKS;
84
Dianne Hackbornce86ba82011-07-13 19:33:41 -070085 static final boolean DEBUG_STATES = false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070086 static final boolean DEBUG_ADD_REMOVE = false;
87 static final boolean DEBUG_SAVED_STATE = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070088
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070089 static final boolean VALIDATE_TOKENS = ActivityManagerService.VALIDATE_TOKENS;
90
91 // How long we wait until giving up on the last activity telling us it
92 // is idle.
93 static final int IDLE_TIMEOUT = 10*1000;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -070094
95 // Ticks during which we check progress while waiting for an app to launch.
96 static final int LAUNCH_TICK = 500;
97
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070098 // How long we wait until giving up on the last activity to pause. This
99 // is short because it directly impacts the responsiveness of starting the
100 // next activity.
101 static final int PAUSE_TIMEOUT = 500;
102
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700103 // How long we wait for the activity to tell us it has stopped before
104 // giving up. This is a good amount of time because we really need this
105 // from the application in order to get its saved state.
106 static final int STOP_TIMEOUT = 10*1000;
107
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800108 // How long we can hold the sleep wake lock before giving up.
109 static final int SLEEP_TIMEOUT = 5*1000;
110
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700111 // How long we can hold the launch wake lock before giving up.
112 static final int LAUNCH_TIMEOUT = 10*1000;
113
114 // How long we wait until giving up on an activity telling us it has
115 // finished destroying itself.
116 static final int DESTROY_TIMEOUT = 10*1000;
117
118 // How long until we reset a task when the user returns to it. Currently
Dianne Hackborn621e17d2010-11-22 15:59:56 -0800119 // disabled.
120 static final long ACTIVITY_INACTIVE_RESET_TIME = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700121
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700122 // How long between activity launches that we consider safe to not warn
123 // the user about an unexpected activity being launched on top.
124 static final long START_WARN_TIME = 5*1000;
125
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700126 // Set to false to disable the preview that is shown while a new activity
127 // is being started.
128 static final boolean SHOW_APP_STARTING_PREVIEW = true;
129
130 enum ActivityState {
131 INITIALIZING,
132 RESUMED,
133 PAUSING,
134 PAUSED,
135 STOPPING,
136 STOPPED,
137 FINISHING,
138 DESTROYING,
139 DESTROYED
140 }
141
142 final ActivityManagerService mService;
143 final boolean mMainStack;
144
145 final Context mContext;
146
147 /**
148 * The back history of all previous (and possibly still
149 * running) activities. It contains HistoryRecord objects.
150 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700151 final ArrayList<ActivityRecord> mHistory = new ArrayList<ActivityRecord>();
Dianne Hackbornbe707852011-11-11 14:32:10 -0800152
153 /**
154 * Used for validating app tokens with window manager.
155 */
156 final ArrayList<IBinder> mValidateAppTokens = new ArrayList<IBinder>();
157
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700158 /**
159 * List of running activities, sorted by recent usage.
160 * The first entry in the list is the least recently used.
161 * It contains HistoryRecord objects.
162 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700163 final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700164
165 /**
166 * List of activities that are waiting for a new activity
167 * to become visible before completing whatever operation they are
168 * supposed to do.
169 */
170 final ArrayList<ActivityRecord> mWaitingVisibleActivities
171 = new ArrayList<ActivityRecord>();
172
173 /**
174 * List of activities that are ready to be stopped, but waiting
175 * for the next activity to settle down before doing so. It contains
176 * HistoryRecord objects.
177 */
178 final ArrayList<ActivityRecord> mStoppingActivities
179 = new ArrayList<ActivityRecord>();
180
181 /**
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800182 * List of activities that are in the process of going to sleep.
183 */
184 final ArrayList<ActivityRecord> mGoingToSleepActivities
185 = new ArrayList<ActivityRecord>();
186
187 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700188 * Animations that for the current transition have requested not to
189 * be considered for the transition animation.
190 */
191 final ArrayList<ActivityRecord> mNoAnimActivities
192 = new ArrayList<ActivityRecord>();
193
194 /**
195 * List of activities that are ready to be finished, but waiting
196 * for the previous activity to settle down before doing so. It contains
197 * HistoryRecord objects.
198 */
199 final ArrayList<ActivityRecord> mFinishingActivities
200 = new ArrayList<ActivityRecord>();
201
202 /**
203 * List of people waiting to find out about the next launched activity.
204 */
205 final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched
206 = new ArrayList<IActivityManager.WaitResult>();
207
208 /**
209 * List of people waiting to find out about the next visible activity.
210 */
211 final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible
212 = new ArrayList<IActivityManager.WaitResult>();
213
214 /**
215 * Set when the system is going to sleep, until we have
216 * successfully paused the current activity and released our wake lock.
217 * At that point the system is allowed to actually sleep.
218 */
219 final PowerManager.WakeLock mGoingToSleep;
220
221 /**
222 * We don't want to allow the device to go to sleep while in the process
223 * of launching an activity. This is primarily to allow alarm intent
224 * receivers to launch an activity and get that to run before the device
225 * goes back to sleep.
226 */
227 final PowerManager.WakeLock mLaunchingActivity;
228
229 /**
230 * When we are in the process of pausing an activity, before starting the
231 * next one, this variable holds the activity that is currently being paused.
232 */
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800233 ActivityRecord mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700234
235 /**
236 * This is the last activity that we put into the paused state. This is
237 * used to determine if we need to do an activity transition while sleeping,
238 * when we normally hold the top activity paused.
239 */
240 ActivityRecord mLastPausedActivity = null;
241
242 /**
243 * Current activity that is resumed, or null if there is none.
244 */
245 ActivityRecord mResumedActivity = null;
246
247 /**
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700248 * This is the last activity that has been started. It is only used to
249 * identify when multiple activities are started at once so that the user
250 * can be warned they may not be in the activity they think they are.
251 */
252 ActivityRecord mLastStartedActivity = null;
253
254 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700255 * Set when we know we are going to be calling updateConfiguration()
256 * soon, so want to skip intermediate config checks.
257 */
258 boolean mConfigWillChange;
259
260 /**
261 * Set to indicate whether to issue an onUserLeaving callback when a
262 * newly launched activity is being brought in front of us.
263 */
264 boolean mUserLeaving = false;
265
266 long mInitialStartTime = 0;
267
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800268 /**
269 * Set when we have taken too long waiting to go to sleep.
270 */
271 boolean mSleepTimeout = false;
272
Dianne Hackborn90c52de2011-09-23 12:57:44 -0700273 /**
274 * Dismiss the keyguard after the next activity is displayed?
275 */
276 boolean mDismissKeyguardOnNextActivity = false;
277
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800278 int mThumbnailWidth = -1;
279 int mThumbnailHeight = -1;
280
Amith Yamasani742a6712011-05-04 14:49:28 -0700281 private int mCurrentUser;
282
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800283 static final int SLEEP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG;
284 static final int PAUSE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 1;
285 static final int IDLE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 2;
286 static final int IDLE_NOW_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 3;
287 static final int LAUNCH_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 4;
288 static final int DESTROY_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 5;
289 static final int RESUME_TOP_ACTIVITY_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 6;
Dianne Hackborn29ba7e62012-03-16 15:03:36 -0700290 static final int LAUNCH_TICK_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 7;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700291 static final int STOP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 8;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700292
293 final Handler mHandler = new Handler() {
294 //public Handler() {
295 // if (localLOGV) Slog.v(TAG, "Handler started!");
296 //}
297
298 public void handleMessage(Message msg) {
299 switch (msg.what) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800300 case SLEEP_TIMEOUT_MSG: {
Dianne Hackborn8e8d65f2011-08-11 19:36:18 -0700301 synchronized (mService) {
302 if (mService.isSleeping()) {
303 Slog.w(TAG, "Sleep timeout! Sleeping now.");
304 mSleepTimeout = true;
305 checkReadyForSleepLocked();
306 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800307 }
308 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700309 case PAUSE_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800310 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700311 // We don't at this point know if the activity is fullscreen,
312 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800313 Slog.w(TAG, "Activity pause timeout for " + r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700314 synchronized (mService) {
315 if (r.app != null) {
316 mService.logAppTooSlow(r.app, r.pauseTime,
317 "pausing " + r);
318 }
319 }
320
Dianne Hackbornbe707852011-11-11 14:32:10 -0800321 activityPaused(r != null ? r.appToken : null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700322 } break;
323 case IDLE_TIMEOUT_MSG: {
324 if (mService.mDidDexOpt) {
325 mService.mDidDexOpt = false;
326 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
327 nmsg.obj = msg.obj;
328 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
329 return;
330 }
331 // We don't at this point know if the activity is fullscreen,
332 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800333 ActivityRecord r = (ActivityRecord)msg.obj;
334 Slog.w(TAG, "Activity idle timeout for " + r);
335 activityIdleInternal(r != null ? r.appToken : null, true, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700336 } break;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700337 case LAUNCH_TICK_MSG: {
338 ActivityRecord r = (ActivityRecord)msg.obj;
339 synchronized (mService) {
340 if (r.continueLaunchTickingLocked()) {
341 mService.logAppTooSlow(r.app, r.launchTickTime,
342 "launching " + r);
343 }
344 }
345 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700346 case DESTROY_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800347 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700348 // We don't at this point know if the activity is fullscreen,
349 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800350 Slog.w(TAG, "Activity destroy timeout for " + r);
351 activityDestroyed(r != null ? r.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700352 } break;
353 case IDLE_NOW_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800354 ActivityRecord r = (ActivityRecord)msg.obj;
355 activityIdleInternal(r != null ? r.appToken : null, false, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700356 } break;
357 case LAUNCH_TIMEOUT_MSG: {
358 if (mService.mDidDexOpt) {
359 mService.mDidDexOpt = false;
360 Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
361 mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
362 return;
363 }
364 synchronized (mService) {
365 if (mLaunchingActivity.isHeld()) {
366 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
367 mLaunchingActivity.release();
368 }
369 }
370 } break;
371 case RESUME_TOP_ACTIVITY_MSG: {
372 synchronized (mService) {
373 resumeTopActivityLocked(null);
374 }
375 } break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700376 case STOP_TIMEOUT_MSG: {
377 ActivityRecord r = (ActivityRecord)msg.obj;
378 // We don't at this point know if the activity is fullscreen,
379 // so we need to be conservative and assume it isn't.
380 Slog.w(TAG, "Activity stop timeout for " + r);
381 synchronized (mService) {
382 if (r.isInHistory()) {
383 activityStoppedLocked(r, null, null, null);
384 }
385 }
386 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700387 }
388 }
389 };
390
391 ActivityStack(ActivityManagerService service, Context context, boolean mainStack) {
392 mService = service;
393 mContext = context;
394 mMainStack = mainStack;
395 PowerManager pm =
396 (PowerManager)context.getSystemService(Context.POWER_SERVICE);
397 mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
398 mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
399 mLaunchingActivity.setReferenceCounted(false);
400 }
401
402 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700403 // TODO: Don't look for any tasks from other users
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700404 int i = mHistory.size()-1;
405 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700406 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700407 if (!r.finishing && r != notTop) {
408 return r;
409 }
410 i--;
411 }
412 return null;
413 }
414
415 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700416 // TODO: Don't look for any tasks from other users
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700417 int i = mHistory.size()-1;
418 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700419 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700420 if (!r.finishing && !r.delayedResume && r != notTop) {
421 return r;
422 }
423 i--;
424 }
425 return null;
426 }
427
428 /**
429 * This is a simplified version of topRunningActivityLocked that provides a number of
430 * optional skip-over modes. It is intended for use with the ActivityController hook only.
431 *
432 * @param token If non-null, any history records matching this token will be skipped.
433 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
434 *
435 * @return Returns the HistoryRecord of the next activity on the stack.
436 */
437 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700438 // TODO: Don't look for any tasks from other users
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700439 int i = mHistory.size()-1;
440 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700441 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700442 // Note: the taskId check depends on real taskId fields being non-zero
Dianne Hackbornbe707852011-11-11 14:32:10 -0800443 if (!r.finishing && (token != r.appToken) && (taskId != r.task.taskId)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700444 return r;
445 }
446 i--;
447 }
448 return null;
449 }
450
451 final int indexOfTokenLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800452 return mHistory.indexOf(ActivityRecord.forToken(token));
453 }
454
455 final int indexOfActivityLocked(ActivityRecord r) {
456 return mHistory.indexOf(r);
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700457 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700458
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700459 final ActivityRecord isInStackLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800460 ActivityRecord r = ActivityRecord.forToken(token);
461 if (mHistory.contains(r)) {
462 return r;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700463 }
464 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700465 }
466
467 private final boolean updateLRUListLocked(ActivityRecord r) {
468 final boolean hadit = mLRUActivities.remove(r);
469 mLRUActivities.add(r);
470 return hadit;
471 }
472
473 /**
474 * Returns the top activity in any existing task matching the given
475 * Intent. Returns null if no such task is found.
476 */
477 private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
478 ComponentName cls = intent.getComponent();
479 if (info.targetActivity != null) {
480 cls = new ComponentName(info.packageName, info.targetActivity);
481 }
482
483 TaskRecord cp = null;
484
Amith Yamasani742a6712011-05-04 14:49:28 -0700485 final int userId = UserId.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700486 final int N = mHistory.size();
487 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700488 ActivityRecord r = mHistory.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -0700489 if (!r.finishing && r.task != cp && r.userId == userId
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700490 && r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
491 cp = r.task;
492 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
493 // + "/aff=" + r.task.affinity + " to new cls="
494 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
495 if (r.task.affinity != null) {
496 if (r.task.affinity.equals(info.taskAffinity)) {
497 //Slog.i(TAG, "Found matching affinity!");
498 return r;
499 }
500 } else if (r.task.intent != null
501 && r.task.intent.getComponent().equals(cls)) {
502 //Slog.i(TAG, "Found matching class!");
503 //dump();
504 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
505 return r;
506 } else if (r.task.affinityIntent != null
507 && r.task.affinityIntent.getComponent().equals(cls)) {
508 //Slog.i(TAG, "Found matching class!");
509 //dump();
510 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
511 return r;
512 }
513 }
514 }
515
516 return null;
517 }
518
519 /**
520 * Returns the first activity (starting from the top of the stack) that
521 * is the same as the given activity. Returns null if no such activity
522 * is found.
523 */
524 private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
525 ComponentName cls = intent.getComponent();
526 if (info.targetActivity != null) {
527 cls = new ComponentName(info.packageName, info.targetActivity);
528 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700529 final int userId = UserId.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700530
531 final int N = mHistory.size();
532 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700533 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700534 if (!r.finishing) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700535 if (r.intent.getComponent().equals(cls) && r.userId == userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700536 //Slog.i(TAG, "Found matching class!");
537 //dump();
538 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
539 return r;
540 }
541 }
542 }
543
544 return null;
545 }
546
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700547 final void showAskCompatModeDialogLocked(ActivityRecord r) {
548 Message msg = Message.obtain();
549 msg.what = ActivityManagerService.SHOW_COMPAT_MODE_DIALOG_MSG;
550 msg.obj = r.task.askedCompatMode ? null : r;
551 mService.mHandler.sendMessage(msg);
552 }
553
Amith Yamasani742a6712011-05-04 14:49:28 -0700554 /*
555 * Move the activities around in the stack to bring a user to the foreground.
556 * @return whether there are any activities for the specified user.
557 */
558 final boolean switchUser(int userId) {
559 synchronized (mService) {
560 mCurrentUser = userId;
561
562 // Only one activity? Nothing to do...
563 if (mHistory.size() < 2)
564 return false;
565
566 boolean haveActivities = false;
567 // Check if the top activity is from the new user.
568 ActivityRecord top = mHistory.get(mHistory.size() - 1);
569 if (top.userId == userId) return true;
570 // Otherwise, move the user's activities to the top.
571 int N = mHistory.size();
572 int i = 0;
573 while (i < N) {
574 ActivityRecord r = mHistory.get(i);
575 if (r.userId == userId) {
576 ActivityRecord moveToTop = mHistory.remove(i);
577 mHistory.add(moveToTop);
578 // No need to check the top one now
579 N--;
580 haveActivities = true;
581 } else {
582 i++;
583 }
584 }
585 // Transition from the old top to the new top
586 resumeTopActivityLocked(top);
587 return haveActivities;
588 }
589 }
590
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700591 final boolean realStartActivityLocked(ActivityRecord r,
592 ProcessRecord app, boolean andResume, boolean checkConfig)
593 throws RemoteException {
594
595 r.startFreezingScreenLocked(app, 0);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800596 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700597
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700598 // schedule launch ticks to collect information about slow apps.
599 r.startLaunchTickingLocked();
600
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700601 // Have the window manager re-evaluate the orientation of
602 // the screen based on the new activity order. Note that
603 // as a result of this, it can call back into the activity
604 // manager with a new orientation. We don't care about that,
605 // because the activity is not currently running so we are
606 // just restarting it anyway.
607 if (checkConfig) {
608 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
609 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -0800610 r.mayFreezeScreenLocked(app) ? r.appToken : null);
Dianne Hackborn813075a62011-11-14 17:45:19 -0800611 mService.updateConfigurationLocked(config, r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700612 }
613
614 r.app = app;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700615 app.waitingToKill = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700616
617 if (localLOGV) Slog.v(TAG, "Launching: " + r);
618
619 int idx = app.activities.indexOf(r);
620 if (idx < 0) {
621 app.activities.add(r);
622 }
623 mService.updateLruProcessLocked(app, true, true);
624
625 try {
626 if (app.thread == null) {
627 throw new RemoteException();
628 }
629 List<ResultInfo> results = null;
630 List<Intent> newIntents = null;
631 if (andResume) {
632 results = r.results;
633 newIntents = r.newIntents;
634 }
635 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
636 + " icicle=" + r.icicle
637 + " with results=" + results + " newIntents=" + newIntents
638 + " andResume=" + andResume);
639 if (andResume) {
640 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
641 System.identityHashCode(r),
642 r.task.taskId, r.shortComponentName);
643 }
644 if (r.isHomeActivity) {
645 mService.mHomeProcess = app;
646 }
647 mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800648 r.sleeping = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400649 r.forceNewConfig = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700650 showAskCompatModeDialogLocked(r);
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700651 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700652 String profileFile = null;
653 ParcelFileDescriptor profileFd = null;
654 boolean profileAutoStop = false;
655 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
656 if (mService.mProfileProc == null || mService.mProfileProc == app) {
657 mService.mProfileProc = app;
658 profileFile = mService.mProfileFile;
659 profileFd = mService.mProfileFd;
660 profileAutoStop = mService.mAutoStopProfiler;
661 }
662 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -0700663 app.hasShownUi = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700664 app.pendingUiClean = true;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700665 if (profileFd != null) {
666 try {
667 profileFd = profileFd.dup();
668 } catch (IOException e) {
669 profileFd = null;
670 }
671 }
Dianne Hackbornbe707852011-11-11 14:32:10 -0800672 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
Dianne Hackborn813075a62011-11-14 17:45:19 -0800673 System.identityHashCode(r), r.info,
674 new Configuration(mService.mConfiguration),
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700675 r.compat, r.icicle, results, newIntents, !andResume,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700676 mService.isNextTransitionForward(), profileFile, profileFd,
677 profileAutoStop);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700678
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700679 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700680 // This may be a heavy-weight process! Note that the package
681 // manager will ensure that only activity can run in the main
682 // process of the .apk, which is the only thing that will be
683 // considered heavy-weight.
684 if (app.processName.equals(app.info.packageName)) {
685 if (mService.mHeavyWeightProcess != null
686 && mService.mHeavyWeightProcess != app) {
687 Log.w(TAG, "Starting new heavy weight process " + app
688 + " when already running "
689 + mService.mHeavyWeightProcess);
690 }
691 mService.mHeavyWeightProcess = app;
692 Message msg = mService.mHandler.obtainMessage(
693 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
694 msg.obj = r;
695 mService.mHandler.sendMessage(msg);
696 }
697 }
698
699 } catch (RemoteException e) {
700 if (r.launchFailed) {
701 // This is the second time we failed -- finish activity
702 // and give up.
703 Slog.e(TAG, "Second failure launching "
704 + r.intent.getComponent().flattenToShortString()
705 + ", giving up", e);
706 mService.appDiedLocked(app, app.pid, app.thread);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800707 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700708 "2nd-crash");
709 return false;
710 }
711
712 // This is the first time we failed -- restart process and
713 // retry.
714 app.activities.remove(r);
715 throw e;
716 }
717
718 r.launchFailed = false;
719 if (updateLRUListLocked(r)) {
720 Slog.w(TAG, "Activity " + r
721 + " being launched, but already in LRU list");
722 }
723
724 if (andResume) {
725 // As part of the process of launching, ActivityThread also performs
726 // a resume.
727 r.state = ActivityState.RESUMED;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700728 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
729 + " (starting new instance)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700730 r.stopped = false;
731 mResumedActivity = r;
732 r.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -0800733 if (mMainStack) {
734 mService.addRecentTaskLocked(r.task);
735 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700736 completeResumeLocked(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800737 checkReadyForSleepLocked();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700738 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Launch completed; removing icicle of " + r.icicle);
739 r.icicle = null;
740 r.haveState = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700741 } else {
742 // This activity is not starting in the resumed state... which
743 // should look like we asked it to pause+stop (but remain visible),
744 // and it has done so and reported back the current icicle and
745 // other state.
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700746 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
747 + " (starting in stopped state)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700748 r.state = ActivityState.STOPPED;
749 r.stopped = true;
750 }
751
752 // Launch the new version setup screen if needed. We do this -after-
753 // launching the initial activity (that is, home), so that it can have
754 // a chance to initialize itself while in the background, making the
755 // switch back to it faster and look better.
756 if (mMainStack) {
757 mService.startSetupActivityLocked();
758 }
759
760 return true;
761 }
762
763 private final void startSpecificActivityLocked(ActivityRecord r,
764 boolean andResume, boolean checkConfig) {
765 // Is this activity's application already running?
766 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
767 r.info.applicationInfo.uid);
768
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700769 if (r.launchTime == 0) {
770 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700771 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700772 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700773 }
774 } else if (mInitialStartTime == 0) {
775 mInitialStartTime = SystemClock.uptimeMillis();
776 }
777
778 if (app != null && app.thread != null) {
779 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700780 app.addPackage(r.info.packageName);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700781 realStartActivityLocked(r, app, andResume, checkConfig);
782 return;
783 } catch (RemoteException e) {
784 Slog.w(TAG, "Exception when starting activity "
785 + r.intent.getComponent().flattenToShortString(), e);
786 }
787
788 // If a dead object exception was thrown -- fall through to
789 // restart the application.
790 }
791
792 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800793 "activity", r.intent.getComponent(), false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700794 }
795
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800796 void stopIfSleepingLocked() {
797 if (mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700798 if (!mGoingToSleep.isHeld()) {
799 mGoingToSleep.acquire();
800 if (mLaunchingActivity.isHeld()) {
801 mLaunchingActivity.release();
802 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
803 }
804 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800805 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
806 Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
807 mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
808 checkReadyForSleepLocked();
809 }
810 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700811
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800812 void awakeFromSleepingLocked() {
813 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
814 mSleepTimeout = false;
815 if (mGoingToSleep.isHeld()) {
816 mGoingToSleep.release();
817 }
818 // Ensure activities are no longer sleeping.
819 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700820 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800821 r.setSleeping(false);
822 }
823 mGoingToSleepActivities.clear();
824 }
825
826 void activitySleptLocked(ActivityRecord r) {
827 mGoingToSleepActivities.remove(r);
828 checkReadyForSleepLocked();
829 }
830
831 void checkReadyForSleepLocked() {
832 if (!mService.isSleeping()) {
833 // Do not care.
834 return;
835 }
836
837 if (!mSleepTimeout) {
838 if (mResumedActivity != null) {
839 // Still have something resumed; can't sleep until it is paused.
840 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700841 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
842 startPausingLocked(false, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800843 return;
844 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800845 if (mPausingActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800846 // Still waiting for something to pause; can't sleep yet.
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800847 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800848 return;
849 }
850
851 if (mStoppingActivities.size() > 0) {
852 // Still need to tell some activities to stop; can't sleep yet.
853 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
854 + mStoppingActivities.size() + " activities");
Dianne Hackborn80a7ac12011-09-22 18:32:52 -0700855 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800856 return;
857 }
858
859 ensureActivitiesVisibleLocked(null, 0);
860
861 // Make sure any stopped but visible activities are now sleeping.
862 // This ensures that the activity's onStop() is called.
863 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700864 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800865 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
866 r.setSleeping(true);
867 }
868 }
869
870 if (mGoingToSleepActivities.size() > 0) {
871 // Still need to tell some activities to sleep; can't sleep yet.
872 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
873 + mGoingToSleepActivities.size() + " activities");
874 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700875 }
876 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800877
878 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
879
880 if (mGoingToSleep.isHeld()) {
881 mGoingToSleep.release();
882 }
883 if (mService.mShuttingDown) {
884 mService.notifyAll();
885 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700886 }
887
Dianne Hackbornd2835932010-12-13 16:28:46 -0800888 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -0800889 if (who.noDisplay) {
890 return null;
891 }
892
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800893 Resources res = mService.mContext.getResources();
894 int w = mThumbnailWidth;
895 int h = mThumbnailHeight;
896 if (w < 0) {
897 mThumbnailWidth = w =
898 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
899 mThumbnailHeight = h =
900 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
901 }
902
903 if (w > 0) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800904 return mService.mWindowManager.screenshotApplications(who.appToken, w, h);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800905 }
906 return null;
907 }
908
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700909 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800910 if (mPausingActivity != null) {
911 RuntimeException e = new RuntimeException();
912 Slog.e(TAG, "Trying to pause when pause is already pending for "
913 + mPausingActivity, e);
914 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700915 ActivityRecord prev = mResumedActivity;
916 if (prev == null) {
917 RuntimeException e = new RuntimeException();
918 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
919 resumeTopActivityLocked(null);
920 return;
921 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700922 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
923 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700924 mResumedActivity = null;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800925 mPausingActivity = prev;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700926 mLastPausedActivity = prev;
927 prev.state = ActivityState.PAUSING;
928 prev.task.touchActiveTime();
Dianne Hackbornf26fd992011-04-08 18:14:09 -0700929 prev.updateThumbnail(screenshotActivities(prev), null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700930
931 mService.updateCpuStats();
932
933 if (prev.app != null && prev.app.thread != null) {
934 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
935 try {
936 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
937 System.identityHashCode(prev),
938 prev.shortComponentName);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800939 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
940 userLeaving, prev.configChangeFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700941 if (mMainStack) {
942 mService.updateUsageStats(prev, false);
943 }
944 } catch (Exception e) {
945 // Ignore exception, if process died other code will cleanup.
946 Slog.w(TAG, "Exception thrown during pause", e);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800947 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700948 mLastPausedActivity = null;
949 }
950 } else {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800951 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700952 mLastPausedActivity = null;
953 }
954
955 // If we are not going to sleep, we want to ensure the device is
956 // awake until the next activity is started.
957 if (!mService.mSleeping && !mService.mShuttingDown) {
958 mLaunchingActivity.acquire();
959 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
960 // To be safe, don't allow the wake lock to be held for too long.
961 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
962 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
963 }
964 }
965
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800966
967 if (mPausingActivity != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700968 // Have the window manager pause its key dispatching until the new
969 // activity has started. If we're pausing the activity just because
970 // the screen is being turned off and the UI is sleeping, don't interrupt
971 // key dispatch; the same activity will pick it up again on wakeup.
972 if (!uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800973 prev.pauseKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700974 } else {
975 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
976 }
977
978 // Schedule a pause timeout in case the app doesn't respond.
979 // We don't give it much time because this directly impacts the
980 // responsiveness seen by the user.
981 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
982 msg.obj = prev;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700983 prev.pauseTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700984 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
985 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
986 } else {
987 // This activity failed to schedule the
988 // pause, so just treat it as being paused now.
989 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800990 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700991 }
992 }
993
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800994 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700995 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800996 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700997
998 ActivityRecord r = null;
999
1000 synchronized (mService) {
1001 int index = indexOfTokenLocked(token);
1002 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001003 r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001004 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001005 if (mPausingActivity == r) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001006 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
1007 + (timeout ? " (due to timeout)" : " (pause complete)"));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001008 r.state = ActivityState.PAUSED;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001009 completePauseLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001010 } else {
1011 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
1012 System.identityHashCode(r), r.shortComponentName,
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001013 mPausingActivity != null
1014 ? mPausingActivity.shortComponentName : "(none)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001015 }
1016 }
1017 }
1018 }
1019
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001020 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
1021 CharSequence description) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001022 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Saving icicle of " + r + ": " + icicle);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001023 if (icicle != null) {
1024 // If icicle is null, this is happening due to a timeout, so we
1025 // haven't really saved the state.
1026 r.icicle = icicle;
1027 r.haveState = true;
1028 r.updateThumbnail(thumbnail, description);
1029 }
1030 if (!r.stopped) {
1031 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
1032 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1033 r.stopped = true;
1034 r.state = ActivityState.STOPPED;
1035 if (!r.finishing) {
1036 if (r.configDestroy) {
1037 destroyActivityLocked(r, true, false, "stop-config");
1038 resumeTopActivityLocked(null);
1039 } else {
1040 // Now that this process has stopped, we may want to consider
1041 // it to be the previous app to try to keep around in case
1042 // the user wants to return to it.
1043 ProcessRecord fgApp = null;
1044 if (mResumedActivity != null) {
1045 fgApp = mResumedActivity.app;
1046 } else if (mPausingActivity != null) {
1047 fgApp = mPausingActivity.app;
1048 }
1049 if (r.app != null && fgApp != null && r.app != fgApp
1050 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
1051 && r.app != mService.mHomeProcess) {
1052 mService.mPreviousProcess = r.app;
1053 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
1054 }
Dianne Hackborn50685602011-12-01 12:23:37 -08001055 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001056 }
1057 }
1058 }
1059
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001060 private final void completePauseLocked() {
1061 ActivityRecord prev = mPausingActivity;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001062 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
1063
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001064 if (prev != null) {
1065 if (prev.finishing) {
1066 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
1067 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE);
1068 } else if (prev.app != null) {
1069 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
1070 if (prev.waitingVisible) {
1071 prev.waitingVisible = false;
1072 mWaitingVisibleActivities.remove(prev);
1073 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
1074 TAG, "Complete pause, no longer waiting: " + prev);
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001075 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001076 if (prev.configDestroy) {
1077 // The previous is being paused because the configuration
1078 // is changing, which means it is actually stopping...
1079 // To juggle the fact that we are also starting a new
1080 // instance right now, we need to first completely stop
1081 // the current instance before starting the new one.
1082 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
1083 destroyActivityLocked(prev, true, false, "pause-config");
1084 } else {
1085 mStoppingActivities.add(prev);
1086 if (mStoppingActivities.size() > 3) {
1087 // If we already have a few activities waiting to stop,
1088 // then give up on things going idle and start clearing
1089 // them out.
1090 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
1091 scheduleIdleLocked();
1092 } else {
1093 checkReadyForSleepLocked();
1094 }
1095 }
1096 } else {
1097 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
1098 prev = null;
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001099 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001100 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001101 }
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001102
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001103 if (!mService.isSleeping()) {
1104 resumeTopActivityLocked(prev);
1105 } else {
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001106 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001107 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001108
1109 if (prev != null) {
1110 prev.resumeKeyDispatchingLocked();
1111 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001112
1113 if (prev.app != null && prev.cpuTimeAtResume > 0
1114 && mService.mBatteryStatsService.isOnBattery()) {
1115 long diff = 0;
1116 synchronized (mService.mProcessStatsThread) {
1117 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
1118 - prev.cpuTimeAtResume;
1119 }
1120 if (diff > 0) {
1121 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
1122 synchronized (bsi) {
1123 BatteryStatsImpl.Uid.Proc ps =
1124 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
1125 prev.info.packageName);
1126 if (ps != null) {
1127 ps.addForegroundTimeLocked(diff);
1128 }
1129 }
1130 }
1131 }
1132 prev.cpuTimeAtResume = 0; // reset it
1133 }
1134
1135 /**
1136 * Once we know that we have asked an application to put an activity in
1137 * the resumed state (either by launching it or explicitly telling it),
1138 * this function updates the rest of our state to match that fact.
1139 */
1140 private final void completeResumeLocked(ActivityRecord next) {
1141 next.idle = false;
1142 next.results = null;
1143 next.newIntents = null;
1144
1145 // schedule an idle timeout in case the app doesn't do it for us.
1146 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1147 msg.obj = next;
1148 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
1149
1150 if (false) {
1151 // The activity was never told to pause, so just keep
1152 // things going as-is. To maintain our own state,
1153 // we need to emulate it coming back and saying it is
1154 // idle.
1155 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
1156 msg.obj = next;
1157 mHandler.sendMessage(msg);
1158 }
1159
1160 if (mMainStack) {
1161 mService.reportResumedActivityLocked(next);
1162 }
1163
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001164 next.clearThumbnail();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001165 if (mMainStack) {
1166 mService.setFocusedActivityLocked(next);
1167 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001168 next.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001169 ensureActivitiesVisibleLocked(null, 0);
1170 mService.mWindowManager.executeAppTransition();
1171 mNoAnimActivities.clear();
1172
1173 // Mark the point when the activity is resuming
1174 // TODO: To be more accurate, the mark should be before the onCreate,
1175 // not after the onResume. But for subsequent starts, onResume is fine.
1176 if (next.app != null) {
1177 synchronized (mService.mProcessStatsThread) {
1178 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1179 }
1180 } else {
1181 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1182 }
1183 }
1184
1185 /**
1186 * Make sure that all activities that need to be visible (that is, they
1187 * currently can be seen by the user) actually are.
1188 */
1189 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1190 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1191 if (DEBUG_VISBILITY) Slog.v(
1192 TAG, "ensureActivitiesVisible behind " + top
1193 + " configChanges=0x" + Integer.toHexString(configChanges));
1194
1195 // If the top activity is not fullscreen, then we need to
1196 // make sure any activities under it are now visible.
1197 final int count = mHistory.size();
1198 int i = count-1;
1199 while (mHistory.get(i) != top) {
1200 i--;
1201 }
1202 ActivityRecord r;
1203 boolean behindFullscreen = false;
1204 for (; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001205 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001206 if (DEBUG_VISBILITY) Slog.v(
1207 TAG, "Make visible? " + r + " finishing=" + r.finishing
1208 + " state=" + r.state);
1209 if (r.finishing) {
1210 continue;
1211 }
1212
1213 final boolean doThisProcess = onlyThisProcess == null
1214 || onlyThisProcess.equals(r.processName);
1215
1216 // First: if this is not the current activity being started, make
1217 // sure it matches the current configuration.
1218 if (r != starting && doThisProcess) {
1219 ensureActivityConfigurationLocked(r, 0);
1220 }
1221
1222 if (r.app == null || r.app.thread == null) {
1223 if (onlyThisProcess == null
1224 || onlyThisProcess.equals(r.processName)) {
1225 // This activity needs to be visible, but isn't even
1226 // running... get it started, but don't resume it
1227 // at this point.
1228 if (DEBUG_VISBILITY) Slog.v(
1229 TAG, "Start and freeze screen for " + r);
1230 if (r != starting) {
1231 r.startFreezingScreenLocked(r.app, configChanges);
1232 }
1233 if (!r.visible) {
1234 if (DEBUG_VISBILITY) Slog.v(
1235 TAG, "Starting and making visible: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001236 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001237 }
1238 if (r != starting) {
1239 startSpecificActivityLocked(r, false, false);
1240 }
1241 }
1242
1243 } else if (r.visible) {
1244 // If this activity is already visible, then there is nothing
1245 // else to do here.
1246 if (DEBUG_VISBILITY) Slog.v(
1247 TAG, "Skipping: already visible at " + r);
1248 r.stopFreezingScreenLocked(false);
1249
1250 } else if (onlyThisProcess == null) {
1251 // This activity is not currently visible, but is running.
1252 // Tell it to become visible.
1253 r.visible = true;
1254 if (r.state != ActivityState.RESUMED && r != starting) {
1255 // If this activity is paused, tell it
1256 // to now show its window.
1257 if (DEBUG_VISBILITY) Slog.v(
1258 TAG, "Making visible and scheduling visibility: " + r);
1259 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001260 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001261 r.sleeping = false;
Dianne Hackborn905577f2011-09-07 18:31:28 -07001262 r.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001263 r.app.thread.scheduleWindowVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001264 r.stopFreezingScreenLocked(false);
1265 } catch (Exception e) {
1266 // Just skip on any failure; we'll make it
1267 // visible when it next restarts.
1268 Slog.w(TAG, "Exception thrown making visibile: "
1269 + r.intent.getComponent(), e);
1270 }
1271 }
1272 }
1273
1274 // Aggregate current change flags.
1275 configChanges |= r.configChangeFlags;
1276
1277 if (r.fullscreen) {
1278 // At this point, nothing else needs to be shown
1279 if (DEBUG_VISBILITY) Slog.v(
1280 TAG, "Stopping: fullscreen at " + r);
1281 behindFullscreen = true;
1282 i--;
1283 break;
1284 }
1285 }
1286
1287 // Now for any activities that aren't visible to the user, make
1288 // sure they no longer are keeping the screen frozen.
1289 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001290 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001291 if (DEBUG_VISBILITY) Slog.v(
1292 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1293 + " state=" + r.state
1294 + " behindFullscreen=" + behindFullscreen);
1295 if (!r.finishing) {
1296 if (behindFullscreen) {
1297 if (r.visible) {
1298 if (DEBUG_VISBILITY) Slog.v(
1299 TAG, "Making invisible: " + r);
1300 r.visible = false;
1301 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001302 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001303 if ((r.state == ActivityState.STOPPING
1304 || r.state == ActivityState.STOPPED)
1305 && r.app != null && r.app.thread != null) {
1306 if (DEBUG_VISBILITY) Slog.v(
1307 TAG, "Scheduling invisibility: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001308 r.app.thread.scheduleWindowVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001309 }
1310 } catch (Exception e) {
1311 // Just skip on any failure; we'll make it
1312 // visible when it next restarts.
1313 Slog.w(TAG, "Exception thrown making hidden: "
1314 + r.intent.getComponent(), e);
1315 }
1316 } else {
1317 if (DEBUG_VISBILITY) Slog.v(
1318 TAG, "Already invisible: " + r);
1319 }
1320 } else if (r.fullscreen) {
1321 if (DEBUG_VISBILITY) Slog.v(
1322 TAG, "Now behindFullscreen: " + r);
1323 behindFullscreen = true;
1324 }
1325 }
1326 i--;
1327 }
1328 }
1329
1330 /**
1331 * Version of ensureActivitiesVisible that can easily be called anywhere.
1332 */
1333 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1334 int configChanges) {
1335 ActivityRecord r = topRunningActivityLocked(null);
1336 if (r != null) {
1337 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1338 }
1339 }
1340
1341 /**
1342 * Ensure that the top activity in the stack is resumed.
1343 *
1344 * @param prev The previously resumed activity, for when in the process
1345 * of pausing; can be null to call from elsewhere.
1346 *
1347 * @return Returns true if something is being resumed, or false if
1348 * nothing happened.
1349 */
1350 final boolean resumeTopActivityLocked(ActivityRecord prev) {
1351 // Find the first activity that is not finishing.
1352 ActivityRecord next = topRunningActivityLocked(null);
1353
1354 // Remember how we'll process this pause/resume situation, and ensure
1355 // that the state is reset however we wind up proceeding.
1356 final boolean userLeaving = mUserLeaving;
1357 mUserLeaving = false;
1358
1359 if (next == null) {
1360 // There are no more activities! Let's just start up the
1361 // Launcher...
1362 if (mMainStack) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001363 return mService.startHomeActivityLocked(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001364 }
1365 }
1366
1367 next.delayedResume = false;
1368
1369 // If the top activity is the resumed one, nothing to do.
1370 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1371 // Make sure we have executed any pending transitions, since there
1372 // should be nothing left to do at this point.
1373 mService.mWindowManager.executeAppTransition();
1374 mNoAnimActivities.clear();
1375 return false;
1376 }
1377
1378 // If we are sleeping, and there is no resumed activity, and the top
1379 // activity is paused, well that is the state we want.
1380 if ((mService.mSleeping || mService.mShuttingDown)
p13451dbad2872012-04-18 11:39:23 +09001381 && mLastPausedActivity == next
1382 && (next.state == ActivityState.PAUSED
1383 || next.state == ActivityState.STOPPED
1384 || next.state == ActivityState.STOPPING)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001385 // Make sure we have executed any pending transitions, since there
1386 // should be nothing left to do at this point.
1387 mService.mWindowManager.executeAppTransition();
1388 mNoAnimActivities.clear();
1389 return false;
1390 }
1391
1392 // The activity may be waiting for stop, but that is no longer
1393 // appropriate for it.
1394 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001395 mGoingToSleepActivities.remove(next);
1396 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001397 mWaitingVisibleActivities.remove(next);
1398
1399 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1400
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001401 // If we are currently pausing an activity, then don't do anything
1402 // until that is done.
1403 if (mPausingActivity != null) {
1404 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
1405 return false;
1406 }
1407
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001408 // Okay we are now going to start a switch, to 'next'. We may first
1409 // have to pause the current activity, but this is an important point
1410 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001411 // XXX "App Redirected" dialog is getting too many false positives
1412 // at this point, so turn off for now.
1413 if (false) {
1414 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1415 long now = SystemClock.uptimeMillis();
1416 final boolean inTime = mLastStartedActivity.startTime != 0
1417 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1418 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1419 final int nextUid = next.info.applicationInfo.uid;
1420 if (inTime && lastUid != nextUid
1421 && lastUid != next.launchedFromUid
1422 && mService.checkPermission(
1423 android.Manifest.permission.STOP_APP_SWITCHES,
1424 -1, next.launchedFromUid)
1425 != PackageManager.PERMISSION_GRANTED) {
1426 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1427 } else {
1428 next.startTime = now;
1429 mLastStartedActivity = next;
1430 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001431 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001432 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001433 mLastStartedActivity = next;
1434 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001435 }
1436
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001437 // We need to start pausing the current activity so the top one
1438 // can be resumed...
1439 if (mResumedActivity != null) {
1440 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
1441 startPausingLocked(userLeaving, false);
1442 return true;
1443 }
1444
1445 if (prev != null && prev != next) {
1446 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1447 prev.waitingVisible = true;
1448 mWaitingVisibleActivities.add(prev);
1449 if (DEBUG_SWITCH) Slog.v(
1450 TAG, "Resuming top, waiting visible to hide: " + prev);
1451 } else {
1452 // The next activity is already visible, so hide the previous
1453 // activity's windows right now so we can show the new one ASAP.
1454 // We only do this if the previous is finishing, which should mean
1455 // it is on top of the one being resumed so hiding it quickly
1456 // is good. Otherwise, we want to do the normal route of allowing
1457 // the resumed activity to be shown so we can decide if the
1458 // previous should actually be hidden depending on whether the
1459 // new one is found to be full-screen or not.
1460 if (prev.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001461 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001462 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1463 + prev + ", waitingVisible="
1464 + (prev != null ? prev.waitingVisible : null)
1465 + ", nowVisible=" + next.nowVisible);
1466 } else {
1467 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1468 + prev + ", waitingVisible="
1469 + (prev != null ? prev.waitingVisible : null)
1470 + ", nowVisible=" + next.nowVisible);
1471 }
1472 }
1473 }
1474
Dianne Hackborne7f97212011-02-24 14:40:20 -08001475 // Launching this app's activity, make sure the app is no longer
1476 // considered stopped.
1477 try {
1478 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001479 next.packageName, false, next.userId); /* TODO: Verify if correct userid */
Dianne Hackborne7f97212011-02-24 14:40:20 -08001480 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001481 } catch (IllegalArgumentException e) {
1482 Slog.w(TAG, "Failed trying to unstop package "
1483 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001484 }
1485
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001486 // We are starting up the next activity, so tell the window manager
1487 // that the previous one will be hidden soon. This way it can know
1488 // to ignore it when computing the desired screen orientation.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001489 boolean noAnim = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001490 if (prev != null) {
1491 if (prev.finishing) {
1492 if (DEBUG_TRANSITION) Slog.v(TAG,
1493 "Prepare close transition: prev=" + prev);
1494 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001495 mService.mWindowManager.prepareAppTransition(
1496 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001497 } else {
1498 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1499 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001500 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001501 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001502 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1503 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001504 } else {
1505 if (DEBUG_TRANSITION) Slog.v(TAG,
1506 "Prepare open transition: prev=" + prev);
1507 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001508 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001509 mService.mWindowManager.prepareAppTransition(
1510 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001511 } else {
1512 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1513 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001514 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001515 }
1516 }
1517 if (false) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001518 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1519 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001520 }
1521 } else if (mHistory.size() > 1) {
1522 if (DEBUG_TRANSITION) Slog.v(TAG,
1523 "Prepare open transition: no previous");
1524 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001525 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001526 mService.mWindowManager.prepareAppTransition(
1527 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001528 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001529 mService.mWindowManager.prepareAppTransition(
1530 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001531 }
1532 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001533 if (!noAnim) {
1534 next.applyOptionsLocked();
1535 } else {
1536 next.clearOptionsLocked();
1537 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001538
1539 if (next.app != null && next.app.thread != null) {
1540 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1541
1542 // This activity is now becoming visible.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001543 mService.mWindowManager.setAppVisibility(next.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001544
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001545 // schedule launch ticks to collect information about slow apps.
1546 next.startLaunchTickingLocked();
1547
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001548 ActivityRecord lastResumedActivity = mResumedActivity;
1549 ActivityState lastState = next.state;
1550
1551 mService.updateCpuStats();
1552
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001553 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001554 next.state = ActivityState.RESUMED;
1555 mResumedActivity = next;
1556 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001557 if (mMainStack) {
1558 mService.addRecentTaskLocked(next.task);
1559 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001560 mService.updateLruProcessLocked(next.app, true, true);
1561 updateLRUListLocked(next);
1562
1563 // Have the window manager re-evaluate the orientation of
1564 // the screen based on the new activity order.
1565 boolean updated = false;
1566 if (mMainStack) {
1567 synchronized (mService) {
1568 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1569 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001570 next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001571 if (config != null) {
1572 next.frozenBeforeDestroy = true;
1573 }
Dianne Hackborn813075a62011-11-14 17:45:19 -08001574 updated = mService.updateConfigurationLocked(config, next, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001575 }
1576 }
1577 if (!updated) {
1578 // The configuration update wasn't able to keep the existing
1579 // instance of the activity, and instead started a new one.
1580 // We should be all done, but let's just make sure our activity
1581 // is still at the top and schedule another run if something
1582 // weird happened.
1583 ActivityRecord nextNext = topRunningActivityLocked(null);
1584 if (DEBUG_SWITCH) Slog.i(TAG,
1585 "Activity config changed during resume: " + next
1586 + ", new next: " + nextNext);
1587 if (nextNext != next) {
1588 // Do over!
1589 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1590 }
1591 if (mMainStack) {
1592 mService.setFocusedActivityLocked(next);
1593 }
1594 ensureActivitiesVisibleLocked(null, 0);
1595 mService.mWindowManager.executeAppTransition();
1596 mNoAnimActivities.clear();
1597 return true;
1598 }
1599
1600 try {
1601 // Deliver all pending results.
1602 ArrayList a = next.results;
1603 if (a != null) {
1604 final int N = a.size();
1605 if (!next.finishing && N > 0) {
1606 if (DEBUG_RESULTS) Slog.v(
1607 TAG, "Delivering results to " + next
1608 + ": " + a);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001609 next.app.thread.scheduleSendResult(next.appToken, a);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001610 }
1611 }
1612
1613 if (next.newIntents != null) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001614 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001615 }
1616
1617 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
1618 System.identityHashCode(next),
1619 next.task.taskId, next.shortComponentName);
1620
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001621 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001622 showAskCompatModeDialogLocked(next);
Dianne Hackborn905577f2011-09-07 18:31:28 -07001623 next.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001624 next.app.thread.scheduleResumeActivity(next.appToken,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001625 mService.isNextTransitionForward());
1626
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001627 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001628
1629 } catch (Exception e) {
1630 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001631 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1632 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001633 next.state = lastState;
1634 mResumedActivity = lastResumedActivity;
1635 Slog.i(TAG, "Restarting because process died: " + next);
1636 if (!next.hasBeenLaunched) {
1637 next.hasBeenLaunched = true;
1638 } else {
1639 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1640 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001641 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001642 mService.compatibilityInfoForPackageLocked(
1643 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001644 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001645 next.labelRes, next.icon, next.windowFlags,
1646 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001647 }
1648 }
1649 startSpecificActivityLocked(next, true, false);
1650 return true;
1651 }
1652
1653 // From this point on, if something goes wrong there is no way
1654 // to recover the activity.
1655 try {
1656 next.visible = true;
1657 completeResumeLocked(next);
1658 } catch (Exception e) {
1659 // If any exception gets thrown, toss away this
1660 // activity and try the next one.
1661 Slog.w(TAG, "Exception thrown during resume of " + next, e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001662 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001663 "resume-exception");
1664 return true;
1665 }
1666
1667 // Didn't need to use the icicle, and it is now out of date.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001668 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Resumed activity; didn't need icicle of: " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001669 next.icicle = null;
1670 next.haveState = false;
1671 next.stopped = false;
1672
1673 } else {
1674 // Whoops, need to restart this activity!
1675 if (!next.hasBeenLaunched) {
1676 next.hasBeenLaunched = true;
1677 } else {
1678 if (SHOW_APP_STARTING_PREVIEW) {
1679 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001680 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001681 mService.compatibilityInfoForPackageLocked(
1682 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001683 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001684 next.labelRes, next.icon, next.windowFlags,
1685 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001686 }
1687 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1688 }
1689 startSpecificActivityLocked(next, true, true);
1690 }
1691
1692 return true;
1693 }
1694
1695 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001696 boolean doResume, boolean keepCurTransition, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001697 final int NH = mHistory.size();
1698
1699 int addPos = -1;
1700
1701 if (!newTask) {
1702 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001703 boolean startIt = true;
1704 for (int i = NH-1; i >= 0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001705 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001706 if (p.finishing) {
1707 continue;
1708 }
1709 if (p.task == r.task) {
1710 // Here it is! Now, if this is not yet visible to the
1711 // user, then just add it without starting; it will
1712 // get started when the user navigates back to it.
1713 addPos = i+1;
1714 if (!startIt) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001715 if (DEBUG_ADD_REMOVE) {
1716 RuntimeException here = new RuntimeException("here");
1717 here.fillInStackTrace();
1718 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos,
1719 here);
1720 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001721 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001722 r.putInHistory();
Dianne Hackbornbe707852011-11-11 14:32:10 -08001723 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001724 r.info.screenOrientation, r.fullscreen);
1725 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001726 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001727 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001728 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001729 return;
1730 }
1731 break;
1732 }
1733 if (p.fullscreen) {
1734 startIt = false;
1735 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001736 }
1737 }
1738
1739 // Place a new activity at top of stack, so it is next to interact
1740 // with the user.
1741 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001742 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001743 }
1744
1745 // If we are not placing the new activity frontmost, we do not want
1746 // to deliver the onUserLeaving callback to the actual frontmost
1747 // activity
1748 if (addPos < NH) {
1749 mUserLeaving = false;
1750 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1751 }
1752
1753 // Slot the activity into the history stack and proceed
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001754 if (DEBUG_ADD_REMOVE) {
1755 RuntimeException here = new RuntimeException("here");
1756 here.fillInStackTrace();
1757 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos, here);
1758 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001759 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001760 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001761 r.frontOfTask = newTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001762 if (NH > 0) {
1763 // We want to show the starting preview window if we are
1764 // switching to a new task, or the next activity's process is
1765 // not currently running.
1766 boolean showStartingIcon = newTask;
1767 ProcessRecord proc = r.app;
1768 if (proc == null) {
1769 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1770 }
1771 if (proc == null || proc.thread == null) {
1772 showStartingIcon = true;
1773 }
1774 if (DEBUG_TRANSITION) Slog.v(TAG,
1775 "Prepare open transition: starting " + r);
1776 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001777 mService.mWindowManager.prepareAppTransition(
1778 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001779 mNoAnimActivities.add(r);
1780 } else if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
1781 mService.mWindowManager.prepareAppTransition(
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001782 WindowManagerPolicy.TRANSIT_TASK_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001783 mNoAnimActivities.remove(r);
1784 } else {
1785 mService.mWindowManager.prepareAppTransition(newTask
1786 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001787 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001788 mNoAnimActivities.remove(r);
1789 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001790 r.updateOptionsLocked(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001791 mService.mWindowManager.addAppToken(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001792 addPos, r.appToken, r.task.taskId, r.info.screenOrientation, r.fullscreen);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001793 boolean doShow = true;
1794 if (newTask) {
1795 // Even though this activity is starting fresh, we still need
1796 // to reset it to make sure we apply affinities to move any
1797 // existing activities from other tasks in to it.
1798 // If the caller has requested that the target task be
1799 // reset, then do so.
1800 if ((r.intent.getFlags()
1801 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1802 resetTaskIfNeededLocked(r, r);
1803 doShow = topRunningNonDelayedActivityLocked(null) == r;
1804 }
1805 }
1806 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1807 // Figure out if we are transitioning from another activity that is
1808 // "has the same starting icon" as the next one. This allows the
1809 // window manager to keep the previous window it had previously
1810 // created, if it still had one.
1811 ActivityRecord prev = mResumedActivity;
1812 if (prev != null) {
1813 // We don't want to reuse the previous starting preview if:
1814 // (1) The current activity is in a different task.
1815 if (prev.task != r.task) prev = null;
1816 // (2) The current activity is already displayed.
1817 else if (prev.nowVisible) prev = null;
1818 }
1819 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001820 r.appToken, r.packageName, r.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001821 mService.compatibilityInfoForPackageLocked(
1822 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001823 r.labelRes, r.icon, r.windowFlags,
1824 prev != null ? prev.appToken : null, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001825 }
1826 } else {
1827 // If this is the first activity, don't do any fancy animations,
1828 // because there is nothing for it to animate on top of.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001829 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001830 r.info.screenOrientation, r.fullscreen);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001831 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001832 }
1833 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001834 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001835 }
1836
1837 if (doResume) {
1838 resumeTopActivityLocked(null);
1839 }
1840 }
1841
Dianne Hackbornbe707852011-11-11 14:32:10 -08001842 final void validateAppTokensLocked() {
1843 mValidateAppTokens.clear();
1844 mValidateAppTokens.ensureCapacity(mHistory.size());
1845 for (int i=0; i<mHistory.size(); i++) {
1846 mValidateAppTokens.add(mHistory.get(i).appToken);
1847 }
1848 mService.mWindowManager.validateAppTokens(mValidateAppTokens);
1849 }
1850
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001851 /**
1852 * Perform a reset of the given task, if needed as part of launching it.
1853 * Returns the new HistoryRecord at the top of the task.
1854 */
1855 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1856 ActivityRecord newActivity) {
1857 boolean forceReset = (newActivity.info.flags
1858 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001859 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1860 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001861 if ((newActivity.info.flags
1862 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1863 forceReset = true;
1864 }
1865 }
1866
1867 final TaskRecord task = taskTop.task;
1868
1869 // We are going to move through the history list so that we can look
1870 // at each activity 'target' with 'below' either the interesting
1871 // activity immediately below it in the stack or null.
1872 ActivityRecord target = null;
1873 int targetI = 0;
1874 int taskTopI = -1;
1875 int replyChainEnd = -1;
1876 int lastReparentPos = -1;
1877 for (int i=mHistory.size()-1; i>=-1; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001878 ActivityRecord below = i >= 0 ? mHistory.get(i) : null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001879
1880 if (below != null && below.finishing) {
1881 continue;
1882 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001883 // Don't check any lower in the stack if we're crossing a user boundary.
1884 if (below != null && below.userId != taskTop.userId) {
1885 break;
1886 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001887 if (target == null) {
1888 target = below;
1889 targetI = i;
1890 // If we were in the middle of a reply chain before this
1891 // task, it doesn't appear like the root of the chain wants
1892 // anything interesting, so drop it.
1893 replyChainEnd = -1;
1894 continue;
1895 }
1896
1897 final int flags = target.info.flags;
1898
1899 final boolean finishOnTaskLaunch =
1900 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1901 final boolean allowTaskReparenting =
1902 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1903
1904 if (target.task == task) {
1905 // We are inside of the task being reset... we'll either
1906 // finish this activity, push it out for another task,
1907 // or leave it as-is. We only do this
1908 // for activities that are not the root of the task (since
1909 // if we finish the root, we may no longer have the task!).
1910 if (taskTopI < 0) {
1911 taskTopI = targetI;
1912 }
1913 if (below != null && below.task == task) {
1914 final boolean clearWhenTaskReset =
1915 (target.intent.getFlags()
1916 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
1917 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
1918 // If this activity is sending a reply to a previous
1919 // activity, we can't do anything with it now until
1920 // we reach the start of the reply chain.
1921 // XXX note that we are assuming the result is always
1922 // to the previous activity, which is almost always
1923 // the case but we really shouldn't count on.
1924 if (replyChainEnd < 0) {
1925 replyChainEnd = targetI;
1926 }
1927 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
1928 && target.taskAffinity != null
1929 && !target.taskAffinity.equals(task.affinity)) {
1930 // If this activity has an affinity for another
1931 // task, then we need to move it out of here. We will
1932 // move it as far out of the way as possible, to the
1933 // bottom of the activity stack. This also keeps it
1934 // correctly ordered with any activities we previously
1935 // moved.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001936 ActivityRecord p = mHistory.get(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001937 if (target.taskAffinity != null
1938 && target.taskAffinity.equals(p.task.affinity)) {
1939 // If the activity currently at the bottom has the
1940 // same task affinity as the one we are moving,
1941 // then merge it into the same task.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001942 target.setTask(p.task, p.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001943 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1944 + " out to bottom task " + p.task);
1945 } else {
1946 mService.mCurTask++;
1947 if (mService.mCurTask <= 0) {
1948 mService.mCurTask = 1;
1949 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001950 target.setTask(new TaskRecord(mService.mCurTask, target.info, null),
1951 null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001952 target.task.affinityIntent = target.intent;
1953 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1954 + " out to new task " + target.task);
1955 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001956 mService.mWindowManager.setAppGroupId(target.appToken, task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001957 if (replyChainEnd < 0) {
1958 replyChainEnd = targetI;
1959 }
1960 int dstPos = 0;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001961 ThumbnailHolder curThumbHolder = target.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001962 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001963 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001964 if (p.finishing) {
1965 continue;
1966 }
1967 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
1968 + " out to target's task " + target.task);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001969 p.setTask(target.task, curThumbHolder, false);
1970 curThumbHolder = p.thumbHolder;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001971 if (DEBUG_ADD_REMOVE) {
1972 RuntimeException here = new RuntimeException("here");
1973 here.fillInStackTrace();
1974 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
1975 + dstPos, here);
1976 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001977 mHistory.remove(srcPos);
1978 mHistory.add(dstPos, p);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001979 mService.mWindowManager.moveAppToken(dstPos, p.appToken);
1980 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001981 dstPos++;
1982 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001983 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001984 }
1985 i++;
1986 }
1987 if (taskTop == p) {
1988 taskTop = below;
1989 }
1990 if (taskTopI == replyChainEnd) {
1991 taskTopI = -1;
1992 }
1993 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001994 } else if (forceReset || finishOnTaskLaunch
1995 || clearWhenTaskReset) {
1996 // If the activity should just be removed -- either
1997 // because it asks for it, or the task should be
1998 // cleared -- then finish it and anything that is
1999 // part of its reply chain.
2000 if (clearWhenTaskReset) {
2001 // In this case, we want to finish this activity
2002 // and everything above it, so be sneaky and pretend
2003 // like these are all in the reply chain.
2004 replyChainEnd = targetI+1;
2005 while (replyChainEnd < mHistory.size() &&
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002006 (mHistory.get(
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002007 replyChainEnd)).task == task) {
2008 replyChainEnd++;
2009 }
2010 replyChainEnd--;
2011 } else if (replyChainEnd < 0) {
2012 replyChainEnd = targetI;
2013 }
2014 ActivityRecord p = null;
2015 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002016 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002017 if (p.finishing) {
2018 continue;
2019 }
2020 if (finishActivityLocked(p, srcPos,
2021 Activity.RESULT_CANCELED, null, "reset")) {
2022 replyChainEnd--;
2023 srcPos--;
2024 }
2025 }
2026 if (taskTop == p) {
2027 taskTop = below;
2028 }
2029 if (taskTopI == replyChainEnd) {
2030 taskTopI = -1;
2031 }
2032 replyChainEnd = -1;
2033 } else {
2034 // If we were in the middle of a chain, well the
2035 // activity that started it all doesn't want anything
2036 // special, so leave it all as-is.
2037 replyChainEnd = -1;
2038 }
2039 } else {
2040 // Reached the bottom of the task -- any reply chain
2041 // should be left as-is.
2042 replyChainEnd = -1;
2043 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002044
2045 } else if (target.resultTo != null && (below == null
2046 || below.task == target.task)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002047 // If this activity is sending a reply to a previous
2048 // activity, we can't do anything with it now until
2049 // we reach the start of the reply chain.
2050 // XXX note that we are assuming the result is always
2051 // to the previous activity, which is almost always
2052 // the case but we really shouldn't count on.
2053 if (replyChainEnd < 0) {
2054 replyChainEnd = targetI;
2055 }
2056
2057 } else if (taskTopI >= 0 && allowTaskReparenting
2058 && task.affinity != null
2059 && task.affinity.equals(target.taskAffinity)) {
2060 // We are inside of another task... if this activity has
2061 // an affinity for our task, then either remove it if we are
2062 // clearing or move it over to our task. Note that
2063 // we currently punt on the case where we are resetting a
2064 // task that is not at the top but who has activities above
2065 // with an affinity to it... this is really not a normal
2066 // case, and we will need to later pull that task to the front
2067 // and usually at that point we will do the reset and pick
2068 // up those remaining activities. (This only happens if
2069 // someone starts an activity in a new task from an activity
2070 // in a task that is not currently on top.)
2071 if (forceReset || finishOnTaskLaunch) {
2072 if (replyChainEnd < 0) {
2073 replyChainEnd = targetI;
2074 }
2075 ActivityRecord p = null;
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002076 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index "
2077 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002078 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002079 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002080 if (p.finishing) {
2081 continue;
2082 }
2083 if (finishActivityLocked(p, srcPos,
2084 Activity.RESULT_CANCELED, null, "reset")) {
2085 taskTopI--;
2086 lastReparentPos--;
2087 replyChainEnd--;
2088 srcPos--;
2089 }
2090 }
2091 replyChainEnd = -1;
2092 } else {
2093 if (replyChainEnd < 0) {
2094 replyChainEnd = targetI;
2095 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002096 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting task at index "
2097 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002098 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002099 ActivityRecord p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002100 if (p.finishing) {
2101 continue;
2102 }
2103 if (lastReparentPos < 0) {
2104 lastReparentPos = taskTopI;
2105 taskTop = p;
2106 } else {
2107 lastReparentPos--;
2108 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002109 if (DEBUG_ADD_REMOVE) {
2110 RuntimeException here = new RuntimeException("here");
2111 here.fillInStackTrace();
2112 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2113 + lastReparentPos, here);
2114 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002115 mHistory.remove(srcPos);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002116 p.setTask(task, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002117 mHistory.add(lastReparentPos, p);
2118 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002119 + " from " + srcPos + " to " + lastReparentPos
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002120 + " in to resetting task " + task);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002121 mService.mWindowManager.moveAppToken(lastReparentPos, p.appToken);
2122 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002123 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002124 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002125 }
2126 }
2127 replyChainEnd = -1;
2128
2129 // Now we've moved it in to place... but what if this is
2130 // a singleTop activity and we have put it on top of another
2131 // instance of the same activity? Then we drop the instance
2132 // below so it remains singleTop.
2133 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2134 for (int j=lastReparentPos-1; j>=0; j--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002135 ActivityRecord p = mHistory.get(j);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002136 if (p.finishing) {
2137 continue;
2138 }
2139 if (p.intent.getComponent().equals(target.intent.getComponent())) {
2140 if (finishActivityLocked(p, j,
2141 Activity.RESULT_CANCELED, null, "replace")) {
2142 taskTopI--;
2143 lastReparentPos--;
2144 }
2145 }
2146 }
2147 }
2148 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002149
2150 } else if (below != null && below.task != target.task) {
2151 // We hit the botton of a task; the reply chain can't
2152 // pass through it.
2153 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002154 }
2155
2156 target = below;
2157 targetI = i;
2158 }
2159
2160 return taskTop;
2161 }
2162
2163 /**
2164 * Perform clear operation as requested by
2165 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2166 * stack to the given task, then look for
2167 * an instance of that activity in the stack and, if found, finish all
2168 * activities on top of it and return the instance.
2169 *
2170 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002171 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002172 * or null if none was found.
2173 */
2174 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002175 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002176 int i = mHistory.size();
2177
2178 // First find the requested task.
2179 while (i > 0) {
2180 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002181 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002182 if (r.task.taskId == taskId) {
2183 i++;
2184 break;
2185 }
2186 }
2187
2188 // Now clear it.
2189 while (i > 0) {
2190 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002191 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002192 if (r.finishing) {
2193 continue;
2194 }
2195 if (r.task.taskId != taskId) {
2196 return null;
2197 }
2198 if (r.realActivity.equals(newR.realActivity)) {
2199 // Here it is! Now finish everything in front...
2200 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002201 while (i < (mHistory.size()-1)) {
2202 i++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002203 r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002204 if (r.task.taskId != taskId) {
2205 break;
2206 }
2207 if (r.finishing) {
2208 continue;
2209 }
2210 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2211 null, "clear")) {
2212 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002213 }
2214 }
2215
2216 // Finally, if this is a normal launch mode (that is, not
2217 // expecting onNewIntent()), then we will finish the current
2218 // instance of the activity so a new fresh one can be started.
2219 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2220 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
2221 if (!ret.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002222 int index = indexOfTokenLocked(ret.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002223 if (index >= 0) {
2224 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
2225 null, "clear");
2226 }
2227 return null;
2228 }
2229 }
2230
2231 return ret;
2232 }
2233 }
2234
2235 return null;
2236 }
2237
2238 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002239 * Completely remove all activities associated with an existing
2240 * task starting at a specified index.
2241 */
2242 private final void performClearTaskAtIndexLocked(int taskId, int i) {
Dianne Hackborneabd3282011-10-13 16:26:49 -07002243 while (i < mHistory.size()) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002244 ActivityRecord r = mHistory.get(i);
2245 if (r.task.taskId != taskId) {
2246 // Whoops hit the end.
2247 return;
2248 }
2249 if (r.finishing) {
2250 i++;
2251 continue;
2252 }
2253 if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2254 null, "clear")) {
2255 i++;
2256 }
2257 }
2258 }
2259
2260 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002261 * Completely remove all activities associated with an existing task.
2262 */
2263 private final void performClearTaskLocked(int taskId) {
2264 int i = mHistory.size();
2265
2266 // First find the requested task.
2267 while (i > 0) {
2268 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002269 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002270 if (r.task.taskId == taskId) {
2271 i++;
2272 break;
2273 }
2274 }
2275
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002276 // Now find the start and clear it.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002277 while (i > 0) {
2278 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002279 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002280 if (r.finishing) {
2281 continue;
2282 }
2283 if (r.task.taskId != taskId) {
2284 // We hit the bottom. Now finish it all...
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002285 performClearTaskAtIndexLocked(taskId, i+1);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002286 return;
2287 }
2288 }
2289 }
2290
2291 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002292 * Find the activity in the history stack within the given task. Returns
2293 * the index within the history at which it's found, or < 0 if not found.
2294 */
2295 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2296 int i = mHistory.size();
2297 while (i > 0) {
2298 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002299 ActivityRecord candidate = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002300 if (candidate.task.taskId != task) {
2301 break;
2302 }
2303 if (candidate.realActivity.equals(r.realActivity)) {
2304 return i;
2305 }
2306 }
2307
2308 return -1;
2309 }
2310
2311 /**
2312 * Reorder the history stack so that the activity at the given index is
2313 * brought to the front.
2314 */
2315 private final ActivityRecord moveActivityToFrontLocked(int where) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002316 ActivityRecord newTop = mHistory.remove(where);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002317 int top = mHistory.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002318 ActivityRecord oldTop = mHistory.get(top-1);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002319 if (DEBUG_ADD_REMOVE) {
2320 RuntimeException here = new RuntimeException("here");
2321 here.fillInStackTrace();
2322 Slog.i(TAG, "Removing and adding activity " + newTop + " to stack at "
2323 + top, here);
2324 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002325 mHistory.add(top, newTop);
2326 oldTop.frontOfTask = false;
2327 newTop.frontOfTask = true;
2328 return newTop;
2329 }
2330
2331 final int startActivityLocked(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002332 Intent intent, String resolvedType, ActivityInfo aInfo, IBinder resultTo,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002333 String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002334 int callingPid, int callingUid, int startFlags, Bundle options,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002335 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002336
Dianne Hackborna4972e92012-03-14 10:38:05 -07002337 int err = ActivityManager.START_SUCCESS;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002338
2339 ProcessRecord callerApp = null;
2340 if (caller != null) {
2341 callerApp = mService.getRecordForAppLocked(caller);
2342 if (callerApp != null) {
2343 callingPid = callerApp.pid;
2344 callingUid = callerApp.info.uid;
2345 } else {
2346 Slog.w(TAG, "Unable to find app for caller " + caller
2347 + " (pid=" + callingPid + ") when starting: "
2348 + intent.toString());
Dianne Hackborna4972e92012-03-14 10:38:05 -07002349 err = ActivityManager.START_PERMISSION_DENIED;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002350 }
2351 }
2352
Dianne Hackborna4972e92012-03-14 10:38:05 -07002353 if (err == ActivityManager.START_SUCCESS) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07002354 final int userId = aInfo != null ? UserId.getUserId(aInfo.applicationInfo.uid) : 0;
Dianne Hackborn21c241e2012-03-08 13:57:23 -08002355 Slog.i(TAG, "START {" + intent.toShortString(true, true, true, false)
Amith Yamasania4a54e22012-04-16 15:44:19 -07002356 + " u=" + userId + "} from pid " + (callerApp != null ? callerApp.pid : callingPid));
Dianne Hackbornefb58102010-10-14 16:47:34 -07002357 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002358
2359 ActivityRecord sourceRecord = null;
2360 ActivityRecord resultRecord = null;
2361 if (resultTo != null) {
2362 int index = indexOfTokenLocked(resultTo);
2363 if (DEBUG_RESULTS) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002364 TAG, "Will send result to " + resultTo + " (index " + index + ")");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002365 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002366 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002367 if (requestCode >= 0 && !sourceRecord.finishing) {
2368 resultRecord = sourceRecord;
2369 }
2370 }
2371 }
2372
2373 int launchFlags = intent.getFlags();
2374
2375 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2376 && sourceRecord != null) {
2377 // Transfer the result target from the source activity to the new
2378 // one being started, including any failures.
2379 if (requestCode >= 0) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002380 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002381 return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002382 }
2383 resultRecord = sourceRecord.resultTo;
2384 resultWho = sourceRecord.resultWho;
2385 requestCode = sourceRecord.requestCode;
2386 sourceRecord.resultTo = null;
2387 if (resultRecord != null) {
2388 resultRecord.removeResultsLocked(
2389 sourceRecord, resultWho, requestCode);
2390 }
2391 }
2392
Dianne Hackborna4972e92012-03-14 10:38:05 -07002393 if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002394 // We couldn't find a class that can handle the given Intent.
2395 // That's the end of that!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002396 err = ActivityManager.START_INTENT_NOT_RESOLVED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002397 }
2398
Dianne Hackborna4972e92012-03-14 10:38:05 -07002399 if (err == ActivityManager.START_SUCCESS && aInfo == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002400 // We couldn't find the specific class specified in the Intent.
2401 // Also the end of the line.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002402 err = ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002403 }
2404
Dianne Hackborna4972e92012-03-14 10:38:05 -07002405 if (err != ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002406 if (resultRecord != null) {
2407 sendActivityResultLocked(-1,
2408 resultRecord, resultWho, requestCode,
2409 Activity.RESULT_CANCELED, null);
2410 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002411 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002412 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002413 return err;
2414 }
2415
Jeff Sharkey35be7562012-04-18 19:16:15 -07002416 final int startAnyPerm = mService.checkPermission(
2417 START_ANY_ACTIVITY, callingPid, callingUid);
2418 final int componentPerm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002419 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Jeff Sharkey35be7562012-04-18 19:16:15 -07002420 if (startAnyPerm != PERMISSION_GRANTED && componentPerm != PERMISSION_GRANTED) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002421 if (resultRecord != null) {
2422 sendActivityResultLocked(-1,
2423 resultRecord, resultWho, requestCode,
2424 Activity.RESULT_CANCELED, null);
2425 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002426 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002427 String msg;
2428 if (!aInfo.exported) {
2429 msg = "Permission Denial: starting " + intent.toString()
2430 + " from " + callerApp + " (pid=" + callingPid
2431 + ", uid=" + callingUid + ")"
2432 + " not exported from uid " + aInfo.applicationInfo.uid;
2433 } else {
2434 msg = "Permission Denial: starting " + intent.toString()
2435 + " from " + callerApp + " (pid=" + callingPid
2436 + ", uid=" + callingUid + ")"
2437 + " requires " + aInfo.permission;
2438 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002439 Slog.w(TAG, msg);
2440 throw new SecurityException(msg);
2441 }
2442
2443 if (mMainStack) {
2444 if (mService.mController != null) {
2445 boolean abort = false;
2446 try {
2447 // The Intent we give to the watcher has the extra data
2448 // stripped off, since it can contain private information.
2449 Intent watchIntent = intent.cloneFilter();
2450 abort = !mService.mController.activityStarting(watchIntent,
2451 aInfo.applicationInfo.packageName);
2452 } catch (RemoteException e) {
2453 mService.mController = null;
2454 }
2455
2456 if (abort) {
2457 if (resultRecord != null) {
2458 sendActivityResultLocked(-1,
2459 resultRecord, resultWho, requestCode,
2460 Activity.RESULT_CANCELED, null);
2461 }
2462 // We pretend to the caller that it was really started, but
2463 // they will just get a cancel result.
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002464 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002465 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002466 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002467 }
2468 }
2469 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002470
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002471 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2472 intent, resolvedType, aInfo, mService.mConfiguration,
2473 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002474 if (outActivity != null) {
2475 outActivity[0] = r;
2476 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002477
2478 if (mMainStack) {
2479 if (mResumedActivity == null
2480 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2481 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2482 PendingActivityLaunch pal = new PendingActivityLaunch();
2483 pal.r = r;
2484 pal.sourceRecord = sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002485 pal.startFlags = startFlags;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002486 mService.mPendingActivityLaunches.add(pal);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002487 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002488 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002489 return ActivityManager.START_SWITCHES_CANCELED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002490 }
2491 }
2492
2493 if (mService.mDidAppSwitch) {
2494 // This is the second allowed switch since we stopped switches,
2495 // so now just generally allow switches. Use case: user presses
2496 // home (switches disabled, switch to home, mDidAppSwitch now true);
2497 // user taps a home icon (coming from home so allowed, we hit here
2498 // and now allow anyone to switch again).
2499 mService.mAppSwitchesAllowedTime = 0;
2500 } else {
2501 mService.mDidAppSwitch = true;
2502 }
2503
2504 mService.doPendingActivityLaunchesLocked(false);
2505 }
2506
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002507 err = startActivityUncheckedLocked(r, sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002508 startFlags, true, options);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002509 if (mDismissKeyguardOnNextActivity && mPausingActivity == null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002510 // Someone asked to have the keyguard dismissed on the next
2511 // activity start, but we are not actually doing an activity
2512 // switch... just dismiss the keyguard now, because we
2513 // probably want to see whatever is behind it.
2514 mDismissKeyguardOnNextActivity = false;
2515 mService.mWindowManager.dismissKeyguard();
2516 }
2517 return err;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002518 }
2519
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002520 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2521 if ((launchFlags &
2522 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2523 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2524 // Caller wants to appear on home activity, so before starting
2525 // their own activity we will bring home to the front.
2526 moveHomeToFrontLocked();
2527 }
2528 }
2529
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002530 final int startActivityUncheckedLocked(ActivityRecord r,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002531 ActivityRecord sourceRecord, int startFlags, boolean doResume,
2532 Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002533 final Intent intent = r.intent;
2534 final int callingUid = r.launchedFromUid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002535 final int userId = r.userId;
2536
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002537 int launchFlags = intent.getFlags();
2538
2539 // We'll invoke onUserLeaving before onPause only if the launching
2540 // activity did not explicitly state that this is an automated launch.
2541 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2542 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2543 "startActivity() => mUserLeaving=" + mUserLeaving);
2544
2545 // If the caller has asked not to resume at this point, we make note
2546 // of this in the record so that we can skip it when trying to find
2547 // the top running activity.
2548 if (!doResume) {
2549 r.delayedResume = true;
2550 }
2551
2552 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2553 != 0 ? r : null;
2554
2555 // If the onlyIfNeeded flag is set, then we can do this if the activity
2556 // being launched is the same as the one making the call... or, as
2557 // a special case, if we do not know the caller then we count the
2558 // current top activity as the caller.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002559 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002560 ActivityRecord checkedCaller = sourceRecord;
2561 if (checkedCaller == null) {
2562 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2563 }
2564 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2565 // Caller is not the same as launcher, so always needed.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002566 startFlags &= ~ActivityManager.START_FLAG_ONLY_IF_NEEDED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002567 }
2568 }
2569
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002570 if (sourceRecord == null) {
2571 // This activity is not being started from another... in this
2572 // case we -always- start a new task.
2573 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2574 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2575 + intent);
2576 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2577 }
2578 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2579 // The original activity who is starting us is running as a single
2580 // instance... this new activity it is starting must go on its
2581 // own task.
2582 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2583 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2584 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2585 // The activity being started is a single instance... it always
2586 // gets launched into its own task.
2587 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2588 }
2589
2590 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2591 // For whatever reason this activity is being launched into a new
2592 // task... yet the caller has requested a result back. Well, that
2593 // is pretty messed up, so instead immediately send back a cancel
2594 // and let the new task continue launched as normal without a
2595 // dependency on its originator.
2596 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2597 sendActivityResultLocked(-1,
2598 r.resultTo, r.resultWho, r.requestCode,
2599 Activity.RESULT_CANCELED, null);
2600 r.resultTo = null;
2601 }
2602
2603 boolean addingToTask = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002604 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002605 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2606 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2607 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2608 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2609 // If bring to front is requested, and no result is requested, and
2610 // we can find a task that was started with this same
2611 // component, then instead of launching bring that one to the front.
2612 if (r.resultTo == null) {
2613 // See if there is a task to bring to the front. If this is
2614 // a SINGLE_INSTANCE activity, there can be one and only one
2615 // instance of it in the history, and it is always in its own
2616 // unique task, so we do a special search.
2617 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2618 ? findTaskLocked(intent, r.info)
2619 : findActivityLocked(intent, r.info);
2620 if (taskTop != null) {
2621 if (taskTop.task.intent == null) {
2622 // This task was started because of movement of
2623 // the activity based on affinity... now that we
2624 // are actually launching it, we can assign the
2625 // base intent.
2626 taskTop.task.setIntent(intent, r.info);
2627 }
2628 // If the target task is not in the front, then we need
2629 // to bring it to the front... except... well, with
2630 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2631 // to have the same behavior as if a new instance was
2632 // being started, which means not bringing it to the front
2633 // if the caller is not itself in the front.
2634 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002635 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002636 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2637 boolean callerAtFront = sourceRecord == null
2638 || curTop.task == sourceRecord.task;
2639 if (callerAtFront) {
2640 // We really do want to push this one into the
2641 // user's face, right now.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002642 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002643 moveTaskToFrontLocked(taskTop.task, r, options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002644 }
2645 }
2646 // If the caller has requested that the target task be
2647 // reset, then do so.
2648 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2649 taskTop = resetTaskIfNeededLocked(taskTop, r);
2650 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002651 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002652 // We don't need to start a new activity, and
2653 // the client said not to do anything if that
2654 // is the case, so this is it! And for paranoia, make
2655 // sure we have correctly resumed the top activity.
2656 if (doResume) {
2657 resumeTopActivityLocked(null);
2658 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002659 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002660 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002661 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002662 if ((launchFlags &
2663 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2664 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2665 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002666 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002667 // not be too hard...
2668 reuseTask = taskTop.task;
2669 performClearTaskLocked(taskTop.task.taskId);
2670 reuseTask.setIntent(r.intent, r.info);
2671 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002672 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2673 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2674 // In this situation we want to remove all activities
2675 // from the task up to the one being started. In most
2676 // cases this means we are resetting the task to its
2677 // initial state.
2678 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002679 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002680 if (top != null) {
2681 if (top.frontOfTask) {
2682 // Activity aliases may mean we use different
2683 // intents for the top activity, so make sure
2684 // the task now has the identity of the new
2685 // intent.
2686 top.task.setIntent(r.intent, r.info);
2687 }
2688 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002689 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002690 } else {
2691 // A special case: we need to
2692 // start the activity because it is not currently
2693 // running, and the caller has asked to clear the
2694 // current task to have this activity at the top.
2695 addingToTask = true;
2696 // Now pretend like this activity is being started
2697 // by the top of its task, so it is put in the
2698 // right place.
2699 sourceRecord = taskTop;
2700 }
2701 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2702 // In this case the top activity on the task is the
2703 // same as the one being launched, so we take that
2704 // as a request to bring the task to the foreground.
2705 // If the top activity in the task is the root
2706 // activity, deliver this new intent to it if it
2707 // desires.
2708 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2709 && taskTop.realActivity.equals(r.realActivity)) {
2710 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2711 if (taskTop.frontOfTask) {
2712 taskTop.task.setIntent(r.intent, r.info);
2713 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002714 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002715 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2716 // In this case we are launching the root activity
2717 // of the task, but with a different intent. We
2718 // should start a new instance on top.
2719 addingToTask = true;
2720 sourceRecord = taskTop;
2721 }
2722 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2723 // In this case an activity is being launched in to an
2724 // existing task, without resetting that task. This
2725 // is typically the situation of launching an activity
2726 // from a notification or shortcut. We want to place
2727 // the new activity on top of the current task.
2728 addingToTask = true;
2729 sourceRecord = taskTop;
2730 } else if (!taskTop.task.rootWasReset) {
2731 // In this case we are launching in to an existing task
2732 // that has not yet been started from its front door.
2733 // The current task has been brought to the front.
2734 // Ideally, we'd probably like to place this new task
2735 // at the bottom of its stack, but that's a little hard
2736 // to do with the current organization of the code so
2737 // for now we'll just drop it.
2738 taskTop.task.setIntent(r.intent, r.info);
2739 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002740 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002741 // We didn't do anything... but it was needed (a.k.a., client
2742 // don't use that intent!) And for paranoia, make
2743 // sure we have correctly resumed the top activity.
2744 if (doResume) {
2745 resumeTopActivityLocked(null);
2746 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002747 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002748 return ActivityManager.START_TASK_TO_FRONT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002749 }
2750 }
2751 }
2752 }
2753
2754 //String uri = r.intent.toURI();
2755 //Intent intent2 = new Intent(uri);
2756 //Slog.i(TAG, "Given intent: " + r.intent);
2757 //Slog.i(TAG, "URI is: " + uri);
2758 //Slog.i(TAG, "To intent: " + intent2);
2759
2760 if (r.packageName != null) {
2761 // If the activity being launched is the same as the one currently
2762 // at the top, then we need to check if it should only be launched
2763 // once.
2764 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2765 if (top != null && r.resultTo == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002766 if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002767 if (top.app != null && top.app.thread != null) {
2768 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2769 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2770 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2771 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2772 // For paranoia, make sure we have correctly
2773 // resumed the top activity.
2774 if (doResume) {
2775 resumeTopActivityLocked(null);
2776 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002777 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002778 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002779 // We don't need to start a new activity, and
2780 // the client said not to do anything if that
2781 // is the case, so this is it!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002782 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002783 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002784 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002785 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002786 }
2787 }
2788 }
2789 }
2790
2791 } else {
2792 if (r.resultTo != null) {
2793 sendActivityResultLocked(-1,
2794 r.resultTo, r.resultWho, r.requestCode,
2795 Activity.RESULT_CANCELED, null);
2796 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002797 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002798 return ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002799 }
2800
2801 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002802 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002803
2804 // Should this be considered a new task?
2805 if (r.resultTo == null && !addingToTask
2806 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002807 if (reuseTask == null) {
2808 // todo: should do better management of integers.
2809 mService.mCurTask++;
2810 if (mService.mCurTask <= 0) {
2811 mService.mCurTask = 1;
2812 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002813 r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002814 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2815 + " in new task " + r.task);
2816 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002817 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002818 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002819 newTask = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002820 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002821
2822 } else if (sourceRecord != null) {
2823 if (!addingToTask &&
2824 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2825 // In this case, we are adding the activity to an existing
2826 // task, but the caller has asked to clear that task if the
2827 // activity is already running.
2828 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002829 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002830 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002831 if (top != null) {
2832 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002833 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002834 // For paranoia, make sure we have correctly
2835 // resumed the top activity.
2836 if (doResume) {
2837 resumeTopActivityLocked(null);
2838 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002839 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002840 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002841 }
2842 } else if (!addingToTask &&
2843 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2844 // In this case, we are launching an activity in our own task
2845 // that may already be running somewhere in the history, and
2846 // we want to shuffle it to the front of the stack if so.
2847 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2848 if (where >= 0) {
2849 ActivityRecord top = moveActivityToFrontLocked(where);
2850 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002851 top.updateOptionsLocked(options);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002852 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002853 if (doResume) {
2854 resumeTopActivityLocked(null);
2855 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002856 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002857 }
2858 }
2859 // An existing activity is starting this new activity, so we want
2860 // to keep the new one in the same task as the one that is starting
2861 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002862 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002863 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2864 + " in existing task " + r.task);
2865
2866 } else {
2867 // This not being started from an existing activity, and not part
2868 // of a new task... just put it in the top task, though these days
2869 // this case should never happen.
2870 final int N = mHistory.size();
2871 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002872 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002873 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002874 ? prev.task
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002875 : new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002876 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2877 + " in new guessed " + r.task);
2878 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002879
Dianne Hackborn39792d22010-08-19 18:01:52 -07002880 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002881 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002882
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002883 if (newTask) {
2884 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
2885 }
2886 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002887 startActivityLocked(r, newTask, doResume, keepCurTransition, options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002888 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002889 }
2890
Dianne Hackborna4972e92012-03-14 10:38:05 -07002891 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002892 String profileFile, ParcelFileDescriptor profileFd, int userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002893 // Collect information about the target of the Intent.
2894 ActivityInfo aInfo;
2895 try {
2896 ResolveInfo rInfo =
2897 AppGlobals.getPackageManager().resolveIntent(
2898 intent, resolvedType,
2899 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07002900 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002901 aInfo = rInfo != null ? rInfo.activityInfo : null;
2902 } catch (RemoteException e) {
2903 aInfo = null;
2904 }
2905
2906 if (aInfo != null) {
2907 // Store the found target back into the intent, because now that
2908 // we have it we never want to do this again. For example, if the
2909 // user navigates back to this point in the history, we should
2910 // always restart the exact same activity.
2911 intent.setComponent(new ComponentName(
2912 aInfo.applicationInfo.packageName, aInfo.name));
2913
2914 // Don't debug things in the system process
Dianne Hackborna4972e92012-03-14 10:38:05 -07002915 if ((startFlags&ActivityManager.START_FLAG_DEBUG) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002916 if (!aInfo.processName.equals("system")) {
2917 mService.setDebugApp(aInfo.processName, true, false);
2918 }
2919 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002920
Dianne Hackborna4972e92012-03-14 10:38:05 -07002921 if ((startFlags&ActivityManager.START_FLAG_OPENGL_TRACES) != 0) {
Siva Velusamy92a8b222012-03-09 16:24:04 -08002922 if (!aInfo.processName.equals("system")) {
2923 mService.setOpenGlTraceApp(aInfo.applicationInfo, aInfo.processName);
2924 }
2925 }
2926
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002927 if (profileFile != null) {
2928 if (!aInfo.processName.equals("system")) {
2929 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002930 profileFile, profileFd,
2931 (startFlags&ActivityManager.START_FLAG_AUTO_STOP_PROFILER) != 0);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002932 }
2933 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002934 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002935 return aInfo;
2936 }
2937
2938 final int startActivityMayWait(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002939 Intent intent, String resolvedType, IBinder resultTo,
2940 String resultWho, int requestCode, int startFlags, String profileFile,
2941 ParcelFileDescriptor profileFd, WaitResult outResult, Configuration config,
2942 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002943 // Refuse possible leaked file descriptors
2944 if (intent != null && intent.hasFileDescriptors()) {
2945 throw new IllegalArgumentException("File descriptors passed in Intent");
2946 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002947 boolean componentSpecified = intent.getComponent() != null;
2948
2949 // Don't modify the client's object!
2950 intent = new Intent(intent);
2951
2952 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002953 ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002954 profileFile, profileFd, userId);
Amith Yamasani95a6a962012-04-18 09:54:43 -07002955 if (aInfo != null && mService.isSingleton(aInfo.processName, aInfo.applicationInfo)) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07002956 userId = 0;
2957 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002958 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002959
2960 synchronized (mService) {
2961 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002962 if (callingUid >= 0) {
2963 callingPid = -1;
2964 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002965 callingPid = Binder.getCallingPid();
2966 callingUid = Binder.getCallingUid();
2967 } else {
2968 callingPid = callingUid = -1;
2969 }
2970
2971 mConfigWillChange = config != null
2972 && mService.mConfiguration.diff(config) != 0;
2973 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2974 "Starting activity when config will change = " + mConfigWillChange);
2975
2976 final long origId = Binder.clearCallingIdentity();
2977
2978 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07002979 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002980 // This may be a heavy-weight process! Check to see if we already
2981 // have another, different heavy-weight process running.
2982 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
2983 if (mService.mHeavyWeightProcess != null &&
2984 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
2985 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
2986 int realCallingPid = callingPid;
2987 int realCallingUid = callingUid;
2988 if (caller != null) {
2989 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
2990 if (callerApp != null) {
2991 realCallingPid = callerApp.pid;
2992 realCallingUid = callerApp.info.uid;
2993 } else {
2994 Slog.w(TAG, "Unable to find app for caller " + caller
2995 + " (pid=" + realCallingPid + ") when starting: "
2996 + intent.toString());
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002997 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002998 return ActivityManager.START_PERMISSION_DENIED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002999 }
3000 }
3001
3002 IIntentSender target = mService.getIntentSenderLocked(
Dianne Hackborna4972e92012-03-14 10:38:05 -07003003 ActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003004 realCallingUid, null, null, 0, new Intent[] { intent },
3005 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003006 | PendingIntent.FLAG_ONE_SHOT, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003007
3008 Intent newIntent = new Intent();
3009 if (requestCode >= 0) {
3010 // Caller is requesting a result.
3011 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
3012 }
3013 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
3014 new IntentSender(target));
3015 if (mService.mHeavyWeightProcess.activities.size() > 0) {
3016 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
3017 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
3018 hist.packageName);
3019 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
3020 hist.task.taskId);
3021 }
3022 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
3023 aInfo.packageName);
3024 newIntent.setFlags(intent.getFlags());
3025 newIntent.setClassName("android",
3026 HeavyWeightSwitcherActivity.class.getName());
3027 intent = newIntent;
3028 resolvedType = null;
3029 caller = null;
3030 callingUid = Binder.getCallingUid();
3031 callingPid = Binder.getCallingPid();
3032 componentSpecified = true;
3033 try {
3034 ResolveInfo rInfo =
3035 AppGlobals.getPackageManager().resolveIntent(
3036 intent, null,
3037 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07003038 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003039 aInfo = rInfo != null ? rInfo.activityInfo : null;
Amith Yamasani742a6712011-05-04 14:49:28 -07003040 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003041 } catch (RemoteException e) {
3042 aInfo = null;
3043 }
3044 }
3045 }
3046 }
3047
3048 int res = startActivityLocked(caller, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003049 aInfo, resultTo, resultWho, requestCode, callingPid, callingUid,
3050 startFlags, options, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003051
3052 if (mConfigWillChange && mMainStack) {
3053 // If the caller also wants to switch to a new configuration,
3054 // do so now. This allows a clean switch, as we are waiting
3055 // for the current activity to pause (so we will not destroy
3056 // it), and have not yet started the next activity.
3057 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
3058 "updateConfiguration()");
3059 mConfigWillChange = false;
3060 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3061 "Updating to new configuration after starting activity.");
Dianne Hackborn813075a62011-11-14 17:45:19 -08003062 mService.updateConfigurationLocked(config, null, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003063 }
3064
3065 Binder.restoreCallingIdentity(origId);
3066
3067 if (outResult != null) {
3068 outResult.result = res;
Dianne Hackborna4972e92012-03-14 10:38:05 -07003069 if (res == ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003070 mWaitingActivityLaunched.add(outResult);
3071 do {
3072 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003073 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003074 } catch (InterruptedException e) {
3075 }
3076 } while (!outResult.timeout && outResult.who == null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003077 } else if (res == ActivityManager.START_TASK_TO_FRONT) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003078 ActivityRecord r = this.topRunningActivityLocked(null);
3079 if (r.nowVisible) {
3080 outResult.timeout = false;
3081 outResult.who = new ComponentName(r.info.packageName, r.info.name);
3082 outResult.totalTime = 0;
3083 outResult.thisTime = 0;
3084 } else {
3085 outResult.thisTime = SystemClock.uptimeMillis();
3086 mWaitingActivityVisible.add(outResult);
3087 do {
3088 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003089 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003090 } catch (InterruptedException e) {
3091 }
3092 } while (!outResult.timeout && outResult.who == null);
3093 }
3094 }
3095 }
3096
3097 return res;
3098 }
3099 }
3100
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003101 final int startActivities(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003102 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
3103 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003104 if (intents == null) {
3105 throw new NullPointerException("intents is null");
3106 }
3107 if (resolvedTypes == null) {
3108 throw new NullPointerException("resolvedTypes is null");
3109 }
3110 if (intents.length != resolvedTypes.length) {
3111 throw new IllegalArgumentException("intents are length different than resolvedTypes");
3112 }
3113
3114 ActivityRecord[] outActivity = new ActivityRecord[1];
3115
3116 int callingPid;
3117 if (callingUid >= 0) {
3118 callingPid = -1;
3119 } else if (caller == null) {
3120 callingPid = Binder.getCallingPid();
3121 callingUid = Binder.getCallingUid();
3122 } else {
3123 callingPid = callingUid = -1;
3124 }
3125 final long origId = Binder.clearCallingIdentity();
3126 try {
3127 synchronized (mService) {
3128
3129 for (int i=0; i<intents.length; i++) {
3130 Intent intent = intents[i];
3131 if (intent == null) {
3132 continue;
3133 }
3134
3135 // Refuse possible leaked file descriptors
3136 if (intent != null && intent.hasFileDescriptors()) {
3137 throw new IllegalArgumentException("File descriptors passed in Intent");
3138 }
3139
3140 boolean componentSpecified = intent.getComponent() != null;
3141
3142 // Don't modify the client's object!
3143 intent = new Intent(intent);
3144
3145 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003146 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i],
Amith Yamasani483f3b02012-03-13 16:08:00 -07003147 0, null, null, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07003148 // TODO: New, check if this is correct
3149 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003150
3151 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
3152 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
3153 throw new IllegalArgumentException(
3154 "FLAG_CANT_SAVE_STATE not supported here");
3155 }
3156
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003157 Bundle theseOptions;
3158 if (options != null && i == intents.length-1) {
3159 theseOptions = options;
3160 } else {
3161 theseOptions = null;
3162 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003163 int res = startActivityLocked(caller, intent, resolvedTypes[i],
Dianne Hackborna4972e92012-03-14 10:38:05 -07003164 aInfo, resultTo, null, -1, callingPid, callingUid,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003165 0, theseOptions, componentSpecified, outActivity);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003166 if (res < 0) {
3167 return res;
3168 }
3169
Dianne Hackbornbe707852011-11-11 14:32:10 -08003170 resultTo = outActivity[0] != null ? outActivity[0].appToken : null;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003171 }
3172 }
3173 } finally {
3174 Binder.restoreCallingIdentity(origId);
3175 }
3176
Dianne Hackborna4972e92012-03-14 10:38:05 -07003177 return ActivityManager.START_SUCCESS;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003178 }
3179
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003180 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
3181 long thisTime, long totalTime) {
3182 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
3183 WaitResult w = mWaitingActivityLaunched.get(i);
3184 w.timeout = timeout;
3185 if (r != null) {
3186 w.who = new ComponentName(r.info.packageName, r.info.name);
3187 }
3188 w.thisTime = thisTime;
3189 w.totalTime = totalTime;
3190 }
3191 mService.notifyAll();
3192 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003193
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003194 void reportActivityVisibleLocked(ActivityRecord r) {
3195 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
3196 WaitResult w = mWaitingActivityVisible.get(i);
3197 w.timeout = false;
3198 if (r != null) {
3199 w.who = new ComponentName(r.info.packageName, r.info.name);
3200 }
3201 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
3202 w.thisTime = w.totalTime;
3203 }
3204 mService.notifyAll();
Dianne Hackborn90c52de2011-09-23 12:57:44 -07003205
3206 if (mDismissKeyguardOnNextActivity) {
3207 mDismissKeyguardOnNextActivity = false;
3208 mService.mWindowManager.dismissKeyguard();
3209 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003210 }
3211
3212 void sendActivityResultLocked(int callingUid, ActivityRecord r,
3213 String resultWho, int requestCode, int resultCode, Intent data) {
3214
3215 if (callingUid > 0) {
3216 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003217 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003218 }
3219
3220 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3221 + " : who=" + resultWho + " req=" + requestCode
3222 + " res=" + resultCode + " data=" + data);
3223 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3224 try {
3225 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3226 list.add(new ResultInfo(resultWho, requestCode,
3227 resultCode, data));
Dianne Hackbornbe707852011-11-11 14:32:10 -08003228 r.app.thread.scheduleSendResult(r.appToken, list);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003229 return;
3230 } catch (Exception e) {
3231 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3232 }
3233 }
3234
3235 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3236 }
3237
3238 private final void stopActivityLocked(ActivityRecord r) {
3239 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3240 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3241 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3242 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003243 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003244 "no-history");
3245 }
3246 } else if (r.app != null && r.app.thread != null) {
3247 if (mMainStack) {
3248 if (mService.mFocusedActivity == r) {
3249 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3250 }
3251 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003252 r.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003253 try {
3254 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003255 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3256 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003257 r.state = ActivityState.STOPPING;
3258 if (DEBUG_VISBILITY) Slog.v(
3259 TAG, "Stopping visible=" + r.visible + " for " + r);
3260 if (!r.visible) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003261 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003262 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003263 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003264 if (mService.isSleeping()) {
3265 r.setSleeping(true);
3266 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003267 Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG);
3268 msg.obj = r;
3269 mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003270 } catch (Exception e) {
3271 // Maybe just ignore exceptions here... if the process
3272 // has crashed, our death notification will clean things
3273 // up.
3274 Slog.w(TAG, "Exception thrown during pause", e);
3275 // Just in case, assume it to be stopped.
3276 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003277 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003278 r.state = ActivityState.STOPPED;
3279 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003280 destroyActivityLocked(r, true, false, "stop-except");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003281 }
3282 }
3283 }
3284 }
3285
3286 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3287 boolean remove) {
3288 int N = mStoppingActivities.size();
3289 if (N <= 0) return null;
3290
3291 ArrayList<ActivityRecord> stops = null;
3292
3293 final boolean nowVisible = mResumedActivity != null
3294 && mResumedActivity.nowVisible
3295 && !mResumedActivity.waitingVisible;
3296 for (int i=0; i<N; i++) {
3297 ActivityRecord s = mStoppingActivities.get(i);
3298 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3299 + nowVisible + " waitingVisible=" + s.waitingVisible
3300 + " finishing=" + s.finishing);
3301 if (s.waitingVisible && nowVisible) {
3302 mWaitingVisibleActivities.remove(s);
3303 s.waitingVisible = false;
3304 if (s.finishing) {
3305 // If this activity is finishing, it is sitting on top of
3306 // everyone else but we now know it is no longer needed...
3307 // so get rid of it. Otherwise, we need to go through the
3308 // normal flow and hide it once we determine that it is
3309 // hidden by the activities in front of it.
3310 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003311 mService.mWindowManager.setAppVisibility(s.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003312 }
3313 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003314 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003315 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3316 if (stops == null) {
3317 stops = new ArrayList<ActivityRecord>();
3318 }
3319 stops.add(s);
3320 mStoppingActivities.remove(i);
3321 N--;
3322 i--;
3323 }
3324 }
3325
3326 return stops;
3327 }
3328
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003329 final void scheduleIdleLocked() {
3330 Message msg = Message.obtain();
3331 msg.what = IDLE_NOW_MSG;
3332 mHandler.sendMessage(msg);
3333 }
3334
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003335 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003336 Configuration config) {
3337 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3338
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003339 ActivityRecord res = null;
3340
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003341 ArrayList<ActivityRecord> stops = null;
3342 ArrayList<ActivityRecord> finishes = null;
3343 ArrayList<ActivityRecord> thumbnails = null;
3344 int NS = 0;
3345 int NF = 0;
3346 int NT = 0;
3347 IApplicationThread sendThumbnail = null;
3348 boolean booting = false;
3349 boolean enableScreen = false;
3350
3351 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003352 ActivityRecord r = ActivityRecord.forToken(token);
3353 if (r != null) {
3354 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003355 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003356 }
3357
3358 // Get the activity record.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003359 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003360 if (index >= 0) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003361 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003362
3363 if (fromTimeout) {
3364 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3365 }
3366
3367 // This is a hack to semi-deal with a race condition
3368 // in the client where it can be constructed with a
3369 // newer configuration from when we asked it to launch.
3370 // We'll update with whatever configuration it now says
3371 // it used to launch.
3372 if (config != null) {
3373 r.configuration = config;
3374 }
3375
3376 // No longer need to keep the device awake.
3377 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3378 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3379 mLaunchingActivity.release();
3380 }
3381
3382 // We are now idle. If someone is waiting for a thumbnail from
3383 // us, we can now deliver.
3384 r.idle = true;
3385 mService.scheduleAppGcsLocked();
3386 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3387 sendThumbnail = r.app.thread;
3388 r.thumbnailNeeded = false;
3389 }
3390
3391 // If this activity is fullscreen, set up to hide those under it.
3392
3393 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3394 ensureActivitiesVisibleLocked(null, 0);
3395
3396 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3397 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003398 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003399 mService.mBooted = true;
3400 enableScreen = true;
3401 }
3402 }
3403
3404 } else if (fromTimeout) {
3405 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3406 }
3407
3408 // Atomically retrieve all of the other things to do.
3409 stops = processStoppingActivitiesLocked(true);
3410 NS = stops != null ? stops.size() : 0;
3411 if ((NF=mFinishingActivities.size()) > 0) {
3412 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3413 mFinishingActivities.clear();
3414 }
3415 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3416 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3417 mService.mCancelledThumbnails.clear();
3418 }
3419
3420 if (mMainStack) {
3421 booting = mService.mBooting;
3422 mService.mBooting = false;
3423 }
3424 }
3425
3426 int i;
3427
3428 // Send thumbnail if requested.
3429 if (sendThumbnail != null) {
3430 try {
3431 sendThumbnail.requestThumbnail(token);
3432 } catch (Exception e) {
3433 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3434 mService.sendPendingThumbnail(null, token, null, null, true);
3435 }
3436 }
3437
3438 // Stop any activities that are scheduled to do so but have been
3439 // waiting for the next one to start.
3440 for (i=0; i<NS; i++) {
3441 ActivityRecord r = (ActivityRecord)stops.get(i);
3442 synchronized (mService) {
3443 if (r.finishing) {
3444 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY);
3445 } else {
3446 stopActivityLocked(r);
3447 }
3448 }
3449 }
3450
3451 // Finish any activities that are scheduled to do so but have been
3452 // waiting for the next one to start.
3453 for (i=0; i<NF; i++) {
3454 ActivityRecord r = (ActivityRecord)finishes.get(i);
3455 synchronized (mService) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003456 destroyActivityLocked(r, true, false, "finish-idle");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003457 }
3458 }
3459
3460 // Report back to any thumbnail receivers.
3461 for (i=0; i<NT; i++) {
3462 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3463 mService.sendPendingThumbnail(r, null, null, null, true);
3464 }
3465
3466 if (booting) {
3467 mService.finishBooting();
3468 }
3469
3470 mService.trimApplications();
3471 //dump();
3472 //mWindowManager.dump();
3473
3474 if (enableScreen) {
3475 mService.enableScreenAfterBoot();
3476 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003477
3478 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003479 }
3480
3481 /**
3482 * @return Returns true if the activity is being finished, false if for
3483 * some reason it is being left as-is.
3484 */
3485 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
3486 Intent resultData, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003487 int index = indexOfTokenLocked(token);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003488 if (DEBUG_RESULTS) Slog.v(
3489 TAG, "Finishing activity @" + index + ": token=" + token
3490 + ", result=" + resultCode + ", data=" + resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003491 if (index < 0) {
3492 return false;
3493 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003494 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003495
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003496 finishActivityLocked(r, index, resultCode, resultData, reason);
3497 return true;
3498 }
3499
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003500 final void finishSubActivityLocked(IBinder token, String resultWho, int requestCode) {
3501 ActivityRecord self = isInStackLocked(token);
3502 if (self == null) {
3503 return;
3504 }
3505
3506 int i;
3507 for (i=mHistory.size()-1; i>=0; i--) {
3508 ActivityRecord r = (ActivityRecord)mHistory.get(i);
3509 if (r.resultTo == self && r.requestCode == requestCode) {
3510 if ((r.resultWho == null && resultWho == null) ||
3511 (r.resultWho != null && r.resultWho.equals(resultWho))) {
3512 finishActivityLocked(r, i,
3513 Activity.RESULT_CANCELED, null, "request-sub");
3514 }
3515 }
3516 }
3517 }
3518
3519 final boolean finishActivityAffinityLocked(IBinder token) {
3520 int index = indexOfTokenLocked(token);
3521 if (DEBUG_RESULTS) Slog.v(
3522 TAG, "Finishing activity affinity @" + index + ": token=" + token);
3523 if (index < 0) {
3524 return false;
3525 }
3526 ActivityRecord r = mHistory.get(index);
3527
3528 while (index > 0) {
3529 ActivityRecord cur = mHistory.get(index);
3530 if (cur.task != r.task) {
3531 break;
3532 }
3533 if (cur.taskAffinity == null && r.taskAffinity != null) {
3534 break;
3535 }
3536 if (cur.taskAffinity != null && !cur.taskAffinity.equals(r.taskAffinity)) {
3537 break;
3538 }
3539 finishActivityLocked(cur, index, Activity.RESULT_CANCELED, null, "request-affinity");
3540 index--;
3541 }
3542 return true;
3543 }
3544
Dianne Hackborn5c607432012-02-28 14:44:19 -08003545 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
3546 // send the result
3547 ActivityRecord resultTo = r.resultTo;
3548 if (resultTo != null) {
3549 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3550 + " who=" + r.resultWho + " req=" + r.requestCode
3551 + " res=" + resultCode + " data=" + resultData);
3552 if (r.info.applicationInfo.uid > 0) {
3553 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3554 resultTo.packageName, resultData,
3555 resultTo.getUriPermissionsLocked());
3556 }
3557 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3558 resultData);
3559 r.resultTo = null;
3560 }
3561 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3562
3563 // Make sure this HistoryRecord is not holding on to other resources,
3564 // because clients have remote IPC references to this object so we
3565 // can't assume that will go away and want to avoid circular IPC refs.
3566 r.results = null;
3567 r.pendingResults = null;
3568 r.newIntents = null;
3569 r.icicle = null;
3570 }
3571
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003572 /**
3573 * @return Returns true if this activity has been removed from the history
3574 * list, or false if it is still in the list and will be removed later.
3575 */
3576 final boolean finishActivityLocked(ActivityRecord r, int index,
3577 int resultCode, Intent resultData, String reason) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003578 return finishActivityLocked(r, index, resultCode, resultData, reason, false);
3579 }
3580
3581 /**
3582 * @return Returns true if this activity has been removed from the history
3583 * list, or false if it is still in the list and will be removed later.
3584 */
3585 final boolean finishActivityLocked(ActivityRecord r, int index,
3586 int resultCode, Intent resultData, String reason, boolean immediate) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003587 if (r.finishing) {
3588 Slog.w(TAG, "Duplicate finish request for " + r);
3589 return false;
3590 }
3591
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003592 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003593 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3594 System.identityHashCode(r),
3595 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003596 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003597 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003598 if (next.task == r.task) {
3599 if (r.frontOfTask) {
3600 // The next activity is now the front of the task.
3601 next.frontOfTask = true;
3602 }
3603 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3604 // If the caller asked that this activity (and all above it)
3605 // be cleared when the task is reset, don't lose that information,
3606 // but propagate it up to the next activity.
3607 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3608 }
3609 }
3610 }
3611
3612 r.pauseKeyDispatchingLocked();
3613 if (mMainStack) {
3614 if (mService.mFocusedActivity == r) {
3615 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3616 }
3617 }
3618
Dianne Hackborn5c607432012-02-28 14:44:19 -08003619 finishActivityResultsLocked(r, resultCode, resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003620
3621 if (mService.mPendingThumbnails.size() > 0) {
3622 // There are clients waiting to receive thumbnails so, in case
3623 // this is an activity that someone is waiting for, add it
3624 // to the pending list so we can correctly update the clients.
3625 mService.mCancelledThumbnails.add(r);
3626 }
3627
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003628 if (immediate) {
3629 return finishCurrentActivityLocked(r, index,
3630 FINISH_IMMEDIATELY) == null;
3631 } else if (mResumedActivity == r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003632 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003633 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003634 if (DEBUG_TRANSITION) Slog.v(TAG,
3635 "Prepare close transition: finishing " + r);
3636 mService.mWindowManager.prepareAppTransition(endTask
3637 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003638 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003639
3640 // Tell window manager to prepare for this one to be removed.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003641 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003642
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003643 if (mPausingActivity == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003644 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3645 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3646 startPausingLocked(false, false);
3647 }
3648
3649 } else if (r.state != ActivityState.PAUSING) {
3650 // If the activity is PAUSING, we will complete the finish once
3651 // it is done pausing; else we can just directly finish it here.
3652 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3653 return finishCurrentActivityLocked(r, index,
3654 FINISH_AFTER_PAUSE) == null;
3655 } else {
3656 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3657 }
3658
3659 return false;
3660 }
3661
3662 private static final int FINISH_IMMEDIATELY = 0;
3663 private static final int FINISH_AFTER_PAUSE = 1;
3664 private static final int FINISH_AFTER_VISIBLE = 2;
3665
3666 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3667 int mode) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003668 final int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003669 if (index < 0) {
3670 return null;
3671 }
3672
3673 return finishCurrentActivityLocked(r, index, mode);
3674 }
3675
3676 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3677 int index, int mode) {
3678 // First things first: if this activity is currently visible,
3679 // and the resumed activity is not yet visible, then hold off on
3680 // finishing until the resumed one becomes visible.
3681 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3682 if (!mStoppingActivities.contains(r)) {
3683 mStoppingActivities.add(r);
3684 if (mStoppingActivities.size() > 3) {
3685 // If we already have a few activities waiting to stop,
3686 // then give up on things going idle and start clearing
3687 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003688 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003689 } else {
3690 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003691 }
3692 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003693 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3694 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003695 r.state = ActivityState.STOPPING;
3696 mService.updateOomAdjLocked();
3697 return r;
3698 }
3699
3700 // make sure the record is cleaned out of other places.
3701 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003702 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003703 mWaitingVisibleActivities.remove(r);
3704 if (mResumedActivity == r) {
3705 mResumedActivity = null;
3706 }
3707 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003708 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003709 r.state = ActivityState.FINISHING;
3710
3711 if (mode == FINISH_IMMEDIATELY
3712 || prevState == ActivityState.STOPPED
3713 || prevState == ActivityState.INITIALIZING) {
3714 // If this activity is already stopped, we can just finish
3715 // it right now.
Dianne Hackborn28695e02011-11-02 21:59:51 -07003716 return destroyActivityLocked(r, true, true, "finish-imm") ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003717 } else {
3718 // Need to go through the full pause cycle to get this
3719 // activity into the stopped state and then finish it.
3720 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3721 mFinishingActivities.add(r);
3722 resumeTopActivityLocked(null);
3723 }
3724 return r;
3725 }
3726
3727 /**
3728 * Perform the common clean-up of an activity record. This is called both
3729 * as part of destroyActivityLocked() (when destroying the client-side
3730 * representation) and cleaning things up as a result of its hosting
3731 * processing going away, in which case there is no remaining client-side
3732 * state to destroy so only the cleanup here is needed.
3733 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003734 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3735 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003736 if (mResumedActivity == r) {
3737 mResumedActivity = null;
3738 }
3739 if (mService.mFocusedActivity == r) {
3740 mService.mFocusedActivity = null;
3741 }
3742
3743 r.configDestroy = false;
3744 r.frozenBeforeDestroy = false;
3745
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003746 if (setState) {
3747 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3748 r.state = ActivityState.DESTROYED;
3749 }
3750
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003751 // Make sure this record is no longer in the pending finishes list.
3752 // This could happen, for example, if we are trimming activities
3753 // down to the max limit while they are still waiting to finish.
3754 mFinishingActivities.remove(r);
3755 mWaitingVisibleActivities.remove(r);
3756
3757 // Remove any pending results.
3758 if (r.finishing && r.pendingResults != null) {
3759 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3760 PendingIntentRecord rec = apr.get();
3761 if (rec != null) {
3762 mService.cancelIntentSenderLocked(rec, false);
3763 }
3764 }
3765 r.pendingResults = null;
3766 }
3767
3768 if (cleanServices) {
3769 cleanUpActivityServicesLocked(r);
3770 }
3771
3772 if (mService.mPendingThumbnails.size() > 0) {
3773 // There are clients waiting to receive thumbnails so, in case
3774 // this is an activity that someone is waiting for, add it
3775 // to the pending list so we can correctly update the clients.
3776 mService.mCancelledThumbnails.add(r);
3777 }
3778
3779 // Get rid of any pending idle timeouts.
3780 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003781 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003782 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003783 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003784 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003785 }
3786
Dianne Hackborn5c607432012-02-28 14:44:19 -08003787 final void removeActivityFromHistoryLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003788 if (r.state != ActivityState.DESTROYED) {
Dianne Hackborn5c607432012-02-28 14:44:19 -08003789 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003790 r.makeFinishing();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003791 if (DEBUG_ADD_REMOVE) {
3792 RuntimeException here = new RuntimeException("here");
3793 here.fillInStackTrace();
3794 Slog.i(TAG, "Removing activity " + r + " from stack");
3795 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003796 mHistory.remove(r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003797 r.takeFromHistory();
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003798 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3799 + " (removed from history)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003800 r.state = ActivityState.DESTROYED;
Dianne Hackbornbe707852011-11-11 14:32:10 -08003801 mService.mWindowManager.removeAppToken(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003802 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003803 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003804 }
3805 cleanUpActivityServicesLocked(r);
3806 r.removeUriPermissionsLocked();
3807 }
3808 }
3809
3810 /**
3811 * Perform clean-up of service connections in an activity record.
3812 */
3813 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3814 // Throw away any services that have been bound by this activity.
3815 if (r.connections != null) {
3816 Iterator<ConnectionRecord> it = r.connections.iterator();
3817 while (it.hasNext()) {
3818 ConnectionRecord c = it.next();
3819 mService.removeConnectionLocked(c, null, r);
3820 }
3821 r.connections = null;
3822 }
3823 }
3824
Dianne Hackborn28695e02011-11-02 21:59:51 -07003825 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003826 for (int i=mHistory.size()-1; i>=0; i--) {
3827 ActivityRecord r = mHistory.get(i);
3828 if (owner != null && r.app != owner) {
3829 continue;
3830 }
3831 // We can destroy this one if we have its icicle saved and
3832 // it is not in the process of pausing/stopping/finishing.
3833 if (r.app != null && r.haveState && !r.visible && r.stopped && !r.finishing
3834 && r.state != ActivityState.DESTROYING
3835 && r.state != ActivityState.DESTROYED) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003836 destroyActivityLocked(r, true, oomAdj, "trim");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003837 }
3838 }
3839 }
3840
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003841 /**
3842 * Destroy the current CLIENT SIDE instance of an activity. This may be
3843 * called both when actually finishing an activity, or when performing
3844 * a configuration switch where we destroy the current client-side object
3845 * but then create a new client-side object for this same HistoryRecord.
3846 */
3847 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackborn28695e02011-11-02 21:59:51 -07003848 boolean removeFromApp, boolean oomAdj, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003849 if (DEBUG_SWITCH) Slog.v(
3850 TAG, "Removing activity: token=" + r
3851 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3852 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3853 System.identityHashCode(r),
Dianne Hackborn28695e02011-11-02 21:59:51 -07003854 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003855
3856 boolean removedFromHistory = false;
3857
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003858 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003859
3860 final boolean hadApp = r.app != null;
3861
3862 if (hadApp) {
3863 if (removeFromApp) {
3864 int idx = r.app.activities.indexOf(r);
3865 if (idx >= 0) {
3866 r.app.activities.remove(idx);
3867 }
3868 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
3869 mService.mHeavyWeightProcess = null;
3870 mService.mHandler.sendEmptyMessage(
3871 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
3872 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003873 if (r.app.activities.size() == 0) {
3874 // No longer have activities, so update location in
3875 // LRU list.
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003876 mService.updateLruProcessLocked(r.app, oomAdj, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003877 }
3878 }
3879
3880 boolean skipDestroy = false;
3881
3882 try {
3883 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003884 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003885 r.configChangeFlags);
3886 } catch (Exception e) {
3887 // We can just ignore exceptions here... if the process
3888 // has crashed, our death notification will clean things
3889 // up.
3890 //Slog.w(TAG, "Exception thrown during finish", e);
3891 if (r.finishing) {
3892 removeActivityFromHistoryLocked(r);
3893 removedFromHistory = true;
3894 skipDestroy = true;
3895 }
3896 }
3897
3898 r.app = null;
3899 r.nowVisible = false;
3900
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003901 // If the activity is finishing, we need to wait on removing it
3902 // from the list to give it a chance to do its cleanup. During
3903 // that time it may make calls back with its token so we need to
3904 // be able to find it on the list and so we don't want to remove
3905 // it from the list yet. Otherwise, we can just immediately put
3906 // it in the destroyed state since we are not removing it from the
3907 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003908 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003909 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
3910 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003911 r.state = ActivityState.DESTROYING;
3912 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
3913 msg.obj = r;
3914 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
3915 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003916 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3917 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003918 r.state = ActivityState.DESTROYED;
3919 }
3920 } else {
3921 // remove this record from the history.
3922 if (r.finishing) {
3923 removeActivityFromHistoryLocked(r);
3924 removedFromHistory = true;
3925 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003926 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3927 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003928 r.state = ActivityState.DESTROYED;
3929 }
3930 }
3931
3932 r.configChangeFlags = 0;
3933
3934 if (!mLRUActivities.remove(r) && hadApp) {
3935 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
3936 }
3937
3938 return removedFromHistory;
3939 }
3940
3941 final void activityDestroyed(IBinder token) {
3942 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003943 ActivityRecord r = ActivityRecord.forToken(token);
3944 if (r != null) {
3945 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
3946 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003947
Dianne Hackbornbe707852011-11-11 14:32:10 -08003948 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003949 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003950 if (r.state == ActivityState.DESTROYING) {
3951 final long origId = Binder.clearCallingIdentity();
3952 removeActivityFromHistoryLocked(r);
3953 Binder.restoreCallingIdentity(origId);
3954 }
3955 }
3956 }
3957 }
3958
3959 private static void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
3960 int i = list.size();
3961 if (localLOGV) Slog.v(
3962 TAG, "Removing app " + app + " from list " + list
3963 + " with " + i + " entries");
3964 while (i > 0) {
3965 i--;
3966 ActivityRecord r = (ActivityRecord)list.get(i);
3967 if (localLOGV) Slog.v(
3968 TAG, "Record #" + i + " " + r + ": app=" + r.app);
3969 if (r.app == app) {
3970 if (localLOGV) Slog.v(TAG, "Removing this entry!");
3971 list.remove(i);
3972 }
3973 }
3974 }
3975
3976 void removeHistoryRecordsForAppLocked(ProcessRecord app) {
3977 removeHistoryRecordsForAppLocked(mLRUActivities, app);
3978 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003979 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003980 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
3981 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
3982 }
3983
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003984 /**
3985 * Move the current home activity's task (if one exists) to the front
3986 * of the stack.
3987 */
3988 final void moveHomeToFrontLocked() {
3989 TaskRecord homeTask = null;
3990 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003991 ActivityRecord hr = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003992 if (hr.isHomeActivity) {
3993 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003994 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003995 }
3996 }
3997 if (homeTask != null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003998 moveTaskToFrontLocked(homeTask, null, null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003999 }
4000 }
4001
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004002 final void updateTransitLocked(int transit, Bundle options) {
4003 if (options != null) {
4004 ActivityRecord r = topRunningActivityLocked(null);
4005 if (r != null && r.state != ActivityState.RESUMED) {
4006 r.updateOptionsLocked(options);
4007 } else {
4008 ActivityOptions.abort(options);
4009 }
4010 }
4011 mService.mWindowManager.prepareAppTransition(transit, false);
4012 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004013
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004014 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004015 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
4016
4017 final int task = tr.taskId;
4018 int top = mHistory.size()-1;
4019
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004020 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004021 // nothing to do!
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004022 if (reason != null &&
4023 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
4024 ActivityOptions.abort(options);
4025 } else {
4026 updateTransitLocked(WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, options);
4027 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004028 return;
4029 }
4030
Dianne Hackbornbe707852011-11-11 14:32:10 -08004031 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004032
4033 // Applying the affinities may have removed entries from the history,
4034 // so get the size again.
4035 top = mHistory.size()-1;
4036 int pos = top;
4037
4038 // Shift all activities with this task up to the top
4039 // of the stack, keeping them in the same internal order.
4040 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004041 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004042 if (localLOGV) Slog.v(
4043 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004044 if (r.task.taskId == task) {
4045 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004046 if (DEBUG_ADD_REMOVE) {
4047 RuntimeException here = new RuntimeException("here");
4048 here.fillInStackTrace();
4049 Slog.i(TAG, "Removing and adding activity " + r + " to stack at " + top, here);
4050 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004051 mHistory.remove(pos);
4052 mHistory.add(top, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004053 moved.add(0, r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004054 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004055 }
4056 pos--;
4057 }
4058
4059 if (DEBUG_TRANSITION) Slog.v(TAG,
4060 "Prepare to front transition: task=" + tr);
4061 if (reason != null &&
4062 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004063 mService.mWindowManager.prepareAppTransition(
4064 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004065 ActivityRecord r = topRunningActivityLocked(null);
4066 if (r != null) {
4067 mNoAnimActivities.add(r);
4068 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004069 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004070 } else {
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004071 updateTransitLocked(WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004072 }
4073
4074 mService.mWindowManager.moveAppTokensToTop(moved);
4075 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004076 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004077 }
4078
4079 finishTaskMoveLocked(task);
4080 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
4081 }
4082
4083 private final void finishTaskMoveLocked(int task) {
4084 resumeTopActivityLocked(null);
4085 }
4086
4087 /**
4088 * Worker method for rearranging history stack. Implements the function of moving all
4089 * activities for a specific task (gathering them if disjoint) into a single group at the
4090 * bottom of the stack.
4091 *
4092 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
4093 * to premeptively cancel the move.
4094 *
4095 * @param task The taskId to collect and move to the bottom.
4096 * @return Returns true if the move completed, false if not.
4097 */
4098 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
4099 Slog.i(TAG, "moveTaskToBack: " + task);
4100
4101 // If we have a watcher, preflight the move before committing to it. First check
4102 // for *other* available tasks, but if none are available, then try again allowing the
4103 // current task to be selected.
4104 if (mMainStack && mService.mController != null) {
4105 ActivityRecord next = topRunningActivityLocked(null, task);
4106 if (next == null) {
4107 next = topRunningActivityLocked(null, 0);
4108 }
4109 if (next != null) {
4110 // ask watcher if this is allowed
4111 boolean moveOK = true;
4112 try {
4113 moveOK = mService.mController.activityResuming(next.packageName);
4114 } catch (RemoteException e) {
4115 mService.mController = null;
4116 }
4117 if (!moveOK) {
4118 return false;
4119 }
4120 }
4121 }
4122
Dianne Hackbornbe707852011-11-11 14:32:10 -08004123 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004124
4125 if (DEBUG_TRANSITION) Slog.v(TAG,
4126 "Prepare to back transition: task=" + task);
4127
4128 final int N = mHistory.size();
4129 int bottom = 0;
4130 int pos = 0;
4131
4132 // Shift all activities with this task down to the bottom
4133 // of the stack, keeping them in the same internal order.
4134 while (pos < N) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004135 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004136 if (localLOGV) Slog.v(
4137 TAG, "At " + pos + " ckp " + r.task + ": " + r);
4138 if (r.task.taskId == task) {
4139 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004140 if (DEBUG_ADD_REMOVE) {
4141 RuntimeException here = new RuntimeException("here");
4142 here.fillInStackTrace();
4143 Slog.i(TAG, "Removing and adding activity " + r + " to stack at "
4144 + bottom, here);
4145 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004146 mHistory.remove(pos);
4147 mHistory.add(bottom, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004148 moved.add(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004149 bottom++;
4150 }
4151 pos++;
4152 }
4153
4154 if (reason != null &&
4155 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004156 mService.mWindowManager.prepareAppTransition(
4157 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004158 ActivityRecord r = topRunningActivityLocked(null);
4159 if (r != null) {
4160 mNoAnimActivities.add(r);
4161 }
4162 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004163 mService.mWindowManager.prepareAppTransition(
4164 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004165 }
4166 mService.mWindowManager.moveAppTokensToBottom(moved);
4167 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004168 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004169 }
4170
4171 finishTaskMoveLocked(task);
4172 return true;
4173 }
4174
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004175 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
4176 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4177 ActivityRecord resumed = mResumedActivity;
4178 if (resumed != null && resumed.thumbHolder == tr) {
4179 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
4180 } else {
4181 info.mainThumbnail = tr.lastThumbnail;
4182 }
4183 return info;
4184 }
4185
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004186 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex,
4187 boolean taskRequired) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004188 TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
4189 if (info.root == null) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004190 if (taskRequired) {
4191 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
4192 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004193 return null;
4194 }
4195
4196 if (subTaskIndex < 0) {
4197 // Just remove the entire task.
4198 performClearTaskAtIndexLocked(taskId, info.rootIndex);
4199 return info.root;
4200 }
4201
4202 if (subTaskIndex >= info.subtasks.size()) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004203 if (taskRequired) {
4204 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
4205 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004206 return null;
4207 }
4208
4209 // Remove all of this task's activies starting at the sub task.
4210 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
4211 performClearTaskAtIndexLocked(taskId, subtask.index);
4212 return subtask.activity;
4213 }
4214
4215 public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
4216 ActivityRecord resumed = mResumedActivity;
4217 final TaskAccessInfo thumbs = new TaskAccessInfo();
4218 // How many different sub-thumbnails?
4219 final int NA = mHistory.size();
4220 int j = 0;
4221 ThumbnailHolder holder = null;
4222 while (j < NA) {
4223 ActivityRecord ar = mHistory.get(j);
4224 if (!ar.finishing && ar.task.taskId == taskId) {
4225 holder = ar.thumbHolder;
4226 break;
4227 }
4228 j++;
4229 }
4230
4231 if (j >= NA) {
4232 return thumbs;
4233 }
4234
4235 thumbs.root = mHistory.get(j);
4236 thumbs.rootIndex = j;
4237
4238 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
4239 thumbs.subtasks = subtasks;
4240 ActivityRecord lastActivity = null;
4241 while (j < NA) {
4242 ActivityRecord ar = mHistory.get(j);
4243 j++;
4244 if (ar.finishing) {
4245 continue;
4246 }
4247 if (ar.task.taskId != taskId) {
4248 break;
4249 }
4250 lastActivity = ar;
4251 if (ar.thumbHolder != holder && holder != null) {
4252 thumbs.numSubThumbbails++;
4253 holder = ar.thumbHolder;
4254 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
4255 sub.thumbnail = holder.lastThumbnail;
4256 sub.activity = ar;
4257 sub.index = j-1;
4258 subtasks.add(sub);
4259 }
4260 }
4261 if (lastActivity != null && subtasks.size() > 0) {
4262 if (resumed == lastActivity) {
4263 TaskAccessInfo.SubTask sub = subtasks.get(subtasks.size()-1);
4264 sub.thumbnail = lastActivity.stack.screenshotActivities(lastActivity);
4265 }
4266 }
4267 if (thumbs.numSubThumbbails > 0) {
4268 thumbs.retriever = new IThumbnailRetriever.Stub() {
4269 public Bitmap getThumbnail(int index) {
4270 if (index < 0 || index >= thumbs.subtasks.size()) {
4271 return null;
4272 }
4273 return thumbs.subtasks.get(index).thumbnail;
4274 }
4275 };
4276 }
4277 return thumbs;
4278 }
4279
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004280 private final void logStartActivity(int tag, ActivityRecord r,
4281 TaskRecord task) {
4282 EventLog.writeEvent(tag,
4283 System.identityHashCode(r), task.taskId,
4284 r.shortComponentName, r.intent.getAction(),
4285 r.intent.getType(), r.intent.getDataString(),
4286 r.intent.getFlags());
4287 }
4288
4289 /**
4290 * Make sure the given activity matches the current configuration. Returns
4291 * false if the activity had to be destroyed. Returns true if the
4292 * configuration is the same, or the activity will remain running as-is
4293 * for whatever reason. Ensures the HistoryRecord is updated with the
4294 * correct configuration and all other bookkeeping is handled.
4295 */
4296 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
4297 int globalChanges) {
4298 if (mConfigWillChange) {
4299 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4300 "Skipping config check (will change): " + r);
4301 return true;
4302 }
4303
4304 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4305 "Ensuring correct configuration: " + r);
4306
4307 // Short circuit: if the two configurations are the exact same
4308 // object (the common case), then there is nothing to do.
4309 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004310 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004311 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4312 "Configuration unchanged in " + r);
4313 return true;
4314 }
4315
4316 // We don't worry about activities that are finishing.
4317 if (r.finishing) {
4318 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4319 "Configuration doesn't matter in finishing " + r);
4320 r.stopFreezingScreenLocked(false);
4321 return true;
4322 }
4323
4324 // Okay we now are going to make this activity have the new config.
4325 // But then we need to figure out how it needs to deal with that.
4326 Configuration oldConfig = r.configuration;
4327 r.configuration = newConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004328
4329 // Determine what has changed. May be nothing, if this is a config
4330 // that has come back from the app after going idle. In that case
4331 // we just want to leave the official config object now in the
4332 // activity and do nothing else.
4333 final int changes = oldConfig.diff(newConfig);
4334 if (changes == 0 && !r.forceNewConfig) {
4335 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4336 "Configuration no differences in " + r);
4337 return true;
4338 }
4339
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004340 // If the activity isn't currently running, just leave the new
4341 // configuration and it will pick that up next time it starts.
4342 if (r.app == null || r.app.thread == null) {
4343 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4344 "Configuration doesn't matter not running " + r);
4345 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004346 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004347 return true;
4348 }
4349
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004350 // Figure out how to handle the changes between the configurations.
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004351 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4352 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
4353 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07004354 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004355 + ", newConfig=" + newConfig);
4356 }
Dianne Hackborne6676352011-06-01 16:51:20 -07004357 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004358 // Aha, the activity isn't handling the change, so DIE DIE DIE.
4359 r.configChangeFlags |= changes;
4360 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004361 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004362 if (r.app == null || r.app.thread == null) {
4363 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4364 "Switch is destroying non-running " + r);
Dianne Hackborn28695e02011-11-02 21:59:51 -07004365 destroyActivityLocked(r, true, false, "config");
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004366 } else if (r.state == ActivityState.PAUSING) {
4367 // A little annoying: we are waiting for this activity to
4368 // finish pausing. Let's not do anything now, but just
4369 // flag that it needs to be restarted when done pausing.
4370 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4371 "Switch is skipping already pausing " + r);
4372 r.configDestroy = true;
4373 return true;
4374 } else if (r.state == ActivityState.RESUMED) {
4375 // Try to optimize this case: the configuration is changing
4376 // and we need to restart the top, resumed activity.
4377 // Instead of doing the normal handshaking, just say
4378 // "restart!".
4379 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4380 "Switch is restarting resumed " + r);
4381 relaunchActivityLocked(r, r.configChangeFlags, true);
4382 r.configChangeFlags = 0;
4383 } else {
4384 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4385 "Switch is restarting non-resumed " + r);
4386 relaunchActivityLocked(r, r.configChangeFlags, false);
4387 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004388 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004389
4390 // All done... tell the caller we weren't able to keep this
4391 // activity around.
4392 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004393 }
4394
4395 // Default case: the activity can handle this new configuration, so
4396 // hand it over. Note that we don't need to give it the new
4397 // configuration, since we always send configuration changes to all
4398 // process when they happen so it can just use whatever configuration
4399 // it last got.
4400 if (r.app != null && r.app.thread != null) {
4401 try {
4402 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004403 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004404 } catch (RemoteException e) {
4405 // If process died, whatever.
4406 }
4407 }
4408 r.stopFreezingScreenLocked(false);
4409
4410 return true;
4411 }
4412
4413 private final boolean relaunchActivityLocked(ActivityRecord r,
4414 int changes, boolean andResume) {
4415 List<ResultInfo> results = null;
4416 List<Intent> newIntents = null;
4417 if (andResume) {
4418 results = r.results;
4419 newIntents = r.newIntents;
4420 }
4421 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4422 + " with results=" + results + " newIntents=" + newIntents
4423 + " andResume=" + andResume);
4424 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
4425 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
4426 r.task.taskId, r.shortComponentName);
4427
4428 r.startFreezingScreenLocked(r.app, 0);
4429
4430 try {
4431 if (DEBUG_SWITCH) Slog.i(TAG, "Switch is restarting resumed " + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004432 r.forceNewConfig = false;
Dianne Hackbornbe707852011-11-11 14:32:10 -08004433 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004434 changes, !andResume, new Configuration(mService.mConfiguration));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004435 // Note: don't need to call pauseIfSleepingLocked() here, because
4436 // the caller will only pass in 'andResume' if this activity is
4437 // currently resumed, which implies we aren't sleeping.
4438 } catch (RemoteException e) {
4439 return false;
4440 }
4441
4442 if (andResume) {
4443 r.results = null;
4444 r.newIntents = null;
4445 if (mMainStack) {
4446 mService.reportResumedActivityLocked(r);
4447 }
4448 }
4449
4450 return true;
4451 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004452
4453 public void dismissKeyguardOnNextActivityLocked() {
4454 mDismissKeyguardOnNextActivity = true;
4455 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004456}