blob: 24bab99a33987d0874ae7441469f935efa85466a [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)
1381 && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
1382 // Make sure we have executed any pending transitions, since there
1383 // should be nothing left to do at this point.
1384 mService.mWindowManager.executeAppTransition();
1385 mNoAnimActivities.clear();
1386 return false;
1387 }
1388
1389 // The activity may be waiting for stop, but that is no longer
1390 // appropriate for it.
1391 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001392 mGoingToSleepActivities.remove(next);
1393 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001394 mWaitingVisibleActivities.remove(next);
1395
1396 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1397
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001398 // If we are currently pausing an activity, then don't do anything
1399 // until that is done.
1400 if (mPausingActivity != null) {
1401 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
1402 return false;
1403 }
1404
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001405 // Okay we are now going to start a switch, to 'next'. We may first
1406 // have to pause the current activity, but this is an important point
1407 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001408 // XXX "App Redirected" dialog is getting too many false positives
1409 // at this point, so turn off for now.
1410 if (false) {
1411 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1412 long now = SystemClock.uptimeMillis();
1413 final boolean inTime = mLastStartedActivity.startTime != 0
1414 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1415 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1416 final int nextUid = next.info.applicationInfo.uid;
1417 if (inTime && lastUid != nextUid
1418 && lastUid != next.launchedFromUid
1419 && mService.checkPermission(
1420 android.Manifest.permission.STOP_APP_SWITCHES,
1421 -1, next.launchedFromUid)
1422 != PackageManager.PERMISSION_GRANTED) {
1423 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1424 } else {
1425 next.startTime = now;
1426 mLastStartedActivity = next;
1427 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001428 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001429 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001430 mLastStartedActivity = next;
1431 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001432 }
1433
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001434 // We need to start pausing the current activity so the top one
1435 // can be resumed...
1436 if (mResumedActivity != null) {
1437 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
1438 startPausingLocked(userLeaving, false);
1439 return true;
1440 }
1441
1442 if (prev != null && prev != next) {
1443 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1444 prev.waitingVisible = true;
1445 mWaitingVisibleActivities.add(prev);
1446 if (DEBUG_SWITCH) Slog.v(
1447 TAG, "Resuming top, waiting visible to hide: " + prev);
1448 } else {
1449 // The next activity is already visible, so hide the previous
1450 // activity's windows right now so we can show the new one ASAP.
1451 // We only do this if the previous is finishing, which should mean
1452 // it is on top of the one being resumed so hiding it quickly
1453 // is good. Otherwise, we want to do the normal route of allowing
1454 // the resumed activity to be shown so we can decide if the
1455 // previous should actually be hidden depending on whether the
1456 // new one is found to be full-screen or not.
1457 if (prev.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001458 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001459 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1460 + prev + ", waitingVisible="
1461 + (prev != null ? prev.waitingVisible : null)
1462 + ", nowVisible=" + next.nowVisible);
1463 } else {
1464 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1465 + prev + ", waitingVisible="
1466 + (prev != null ? prev.waitingVisible : null)
1467 + ", nowVisible=" + next.nowVisible);
1468 }
1469 }
1470 }
1471
Dianne Hackborne7f97212011-02-24 14:40:20 -08001472 // Launching this app's activity, make sure the app is no longer
1473 // considered stopped.
1474 try {
1475 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001476 next.packageName, false, next.userId); /* TODO: Verify if correct userid */
Dianne Hackborne7f97212011-02-24 14:40:20 -08001477 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001478 } catch (IllegalArgumentException e) {
1479 Slog.w(TAG, "Failed trying to unstop package "
1480 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001481 }
1482
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001483 // We are starting up the next activity, so tell the window manager
1484 // that the previous one will be hidden soon. This way it can know
1485 // to ignore it when computing the desired screen orientation.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001486 boolean noAnim = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001487 if (prev != null) {
1488 if (prev.finishing) {
1489 if (DEBUG_TRANSITION) Slog.v(TAG,
1490 "Prepare close transition: prev=" + prev);
1491 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001492 mService.mWindowManager.prepareAppTransition(
1493 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001494 } else {
1495 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1496 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001497 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001498 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001499 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1500 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001501 } else {
1502 if (DEBUG_TRANSITION) Slog.v(TAG,
1503 "Prepare open transition: prev=" + prev);
1504 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001505 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001506 mService.mWindowManager.prepareAppTransition(
1507 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001508 } else {
1509 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1510 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001511 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001512 }
1513 }
1514 if (false) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001515 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1516 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001517 }
1518 } else if (mHistory.size() > 1) {
1519 if (DEBUG_TRANSITION) Slog.v(TAG,
1520 "Prepare open transition: no previous");
1521 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001522 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001523 mService.mWindowManager.prepareAppTransition(
1524 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001525 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001526 mService.mWindowManager.prepareAppTransition(
1527 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001528 }
1529 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001530 if (!noAnim) {
1531 next.applyOptionsLocked();
1532 } else {
1533 next.clearOptionsLocked();
1534 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001535
1536 if (next.app != null && next.app.thread != null) {
1537 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1538
1539 // This activity is now becoming visible.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001540 mService.mWindowManager.setAppVisibility(next.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001541
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001542 // schedule launch ticks to collect information about slow apps.
1543 next.startLaunchTickingLocked();
1544
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001545 ActivityRecord lastResumedActivity = mResumedActivity;
1546 ActivityState lastState = next.state;
1547
1548 mService.updateCpuStats();
1549
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001550 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001551 next.state = ActivityState.RESUMED;
1552 mResumedActivity = next;
1553 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001554 if (mMainStack) {
1555 mService.addRecentTaskLocked(next.task);
1556 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001557 mService.updateLruProcessLocked(next.app, true, true);
1558 updateLRUListLocked(next);
1559
1560 // Have the window manager re-evaluate the orientation of
1561 // the screen based on the new activity order.
1562 boolean updated = false;
1563 if (mMainStack) {
1564 synchronized (mService) {
1565 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1566 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001567 next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001568 if (config != null) {
1569 next.frozenBeforeDestroy = true;
1570 }
Dianne Hackborn813075a62011-11-14 17:45:19 -08001571 updated = mService.updateConfigurationLocked(config, next, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001572 }
1573 }
1574 if (!updated) {
1575 // The configuration update wasn't able to keep the existing
1576 // instance of the activity, and instead started a new one.
1577 // We should be all done, but let's just make sure our activity
1578 // is still at the top and schedule another run if something
1579 // weird happened.
1580 ActivityRecord nextNext = topRunningActivityLocked(null);
1581 if (DEBUG_SWITCH) Slog.i(TAG,
1582 "Activity config changed during resume: " + next
1583 + ", new next: " + nextNext);
1584 if (nextNext != next) {
1585 // Do over!
1586 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1587 }
1588 if (mMainStack) {
1589 mService.setFocusedActivityLocked(next);
1590 }
1591 ensureActivitiesVisibleLocked(null, 0);
1592 mService.mWindowManager.executeAppTransition();
1593 mNoAnimActivities.clear();
1594 return true;
1595 }
1596
1597 try {
1598 // Deliver all pending results.
1599 ArrayList a = next.results;
1600 if (a != null) {
1601 final int N = a.size();
1602 if (!next.finishing && N > 0) {
1603 if (DEBUG_RESULTS) Slog.v(
1604 TAG, "Delivering results to " + next
1605 + ": " + a);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001606 next.app.thread.scheduleSendResult(next.appToken, a);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001607 }
1608 }
1609
1610 if (next.newIntents != null) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001611 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001612 }
1613
1614 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
1615 System.identityHashCode(next),
1616 next.task.taskId, next.shortComponentName);
1617
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001618 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001619 showAskCompatModeDialogLocked(next);
Dianne Hackborn905577f2011-09-07 18:31:28 -07001620 next.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001621 next.app.thread.scheduleResumeActivity(next.appToken,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001622 mService.isNextTransitionForward());
1623
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001624 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001625
1626 } catch (Exception e) {
1627 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001628 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1629 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001630 next.state = lastState;
1631 mResumedActivity = lastResumedActivity;
1632 Slog.i(TAG, "Restarting because process died: " + next);
1633 if (!next.hasBeenLaunched) {
1634 next.hasBeenLaunched = true;
1635 } else {
1636 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1637 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001638 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001639 mService.compatibilityInfoForPackageLocked(
1640 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001641 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001642 next.labelRes, next.icon, next.windowFlags,
1643 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001644 }
1645 }
1646 startSpecificActivityLocked(next, true, false);
1647 return true;
1648 }
1649
1650 // From this point on, if something goes wrong there is no way
1651 // to recover the activity.
1652 try {
1653 next.visible = true;
1654 completeResumeLocked(next);
1655 } catch (Exception e) {
1656 // If any exception gets thrown, toss away this
1657 // activity and try the next one.
1658 Slog.w(TAG, "Exception thrown during resume of " + next, e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001659 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001660 "resume-exception");
1661 return true;
1662 }
1663
1664 // Didn't need to use the icicle, and it is now out of date.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001665 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Resumed activity; didn't need icicle of: " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001666 next.icicle = null;
1667 next.haveState = false;
1668 next.stopped = false;
1669
1670 } else {
1671 // Whoops, need to restart this activity!
1672 if (!next.hasBeenLaunched) {
1673 next.hasBeenLaunched = true;
1674 } else {
1675 if (SHOW_APP_STARTING_PREVIEW) {
1676 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001677 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001678 mService.compatibilityInfoForPackageLocked(
1679 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001680 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001681 next.labelRes, next.icon, next.windowFlags,
1682 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001683 }
1684 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1685 }
1686 startSpecificActivityLocked(next, true, true);
1687 }
1688
1689 return true;
1690 }
1691
1692 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001693 boolean doResume, boolean keepCurTransition, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001694 final int NH = mHistory.size();
1695
1696 int addPos = -1;
1697
1698 if (!newTask) {
1699 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001700 boolean startIt = true;
1701 for (int i = NH-1; i >= 0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001702 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001703 if (p.finishing) {
1704 continue;
1705 }
1706 if (p.task == r.task) {
1707 // Here it is! Now, if this is not yet visible to the
1708 // user, then just add it without starting; it will
1709 // get started when the user navigates back to it.
1710 addPos = i+1;
1711 if (!startIt) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001712 if (DEBUG_ADD_REMOVE) {
1713 RuntimeException here = new RuntimeException("here");
1714 here.fillInStackTrace();
1715 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos,
1716 here);
1717 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001718 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001719 r.putInHistory();
Dianne Hackbornbe707852011-11-11 14:32:10 -08001720 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001721 r.info.screenOrientation, r.fullscreen);
1722 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001723 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001724 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001725 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001726 return;
1727 }
1728 break;
1729 }
1730 if (p.fullscreen) {
1731 startIt = false;
1732 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001733 }
1734 }
1735
1736 // Place a new activity at top of stack, so it is next to interact
1737 // with the user.
1738 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001739 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001740 }
1741
1742 // If we are not placing the new activity frontmost, we do not want
1743 // to deliver the onUserLeaving callback to the actual frontmost
1744 // activity
1745 if (addPos < NH) {
1746 mUserLeaving = false;
1747 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1748 }
1749
1750 // Slot the activity into the history stack and proceed
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001751 if (DEBUG_ADD_REMOVE) {
1752 RuntimeException here = new RuntimeException("here");
1753 here.fillInStackTrace();
1754 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos, here);
1755 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001756 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001757 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001758 r.frontOfTask = newTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001759 if (NH > 0) {
1760 // We want to show the starting preview window if we are
1761 // switching to a new task, or the next activity's process is
1762 // not currently running.
1763 boolean showStartingIcon = newTask;
1764 ProcessRecord proc = r.app;
1765 if (proc == null) {
1766 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1767 }
1768 if (proc == null || proc.thread == null) {
1769 showStartingIcon = true;
1770 }
1771 if (DEBUG_TRANSITION) Slog.v(TAG,
1772 "Prepare open transition: starting " + r);
1773 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001774 mService.mWindowManager.prepareAppTransition(
1775 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001776 mNoAnimActivities.add(r);
1777 } else if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
1778 mService.mWindowManager.prepareAppTransition(
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001779 WindowManagerPolicy.TRANSIT_TASK_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001780 mNoAnimActivities.remove(r);
1781 } else {
1782 mService.mWindowManager.prepareAppTransition(newTask
1783 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001784 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001785 mNoAnimActivities.remove(r);
1786 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001787 r.updateOptionsLocked(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001788 mService.mWindowManager.addAppToken(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001789 addPos, r.appToken, r.task.taskId, r.info.screenOrientation, r.fullscreen);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001790 boolean doShow = true;
1791 if (newTask) {
1792 // Even though this activity is starting fresh, we still need
1793 // to reset it to make sure we apply affinities to move any
1794 // existing activities from other tasks in to it.
1795 // If the caller has requested that the target task be
1796 // reset, then do so.
1797 if ((r.intent.getFlags()
1798 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1799 resetTaskIfNeededLocked(r, r);
1800 doShow = topRunningNonDelayedActivityLocked(null) == r;
1801 }
1802 }
1803 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1804 // Figure out if we are transitioning from another activity that is
1805 // "has the same starting icon" as the next one. This allows the
1806 // window manager to keep the previous window it had previously
1807 // created, if it still had one.
1808 ActivityRecord prev = mResumedActivity;
1809 if (prev != null) {
1810 // We don't want to reuse the previous starting preview if:
1811 // (1) The current activity is in a different task.
1812 if (prev.task != r.task) prev = null;
1813 // (2) The current activity is already displayed.
1814 else if (prev.nowVisible) prev = null;
1815 }
1816 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001817 r.appToken, r.packageName, r.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001818 mService.compatibilityInfoForPackageLocked(
1819 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001820 r.labelRes, r.icon, r.windowFlags,
1821 prev != null ? prev.appToken : null, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001822 }
1823 } else {
1824 // If this is the first activity, don't do any fancy animations,
1825 // because there is nothing for it to animate on top of.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001826 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001827 r.info.screenOrientation, r.fullscreen);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001828 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001829 }
1830 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001831 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001832 }
1833
1834 if (doResume) {
1835 resumeTopActivityLocked(null);
1836 }
1837 }
1838
Dianne Hackbornbe707852011-11-11 14:32:10 -08001839 final void validateAppTokensLocked() {
1840 mValidateAppTokens.clear();
1841 mValidateAppTokens.ensureCapacity(mHistory.size());
1842 for (int i=0; i<mHistory.size(); i++) {
1843 mValidateAppTokens.add(mHistory.get(i).appToken);
1844 }
1845 mService.mWindowManager.validateAppTokens(mValidateAppTokens);
1846 }
1847
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001848 /**
1849 * Perform a reset of the given task, if needed as part of launching it.
1850 * Returns the new HistoryRecord at the top of the task.
1851 */
1852 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1853 ActivityRecord newActivity) {
1854 boolean forceReset = (newActivity.info.flags
1855 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001856 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1857 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001858 if ((newActivity.info.flags
1859 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1860 forceReset = true;
1861 }
1862 }
1863
1864 final TaskRecord task = taskTop.task;
1865
1866 // We are going to move through the history list so that we can look
1867 // at each activity 'target' with 'below' either the interesting
1868 // activity immediately below it in the stack or null.
1869 ActivityRecord target = null;
1870 int targetI = 0;
1871 int taskTopI = -1;
1872 int replyChainEnd = -1;
1873 int lastReparentPos = -1;
1874 for (int i=mHistory.size()-1; i>=-1; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001875 ActivityRecord below = i >= 0 ? mHistory.get(i) : null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001876
1877 if (below != null && below.finishing) {
1878 continue;
1879 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001880 // Don't check any lower in the stack if we're crossing a user boundary.
1881 if (below != null && below.userId != taskTop.userId) {
1882 break;
1883 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001884 if (target == null) {
1885 target = below;
1886 targetI = i;
1887 // If we were in the middle of a reply chain before this
1888 // task, it doesn't appear like the root of the chain wants
1889 // anything interesting, so drop it.
1890 replyChainEnd = -1;
1891 continue;
1892 }
1893
1894 final int flags = target.info.flags;
1895
1896 final boolean finishOnTaskLaunch =
1897 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1898 final boolean allowTaskReparenting =
1899 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1900
1901 if (target.task == task) {
1902 // We are inside of the task being reset... we'll either
1903 // finish this activity, push it out for another task,
1904 // or leave it as-is. We only do this
1905 // for activities that are not the root of the task (since
1906 // if we finish the root, we may no longer have the task!).
1907 if (taskTopI < 0) {
1908 taskTopI = targetI;
1909 }
1910 if (below != null && below.task == task) {
1911 final boolean clearWhenTaskReset =
1912 (target.intent.getFlags()
1913 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
1914 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
1915 // If this activity is sending a reply to a previous
1916 // activity, we can't do anything with it now until
1917 // we reach the start of the reply chain.
1918 // XXX note that we are assuming the result is always
1919 // to the previous activity, which is almost always
1920 // the case but we really shouldn't count on.
1921 if (replyChainEnd < 0) {
1922 replyChainEnd = targetI;
1923 }
1924 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
1925 && target.taskAffinity != null
1926 && !target.taskAffinity.equals(task.affinity)) {
1927 // If this activity has an affinity for another
1928 // task, then we need to move it out of here. We will
1929 // move it as far out of the way as possible, to the
1930 // bottom of the activity stack. This also keeps it
1931 // correctly ordered with any activities we previously
1932 // moved.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001933 ActivityRecord p = mHistory.get(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001934 if (target.taskAffinity != null
1935 && target.taskAffinity.equals(p.task.affinity)) {
1936 // If the activity currently at the bottom has the
1937 // same task affinity as the one we are moving,
1938 // then merge it into the same task.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001939 target.setTask(p.task, p.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001940 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1941 + " out to bottom task " + p.task);
1942 } else {
1943 mService.mCurTask++;
1944 if (mService.mCurTask <= 0) {
1945 mService.mCurTask = 1;
1946 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001947 target.setTask(new TaskRecord(mService.mCurTask, target.info, null),
1948 null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001949 target.task.affinityIntent = target.intent;
1950 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1951 + " out to new task " + target.task);
1952 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001953 mService.mWindowManager.setAppGroupId(target.appToken, task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001954 if (replyChainEnd < 0) {
1955 replyChainEnd = targetI;
1956 }
1957 int dstPos = 0;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001958 ThumbnailHolder curThumbHolder = target.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001959 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001960 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001961 if (p.finishing) {
1962 continue;
1963 }
1964 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
1965 + " out to target's task " + target.task);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001966 p.setTask(target.task, curThumbHolder, false);
1967 curThumbHolder = p.thumbHolder;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001968 if (DEBUG_ADD_REMOVE) {
1969 RuntimeException here = new RuntimeException("here");
1970 here.fillInStackTrace();
1971 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
1972 + dstPos, here);
1973 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001974 mHistory.remove(srcPos);
1975 mHistory.add(dstPos, p);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001976 mService.mWindowManager.moveAppToken(dstPos, p.appToken);
1977 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001978 dstPos++;
1979 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001980 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001981 }
1982 i++;
1983 }
1984 if (taskTop == p) {
1985 taskTop = below;
1986 }
1987 if (taskTopI == replyChainEnd) {
1988 taskTopI = -1;
1989 }
1990 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001991 } else if (forceReset || finishOnTaskLaunch
1992 || clearWhenTaskReset) {
1993 // If the activity should just be removed -- either
1994 // because it asks for it, or the task should be
1995 // cleared -- then finish it and anything that is
1996 // part of its reply chain.
1997 if (clearWhenTaskReset) {
1998 // In this case, we want to finish this activity
1999 // and everything above it, so be sneaky and pretend
2000 // like these are all in the reply chain.
2001 replyChainEnd = targetI+1;
2002 while (replyChainEnd < mHistory.size() &&
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002003 (mHistory.get(
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002004 replyChainEnd)).task == task) {
2005 replyChainEnd++;
2006 }
2007 replyChainEnd--;
2008 } else if (replyChainEnd < 0) {
2009 replyChainEnd = targetI;
2010 }
2011 ActivityRecord p = null;
2012 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002013 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002014 if (p.finishing) {
2015 continue;
2016 }
2017 if (finishActivityLocked(p, srcPos,
2018 Activity.RESULT_CANCELED, null, "reset")) {
2019 replyChainEnd--;
2020 srcPos--;
2021 }
2022 }
2023 if (taskTop == p) {
2024 taskTop = below;
2025 }
2026 if (taskTopI == replyChainEnd) {
2027 taskTopI = -1;
2028 }
2029 replyChainEnd = -1;
2030 } else {
2031 // If we were in the middle of a chain, well the
2032 // activity that started it all doesn't want anything
2033 // special, so leave it all as-is.
2034 replyChainEnd = -1;
2035 }
2036 } else {
2037 // Reached the bottom of the task -- any reply chain
2038 // should be left as-is.
2039 replyChainEnd = -1;
2040 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002041
2042 } else if (target.resultTo != null && (below == null
2043 || below.task == target.task)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002044 // If this activity is sending a reply to a previous
2045 // activity, we can't do anything with it now until
2046 // we reach the start of the reply chain.
2047 // XXX note that we are assuming the result is always
2048 // to the previous activity, which is almost always
2049 // the case but we really shouldn't count on.
2050 if (replyChainEnd < 0) {
2051 replyChainEnd = targetI;
2052 }
2053
2054 } else if (taskTopI >= 0 && allowTaskReparenting
2055 && task.affinity != null
2056 && task.affinity.equals(target.taskAffinity)) {
2057 // We are inside of another task... if this activity has
2058 // an affinity for our task, then either remove it if we are
2059 // clearing or move it over to our task. Note that
2060 // we currently punt on the case where we are resetting a
2061 // task that is not at the top but who has activities above
2062 // with an affinity to it... this is really not a normal
2063 // case, and we will need to later pull that task to the front
2064 // and usually at that point we will do the reset and pick
2065 // up those remaining activities. (This only happens if
2066 // someone starts an activity in a new task from an activity
2067 // in a task that is not currently on top.)
2068 if (forceReset || finishOnTaskLaunch) {
2069 if (replyChainEnd < 0) {
2070 replyChainEnd = targetI;
2071 }
2072 ActivityRecord p = null;
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002073 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index "
2074 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002075 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002076 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002077 if (p.finishing) {
2078 continue;
2079 }
2080 if (finishActivityLocked(p, srcPos,
2081 Activity.RESULT_CANCELED, null, "reset")) {
2082 taskTopI--;
2083 lastReparentPos--;
2084 replyChainEnd--;
2085 srcPos--;
2086 }
2087 }
2088 replyChainEnd = -1;
2089 } else {
2090 if (replyChainEnd < 0) {
2091 replyChainEnd = targetI;
2092 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002093 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting task at index "
2094 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002095 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002096 ActivityRecord p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002097 if (p.finishing) {
2098 continue;
2099 }
2100 if (lastReparentPos < 0) {
2101 lastReparentPos = taskTopI;
2102 taskTop = p;
2103 } else {
2104 lastReparentPos--;
2105 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002106 if (DEBUG_ADD_REMOVE) {
2107 RuntimeException here = new RuntimeException("here");
2108 here.fillInStackTrace();
2109 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2110 + lastReparentPos, here);
2111 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002112 mHistory.remove(srcPos);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002113 p.setTask(task, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002114 mHistory.add(lastReparentPos, p);
2115 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002116 + " from " + srcPos + " to " + lastReparentPos
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002117 + " in to resetting task " + task);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002118 mService.mWindowManager.moveAppToken(lastReparentPos, p.appToken);
2119 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002120 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002121 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002122 }
2123 }
2124 replyChainEnd = -1;
2125
2126 // Now we've moved it in to place... but what if this is
2127 // a singleTop activity and we have put it on top of another
2128 // instance of the same activity? Then we drop the instance
2129 // below so it remains singleTop.
2130 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2131 for (int j=lastReparentPos-1; j>=0; j--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002132 ActivityRecord p = mHistory.get(j);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002133 if (p.finishing) {
2134 continue;
2135 }
2136 if (p.intent.getComponent().equals(target.intent.getComponent())) {
2137 if (finishActivityLocked(p, j,
2138 Activity.RESULT_CANCELED, null, "replace")) {
2139 taskTopI--;
2140 lastReparentPos--;
2141 }
2142 }
2143 }
2144 }
2145 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002146
2147 } else if (below != null && below.task != target.task) {
2148 // We hit the botton of a task; the reply chain can't
2149 // pass through it.
2150 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002151 }
2152
2153 target = below;
2154 targetI = i;
2155 }
2156
2157 return taskTop;
2158 }
2159
2160 /**
2161 * Perform clear operation as requested by
2162 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2163 * stack to the given task, then look for
2164 * an instance of that activity in the stack and, if found, finish all
2165 * activities on top of it and return the instance.
2166 *
2167 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002168 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002169 * or null if none was found.
2170 */
2171 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002172 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002173 int i = mHistory.size();
2174
2175 // First find the requested task.
2176 while (i > 0) {
2177 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002178 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002179 if (r.task.taskId == taskId) {
2180 i++;
2181 break;
2182 }
2183 }
2184
2185 // Now clear it.
2186 while (i > 0) {
2187 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002188 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002189 if (r.finishing) {
2190 continue;
2191 }
2192 if (r.task.taskId != taskId) {
2193 return null;
2194 }
2195 if (r.realActivity.equals(newR.realActivity)) {
2196 // Here it is! Now finish everything in front...
2197 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002198 while (i < (mHistory.size()-1)) {
2199 i++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002200 r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002201 if (r.task.taskId != taskId) {
2202 break;
2203 }
2204 if (r.finishing) {
2205 continue;
2206 }
2207 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2208 null, "clear")) {
2209 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002210 }
2211 }
2212
2213 // Finally, if this is a normal launch mode (that is, not
2214 // expecting onNewIntent()), then we will finish the current
2215 // instance of the activity so a new fresh one can be started.
2216 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2217 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
2218 if (!ret.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002219 int index = indexOfTokenLocked(ret.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002220 if (index >= 0) {
2221 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
2222 null, "clear");
2223 }
2224 return null;
2225 }
2226 }
2227
2228 return ret;
2229 }
2230 }
2231
2232 return null;
2233 }
2234
2235 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002236 * Completely remove all activities associated with an existing
2237 * task starting at a specified index.
2238 */
2239 private final void performClearTaskAtIndexLocked(int taskId, int i) {
Dianne Hackborneabd3282011-10-13 16:26:49 -07002240 while (i < mHistory.size()) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002241 ActivityRecord r = mHistory.get(i);
2242 if (r.task.taskId != taskId) {
2243 // Whoops hit the end.
2244 return;
2245 }
2246 if (r.finishing) {
2247 i++;
2248 continue;
2249 }
2250 if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2251 null, "clear")) {
2252 i++;
2253 }
2254 }
2255 }
2256
2257 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002258 * Completely remove all activities associated with an existing task.
2259 */
2260 private final void performClearTaskLocked(int taskId) {
2261 int i = mHistory.size();
2262
2263 // First find the requested task.
2264 while (i > 0) {
2265 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002266 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002267 if (r.task.taskId == taskId) {
2268 i++;
2269 break;
2270 }
2271 }
2272
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002273 // Now find the start and clear it.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002274 while (i > 0) {
2275 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002276 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002277 if (r.finishing) {
2278 continue;
2279 }
2280 if (r.task.taskId != taskId) {
2281 // We hit the bottom. Now finish it all...
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002282 performClearTaskAtIndexLocked(taskId, i+1);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002283 return;
2284 }
2285 }
2286 }
2287
2288 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002289 * Find the activity in the history stack within the given task. Returns
2290 * the index within the history at which it's found, or < 0 if not found.
2291 */
2292 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2293 int i = mHistory.size();
2294 while (i > 0) {
2295 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002296 ActivityRecord candidate = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002297 if (candidate.task.taskId != task) {
2298 break;
2299 }
2300 if (candidate.realActivity.equals(r.realActivity)) {
2301 return i;
2302 }
2303 }
2304
2305 return -1;
2306 }
2307
2308 /**
2309 * Reorder the history stack so that the activity at the given index is
2310 * brought to the front.
2311 */
2312 private final ActivityRecord moveActivityToFrontLocked(int where) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002313 ActivityRecord newTop = mHistory.remove(where);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002314 int top = mHistory.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002315 ActivityRecord oldTop = mHistory.get(top-1);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002316 if (DEBUG_ADD_REMOVE) {
2317 RuntimeException here = new RuntimeException("here");
2318 here.fillInStackTrace();
2319 Slog.i(TAG, "Removing and adding activity " + newTop + " to stack at "
2320 + top, here);
2321 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002322 mHistory.add(top, newTop);
2323 oldTop.frontOfTask = false;
2324 newTop.frontOfTask = true;
2325 return newTop;
2326 }
2327
2328 final int startActivityLocked(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002329 Intent intent, String resolvedType, ActivityInfo aInfo, IBinder resultTo,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002330 String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002331 int callingPid, int callingUid, int startFlags, Bundle options,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002332 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002333
Dianne Hackborna4972e92012-03-14 10:38:05 -07002334 int err = ActivityManager.START_SUCCESS;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002335
2336 ProcessRecord callerApp = null;
2337 if (caller != null) {
2338 callerApp = mService.getRecordForAppLocked(caller);
2339 if (callerApp != null) {
2340 callingPid = callerApp.pid;
2341 callingUid = callerApp.info.uid;
2342 } else {
2343 Slog.w(TAG, "Unable to find app for caller " + caller
2344 + " (pid=" + callingPid + ") when starting: "
2345 + intent.toString());
Dianne Hackborna4972e92012-03-14 10:38:05 -07002346 err = ActivityManager.START_PERMISSION_DENIED;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002347 }
2348 }
2349
Dianne Hackborna4972e92012-03-14 10:38:05 -07002350 if (err == ActivityManager.START_SUCCESS) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07002351 final int userId = aInfo != null ? UserId.getUserId(aInfo.applicationInfo.uid) : 0;
Dianne Hackborn21c241e2012-03-08 13:57:23 -08002352 Slog.i(TAG, "START {" + intent.toShortString(true, true, true, false)
Amith Yamasania4a54e22012-04-16 15:44:19 -07002353 + " u=" + userId + "} from pid " + (callerApp != null ? callerApp.pid : callingPid));
Dianne Hackbornefb58102010-10-14 16:47:34 -07002354 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002355
2356 ActivityRecord sourceRecord = null;
2357 ActivityRecord resultRecord = null;
2358 if (resultTo != null) {
2359 int index = indexOfTokenLocked(resultTo);
2360 if (DEBUG_RESULTS) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002361 TAG, "Will send result to " + resultTo + " (index " + index + ")");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002362 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002363 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002364 if (requestCode >= 0 && !sourceRecord.finishing) {
2365 resultRecord = sourceRecord;
2366 }
2367 }
2368 }
2369
2370 int launchFlags = intent.getFlags();
2371
2372 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2373 && sourceRecord != null) {
2374 // Transfer the result target from the source activity to the new
2375 // one being started, including any failures.
2376 if (requestCode >= 0) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002377 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002378 return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002379 }
2380 resultRecord = sourceRecord.resultTo;
2381 resultWho = sourceRecord.resultWho;
2382 requestCode = sourceRecord.requestCode;
2383 sourceRecord.resultTo = null;
2384 if (resultRecord != null) {
2385 resultRecord.removeResultsLocked(
2386 sourceRecord, resultWho, requestCode);
2387 }
2388 }
2389
Dianne Hackborna4972e92012-03-14 10:38:05 -07002390 if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002391 // We couldn't find a class that can handle the given Intent.
2392 // That's the end of that!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002393 err = ActivityManager.START_INTENT_NOT_RESOLVED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002394 }
2395
Dianne Hackborna4972e92012-03-14 10:38:05 -07002396 if (err == ActivityManager.START_SUCCESS && aInfo == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002397 // We couldn't find the specific class specified in the Intent.
2398 // Also the end of the line.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002399 err = ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002400 }
2401
Dianne Hackborna4972e92012-03-14 10:38:05 -07002402 if (err != ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002403 if (resultRecord != null) {
2404 sendActivityResultLocked(-1,
2405 resultRecord, resultWho, requestCode,
2406 Activity.RESULT_CANCELED, null);
2407 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002408 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002409 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002410 return err;
2411 }
2412
Jeff Sharkey35be7562012-04-18 19:16:15 -07002413 final int startAnyPerm = mService.checkPermission(
2414 START_ANY_ACTIVITY, callingPid, callingUid);
2415 final int componentPerm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002416 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Jeff Sharkey35be7562012-04-18 19:16:15 -07002417 if (startAnyPerm != PERMISSION_GRANTED && componentPerm != PERMISSION_GRANTED) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002418 if (resultRecord != null) {
2419 sendActivityResultLocked(-1,
2420 resultRecord, resultWho, requestCode,
2421 Activity.RESULT_CANCELED, null);
2422 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002423 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002424 String msg;
2425 if (!aInfo.exported) {
2426 msg = "Permission Denial: starting " + intent.toString()
2427 + " from " + callerApp + " (pid=" + callingPid
2428 + ", uid=" + callingUid + ")"
2429 + " not exported from uid " + aInfo.applicationInfo.uid;
2430 } else {
2431 msg = "Permission Denial: starting " + intent.toString()
2432 + " from " + callerApp + " (pid=" + callingPid
2433 + ", uid=" + callingUid + ")"
2434 + " requires " + aInfo.permission;
2435 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002436 Slog.w(TAG, msg);
2437 throw new SecurityException(msg);
2438 }
2439
2440 if (mMainStack) {
2441 if (mService.mController != null) {
2442 boolean abort = false;
2443 try {
2444 // The Intent we give to the watcher has the extra data
2445 // stripped off, since it can contain private information.
2446 Intent watchIntent = intent.cloneFilter();
2447 abort = !mService.mController.activityStarting(watchIntent,
2448 aInfo.applicationInfo.packageName);
2449 } catch (RemoteException e) {
2450 mService.mController = null;
2451 }
2452
2453 if (abort) {
2454 if (resultRecord != null) {
2455 sendActivityResultLocked(-1,
2456 resultRecord, resultWho, requestCode,
2457 Activity.RESULT_CANCELED, null);
2458 }
2459 // We pretend to the caller that it was really started, but
2460 // they will just get a cancel result.
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002461 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002462 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002463 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002464 }
2465 }
2466 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002467
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002468 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2469 intent, resolvedType, aInfo, mService.mConfiguration,
2470 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002471 if (outActivity != null) {
2472 outActivity[0] = r;
2473 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002474
2475 if (mMainStack) {
2476 if (mResumedActivity == null
2477 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2478 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2479 PendingActivityLaunch pal = new PendingActivityLaunch();
2480 pal.r = r;
2481 pal.sourceRecord = sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002482 pal.startFlags = startFlags;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002483 mService.mPendingActivityLaunches.add(pal);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002484 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002485 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002486 return ActivityManager.START_SWITCHES_CANCELED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002487 }
2488 }
2489
2490 if (mService.mDidAppSwitch) {
2491 // This is the second allowed switch since we stopped switches,
2492 // so now just generally allow switches. Use case: user presses
2493 // home (switches disabled, switch to home, mDidAppSwitch now true);
2494 // user taps a home icon (coming from home so allowed, we hit here
2495 // and now allow anyone to switch again).
2496 mService.mAppSwitchesAllowedTime = 0;
2497 } else {
2498 mService.mDidAppSwitch = true;
2499 }
2500
2501 mService.doPendingActivityLaunchesLocked(false);
2502 }
2503
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002504 err = startActivityUncheckedLocked(r, sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002505 startFlags, true, options);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002506 if (mDismissKeyguardOnNextActivity && mPausingActivity == null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002507 // Someone asked to have the keyguard dismissed on the next
2508 // activity start, but we are not actually doing an activity
2509 // switch... just dismiss the keyguard now, because we
2510 // probably want to see whatever is behind it.
2511 mDismissKeyguardOnNextActivity = false;
2512 mService.mWindowManager.dismissKeyguard();
2513 }
2514 return err;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002515 }
2516
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002517 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2518 if ((launchFlags &
2519 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2520 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2521 // Caller wants to appear on home activity, so before starting
2522 // their own activity we will bring home to the front.
2523 moveHomeToFrontLocked();
2524 }
2525 }
2526
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002527 final int startActivityUncheckedLocked(ActivityRecord r,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002528 ActivityRecord sourceRecord, int startFlags, boolean doResume,
2529 Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002530 final Intent intent = r.intent;
2531 final int callingUid = r.launchedFromUid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002532 final int userId = r.userId;
2533
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002534 int launchFlags = intent.getFlags();
2535
2536 // We'll invoke onUserLeaving before onPause only if the launching
2537 // activity did not explicitly state that this is an automated launch.
2538 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2539 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2540 "startActivity() => mUserLeaving=" + mUserLeaving);
2541
2542 // If the caller has asked not to resume at this point, we make note
2543 // of this in the record so that we can skip it when trying to find
2544 // the top running activity.
2545 if (!doResume) {
2546 r.delayedResume = true;
2547 }
2548
2549 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2550 != 0 ? r : null;
2551
2552 // If the onlyIfNeeded flag is set, then we can do this if the activity
2553 // being launched is the same as the one making the call... or, as
2554 // a special case, if we do not know the caller then we count the
2555 // current top activity as the caller.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002556 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002557 ActivityRecord checkedCaller = sourceRecord;
2558 if (checkedCaller == null) {
2559 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2560 }
2561 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2562 // Caller is not the same as launcher, so always needed.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002563 startFlags &= ~ActivityManager.START_FLAG_ONLY_IF_NEEDED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002564 }
2565 }
2566
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002567 if (sourceRecord == null) {
2568 // This activity is not being started from another... in this
2569 // case we -always- start a new task.
2570 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2571 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2572 + intent);
2573 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2574 }
2575 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2576 // The original activity who is starting us is running as a single
2577 // instance... this new activity it is starting must go on its
2578 // own task.
2579 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2580 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2581 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2582 // The activity being started is a single instance... it always
2583 // gets launched into its own task.
2584 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2585 }
2586
2587 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2588 // For whatever reason this activity is being launched into a new
2589 // task... yet the caller has requested a result back. Well, that
2590 // is pretty messed up, so instead immediately send back a cancel
2591 // and let the new task continue launched as normal without a
2592 // dependency on its originator.
2593 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2594 sendActivityResultLocked(-1,
2595 r.resultTo, r.resultWho, r.requestCode,
2596 Activity.RESULT_CANCELED, null);
2597 r.resultTo = null;
2598 }
2599
2600 boolean addingToTask = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002601 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002602 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2603 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2604 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2605 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2606 // If bring to front is requested, and no result is requested, and
2607 // we can find a task that was started with this same
2608 // component, then instead of launching bring that one to the front.
2609 if (r.resultTo == null) {
2610 // See if there is a task to bring to the front. If this is
2611 // a SINGLE_INSTANCE activity, there can be one and only one
2612 // instance of it in the history, and it is always in its own
2613 // unique task, so we do a special search.
2614 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2615 ? findTaskLocked(intent, r.info)
2616 : findActivityLocked(intent, r.info);
2617 if (taskTop != null) {
2618 if (taskTop.task.intent == null) {
2619 // This task was started because of movement of
2620 // the activity based on affinity... now that we
2621 // are actually launching it, we can assign the
2622 // base intent.
2623 taskTop.task.setIntent(intent, r.info);
2624 }
2625 // If the target task is not in the front, then we need
2626 // to bring it to the front... except... well, with
2627 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2628 // to have the same behavior as if a new instance was
2629 // being started, which means not bringing it to the front
2630 // if the caller is not itself in the front.
2631 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002632 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002633 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2634 boolean callerAtFront = sourceRecord == null
2635 || curTop.task == sourceRecord.task;
2636 if (callerAtFront) {
2637 // We really do want to push this one into the
2638 // user's face, right now.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002639 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002640 moveTaskToFrontLocked(taskTop.task, r, options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002641 }
2642 }
2643 // If the caller has requested that the target task be
2644 // reset, then do so.
2645 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2646 taskTop = resetTaskIfNeededLocked(taskTop, r);
2647 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002648 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002649 // We don't need to start a new activity, and
2650 // the client said not to do anything if that
2651 // is the case, so this is it! And for paranoia, make
2652 // sure we have correctly resumed the top activity.
2653 if (doResume) {
2654 resumeTopActivityLocked(null);
2655 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002656 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002657 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002658 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002659 if ((launchFlags &
2660 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2661 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2662 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002663 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002664 // not be too hard...
2665 reuseTask = taskTop.task;
2666 performClearTaskLocked(taskTop.task.taskId);
2667 reuseTask.setIntent(r.intent, r.info);
2668 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002669 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2670 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2671 // In this situation we want to remove all activities
2672 // from the task up to the one being started. In most
2673 // cases this means we are resetting the task to its
2674 // initial state.
2675 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002676 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002677 if (top != null) {
2678 if (top.frontOfTask) {
2679 // Activity aliases may mean we use different
2680 // intents for the top activity, so make sure
2681 // the task now has the identity of the new
2682 // intent.
2683 top.task.setIntent(r.intent, r.info);
2684 }
2685 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002686 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002687 } else {
2688 // A special case: we need to
2689 // start the activity because it is not currently
2690 // running, and the caller has asked to clear the
2691 // current task to have this activity at the top.
2692 addingToTask = true;
2693 // Now pretend like this activity is being started
2694 // by the top of its task, so it is put in the
2695 // right place.
2696 sourceRecord = taskTop;
2697 }
2698 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2699 // In this case the top activity on the task is the
2700 // same as the one being launched, so we take that
2701 // as a request to bring the task to the foreground.
2702 // If the top activity in the task is the root
2703 // activity, deliver this new intent to it if it
2704 // desires.
2705 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2706 && taskTop.realActivity.equals(r.realActivity)) {
2707 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2708 if (taskTop.frontOfTask) {
2709 taskTop.task.setIntent(r.intent, r.info);
2710 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002711 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002712 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2713 // In this case we are launching the root activity
2714 // of the task, but with a different intent. We
2715 // should start a new instance on top.
2716 addingToTask = true;
2717 sourceRecord = taskTop;
2718 }
2719 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2720 // In this case an activity is being launched in to an
2721 // existing task, without resetting that task. This
2722 // is typically the situation of launching an activity
2723 // from a notification or shortcut. We want to place
2724 // the new activity on top of the current task.
2725 addingToTask = true;
2726 sourceRecord = taskTop;
2727 } else if (!taskTop.task.rootWasReset) {
2728 // In this case we are launching in to an existing task
2729 // that has not yet been started from its front door.
2730 // The current task has been brought to the front.
2731 // Ideally, we'd probably like to place this new task
2732 // at the bottom of its stack, but that's a little hard
2733 // to do with the current organization of the code so
2734 // for now we'll just drop it.
2735 taskTop.task.setIntent(r.intent, r.info);
2736 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002737 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002738 // We didn't do anything... but it was needed (a.k.a., client
2739 // don't use that intent!) And for paranoia, make
2740 // sure we have correctly resumed the top activity.
2741 if (doResume) {
2742 resumeTopActivityLocked(null);
2743 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002744 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002745 return ActivityManager.START_TASK_TO_FRONT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002746 }
2747 }
2748 }
2749 }
2750
2751 //String uri = r.intent.toURI();
2752 //Intent intent2 = new Intent(uri);
2753 //Slog.i(TAG, "Given intent: " + r.intent);
2754 //Slog.i(TAG, "URI is: " + uri);
2755 //Slog.i(TAG, "To intent: " + intent2);
2756
2757 if (r.packageName != null) {
2758 // If the activity being launched is the same as the one currently
2759 // at the top, then we need to check if it should only be launched
2760 // once.
2761 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2762 if (top != null && r.resultTo == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002763 if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002764 if (top.app != null && top.app.thread != null) {
2765 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2766 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2767 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2768 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2769 // For paranoia, make sure we have correctly
2770 // resumed the top activity.
2771 if (doResume) {
2772 resumeTopActivityLocked(null);
2773 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002774 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002775 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002776 // We don't need to start a new activity, and
2777 // the client said not to do anything if that
2778 // is the case, so this is it!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002779 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002780 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002781 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002782 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002783 }
2784 }
2785 }
2786 }
2787
2788 } else {
2789 if (r.resultTo != null) {
2790 sendActivityResultLocked(-1,
2791 r.resultTo, r.resultWho, r.requestCode,
2792 Activity.RESULT_CANCELED, null);
2793 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002794 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002795 return ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002796 }
2797
2798 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002799 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002800
2801 // Should this be considered a new task?
2802 if (r.resultTo == null && !addingToTask
2803 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002804 if (reuseTask == null) {
2805 // todo: should do better management of integers.
2806 mService.mCurTask++;
2807 if (mService.mCurTask <= 0) {
2808 mService.mCurTask = 1;
2809 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002810 r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002811 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2812 + " in new task " + r.task);
2813 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002814 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002815 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002816 newTask = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002817 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002818
2819 } else if (sourceRecord != null) {
2820 if (!addingToTask &&
2821 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2822 // In this case, we are adding the activity to an existing
2823 // task, but the caller has asked to clear that task if the
2824 // activity is already running.
2825 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002826 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002827 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002828 if (top != null) {
2829 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002830 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002831 // For paranoia, make sure we have correctly
2832 // resumed the top activity.
2833 if (doResume) {
2834 resumeTopActivityLocked(null);
2835 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002836 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002837 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002838 }
2839 } else if (!addingToTask &&
2840 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2841 // In this case, we are launching an activity in our own task
2842 // that may already be running somewhere in the history, and
2843 // we want to shuffle it to the front of the stack if so.
2844 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2845 if (where >= 0) {
2846 ActivityRecord top = moveActivityToFrontLocked(where);
2847 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002848 top.updateOptionsLocked(options);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002849 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002850 if (doResume) {
2851 resumeTopActivityLocked(null);
2852 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002853 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002854 }
2855 }
2856 // An existing activity is starting this new activity, so we want
2857 // to keep the new one in the same task as the one that is starting
2858 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002859 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002860 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2861 + " in existing task " + r.task);
2862
2863 } else {
2864 // This not being started from an existing activity, and not part
2865 // of a new task... just put it in the top task, though these days
2866 // this case should never happen.
2867 final int N = mHistory.size();
2868 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002869 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002870 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002871 ? prev.task
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002872 : new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002873 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2874 + " in new guessed " + r.task);
2875 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002876
Dianne Hackborn39792d22010-08-19 18:01:52 -07002877 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002878 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002879
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002880 if (newTask) {
2881 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
2882 }
2883 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002884 startActivityLocked(r, newTask, doResume, keepCurTransition, options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002885 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002886 }
2887
Dianne Hackborna4972e92012-03-14 10:38:05 -07002888 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002889 String profileFile, ParcelFileDescriptor profileFd, int userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002890 // Collect information about the target of the Intent.
2891 ActivityInfo aInfo;
2892 try {
2893 ResolveInfo rInfo =
2894 AppGlobals.getPackageManager().resolveIntent(
2895 intent, resolvedType,
2896 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07002897 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002898 aInfo = rInfo != null ? rInfo.activityInfo : null;
2899 } catch (RemoteException e) {
2900 aInfo = null;
2901 }
2902
2903 if (aInfo != null) {
2904 // Store the found target back into the intent, because now that
2905 // we have it we never want to do this again. For example, if the
2906 // user navigates back to this point in the history, we should
2907 // always restart the exact same activity.
2908 intent.setComponent(new ComponentName(
2909 aInfo.applicationInfo.packageName, aInfo.name));
2910
2911 // Don't debug things in the system process
Dianne Hackborna4972e92012-03-14 10:38:05 -07002912 if ((startFlags&ActivityManager.START_FLAG_DEBUG) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002913 if (!aInfo.processName.equals("system")) {
2914 mService.setDebugApp(aInfo.processName, true, false);
2915 }
2916 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002917
Dianne Hackborna4972e92012-03-14 10:38:05 -07002918 if ((startFlags&ActivityManager.START_FLAG_OPENGL_TRACES) != 0) {
Siva Velusamy92a8b222012-03-09 16:24:04 -08002919 if (!aInfo.processName.equals("system")) {
2920 mService.setOpenGlTraceApp(aInfo.applicationInfo, aInfo.processName);
2921 }
2922 }
2923
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002924 if (profileFile != null) {
2925 if (!aInfo.processName.equals("system")) {
2926 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002927 profileFile, profileFd,
2928 (startFlags&ActivityManager.START_FLAG_AUTO_STOP_PROFILER) != 0);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002929 }
2930 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002931 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002932 return aInfo;
2933 }
2934
2935 final int startActivityMayWait(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002936 Intent intent, String resolvedType, IBinder resultTo,
2937 String resultWho, int requestCode, int startFlags, String profileFile,
2938 ParcelFileDescriptor profileFd, WaitResult outResult, Configuration config,
2939 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002940 // Refuse possible leaked file descriptors
2941 if (intent != null && intent.hasFileDescriptors()) {
2942 throw new IllegalArgumentException("File descriptors passed in Intent");
2943 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002944 boolean componentSpecified = intent.getComponent() != null;
2945
2946 // Don't modify the client's object!
2947 intent = new Intent(intent);
2948
2949 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002950 ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002951 profileFile, profileFd, userId);
Amith Yamasani95a6a962012-04-18 09:54:43 -07002952 if (aInfo != null && mService.isSingleton(aInfo.processName, aInfo.applicationInfo)) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07002953 userId = 0;
2954 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002955 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002956
2957 synchronized (mService) {
2958 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002959 if (callingUid >= 0) {
2960 callingPid = -1;
2961 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002962 callingPid = Binder.getCallingPid();
2963 callingUid = Binder.getCallingUid();
2964 } else {
2965 callingPid = callingUid = -1;
2966 }
2967
2968 mConfigWillChange = config != null
2969 && mService.mConfiguration.diff(config) != 0;
2970 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2971 "Starting activity when config will change = " + mConfigWillChange);
2972
2973 final long origId = Binder.clearCallingIdentity();
2974
2975 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07002976 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002977 // This may be a heavy-weight process! Check to see if we already
2978 // have another, different heavy-weight process running.
2979 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
2980 if (mService.mHeavyWeightProcess != null &&
2981 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
2982 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
2983 int realCallingPid = callingPid;
2984 int realCallingUid = callingUid;
2985 if (caller != null) {
2986 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
2987 if (callerApp != null) {
2988 realCallingPid = callerApp.pid;
2989 realCallingUid = callerApp.info.uid;
2990 } else {
2991 Slog.w(TAG, "Unable to find app for caller " + caller
2992 + " (pid=" + realCallingPid + ") when starting: "
2993 + intent.toString());
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002994 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002995 return ActivityManager.START_PERMISSION_DENIED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002996 }
2997 }
2998
2999 IIntentSender target = mService.getIntentSenderLocked(
Dianne Hackborna4972e92012-03-14 10:38:05 -07003000 ActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003001 realCallingUid, null, null, 0, new Intent[] { intent },
3002 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003003 | PendingIntent.FLAG_ONE_SHOT, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003004
3005 Intent newIntent = new Intent();
3006 if (requestCode >= 0) {
3007 // Caller is requesting a result.
3008 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
3009 }
3010 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
3011 new IntentSender(target));
3012 if (mService.mHeavyWeightProcess.activities.size() > 0) {
3013 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
3014 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
3015 hist.packageName);
3016 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
3017 hist.task.taskId);
3018 }
3019 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
3020 aInfo.packageName);
3021 newIntent.setFlags(intent.getFlags());
3022 newIntent.setClassName("android",
3023 HeavyWeightSwitcherActivity.class.getName());
3024 intent = newIntent;
3025 resolvedType = null;
3026 caller = null;
3027 callingUid = Binder.getCallingUid();
3028 callingPid = Binder.getCallingPid();
3029 componentSpecified = true;
3030 try {
3031 ResolveInfo rInfo =
3032 AppGlobals.getPackageManager().resolveIntent(
3033 intent, null,
3034 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07003035 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003036 aInfo = rInfo != null ? rInfo.activityInfo : null;
Amith Yamasani742a6712011-05-04 14:49:28 -07003037 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003038 } catch (RemoteException e) {
3039 aInfo = null;
3040 }
3041 }
3042 }
3043 }
3044
3045 int res = startActivityLocked(caller, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003046 aInfo, resultTo, resultWho, requestCode, callingPid, callingUid,
3047 startFlags, options, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003048
3049 if (mConfigWillChange && mMainStack) {
3050 // If the caller also wants to switch to a new configuration,
3051 // do so now. This allows a clean switch, as we are waiting
3052 // for the current activity to pause (so we will not destroy
3053 // it), and have not yet started the next activity.
3054 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
3055 "updateConfiguration()");
3056 mConfigWillChange = false;
3057 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3058 "Updating to new configuration after starting activity.");
Dianne Hackborn813075a62011-11-14 17:45:19 -08003059 mService.updateConfigurationLocked(config, null, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003060 }
3061
3062 Binder.restoreCallingIdentity(origId);
3063
3064 if (outResult != null) {
3065 outResult.result = res;
Dianne Hackborna4972e92012-03-14 10:38:05 -07003066 if (res == ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003067 mWaitingActivityLaunched.add(outResult);
3068 do {
3069 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003070 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003071 } catch (InterruptedException e) {
3072 }
3073 } while (!outResult.timeout && outResult.who == null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003074 } else if (res == ActivityManager.START_TASK_TO_FRONT) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003075 ActivityRecord r = this.topRunningActivityLocked(null);
3076 if (r.nowVisible) {
3077 outResult.timeout = false;
3078 outResult.who = new ComponentName(r.info.packageName, r.info.name);
3079 outResult.totalTime = 0;
3080 outResult.thisTime = 0;
3081 } else {
3082 outResult.thisTime = SystemClock.uptimeMillis();
3083 mWaitingActivityVisible.add(outResult);
3084 do {
3085 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003086 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003087 } catch (InterruptedException e) {
3088 }
3089 } while (!outResult.timeout && outResult.who == null);
3090 }
3091 }
3092 }
3093
3094 return res;
3095 }
3096 }
3097
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003098 final int startActivities(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003099 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
3100 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003101 if (intents == null) {
3102 throw new NullPointerException("intents is null");
3103 }
3104 if (resolvedTypes == null) {
3105 throw new NullPointerException("resolvedTypes is null");
3106 }
3107 if (intents.length != resolvedTypes.length) {
3108 throw new IllegalArgumentException("intents are length different than resolvedTypes");
3109 }
3110
3111 ActivityRecord[] outActivity = new ActivityRecord[1];
3112
3113 int callingPid;
3114 if (callingUid >= 0) {
3115 callingPid = -1;
3116 } else if (caller == null) {
3117 callingPid = Binder.getCallingPid();
3118 callingUid = Binder.getCallingUid();
3119 } else {
3120 callingPid = callingUid = -1;
3121 }
3122 final long origId = Binder.clearCallingIdentity();
3123 try {
3124 synchronized (mService) {
3125
3126 for (int i=0; i<intents.length; i++) {
3127 Intent intent = intents[i];
3128 if (intent == null) {
3129 continue;
3130 }
3131
3132 // Refuse possible leaked file descriptors
3133 if (intent != null && intent.hasFileDescriptors()) {
3134 throw new IllegalArgumentException("File descriptors passed in Intent");
3135 }
3136
3137 boolean componentSpecified = intent.getComponent() != null;
3138
3139 // Don't modify the client's object!
3140 intent = new Intent(intent);
3141
3142 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003143 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i],
Amith Yamasani483f3b02012-03-13 16:08:00 -07003144 0, null, null, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07003145 // TODO: New, check if this is correct
3146 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003147
3148 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
3149 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
3150 throw new IllegalArgumentException(
3151 "FLAG_CANT_SAVE_STATE not supported here");
3152 }
3153
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003154 Bundle theseOptions;
3155 if (options != null && i == intents.length-1) {
3156 theseOptions = options;
3157 } else {
3158 theseOptions = null;
3159 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003160 int res = startActivityLocked(caller, intent, resolvedTypes[i],
Dianne Hackborna4972e92012-03-14 10:38:05 -07003161 aInfo, resultTo, null, -1, callingPid, callingUid,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003162 0, theseOptions, componentSpecified, outActivity);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003163 if (res < 0) {
3164 return res;
3165 }
3166
Dianne Hackbornbe707852011-11-11 14:32:10 -08003167 resultTo = outActivity[0] != null ? outActivity[0].appToken : null;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003168 }
3169 }
3170 } finally {
3171 Binder.restoreCallingIdentity(origId);
3172 }
3173
Dianne Hackborna4972e92012-03-14 10:38:05 -07003174 return ActivityManager.START_SUCCESS;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003175 }
3176
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003177 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
3178 long thisTime, long totalTime) {
3179 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
3180 WaitResult w = mWaitingActivityLaunched.get(i);
3181 w.timeout = timeout;
3182 if (r != null) {
3183 w.who = new ComponentName(r.info.packageName, r.info.name);
3184 }
3185 w.thisTime = thisTime;
3186 w.totalTime = totalTime;
3187 }
3188 mService.notifyAll();
3189 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003190
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003191 void reportActivityVisibleLocked(ActivityRecord r) {
3192 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
3193 WaitResult w = mWaitingActivityVisible.get(i);
3194 w.timeout = false;
3195 if (r != null) {
3196 w.who = new ComponentName(r.info.packageName, r.info.name);
3197 }
3198 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
3199 w.thisTime = w.totalTime;
3200 }
3201 mService.notifyAll();
Dianne Hackborn90c52de2011-09-23 12:57:44 -07003202
3203 if (mDismissKeyguardOnNextActivity) {
3204 mDismissKeyguardOnNextActivity = false;
3205 mService.mWindowManager.dismissKeyguard();
3206 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003207 }
3208
3209 void sendActivityResultLocked(int callingUid, ActivityRecord r,
3210 String resultWho, int requestCode, int resultCode, Intent data) {
3211
3212 if (callingUid > 0) {
3213 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003214 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003215 }
3216
3217 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3218 + " : who=" + resultWho + " req=" + requestCode
3219 + " res=" + resultCode + " data=" + data);
3220 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3221 try {
3222 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3223 list.add(new ResultInfo(resultWho, requestCode,
3224 resultCode, data));
Dianne Hackbornbe707852011-11-11 14:32:10 -08003225 r.app.thread.scheduleSendResult(r.appToken, list);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003226 return;
3227 } catch (Exception e) {
3228 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3229 }
3230 }
3231
3232 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3233 }
3234
3235 private final void stopActivityLocked(ActivityRecord r) {
3236 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3237 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3238 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3239 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003240 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003241 "no-history");
3242 }
3243 } else if (r.app != null && r.app.thread != null) {
3244 if (mMainStack) {
3245 if (mService.mFocusedActivity == r) {
3246 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3247 }
3248 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003249 r.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003250 try {
3251 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003252 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3253 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003254 r.state = ActivityState.STOPPING;
3255 if (DEBUG_VISBILITY) Slog.v(
3256 TAG, "Stopping visible=" + r.visible + " for " + r);
3257 if (!r.visible) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003258 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003259 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003260 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003261 if (mService.isSleeping()) {
3262 r.setSleeping(true);
3263 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003264 Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG);
3265 msg.obj = r;
3266 mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003267 } catch (Exception e) {
3268 // Maybe just ignore exceptions here... if the process
3269 // has crashed, our death notification will clean things
3270 // up.
3271 Slog.w(TAG, "Exception thrown during pause", e);
3272 // Just in case, assume it to be stopped.
3273 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003274 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003275 r.state = ActivityState.STOPPED;
3276 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003277 destroyActivityLocked(r, true, false, "stop-except");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003278 }
3279 }
3280 }
3281 }
3282
3283 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3284 boolean remove) {
3285 int N = mStoppingActivities.size();
3286 if (N <= 0) return null;
3287
3288 ArrayList<ActivityRecord> stops = null;
3289
3290 final boolean nowVisible = mResumedActivity != null
3291 && mResumedActivity.nowVisible
3292 && !mResumedActivity.waitingVisible;
3293 for (int i=0; i<N; i++) {
3294 ActivityRecord s = mStoppingActivities.get(i);
3295 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3296 + nowVisible + " waitingVisible=" + s.waitingVisible
3297 + " finishing=" + s.finishing);
3298 if (s.waitingVisible && nowVisible) {
3299 mWaitingVisibleActivities.remove(s);
3300 s.waitingVisible = false;
3301 if (s.finishing) {
3302 // If this activity is finishing, it is sitting on top of
3303 // everyone else but we now know it is no longer needed...
3304 // so get rid of it. Otherwise, we need to go through the
3305 // normal flow and hide it once we determine that it is
3306 // hidden by the activities in front of it.
3307 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003308 mService.mWindowManager.setAppVisibility(s.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003309 }
3310 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003311 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003312 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3313 if (stops == null) {
3314 stops = new ArrayList<ActivityRecord>();
3315 }
3316 stops.add(s);
3317 mStoppingActivities.remove(i);
3318 N--;
3319 i--;
3320 }
3321 }
3322
3323 return stops;
3324 }
3325
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003326 final void scheduleIdleLocked() {
3327 Message msg = Message.obtain();
3328 msg.what = IDLE_NOW_MSG;
3329 mHandler.sendMessage(msg);
3330 }
3331
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003332 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003333 Configuration config) {
3334 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3335
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003336 ActivityRecord res = null;
3337
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003338 ArrayList<ActivityRecord> stops = null;
3339 ArrayList<ActivityRecord> finishes = null;
3340 ArrayList<ActivityRecord> thumbnails = null;
3341 int NS = 0;
3342 int NF = 0;
3343 int NT = 0;
3344 IApplicationThread sendThumbnail = null;
3345 boolean booting = false;
3346 boolean enableScreen = false;
3347
3348 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003349 ActivityRecord r = ActivityRecord.forToken(token);
3350 if (r != null) {
3351 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003352 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003353 }
3354
3355 // Get the activity record.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003356 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003357 if (index >= 0) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003358 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003359
3360 if (fromTimeout) {
3361 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3362 }
3363
3364 // This is a hack to semi-deal with a race condition
3365 // in the client where it can be constructed with a
3366 // newer configuration from when we asked it to launch.
3367 // We'll update with whatever configuration it now says
3368 // it used to launch.
3369 if (config != null) {
3370 r.configuration = config;
3371 }
3372
3373 // No longer need to keep the device awake.
3374 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3375 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3376 mLaunchingActivity.release();
3377 }
3378
3379 // We are now idle. If someone is waiting for a thumbnail from
3380 // us, we can now deliver.
3381 r.idle = true;
3382 mService.scheduleAppGcsLocked();
3383 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3384 sendThumbnail = r.app.thread;
3385 r.thumbnailNeeded = false;
3386 }
3387
3388 // If this activity is fullscreen, set up to hide those under it.
3389
3390 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3391 ensureActivitiesVisibleLocked(null, 0);
3392
3393 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3394 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003395 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003396 mService.mBooted = true;
3397 enableScreen = true;
3398 }
3399 }
3400
3401 } else if (fromTimeout) {
3402 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3403 }
3404
3405 // Atomically retrieve all of the other things to do.
3406 stops = processStoppingActivitiesLocked(true);
3407 NS = stops != null ? stops.size() : 0;
3408 if ((NF=mFinishingActivities.size()) > 0) {
3409 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3410 mFinishingActivities.clear();
3411 }
3412 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3413 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3414 mService.mCancelledThumbnails.clear();
3415 }
3416
3417 if (mMainStack) {
3418 booting = mService.mBooting;
3419 mService.mBooting = false;
3420 }
3421 }
3422
3423 int i;
3424
3425 // Send thumbnail if requested.
3426 if (sendThumbnail != null) {
3427 try {
3428 sendThumbnail.requestThumbnail(token);
3429 } catch (Exception e) {
3430 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3431 mService.sendPendingThumbnail(null, token, null, null, true);
3432 }
3433 }
3434
3435 // Stop any activities that are scheduled to do so but have been
3436 // waiting for the next one to start.
3437 for (i=0; i<NS; i++) {
3438 ActivityRecord r = (ActivityRecord)stops.get(i);
3439 synchronized (mService) {
3440 if (r.finishing) {
3441 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY);
3442 } else {
3443 stopActivityLocked(r);
3444 }
3445 }
3446 }
3447
3448 // Finish any activities that are scheduled to do so but have been
3449 // waiting for the next one to start.
3450 for (i=0; i<NF; i++) {
3451 ActivityRecord r = (ActivityRecord)finishes.get(i);
3452 synchronized (mService) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003453 destroyActivityLocked(r, true, false, "finish-idle");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003454 }
3455 }
3456
3457 // Report back to any thumbnail receivers.
3458 for (i=0; i<NT; i++) {
3459 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3460 mService.sendPendingThumbnail(r, null, null, null, true);
3461 }
3462
3463 if (booting) {
3464 mService.finishBooting();
3465 }
3466
3467 mService.trimApplications();
3468 //dump();
3469 //mWindowManager.dump();
3470
3471 if (enableScreen) {
3472 mService.enableScreenAfterBoot();
3473 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003474
3475 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003476 }
3477
3478 /**
3479 * @return Returns true if the activity is being finished, false if for
3480 * some reason it is being left as-is.
3481 */
3482 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
3483 Intent resultData, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003484 int index = indexOfTokenLocked(token);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003485 if (DEBUG_RESULTS) Slog.v(
3486 TAG, "Finishing activity @" + index + ": token=" + token
3487 + ", result=" + resultCode + ", data=" + resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003488 if (index < 0) {
3489 return false;
3490 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003491 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003492
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003493 finishActivityLocked(r, index, resultCode, resultData, reason);
3494 return true;
3495 }
3496
Dianne Hackborn5c607432012-02-28 14:44:19 -08003497 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
3498 // send the result
3499 ActivityRecord resultTo = r.resultTo;
3500 if (resultTo != null) {
3501 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3502 + " who=" + r.resultWho + " req=" + r.requestCode
3503 + " res=" + resultCode + " data=" + resultData);
3504 if (r.info.applicationInfo.uid > 0) {
3505 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3506 resultTo.packageName, resultData,
3507 resultTo.getUriPermissionsLocked());
3508 }
3509 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3510 resultData);
3511 r.resultTo = null;
3512 }
3513 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3514
3515 // Make sure this HistoryRecord is not holding on to other resources,
3516 // because clients have remote IPC references to this object so we
3517 // can't assume that will go away and want to avoid circular IPC refs.
3518 r.results = null;
3519 r.pendingResults = null;
3520 r.newIntents = null;
3521 r.icicle = null;
3522 }
3523
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003524 /**
3525 * @return Returns true if this activity has been removed from the history
3526 * list, or false if it is still in the list and will be removed later.
3527 */
3528 final boolean finishActivityLocked(ActivityRecord r, int index,
3529 int resultCode, Intent resultData, String reason) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003530 return finishActivityLocked(r, index, resultCode, resultData, reason, false);
3531 }
3532
3533 /**
3534 * @return Returns true if this activity has been removed from the history
3535 * list, or false if it is still in the list and will be removed later.
3536 */
3537 final boolean finishActivityLocked(ActivityRecord r, int index,
3538 int resultCode, Intent resultData, String reason, boolean immediate) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003539 if (r.finishing) {
3540 Slog.w(TAG, "Duplicate finish request for " + r);
3541 return false;
3542 }
3543
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003544 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003545 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3546 System.identityHashCode(r),
3547 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003548 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003549 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003550 if (next.task == r.task) {
3551 if (r.frontOfTask) {
3552 // The next activity is now the front of the task.
3553 next.frontOfTask = true;
3554 }
3555 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3556 // If the caller asked that this activity (and all above it)
3557 // be cleared when the task is reset, don't lose that information,
3558 // but propagate it up to the next activity.
3559 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3560 }
3561 }
3562 }
3563
3564 r.pauseKeyDispatchingLocked();
3565 if (mMainStack) {
3566 if (mService.mFocusedActivity == r) {
3567 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3568 }
3569 }
3570
Dianne Hackborn5c607432012-02-28 14:44:19 -08003571 finishActivityResultsLocked(r, resultCode, resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003572
3573 if (mService.mPendingThumbnails.size() > 0) {
3574 // There are clients waiting to receive thumbnails so, in case
3575 // this is an activity that someone is waiting for, add it
3576 // to the pending list so we can correctly update the clients.
3577 mService.mCancelledThumbnails.add(r);
3578 }
3579
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003580 if (immediate) {
3581 return finishCurrentActivityLocked(r, index,
3582 FINISH_IMMEDIATELY) == null;
3583 } else if (mResumedActivity == r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003584 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003585 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003586 if (DEBUG_TRANSITION) Slog.v(TAG,
3587 "Prepare close transition: finishing " + r);
3588 mService.mWindowManager.prepareAppTransition(endTask
3589 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003590 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003591
3592 // Tell window manager to prepare for this one to be removed.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003593 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003594
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003595 if (mPausingActivity == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003596 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3597 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3598 startPausingLocked(false, false);
3599 }
3600
3601 } else if (r.state != ActivityState.PAUSING) {
3602 // If the activity is PAUSING, we will complete the finish once
3603 // it is done pausing; else we can just directly finish it here.
3604 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3605 return finishCurrentActivityLocked(r, index,
3606 FINISH_AFTER_PAUSE) == null;
3607 } else {
3608 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3609 }
3610
3611 return false;
3612 }
3613
3614 private static final int FINISH_IMMEDIATELY = 0;
3615 private static final int FINISH_AFTER_PAUSE = 1;
3616 private static final int FINISH_AFTER_VISIBLE = 2;
3617
3618 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3619 int mode) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003620 final int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003621 if (index < 0) {
3622 return null;
3623 }
3624
3625 return finishCurrentActivityLocked(r, index, mode);
3626 }
3627
3628 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3629 int index, int mode) {
3630 // First things first: if this activity is currently visible,
3631 // and the resumed activity is not yet visible, then hold off on
3632 // finishing until the resumed one becomes visible.
3633 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3634 if (!mStoppingActivities.contains(r)) {
3635 mStoppingActivities.add(r);
3636 if (mStoppingActivities.size() > 3) {
3637 // If we already have a few activities waiting to stop,
3638 // then give up on things going idle and start clearing
3639 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003640 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003641 } else {
3642 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003643 }
3644 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003645 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3646 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003647 r.state = ActivityState.STOPPING;
3648 mService.updateOomAdjLocked();
3649 return r;
3650 }
3651
3652 // make sure the record is cleaned out of other places.
3653 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003654 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003655 mWaitingVisibleActivities.remove(r);
3656 if (mResumedActivity == r) {
3657 mResumedActivity = null;
3658 }
3659 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003660 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003661 r.state = ActivityState.FINISHING;
3662
3663 if (mode == FINISH_IMMEDIATELY
3664 || prevState == ActivityState.STOPPED
3665 || prevState == ActivityState.INITIALIZING) {
3666 // If this activity is already stopped, we can just finish
3667 // it right now.
Dianne Hackborn28695e02011-11-02 21:59:51 -07003668 return destroyActivityLocked(r, true, true, "finish-imm") ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003669 } else {
3670 // Need to go through the full pause cycle to get this
3671 // activity into the stopped state and then finish it.
3672 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3673 mFinishingActivities.add(r);
3674 resumeTopActivityLocked(null);
3675 }
3676 return r;
3677 }
3678
3679 /**
3680 * Perform the common clean-up of an activity record. This is called both
3681 * as part of destroyActivityLocked() (when destroying the client-side
3682 * representation) and cleaning things up as a result of its hosting
3683 * processing going away, in which case there is no remaining client-side
3684 * state to destroy so only the cleanup here is needed.
3685 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003686 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3687 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003688 if (mResumedActivity == r) {
3689 mResumedActivity = null;
3690 }
3691 if (mService.mFocusedActivity == r) {
3692 mService.mFocusedActivity = null;
3693 }
3694
3695 r.configDestroy = false;
3696 r.frozenBeforeDestroy = false;
3697
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003698 if (setState) {
3699 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3700 r.state = ActivityState.DESTROYED;
3701 }
3702
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003703 // Make sure this record is no longer in the pending finishes list.
3704 // This could happen, for example, if we are trimming activities
3705 // down to the max limit while they are still waiting to finish.
3706 mFinishingActivities.remove(r);
3707 mWaitingVisibleActivities.remove(r);
3708
3709 // Remove any pending results.
3710 if (r.finishing && r.pendingResults != null) {
3711 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3712 PendingIntentRecord rec = apr.get();
3713 if (rec != null) {
3714 mService.cancelIntentSenderLocked(rec, false);
3715 }
3716 }
3717 r.pendingResults = null;
3718 }
3719
3720 if (cleanServices) {
3721 cleanUpActivityServicesLocked(r);
3722 }
3723
3724 if (mService.mPendingThumbnails.size() > 0) {
3725 // There are clients waiting to receive thumbnails so, in case
3726 // this is an activity that someone is waiting for, add it
3727 // to the pending list so we can correctly update the clients.
3728 mService.mCancelledThumbnails.add(r);
3729 }
3730
3731 // Get rid of any pending idle timeouts.
3732 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003733 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003734 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003735 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003736 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003737 }
3738
Dianne Hackborn5c607432012-02-28 14:44:19 -08003739 final void removeActivityFromHistoryLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003740 if (r.state != ActivityState.DESTROYED) {
Dianne Hackborn5c607432012-02-28 14:44:19 -08003741 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003742 r.makeFinishing();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003743 if (DEBUG_ADD_REMOVE) {
3744 RuntimeException here = new RuntimeException("here");
3745 here.fillInStackTrace();
3746 Slog.i(TAG, "Removing activity " + r + " from stack");
3747 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003748 mHistory.remove(r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003749 r.takeFromHistory();
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003750 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3751 + " (removed from history)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003752 r.state = ActivityState.DESTROYED;
Dianne Hackbornbe707852011-11-11 14:32:10 -08003753 mService.mWindowManager.removeAppToken(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003754 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003755 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003756 }
3757 cleanUpActivityServicesLocked(r);
3758 r.removeUriPermissionsLocked();
3759 }
3760 }
3761
3762 /**
3763 * Perform clean-up of service connections in an activity record.
3764 */
3765 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3766 // Throw away any services that have been bound by this activity.
3767 if (r.connections != null) {
3768 Iterator<ConnectionRecord> it = r.connections.iterator();
3769 while (it.hasNext()) {
3770 ConnectionRecord c = it.next();
3771 mService.removeConnectionLocked(c, null, r);
3772 }
3773 r.connections = null;
3774 }
3775 }
3776
Dianne Hackborn28695e02011-11-02 21:59:51 -07003777 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003778 for (int i=mHistory.size()-1; i>=0; i--) {
3779 ActivityRecord r = mHistory.get(i);
3780 if (owner != null && r.app != owner) {
3781 continue;
3782 }
3783 // We can destroy this one if we have its icicle saved and
3784 // it is not in the process of pausing/stopping/finishing.
3785 if (r.app != null && r.haveState && !r.visible && r.stopped && !r.finishing
3786 && r.state != ActivityState.DESTROYING
3787 && r.state != ActivityState.DESTROYED) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003788 destroyActivityLocked(r, true, oomAdj, "trim");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003789 }
3790 }
3791 }
3792
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003793 /**
3794 * Destroy the current CLIENT SIDE instance of an activity. This may be
3795 * called both when actually finishing an activity, or when performing
3796 * a configuration switch where we destroy the current client-side object
3797 * but then create a new client-side object for this same HistoryRecord.
3798 */
3799 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackborn28695e02011-11-02 21:59:51 -07003800 boolean removeFromApp, boolean oomAdj, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003801 if (DEBUG_SWITCH) Slog.v(
3802 TAG, "Removing activity: token=" + r
3803 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3804 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3805 System.identityHashCode(r),
Dianne Hackborn28695e02011-11-02 21:59:51 -07003806 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003807
3808 boolean removedFromHistory = false;
3809
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003810 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003811
3812 final boolean hadApp = r.app != null;
3813
3814 if (hadApp) {
3815 if (removeFromApp) {
3816 int idx = r.app.activities.indexOf(r);
3817 if (idx >= 0) {
3818 r.app.activities.remove(idx);
3819 }
3820 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
3821 mService.mHeavyWeightProcess = null;
3822 mService.mHandler.sendEmptyMessage(
3823 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
3824 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003825 if (r.app.activities.size() == 0) {
3826 // No longer have activities, so update location in
3827 // LRU list.
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003828 mService.updateLruProcessLocked(r.app, oomAdj, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003829 }
3830 }
3831
3832 boolean skipDestroy = false;
3833
3834 try {
3835 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003836 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003837 r.configChangeFlags);
3838 } catch (Exception e) {
3839 // We can just ignore exceptions here... if the process
3840 // has crashed, our death notification will clean things
3841 // up.
3842 //Slog.w(TAG, "Exception thrown during finish", e);
3843 if (r.finishing) {
3844 removeActivityFromHistoryLocked(r);
3845 removedFromHistory = true;
3846 skipDestroy = true;
3847 }
3848 }
3849
3850 r.app = null;
3851 r.nowVisible = false;
3852
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003853 // If the activity is finishing, we need to wait on removing it
3854 // from the list to give it a chance to do its cleanup. During
3855 // that time it may make calls back with its token so we need to
3856 // be able to find it on the list and so we don't want to remove
3857 // it from the list yet. Otherwise, we can just immediately put
3858 // it in the destroyed state since we are not removing it from the
3859 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003860 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003861 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
3862 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003863 r.state = ActivityState.DESTROYING;
3864 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
3865 msg.obj = r;
3866 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
3867 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003868 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3869 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003870 r.state = ActivityState.DESTROYED;
3871 }
3872 } else {
3873 // remove this record from the history.
3874 if (r.finishing) {
3875 removeActivityFromHistoryLocked(r);
3876 removedFromHistory = true;
3877 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003878 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3879 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003880 r.state = ActivityState.DESTROYED;
3881 }
3882 }
3883
3884 r.configChangeFlags = 0;
3885
3886 if (!mLRUActivities.remove(r) && hadApp) {
3887 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
3888 }
3889
3890 return removedFromHistory;
3891 }
3892
3893 final void activityDestroyed(IBinder token) {
3894 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003895 ActivityRecord r = ActivityRecord.forToken(token);
3896 if (r != null) {
3897 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
3898 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003899
Dianne Hackbornbe707852011-11-11 14:32:10 -08003900 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003901 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003902 if (r.state == ActivityState.DESTROYING) {
3903 final long origId = Binder.clearCallingIdentity();
3904 removeActivityFromHistoryLocked(r);
3905 Binder.restoreCallingIdentity(origId);
3906 }
3907 }
3908 }
3909 }
3910
3911 private static void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
3912 int i = list.size();
3913 if (localLOGV) Slog.v(
3914 TAG, "Removing app " + app + " from list " + list
3915 + " with " + i + " entries");
3916 while (i > 0) {
3917 i--;
3918 ActivityRecord r = (ActivityRecord)list.get(i);
3919 if (localLOGV) Slog.v(
3920 TAG, "Record #" + i + " " + r + ": app=" + r.app);
3921 if (r.app == app) {
3922 if (localLOGV) Slog.v(TAG, "Removing this entry!");
3923 list.remove(i);
3924 }
3925 }
3926 }
3927
3928 void removeHistoryRecordsForAppLocked(ProcessRecord app) {
3929 removeHistoryRecordsForAppLocked(mLRUActivities, app);
3930 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003931 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003932 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
3933 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
3934 }
3935
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003936 /**
3937 * Move the current home activity's task (if one exists) to the front
3938 * of the stack.
3939 */
3940 final void moveHomeToFrontLocked() {
3941 TaskRecord homeTask = null;
3942 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003943 ActivityRecord hr = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003944 if (hr.isHomeActivity) {
3945 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003946 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003947 }
3948 }
3949 if (homeTask != null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003950 moveTaskToFrontLocked(homeTask, null, null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003951 }
3952 }
3953
Dianne Hackborn7f58b952012-04-18 12:59:29 -07003954 final void updateTransitLocked(int transit, Bundle options) {
3955 if (options != null) {
3956 ActivityRecord r = topRunningActivityLocked(null);
3957 if (r != null && r.state != ActivityState.RESUMED) {
3958 r.updateOptionsLocked(options);
3959 } else {
3960 ActivityOptions.abort(options);
3961 }
3962 }
3963 mService.mWindowManager.prepareAppTransition(transit, false);
3964 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003965
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003966 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003967 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
3968
3969 final int task = tr.taskId;
3970 int top = mHistory.size()-1;
3971
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003972 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003973 // nothing to do!
Dianne Hackborn7f58b952012-04-18 12:59:29 -07003974 if (reason != null &&
3975 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
3976 ActivityOptions.abort(options);
3977 } else {
3978 updateTransitLocked(WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, options);
3979 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003980 return;
3981 }
3982
Dianne Hackbornbe707852011-11-11 14:32:10 -08003983 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003984
3985 // Applying the affinities may have removed entries from the history,
3986 // so get the size again.
3987 top = mHistory.size()-1;
3988 int pos = top;
3989
3990 // Shift all activities with this task up to the top
3991 // of the stack, keeping them in the same internal order.
3992 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003993 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003994 if (localLOGV) Slog.v(
3995 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003996 if (r.task.taskId == task) {
3997 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003998 if (DEBUG_ADD_REMOVE) {
3999 RuntimeException here = new RuntimeException("here");
4000 here.fillInStackTrace();
4001 Slog.i(TAG, "Removing and adding activity " + r + " to stack at " + top, here);
4002 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004003 mHistory.remove(pos);
4004 mHistory.add(top, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004005 moved.add(0, r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004006 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004007 }
4008 pos--;
4009 }
4010
4011 if (DEBUG_TRANSITION) Slog.v(TAG,
4012 "Prepare to front transition: task=" + tr);
4013 if (reason != null &&
4014 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004015 mService.mWindowManager.prepareAppTransition(
4016 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004017 ActivityRecord r = topRunningActivityLocked(null);
4018 if (r != null) {
4019 mNoAnimActivities.add(r);
4020 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004021 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004022 } else {
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004023 updateTransitLocked(WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004024 }
4025
4026 mService.mWindowManager.moveAppTokensToTop(moved);
4027 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004028 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004029 }
4030
4031 finishTaskMoveLocked(task);
4032 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
4033 }
4034
4035 private final void finishTaskMoveLocked(int task) {
4036 resumeTopActivityLocked(null);
4037 }
4038
4039 /**
4040 * Worker method for rearranging history stack. Implements the function of moving all
4041 * activities for a specific task (gathering them if disjoint) into a single group at the
4042 * bottom of the stack.
4043 *
4044 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
4045 * to premeptively cancel the move.
4046 *
4047 * @param task The taskId to collect and move to the bottom.
4048 * @return Returns true if the move completed, false if not.
4049 */
4050 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
4051 Slog.i(TAG, "moveTaskToBack: " + task);
4052
4053 // If we have a watcher, preflight the move before committing to it. First check
4054 // for *other* available tasks, but if none are available, then try again allowing the
4055 // current task to be selected.
4056 if (mMainStack && mService.mController != null) {
4057 ActivityRecord next = topRunningActivityLocked(null, task);
4058 if (next == null) {
4059 next = topRunningActivityLocked(null, 0);
4060 }
4061 if (next != null) {
4062 // ask watcher if this is allowed
4063 boolean moveOK = true;
4064 try {
4065 moveOK = mService.mController.activityResuming(next.packageName);
4066 } catch (RemoteException e) {
4067 mService.mController = null;
4068 }
4069 if (!moveOK) {
4070 return false;
4071 }
4072 }
4073 }
4074
Dianne Hackbornbe707852011-11-11 14:32:10 -08004075 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004076
4077 if (DEBUG_TRANSITION) Slog.v(TAG,
4078 "Prepare to back transition: task=" + task);
4079
4080 final int N = mHistory.size();
4081 int bottom = 0;
4082 int pos = 0;
4083
4084 // Shift all activities with this task down to the bottom
4085 // of the stack, keeping them in the same internal order.
4086 while (pos < N) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004087 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004088 if (localLOGV) Slog.v(
4089 TAG, "At " + pos + " ckp " + r.task + ": " + r);
4090 if (r.task.taskId == task) {
4091 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004092 if (DEBUG_ADD_REMOVE) {
4093 RuntimeException here = new RuntimeException("here");
4094 here.fillInStackTrace();
4095 Slog.i(TAG, "Removing and adding activity " + r + " to stack at "
4096 + bottom, here);
4097 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004098 mHistory.remove(pos);
4099 mHistory.add(bottom, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004100 moved.add(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004101 bottom++;
4102 }
4103 pos++;
4104 }
4105
4106 if (reason != null &&
4107 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004108 mService.mWindowManager.prepareAppTransition(
4109 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004110 ActivityRecord r = topRunningActivityLocked(null);
4111 if (r != null) {
4112 mNoAnimActivities.add(r);
4113 }
4114 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004115 mService.mWindowManager.prepareAppTransition(
4116 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004117 }
4118 mService.mWindowManager.moveAppTokensToBottom(moved);
4119 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004120 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004121 }
4122
4123 finishTaskMoveLocked(task);
4124 return true;
4125 }
4126
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004127 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
4128 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4129 ActivityRecord resumed = mResumedActivity;
4130 if (resumed != null && resumed.thumbHolder == tr) {
4131 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
4132 } else {
4133 info.mainThumbnail = tr.lastThumbnail;
4134 }
4135 return info;
4136 }
4137
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004138 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex,
4139 boolean taskRequired) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004140 TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
4141 if (info.root == null) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004142 if (taskRequired) {
4143 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
4144 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004145 return null;
4146 }
4147
4148 if (subTaskIndex < 0) {
4149 // Just remove the entire task.
4150 performClearTaskAtIndexLocked(taskId, info.rootIndex);
4151 return info.root;
4152 }
4153
4154 if (subTaskIndex >= info.subtasks.size()) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004155 if (taskRequired) {
4156 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
4157 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004158 return null;
4159 }
4160
4161 // Remove all of this task's activies starting at the sub task.
4162 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
4163 performClearTaskAtIndexLocked(taskId, subtask.index);
4164 return subtask.activity;
4165 }
4166
4167 public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
4168 ActivityRecord resumed = mResumedActivity;
4169 final TaskAccessInfo thumbs = new TaskAccessInfo();
4170 // How many different sub-thumbnails?
4171 final int NA = mHistory.size();
4172 int j = 0;
4173 ThumbnailHolder holder = null;
4174 while (j < NA) {
4175 ActivityRecord ar = mHistory.get(j);
4176 if (!ar.finishing && ar.task.taskId == taskId) {
4177 holder = ar.thumbHolder;
4178 break;
4179 }
4180 j++;
4181 }
4182
4183 if (j >= NA) {
4184 return thumbs;
4185 }
4186
4187 thumbs.root = mHistory.get(j);
4188 thumbs.rootIndex = j;
4189
4190 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
4191 thumbs.subtasks = subtasks;
4192 ActivityRecord lastActivity = null;
4193 while (j < NA) {
4194 ActivityRecord ar = mHistory.get(j);
4195 j++;
4196 if (ar.finishing) {
4197 continue;
4198 }
4199 if (ar.task.taskId != taskId) {
4200 break;
4201 }
4202 lastActivity = ar;
4203 if (ar.thumbHolder != holder && holder != null) {
4204 thumbs.numSubThumbbails++;
4205 holder = ar.thumbHolder;
4206 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
4207 sub.thumbnail = holder.lastThumbnail;
4208 sub.activity = ar;
4209 sub.index = j-1;
4210 subtasks.add(sub);
4211 }
4212 }
4213 if (lastActivity != null && subtasks.size() > 0) {
4214 if (resumed == lastActivity) {
4215 TaskAccessInfo.SubTask sub = subtasks.get(subtasks.size()-1);
4216 sub.thumbnail = lastActivity.stack.screenshotActivities(lastActivity);
4217 }
4218 }
4219 if (thumbs.numSubThumbbails > 0) {
4220 thumbs.retriever = new IThumbnailRetriever.Stub() {
4221 public Bitmap getThumbnail(int index) {
4222 if (index < 0 || index >= thumbs.subtasks.size()) {
4223 return null;
4224 }
4225 return thumbs.subtasks.get(index).thumbnail;
4226 }
4227 };
4228 }
4229 return thumbs;
4230 }
4231
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004232 private final void logStartActivity(int tag, ActivityRecord r,
4233 TaskRecord task) {
4234 EventLog.writeEvent(tag,
4235 System.identityHashCode(r), task.taskId,
4236 r.shortComponentName, r.intent.getAction(),
4237 r.intent.getType(), r.intent.getDataString(),
4238 r.intent.getFlags());
4239 }
4240
4241 /**
4242 * Make sure the given activity matches the current configuration. Returns
4243 * false if the activity had to be destroyed. Returns true if the
4244 * configuration is the same, or the activity will remain running as-is
4245 * for whatever reason. Ensures the HistoryRecord is updated with the
4246 * correct configuration and all other bookkeeping is handled.
4247 */
4248 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
4249 int globalChanges) {
4250 if (mConfigWillChange) {
4251 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4252 "Skipping config check (will change): " + r);
4253 return true;
4254 }
4255
4256 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4257 "Ensuring correct configuration: " + r);
4258
4259 // Short circuit: if the two configurations are the exact same
4260 // object (the common case), then there is nothing to do.
4261 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004262 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004263 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4264 "Configuration unchanged in " + r);
4265 return true;
4266 }
4267
4268 // We don't worry about activities that are finishing.
4269 if (r.finishing) {
4270 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4271 "Configuration doesn't matter in finishing " + r);
4272 r.stopFreezingScreenLocked(false);
4273 return true;
4274 }
4275
4276 // Okay we now are going to make this activity have the new config.
4277 // But then we need to figure out how it needs to deal with that.
4278 Configuration oldConfig = r.configuration;
4279 r.configuration = newConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004280
4281 // Determine what has changed. May be nothing, if this is a config
4282 // that has come back from the app after going idle. In that case
4283 // we just want to leave the official config object now in the
4284 // activity and do nothing else.
4285 final int changes = oldConfig.diff(newConfig);
4286 if (changes == 0 && !r.forceNewConfig) {
4287 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4288 "Configuration no differences in " + r);
4289 return true;
4290 }
4291
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004292 // If the activity isn't currently running, just leave the new
4293 // configuration and it will pick that up next time it starts.
4294 if (r.app == null || r.app.thread == null) {
4295 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4296 "Configuration doesn't matter not running " + r);
4297 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004298 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004299 return true;
4300 }
4301
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004302 // Figure out how to handle the changes between the configurations.
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004303 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4304 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
4305 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07004306 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004307 + ", newConfig=" + newConfig);
4308 }
Dianne Hackborne6676352011-06-01 16:51:20 -07004309 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004310 // Aha, the activity isn't handling the change, so DIE DIE DIE.
4311 r.configChangeFlags |= changes;
4312 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004313 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004314 if (r.app == null || r.app.thread == null) {
4315 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4316 "Switch is destroying non-running " + r);
Dianne Hackborn28695e02011-11-02 21:59:51 -07004317 destroyActivityLocked(r, true, false, "config");
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004318 } else if (r.state == ActivityState.PAUSING) {
4319 // A little annoying: we are waiting for this activity to
4320 // finish pausing. Let's not do anything now, but just
4321 // flag that it needs to be restarted when done pausing.
4322 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4323 "Switch is skipping already pausing " + r);
4324 r.configDestroy = true;
4325 return true;
4326 } else if (r.state == ActivityState.RESUMED) {
4327 // Try to optimize this case: the configuration is changing
4328 // and we need to restart the top, resumed activity.
4329 // Instead of doing the normal handshaking, just say
4330 // "restart!".
4331 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4332 "Switch is restarting resumed " + r);
4333 relaunchActivityLocked(r, r.configChangeFlags, true);
4334 r.configChangeFlags = 0;
4335 } else {
4336 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4337 "Switch is restarting non-resumed " + r);
4338 relaunchActivityLocked(r, r.configChangeFlags, false);
4339 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004340 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004341
4342 // All done... tell the caller we weren't able to keep this
4343 // activity around.
4344 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004345 }
4346
4347 // Default case: the activity can handle this new configuration, so
4348 // hand it over. Note that we don't need to give it the new
4349 // configuration, since we always send configuration changes to all
4350 // process when they happen so it can just use whatever configuration
4351 // it last got.
4352 if (r.app != null && r.app.thread != null) {
4353 try {
4354 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004355 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004356 } catch (RemoteException e) {
4357 // If process died, whatever.
4358 }
4359 }
4360 r.stopFreezingScreenLocked(false);
4361
4362 return true;
4363 }
4364
4365 private final boolean relaunchActivityLocked(ActivityRecord r,
4366 int changes, boolean andResume) {
4367 List<ResultInfo> results = null;
4368 List<Intent> newIntents = null;
4369 if (andResume) {
4370 results = r.results;
4371 newIntents = r.newIntents;
4372 }
4373 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4374 + " with results=" + results + " newIntents=" + newIntents
4375 + " andResume=" + andResume);
4376 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
4377 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
4378 r.task.taskId, r.shortComponentName);
4379
4380 r.startFreezingScreenLocked(r.app, 0);
4381
4382 try {
4383 if (DEBUG_SWITCH) Slog.i(TAG, "Switch is restarting resumed " + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004384 r.forceNewConfig = false;
Dianne Hackbornbe707852011-11-11 14:32:10 -08004385 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004386 changes, !andResume, new Configuration(mService.mConfiguration));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004387 // Note: don't need to call pauseIfSleepingLocked() here, because
4388 // the caller will only pass in 'andResume' if this activity is
4389 // currently resumed, which implies we aren't sleeping.
4390 } catch (RemoteException e) {
4391 return false;
4392 }
4393
4394 if (andResume) {
4395 r.results = null;
4396 r.newIntents = null;
4397 if (mMainStack) {
4398 mService.reportResumedActivityLocked(r);
4399 }
4400 }
4401
4402 return true;
4403 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004404
4405 public void dismissKeyguardOnNextActivityLocked() {
4406 mDismissKeyguardOnNextActivity = true;
4407 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004408}