blob: 13ee008a6008a8eaeb12cde48b0e12883021d521 [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
19import com.android.internal.app.HeavyWeightSwitcherActivity;
20import com.android.internal.os.BatteryStatsImpl;
21import com.android.server.am.ActivityManagerService.PendingActivityLaunch;
22
23import android.app.Activity;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070024import android.app.ActivityManager;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070025import android.app.AppGlobals;
26import android.app.IActivityManager;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070027import android.app.IThumbnailRetriever;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070028import android.app.IApplicationThread;
29import android.app.PendingIntent;
30import android.app.ResultInfo;
31import android.app.IActivityManager.WaitResult;
32import android.content.ComponentName;
33import android.content.Context;
34import android.content.IIntentSender;
35import android.content.Intent;
36import android.content.IntentSender;
37import android.content.pm.ActivityInfo;
38import android.content.pm.ApplicationInfo;
39import android.content.pm.PackageManager;
40import android.content.pm.ResolveInfo;
41import android.content.res.Configuration;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -080042import android.content.res.Resources;
43import android.graphics.Bitmap;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070044import android.net.Uri;
45import android.os.Binder;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070046import android.os.Bundle;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070047import android.os.Handler;
48import android.os.IBinder;
49import android.os.Message;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070050import android.os.ParcelFileDescriptor;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070051import android.os.PowerManager;
52import android.os.RemoteException;
53import android.os.SystemClock;
Amith Yamasani742a6712011-05-04 14:49:28 -070054import android.os.UserId;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070055import android.util.EventLog;
56import android.util.Log;
57import android.util.Slog;
58import android.view.WindowManagerPolicy;
59
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070060import java.io.IOException;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070061import java.lang.ref.WeakReference;
62import java.util.ArrayList;
63import java.util.Iterator;
64import java.util.List;
65
66/**
67 * State and management of a single stack of activities.
68 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070069final class ActivityStack {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070070 static final String TAG = ActivityManagerService.TAG;
Dianne Hackbornb961cd22011-06-21 12:13:37 -070071 static final boolean localLOGV = ActivityManagerService.localLOGV;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070072 static final boolean DEBUG_SWITCH = ActivityManagerService.DEBUG_SWITCH;
73 static final boolean DEBUG_PAUSE = ActivityManagerService.DEBUG_PAUSE;
74 static final boolean DEBUG_VISBILITY = ActivityManagerService.DEBUG_VISBILITY;
75 static final boolean DEBUG_USER_LEAVING = ActivityManagerService.DEBUG_USER_LEAVING;
76 static final boolean DEBUG_TRANSITION = ActivityManagerService.DEBUG_TRANSITION;
77 static final boolean DEBUG_RESULTS = ActivityManagerService.DEBUG_RESULTS;
78 static final boolean DEBUG_CONFIGURATION = ActivityManagerService.DEBUG_CONFIGURATION;
79 static final boolean DEBUG_TASKS = ActivityManagerService.DEBUG_TASKS;
80
Dianne Hackbornce86ba82011-07-13 19:33:41 -070081 static final boolean DEBUG_STATES = false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070082 static final boolean DEBUG_ADD_REMOVE = false;
83 static final boolean DEBUG_SAVED_STATE = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070084
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070085 static final boolean VALIDATE_TOKENS = ActivityManagerService.VALIDATE_TOKENS;
86
87 // How long we wait until giving up on the last activity telling us it
88 // is idle.
89 static final int IDLE_TIMEOUT = 10*1000;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -070090
91 // Ticks during which we check progress while waiting for an app to launch.
92 static final int LAUNCH_TICK = 500;
93
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070094 // How long we wait until giving up on the last activity to pause. This
95 // is short because it directly impacts the responsiveness of starting the
96 // next activity.
97 static final int PAUSE_TIMEOUT = 500;
98
Dianne Hackborn4eba96b2011-01-21 13:34:36 -080099 // How long we can hold the sleep wake lock before giving up.
100 static final int SLEEP_TIMEOUT = 5*1000;
101
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700102 // How long we can hold the launch wake lock before giving up.
103 static final int LAUNCH_TIMEOUT = 10*1000;
104
105 // How long we wait until giving up on an activity telling us it has
106 // finished destroying itself.
107 static final int DESTROY_TIMEOUT = 10*1000;
108
109 // How long until we reset a task when the user returns to it. Currently
Dianne Hackborn621e17d2010-11-22 15:59:56 -0800110 // disabled.
111 static final long ACTIVITY_INACTIVE_RESET_TIME = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700112
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700113 // How long between activity launches that we consider safe to not warn
114 // the user about an unexpected activity being launched on top.
115 static final long START_WARN_TIME = 5*1000;
116
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700117 // Set to false to disable the preview that is shown while a new activity
118 // is being started.
119 static final boolean SHOW_APP_STARTING_PREVIEW = true;
120
121 enum ActivityState {
122 INITIALIZING,
123 RESUMED,
124 PAUSING,
125 PAUSED,
126 STOPPING,
127 STOPPED,
128 FINISHING,
129 DESTROYING,
130 DESTROYED
131 }
132
133 final ActivityManagerService mService;
134 final boolean mMainStack;
135
136 final Context mContext;
137
138 /**
139 * The back history of all previous (and possibly still
140 * running) activities. It contains HistoryRecord objects.
141 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700142 final ArrayList<ActivityRecord> mHistory = new ArrayList<ActivityRecord>();
Dianne Hackbornbe707852011-11-11 14:32:10 -0800143
144 /**
145 * Used for validating app tokens with window manager.
146 */
147 final ArrayList<IBinder> mValidateAppTokens = new ArrayList<IBinder>();
148
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700149 /**
150 * List of running activities, sorted by recent usage.
151 * The first entry in the list is the least recently used.
152 * It contains HistoryRecord objects.
153 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700154 final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700155
156 /**
157 * List of activities that are waiting for a new activity
158 * to become visible before completing whatever operation they are
159 * supposed to do.
160 */
161 final ArrayList<ActivityRecord> mWaitingVisibleActivities
162 = new ArrayList<ActivityRecord>();
163
164 /**
165 * List of activities that are ready to be stopped, but waiting
166 * for the next activity to settle down before doing so. It contains
167 * HistoryRecord objects.
168 */
169 final ArrayList<ActivityRecord> mStoppingActivities
170 = new ArrayList<ActivityRecord>();
171
172 /**
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800173 * List of activities that are in the process of going to sleep.
174 */
175 final ArrayList<ActivityRecord> mGoingToSleepActivities
176 = new ArrayList<ActivityRecord>();
177
178 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700179 * Animations that for the current transition have requested not to
180 * be considered for the transition animation.
181 */
182 final ArrayList<ActivityRecord> mNoAnimActivities
183 = new ArrayList<ActivityRecord>();
184
185 /**
186 * List of activities that are ready to be finished, but waiting
187 * for the previous activity to settle down before doing so. It contains
188 * HistoryRecord objects.
189 */
190 final ArrayList<ActivityRecord> mFinishingActivities
191 = new ArrayList<ActivityRecord>();
192
193 /**
194 * List of people waiting to find out about the next launched activity.
195 */
196 final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched
197 = new ArrayList<IActivityManager.WaitResult>();
198
199 /**
200 * List of people waiting to find out about the next visible activity.
201 */
202 final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible
203 = new ArrayList<IActivityManager.WaitResult>();
204
205 /**
206 * Set when the system is going to sleep, until we have
207 * successfully paused the current activity and released our wake lock.
208 * At that point the system is allowed to actually sleep.
209 */
210 final PowerManager.WakeLock mGoingToSleep;
211
212 /**
213 * We don't want to allow the device to go to sleep while in the process
214 * of launching an activity. This is primarily to allow alarm intent
215 * receivers to launch an activity and get that to run before the device
216 * goes back to sleep.
217 */
218 final PowerManager.WakeLock mLaunchingActivity;
219
220 /**
221 * When we are in the process of pausing an activity, before starting the
222 * next one, this variable holds the activity that is currently being paused.
223 */
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800224 ActivityRecord mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700225
226 /**
227 * This is the last activity that we put into the paused state. This is
228 * used to determine if we need to do an activity transition while sleeping,
229 * when we normally hold the top activity paused.
230 */
231 ActivityRecord mLastPausedActivity = null;
232
233 /**
234 * Current activity that is resumed, or null if there is none.
235 */
236 ActivityRecord mResumedActivity = null;
237
238 /**
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700239 * This is the last activity that has been started. It is only used to
240 * identify when multiple activities are started at once so that the user
241 * can be warned they may not be in the activity they think they are.
242 */
243 ActivityRecord mLastStartedActivity = null;
244
245 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700246 * Set when we know we are going to be calling updateConfiguration()
247 * soon, so want to skip intermediate config checks.
248 */
249 boolean mConfigWillChange;
250
251 /**
252 * Set to indicate whether to issue an onUserLeaving callback when a
253 * newly launched activity is being brought in front of us.
254 */
255 boolean mUserLeaving = false;
256
257 long mInitialStartTime = 0;
258
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800259 /**
260 * Set when we have taken too long waiting to go to sleep.
261 */
262 boolean mSleepTimeout = false;
263
Dianne Hackborn90c52de2011-09-23 12:57:44 -0700264 /**
265 * Dismiss the keyguard after the next activity is displayed?
266 */
267 boolean mDismissKeyguardOnNextActivity = false;
268
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800269 int mThumbnailWidth = -1;
270 int mThumbnailHeight = -1;
271
Amith Yamasani742a6712011-05-04 14:49:28 -0700272 private int mCurrentUser;
273
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800274 static final int SLEEP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG;
275 static final int PAUSE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 1;
276 static final int IDLE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 2;
277 static final int IDLE_NOW_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 3;
278 static final int LAUNCH_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 4;
279 static final int DESTROY_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 5;
280 static final int RESUME_TOP_ACTIVITY_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 6;
Dianne Hackborn29ba7e62012-03-16 15:03:36 -0700281 static final int LAUNCH_TICK_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 7;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700282
283 final Handler mHandler = new Handler() {
284 //public Handler() {
285 // if (localLOGV) Slog.v(TAG, "Handler started!");
286 //}
287
288 public void handleMessage(Message msg) {
289 switch (msg.what) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800290 case SLEEP_TIMEOUT_MSG: {
Dianne Hackborn8e8d65f2011-08-11 19:36:18 -0700291 synchronized (mService) {
292 if (mService.isSleeping()) {
293 Slog.w(TAG, "Sleep timeout! Sleeping now.");
294 mSleepTimeout = true;
295 checkReadyForSleepLocked();
296 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800297 }
298 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700299 case PAUSE_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800300 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700301 // We don't at this point know if the activity is fullscreen,
302 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800303 Slog.w(TAG, "Activity pause timeout for " + r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700304 synchronized (mService) {
305 if (r.app != null) {
306 mService.logAppTooSlow(r.app, r.pauseTime,
307 "pausing " + r);
308 }
309 }
310
Dianne Hackbornbe707852011-11-11 14:32:10 -0800311 activityPaused(r != null ? r.appToken : null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700312 } break;
313 case IDLE_TIMEOUT_MSG: {
314 if (mService.mDidDexOpt) {
315 mService.mDidDexOpt = false;
316 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
317 nmsg.obj = msg.obj;
318 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
319 return;
320 }
321 // We don't at this point know if the activity is fullscreen,
322 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800323 ActivityRecord r = (ActivityRecord)msg.obj;
324 Slog.w(TAG, "Activity idle timeout for " + r);
325 activityIdleInternal(r != null ? r.appToken : null, true, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700326 } break;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700327 case LAUNCH_TICK_MSG: {
328 ActivityRecord r = (ActivityRecord)msg.obj;
329 synchronized (mService) {
330 if (r.continueLaunchTickingLocked()) {
331 mService.logAppTooSlow(r.app, r.launchTickTime,
332 "launching " + r);
333 }
334 }
335 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700336 case DESTROY_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800337 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700338 // We don't at this point know if the activity is fullscreen,
339 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800340 Slog.w(TAG, "Activity destroy timeout for " + r);
341 activityDestroyed(r != null ? r.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700342 } break;
343 case IDLE_NOW_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800344 ActivityRecord r = (ActivityRecord)msg.obj;
345 activityIdleInternal(r != null ? r.appToken : null, false, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700346 } break;
347 case LAUNCH_TIMEOUT_MSG: {
348 if (mService.mDidDexOpt) {
349 mService.mDidDexOpt = false;
350 Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
351 mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
352 return;
353 }
354 synchronized (mService) {
355 if (mLaunchingActivity.isHeld()) {
356 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
357 mLaunchingActivity.release();
358 }
359 }
360 } break;
361 case RESUME_TOP_ACTIVITY_MSG: {
362 synchronized (mService) {
363 resumeTopActivityLocked(null);
364 }
365 } break;
366 }
367 }
368 };
369
370 ActivityStack(ActivityManagerService service, Context context, boolean mainStack) {
371 mService = service;
372 mContext = context;
373 mMainStack = mainStack;
374 PowerManager pm =
375 (PowerManager)context.getSystemService(Context.POWER_SERVICE);
376 mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
377 mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
378 mLaunchingActivity.setReferenceCounted(false);
379 }
380
381 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700382 // TODO: Don't look for any tasks from other users
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700383 int i = mHistory.size()-1;
384 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700385 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700386 if (!r.finishing && r != notTop) {
387 return r;
388 }
389 i--;
390 }
391 return null;
392 }
393
394 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700395 // TODO: Don't look for any tasks from other users
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700396 int i = mHistory.size()-1;
397 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700398 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700399 if (!r.finishing && !r.delayedResume && r != notTop) {
400 return r;
401 }
402 i--;
403 }
404 return null;
405 }
406
407 /**
408 * This is a simplified version of topRunningActivityLocked that provides a number of
409 * optional skip-over modes. It is intended for use with the ActivityController hook only.
410 *
411 * @param token If non-null, any history records matching this token will be skipped.
412 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
413 *
414 * @return Returns the HistoryRecord of the next activity on the stack.
415 */
416 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700417 // TODO: Don't look for any tasks from other users
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700418 int i = mHistory.size()-1;
419 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700420 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700421 // Note: the taskId check depends on real taskId fields being non-zero
Dianne Hackbornbe707852011-11-11 14:32:10 -0800422 if (!r.finishing && (token != r.appToken) && (taskId != r.task.taskId)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700423 return r;
424 }
425 i--;
426 }
427 return null;
428 }
429
430 final int indexOfTokenLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800431 return mHistory.indexOf(ActivityRecord.forToken(token));
432 }
433
434 final int indexOfActivityLocked(ActivityRecord r) {
435 return mHistory.indexOf(r);
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700436 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700437
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700438 final ActivityRecord isInStackLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800439 ActivityRecord r = ActivityRecord.forToken(token);
440 if (mHistory.contains(r)) {
441 return r;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700442 }
443 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700444 }
445
446 private final boolean updateLRUListLocked(ActivityRecord r) {
447 final boolean hadit = mLRUActivities.remove(r);
448 mLRUActivities.add(r);
449 return hadit;
450 }
451
452 /**
453 * Returns the top activity in any existing task matching the given
454 * Intent. Returns null if no such task is found.
455 */
456 private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
457 ComponentName cls = intent.getComponent();
458 if (info.targetActivity != null) {
459 cls = new ComponentName(info.packageName, info.targetActivity);
460 }
461
462 TaskRecord cp = null;
463
Amith Yamasani742a6712011-05-04 14:49:28 -0700464 final int userId = UserId.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700465 final int N = mHistory.size();
466 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700467 ActivityRecord r = mHistory.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -0700468 if (!r.finishing && r.task != cp && r.userId == userId
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700469 && r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
470 cp = r.task;
471 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
472 // + "/aff=" + r.task.affinity + " to new cls="
473 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
474 if (r.task.affinity != null) {
475 if (r.task.affinity.equals(info.taskAffinity)) {
476 //Slog.i(TAG, "Found matching affinity!");
477 return r;
478 }
479 } else if (r.task.intent != null
480 && r.task.intent.getComponent().equals(cls)) {
481 //Slog.i(TAG, "Found matching class!");
482 //dump();
483 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
484 return r;
485 } else if (r.task.affinityIntent != null
486 && r.task.affinityIntent.getComponent().equals(cls)) {
487 //Slog.i(TAG, "Found matching class!");
488 //dump();
489 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
490 return r;
491 }
492 }
493 }
494
495 return null;
496 }
497
498 /**
499 * Returns the first activity (starting from the top of the stack) that
500 * is the same as the given activity. Returns null if no such activity
501 * is found.
502 */
503 private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
504 ComponentName cls = intent.getComponent();
505 if (info.targetActivity != null) {
506 cls = new ComponentName(info.packageName, info.targetActivity);
507 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700508 final int userId = UserId.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700509
510 final int N = mHistory.size();
511 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700512 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700513 if (!r.finishing) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700514 if (r.intent.getComponent().equals(cls) && r.userId == userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700515 //Slog.i(TAG, "Found matching class!");
516 //dump();
517 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
518 return r;
519 }
520 }
521 }
522
523 return null;
524 }
525
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700526 final void showAskCompatModeDialogLocked(ActivityRecord r) {
527 Message msg = Message.obtain();
528 msg.what = ActivityManagerService.SHOW_COMPAT_MODE_DIALOG_MSG;
529 msg.obj = r.task.askedCompatMode ? null : r;
530 mService.mHandler.sendMessage(msg);
531 }
532
Amith Yamasani742a6712011-05-04 14:49:28 -0700533 /*
534 * Move the activities around in the stack to bring a user to the foreground.
535 * @return whether there are any activities for the specified user.
536 */
537 final boolean switchUser(int userId) {
538 synchronized (mService) {
539 mCurrentUser = userId;
540
541 // Only one activity? Nothing to do...
542 if (mHistory.size() < 2)
543 return false;
544
545 boolean haveActivities = false;
546 // Check if the top activity is from the new user.
547 ActivityRecord top = mHistory.get(mHistory.size() - 1);
548 if (top.userId == userId) return true;
549 // Otherwise, move the user's activities to the top.
550 int N = mHistory.size();
551 int i = 0;
552 while (i < N) {
553 ActivityRecord r = mHistory.get(i);
554 if (r.userId == userId) {
555 ActivityRecord moveToTop = mHistory.remove(i);
556 mHistory.add(moveToTop);
557 // No need to check the top one now
558 N--;
559 haveActivities = true;
560 } else {
561 i++;
562 }
563 }
564 // Transition from the old top to the new top
565 resumeTopActivityLocked(top);
566 return haveActivities;
567 }
568 }
569
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700570 final boolean realStartActivityLocked(ActivityRecord r,
571 ProcessRecord app, boolean andResume, boolean checkConfig)
572 throws RemoteException {
573
574 r.startFreezingScreenLocked(app, 0);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800575 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700576
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700577 // schedule launch ticks to collect information about slow apps.
578 r.startLaunchTickingLocked();
579
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700580 // Have the window manager re-evaluate the orientation of
581 // the screen based on the new activity order. Note that
582 // as a result of this, it can call back into the activity
583 // manager with a new orientation. We don't care about that,
584 // because the activity is not currently running so we are
585 // just restarting it anyway.
586 if (checkConfig) {
587 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
588 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -0800589 r.mayFreezeScreenLocked(app) ? r.appToken : null);
Dianne Hackborn813075a62011-11-14 17:45:19 -0800590 mService.updateConfigurationLocked(config, r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700591 }
592
593 r.app = app;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700594 app.waitingToKill = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700595
596 if (localLOGV) Slog.v(TAG, "Launching: " + r);
597
598 int idx = app.activities.indexOf(r);
599 if (idx < 0) {
600 app.activities.add(r);
601 }
602 mService.updateLruProcessLocked(app, true, true);
603
604 try {
605 if (app.thread == null) {
606 throw new RemoteException();
607 }
608 List<ResultInfo> results = null;
609 List<Intent> newIntents = null;
610 if (andResume) {
611 results = r.results;
612 newIntents = r.newIntents;
613 }
614 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
615 + " icicle=" + r.icicle
616 + " with results=" + results + " newIntents=" + newIntents
617 + " andResume=" + andResume);
618 if (andResume) {
619 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
620 System.identityHashCode(r),
621 r.task.taskId, r.shortComponentName);
622 }
623 if (r.isHomeActivity) {
624 mService.mHomeProcess = app;
625 }
626 mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800627 r.sleeping = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400628 r.forceNewConfig = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700629 showAskCompatModeDialogLocked(r);
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700630 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700631 String profileFile = null;
632 ParcelFileDescriptor profileFd = null;
633 boolean profileAutoStop = false;
634 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
635 if (mService.mProfileProc == null || mService.mProfileProc == app) {
636 mService.mProfileProc = app;
637 profileFile = mService.mProfileFile;
638 profileFd = mService.mProfileFd;
639 profileAutoStop = mService.mAutoStopProfiler;
640 }
641 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -0700642 app.hasShownUi = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700643 app.pendingUiClean = true;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700644 if (profileFd != null) {
645 try {
646 profileFd = profileFd.dup();
647 } catch (IOException e) {
648 profileFd = null;
649 }
650 }
Dianne Hackbornbe707852011-11-11 14:32:10 -0800651 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
Dianne Hackborn813075a62011-11-14 17:45:19 -0800652 System.identityHashCode(r), r.info,
653 new Configuration(mService.mConfiguration),
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700654 r.compat, r.icicle, results, newIntents, !andResume,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700655 mService.isNextTransitionForward(), profileFile, profileFd,
656 profileAutoStop);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700657
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700658 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700659 // This may be a heavy-weight process! Note that the package
660 // manager will ensure that only activity can run in the main
661 // process of the .apk, which is the only thing that will be
662 // considered heavy-weight.
663 if (app.processName.equals(app.info.packageName)) {
664 if (mService.mHeavyWeightProcess != null
665 && mService.mHeavyWeightProcess != app) {
666 Log.w(TAG, "Starting new heavy weight process " + app
667 + " when already running "
668 + mService.mHeavyWeightProcess);
669 }
670 mService.mHeavyWeightProcess = app;
671 Message msg = mService.mHandler.obtainMessage(
672 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
673 msg.obj = r;
674 mService.mHandler.sendMessage(msg);
675 }
676 }
677
678 } catch (RemoteException e) {
679 if (r.launchFailed) {
680 // This is the second time we failed -- finish activity
681 // and give up.
682 Slog.e(TAG, "Second failure launching "
683 + r.intent.getComponent().flattenToShortString()
684 + ", giving up", e);
685 mService.appDiedLocked(app, app.pid, app.thread);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800686 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700687 "2nd-crash");
688 return false;
689 }
690
691 // This is the first time we failed -- restart process and
692 // retry.
693 app.activities.remove(r);
694 throw e;
695 }
696
697 r.launchFailed = false;
698 if (updateLRUListLocked(r)) {
699 Slog.w(TAG, "Activity " + r
700 + " being launched, but already in LRU list");
701 }
702
703 if (andResume) {
704 // As part of the process of launching, ActivityThread also performs
705 // a resume.
706 r.state = ActivityState.RESUMED;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700707 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
708 + " (starting new instance)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700709 r.stopped = false;
710 mResumedActivity = r;
711 r.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -0800712 if (mMainStack) {
713 mService.addRecentTaskLocked(r.task);
714 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700715 completeResumeLocked(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800716 checkReadyForSleepLocked();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700717 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Launch completed; removing icicle of " + r.icicle);
718 r.icicle = null;
719 r.haveState = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700720 } else {
721 // This activity is not starting in the resumed state... which
722 // should look like we asked it to pause+stop (but remain visible),
723 // and it has done so and reported back the current icicle and
724 // other state.
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700725 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
726 + " (starting in stopped state)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700727 r.state = ActivityState.STOPPED;
728 r.stopped = true;
729 }
730
731 // Launch the new version setup screen if needed. We do this -after-
732 // launching the initial activity (that is, home), so that it can have
733 // a chance to initialize itself while in the background, making the
734 // switch back to it faster and look better.
735 if (mMainStack) {
736 mService.startSetupActivityLocked();
737 }
738
739 return true;
740 }
741
742 private final void startSpecificActivityLocked(ActivityRecord r,
743 boolean andResume, boolean checkConfig) {
744 // Is this activity's application already running?
745 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
746 r.info.applicationInfo.uid);
747
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700748 if (r.launchTime == 0) {
749 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700750 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700751 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700752 }
753 } else if (mInitialStartTime == 0) {
754 mInitialStartTime = SystemClock.uptimeMillis();
755 }
756
757 if (app != null && app.thread != null) {
758 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700759 app.addPackage(r.info.packageName);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700760 realStartActivityLocked(r, app, andResume, checkConfig);
761 return;
762 } catch (RemoteException e) {
763 Slog.w(TAG, "Exception when starting activity "
764 + r.intent.getComponent().flattenToShortString(), e);
765 }
766
767 // If a dead object exception was thrown -- fall through to
768 // restart the application.
769 }
770
771 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800772 "activity", r.intent.getComponent(), false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700773 }
774
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800775 void stopIfSleepingLocked() {
776 if (mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700777 if (!mGoingToSleep.isHeld()) {
778 mGoingToSleep.acquire();
779 if (mLaunchingActivity.isHeld()) {
780 mLaunchingActivity.release();
781 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
782 }
783 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800784 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
785 Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
786 mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
787 checkReadyForSleepLocked();
788 }
789 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700790
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800791 void awakeFromSleepingLocked() {
792 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
793 mSleepTimeout = false;
794 if (mGoingToSleep.isHeld()) {
795 mGoingToSleep.release();
796 }
797 // Ensure activities are no longer sleeping.
798 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700799 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800800 r.setSleeping(false);
801 }
802 mGoingToSleepActivities.clear();
803 }
804
805 void activitySleptLocked(ActivityRecord r) {
806 mGoingToSleepActivities.remove(r);
807 checkReadyForSleepLocked();
808 }
809
810 void checkReadyForSleepLocked() {
811 if (!mService.isSleeping()) {
812 // Do not care.
813 return;
814 }
815
816 if (!mSleepTimeout) {
817 if (mResumedActivity != null) {
818 // Still have something resumed; can't sleep until it is paused.
819 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700820 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
821 startPausingLocked(false, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800822 return;
823 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800824 if (mPausingActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800825 // Still waiting for something to pause; can't sleep yet.
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800826 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800827 return;
828 }
829
830 if (mStoppingActivities.size() > 0) {
831 // Still need to tell some activities to stop; can't sleep yet.
832 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
833 + mStoppingActivities.size() + " activities");
Dianne Hackborn80a7ac12011-09-22 18:32:52 -0700834 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800835 return;
836 }
837
838 ensureActivitiesVisibleLocked(null, 0);
839
840 // Make sure any stopped but visible activities are now sleeping.
841 // This ensures that the activity's onStop() is called.
842 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700843 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800844 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
845 r.setSleeping(true);
846 }
847 }
848
849 if (mGoingToSleepActivities.size() > 0) {
850 // Still need to tell some activities to sleep; can't sleep yet.
851 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
852 + mGoingToSleepActivities.size() + " activities");
853 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700854 }
855 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800856
857 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
858
859 if (mGoingToSleep.isHeld()) {
860 mGoingToSleep.release();
861 }
862 if (mService.mShuttingDown) {
863 mService.notifyAll();
864 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700865 }
866
Dianne Hackbornd2835932010-12-13 16:28:46 -0800867 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -0800868 if (who.noDisplay) {
869 return null;
870 }
871
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800872 Resources res = mService.mContext.getResources();
873 int w = mThumbnailWidth;
874 int h = mThumbnailHeight;
875 if (w < 0) {
876 mThumbnailWidth = w =
877 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
878 mThumbnailHeight = h =
879 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
880 }
881
882 if (w > 0) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800883 return mService.mWindowManager.screenshotApplications(who.appToken, w, h);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800884 }
885 return null;
886 }
887
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700888 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800889 if (mPausingActivity != null) {
890 RuntimeException e = new RuntimeException();
891 Slog.e(TAG, "Trying to pause when pause is already pending for "
892 + mPausingActivity, e);
893 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700894 ActivityRecord prev = mResumedActivity;
895 if (prev == null) {
896 RuntimeException e = new RuntimeException();
897 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
898 resumeTopActivityLocked(null);
899 return;
900 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700901 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
902 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700903 mResumedActivity = null;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800904 mPausingActivity = prev;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700905 mLastPausedActivity = prev;
906 prev.state = ActivityState.PAUSING;
907 prev.task.touchActiveTime();
Dianne Hackbornf26fd992011-04-08 18:14:09 -0700908 prev.updateThumbnail(screenshotActivities(prev), null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700909
910 mService.updateCpuStats();
911
912 if (prev.app != null && prev.app.thread != null) {
913 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
914 try {
915 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
916 System.identityHashCode(prev),
917 prev.shortComponentName);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800918 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
919 userLeaving, prev.configChangeFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700920 if (mMainStack) {
921 mService.updateUsageStats(prev, false);
922 }
923 } catch (Exception e) {
924 // Ignore exception, if process died other code will cleanup.
925 Slog.w(TAG, "Exception thrown during pause", e);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800926 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700927 mLastPausedActivity = null;
928 }
929 } else {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800930 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700931 mLastPausedActivity = null;
932 }
933
934 // If we are not going to sleep, we want to ensure the device is
935 // awake until the next activity is started.
936 if (!mService.mSleeping && !mService.mShuttingDown) {
937 mLaunchingActivity.acquire();
938 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
939 // To be safe, don't allow the wake lock to be held for too long.
940 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
941 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
942 }
943 }
944
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800945
946 if (mPausingActivity != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700947 // Have the window manager pause its key dispatching until the new
948 // activity has started. If we're pausing the activity just because
949 // the screen is being turned off and the UI is sleeping, don't interrupt
950 // key dispatch; the same activity will pick it up again on wakeup.
951 if (!uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800952 prev.pauseKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700953 } else {
954 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
955 }
956
957 // Schedule a pause timeout in case the app doesn't respond.
958 // We don't give it much time because this directly impacts the
959 // responsiveness seen by the user.
960 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
961 msg.obj = prev;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700962 prev.pauseTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700963 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
964 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
965 } else {
966 // This activity failed to schedule the
967 // pause, so just treat it as being paused now.
968 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800969 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700970 }
971 }
972
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800973 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700974 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800975 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700976
977 ActivityRecord r = null;
978
979 synchronized (mService) {
980 int index = indexOfTokenLocked(token);
981 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700982 r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700983 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800984 if (mPausingActivity == r) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700985 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
986 + (timeout ? " (due to timeout)" : " (pause complete)"));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700987 r.state = ActivityState.PAUSED;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800988 completePauseLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700989 } else {
990 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
991 System.identityHashCode(r), r.shortComponentName,
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800992 mPausingActivity != null
993 ? mPausingActivity.shortComponentName : "(none)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700994 }
995 }
996 }
997 }
998
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700999 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
1000 CharSequence description) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001001 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Saving icicle of " + r + ": " + icicle);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001002 r.icicle = icicle;
1003 r.haveState = true;
1004 r.updateThumbnail(thumbnail, description);
1005 r.stopped = true;
1006 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
1007 r.state = ActivityState.STOPPED;
1008 if (!r.finishing) {
1009 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07001010 destroyActivityLocked(r, true, false, "stop-config");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001011 resumeTopActivityLocked(null);
Dianne Hackborn50685602011-12-01 12:23:37 -08001012 } else {
1013 // Now that this process has stopped, we may want to consider
1014 // it to be the previous app to try to keep around in case
1015 // the user wants to return to it.
1016 ProcessRecord fgApp = null;
1017 if (mResumedActivity != null) {
1018 fgApp = mResumedActivity.app;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001019 } else if (mPausingActivity != null) {
1020 fgApp = mPausingActivity.app;
Dianne Hackborn50685602011-12-01 12:23:37 -08001021 }
1022 if (r.app != null && fgApp != null && r.app != fgApp
1023 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
1024 && r.app != mService.mHomeProcess) {
1025 mService.mPreviousProcess = r.app;
1026 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
1027 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001028 }
1029 }
1030 }
1031
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001032 private final void completePauseLocked() {
1033 ActivityRecord prev = mPausingActivity;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001034 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
1035
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001036 if (prev != null) {
1037 if (prev.finishing) {
1038 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
1039 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE);
1040 } else if (prev.app != null) {
1041 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
1042 if (prev.waitingVisible) {
1043 prev.waitingVisible = false;
1044 mWaitingVisibleActivities.remove(prev);
1045 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
1046 TAG, "Complete pause, no longer waiting: " + prev);
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001047 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001048 if (prev.configDestroy) {
1049 // The previous is being paused because the configuration
1050 // is changing, which means it is actually stopping...
1051 // To juggle the fact that we are also starting a new
1052 // instance right now, we need to first completely stop
1053 // the current instance before starting the new one.
1054 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
1055 destroyActivityLocked(prev, true, false, "pause-config");
1056 } else {
1057 mStoppingActivities.add(prev);
1058 if (mStoppingActivities.size() > 3) {
1059 // If we already have a few activities waiting to stop,
1060 // then give up on things going idle and start clearing
1061 // them out.
1062 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
1063 scheduleIdleLocked();
1064 } else {
1065 checkReadyForSleepLocked();
1066 }
1067 }
1068 } else {
1069 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
1070 prev = null;
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001071 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001072 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001073 }
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001074
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001075 if (!mService.isSleeping()) {
1076 resumeTopActivityLocked(prev);
1077 } else {
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001078 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001079 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001080
1081 if (prev != null) {
1082 prev.resumeKeyDispatchingLocked();
1083 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001084
1085 if (prev.app != null && prev.cpuTimeAtResume > 0
1086 && mService.mBatteryStatsService.isOnBattery()) {
1087 long diff = 0;
1088 synchronized (mService.mProcessStatsThread) {
1089 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
1090 - prev.cpuTimeAtResume;
1091 }
1092 if (diff > 0) {
1093 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
1094 synchronized (bsi) {
1095 BatteryStatsImpl.Uid.Proc ps =
1096 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
1097 prev.info.packageName);
1098 if (ps != null) {
1099 ps.addForegroundTimeLocked(diff);
1100 }
1101 }
1102 }
1103 }
1104 prev.cpuTimeAtResume = 0; // reset it
1105 }
1106
1107 /**
1108 * Once we know that we have asked an application to put an activity in
1109 * the resumed state (either by launching it or explicitly telling it),
1110 * this function updates the rest of our state to match that fact.
1111 */
1112 private final void completeResumeLocked(ActivityRecord next) {
1113 next.idle = false;
1114 next.results = null;
1115 next.newIntents = null;
1116
1117 // schedule an idle timeout in case the app doesn't do it for us.
1118 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1119 msg.obj = next;
1120 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
1121
1122 if (false) {
1123 // The activity was never told to pause, so just keep
1124 // things going as-is. To maintain our own state,
1125 // we need to emulate it coming back and saying it is
1126 // idle.
1127 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
1128 msg.obj = next;
1129 mHandler.sendMessage(msg);
1130 }
1131
1132 if (mMainStack) {
1133 mService.reportResumedActivityLocked(next);
1134 }
1135
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001136 next.clearThumbnail();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001137 if (mMainStack) {
1138 mService.setFocusedActivityLocked(next);
1139 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001140 next.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001141 ensureActivitiesVisibleLocked(null, 0);
1142 mService.mWindowManager.executeAppTransition();
1143 mNoAnimActivities.clear();
1144
1145 // Mark the point when the activity is resuming
1146 // TODO: To be more accurate, the mark should be before the onCreate,
1147 // not after the onResume. But for subsequent starts, onResume is fine.
1148 if (next.app != null) {
1149 synchronized (mService.mProcessStatsThread) {
1150 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1151 }
1152 } else {
1153 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1154 }
1155 }
1156
1157 /**
1158 * Make sure that all activities that need to be visible (that is, they
1159 * currently can be seen by the user) actually are.
1160 */
1161 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1162 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1163 if (DEBUG_VISBILITY) Slog.v(
1164 TAG, "ensureActivitiesVisible behind " + top
1165 + " configChanges=0x" + Integer.toHexString(configChanges));
1166
1167 // If the top activity is not fullscreen, then we need to
1168 // make sure any activities under it are now visible.
1169 final int count = mHistory.size();
1170 int i = count-1;
1171 while (mHistory.get(i) != top) {
1172 i--;
1173 }
1174 ActivityRecord r;
1175 boolean behindFullscreen = false;
1176 for (; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001177 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001178 if (DEBUG_VISBILITY) Slog.v(
1179 TAG, "Make visible? " + r + " finishing=" + r.finishing
1180 + " state=" + r.state);
1181 if (r.finishing) {
1182 continue;
1183 }
1184
1185 final boolean doThisProcess = onlyThisProcess == null
1186 || onlyThisProcess.equals(r.processName);
1187
1188 // First: if this is not the current activity being started, make
1189 // sure it matches the current configuration.
1190 if (r != starting && doThisProcess) {
1191 ensureActivityConfigurationLocked(r, 0);
1192 }
1193
1194 if (r.app == null || r.app.thread == null) {
1195 if (onlyThisProcess == null
1196 || onlyThisProcess.equals(r.processName)) {
1197 // This activity needs to be visible, but isn't even
1198 // running... get it started, but don't resume it
1199 // at this point.
1200 if (DEBUG_VISBILITY) Slog.v(
1201 TAG, "Start and freeze screen for " + r);
1202 if (r != starting) {
1203 r.startFreezingScreenLocked(r.app, configChanges);
1204 }
1205 if (!r.visible) {
1206 if (DEBUG_VISBILITY) Slog.v(
1207 TAG, "Starting and making visible: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001208 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001209 }
1210 if (r != starting) {
1211 startSpecificActivityLocked(r, false, false);
1212 }
1213 }
1214
1215 } else if (r.visible) {
1216 // If this activity is already visible, then there is nothing
1217 // else to do here.
1218 if (DEBUG_VISBILITY) Slog.v(
1219 TAG, "Skipping: already visible at " + r);
1220 r.stopFreezingScreenLocked(false);
1221
1222 } else if (onlyThisProcess == null) {
1223 // This activity is not currently visible, but is running.
1224 // Tell it to become visible.
1225 r.visible = true;
1226 if (r.state != ActivityState.RESUMED && r != starting) {
1227 // If this activity is paused, tell it
1228 // to now show its window.
1229 if (DEBUG_VISBILITY) Slog.v(
1230 TAG, "Making visible and scheduling visibility: " + r);
1231 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001232 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001233 r.sleeping = false;
Dianne Hackborn905577f2011-09-07 18:31:28 -07001234 r.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001235 r.app.thread.scheduleWindowVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001236 r.stopFreezingScreenLocked(false);
1237 } catch (Exception e) {
1238 // Just skip on any failure; we'll make it
1239 // visible when it next restarts.
1240 Slog.w(TAG, "Exception thrown making visibile: "
1241 + r.intent.getComponent(), e);
1242 }
1243 }
1244 }
1245
1246 // Aggregate current change flags.
1247 configChanges |= r.configChangeFlags;
1248
1249 if (r.fullscreen) {
1250 // At this point, nothing else needs to be shown
1251 if (DEBUG_VISBILITY) Slog.v(
1252 TAG, "Stopping: fullscreen at " + r);
1253 behindFullscreen = true;
1254 i--;
1255 break;
1256 }
1257 }
1258
1259 // Now for any activities that aren't visible to the user, make
1260 // sure they no longer are keeping the screen frozen.
1261 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001262 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001263 if (DEBUG_VISBILITY) Slog.v(
1264 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1265 + " state=" + r.state
1266 + " behindFullscreen=" + behindFullscreen);
1267 if (!r.finishing) {
1268 if (behindFullscreen) {
1269 if (r.visible) {
1270 if (DEBUG_VISBILITY) Slog.v(
1271 TAG, "Making invisible: " + r);
1272 r.visible = false;
1273 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001274 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001275 if ((r.state == ActivityState.STOPPING
1276 || r.state == ActivityState.STOPPED)
1277 && r.app != null && r.app.thread != null) {
1278 if (DEBUG_VISBILITY) Slog.v(
1279 TAG, "Scheduling invisibility: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001280 r.app.thread.scheduleWindowVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001281 }
1282 } catch (Exception e) {
1283 // Just skip on any failure; we'll make it
1284 // visible when it next restarts.
1285 Slog.w(TAG, "Exception thrown making hidden: "
1286 + r.intent.getComponent(), e);
1287 }
1288 } else {
1289 if (DEBUG_VISBILITY) Slog.v(
1290 TAG, "Already invisible: " + r);
1291 }
1292 } else if (r.fullscreen) {
1293 if (DEBUG_VISBILITY) Slog.v(
1294 TAG, "Now behindFullscreen: " + r);
1295 behindFullscreen = true;
1296 }
1297 }
1298 i--;
1299 }
1300 }
1301
1302 /**
1303 * Version of ensureActivitiesVisible that can easily be called anywhere.
1304 */
1305 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1306 int configChanges) {
1307 ActivityRecord r = topRunningActivityLocked(null);
1308 if (r != null) {
1309 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1310 }
1311 }
1312
1313 /**
1314 * Ensure that the top activity in the stack is resumed.
1315 *
1316 * @param prev The previously resumed activity, for when in the process
1317 * of pausing; can be null to call from elsewhere.
1318 *
1319 * @return Returns true if something is being resumed, or false if
1320 * nothing happened.
1321 */
1322 final boolean resumeTopActivityLocked(ActivityRecord prev) {
1323 // Find the first activity that is not finishing.
1324 ActivityRecord next = topRunningActivityLocked(null);
1325
1326 // Remember how we'll process this pause/resume situation, and ensure
1327 // that the state is reset however we wind up proceeding.
1328 final boolean userLeaving = mUserLeaving;
1329 mUserLeaving = false;
1330
1331 if (next == null) {
1332 // There are no more activities! Let's just start up the
1333 // Launcher...
1334 if (mMainStack) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001335 return mService.startHomeActivityLocked(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001336 }
1337 }
1338
1339 next.delayedResume = false;
1340
1341 // If the top activity is the resumed one, nothing to do.
1342 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1343 // Make sure we have executed any pending transitions, since there
1344 // should be nothing left to do at this point.
1345 mService.mWindowManager.executeAppTransition();
1346 mNoAnimActivities.clear();
1347 return false;
1348 }
1349
1350 // If we are sleeping, and there is no resumed activity, and the top
1351 // activity is paused, well that is the state we want.
1352 if ((mService.mSleeping || mService.mShuttingDown)
1353 && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
1354 // Make sure we have executed any pending transitions, since there
1355 // should be nothing left to do at this point.
1356 mService.mWindowManager.executeAppTransition();
1357 mNoAnimActivities.clear();
1358 return false;
1359 }
1360
1361 // The activity may be waiting for stop, but that is no longer
1362 // appropriate for it.
1363 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001364 mGoingToSleepActivities.remove(next);
1365 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001366 mWaitingVisibleActivities.remove(next);
1367
1368 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1369
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001370 // If we are currently pausing an activity, then don't do anything
1371 // until that is done.
1372 if (mPausingActivity != null) {
1373 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
1374 return false;
1375 }
1376
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001377 // Okay we are now going to start a switch, to 'next'. We may first
1378 // have to pause the current activity, but this is an important point
1379 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001380 // XXX "App Redirected" dialog is getting too many false positives
1381 // at this point, so turn off for now.
1382 if (false) {
1383 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1384 long now = SystemClock.uptimeMillis();
1385 final boolean inTime = mLastStartedActivity.startTime != 0
1386 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1387 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1388 final int nextUid = next.info.applicationInfo.uid;
1389 if (inTime && lastUid != nextUid
1390 && lastUid != next.launchedFromUid
1391 && mService.checkPermission(
1392 android.Manifest.permission.STOP_APP_SWITCHES,
1393 -1, next.launchedFromUid)
1394 != PackageManager.PERMISSION_GRANTED) {
1395 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1396 } else {
1397 next.startTime = now;
1398 mLastStartedActivity = next;
1399 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001400 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001401 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001402 mLastStartedActivity = next;
1403 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001404 }
1405
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001406 // We need to start pausing the current activity so the top one
1407 // can be resumed...
1408 if (mResumedActivity != null) {
1409 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
1410 startPausingLocked(userLeaving, false);
1411 return true;
1412 }
1413
1414 if (prev != null && prev != next) {
1415 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1416 prev.waitingVisible = true;
1417 mWaitingVisibleActivities.add(prev);
1418 if (DEBUG_SWITCH) Slog.v(
1419 TAG, "Resuming top, waiting visible to hide: " + prev);
1420 } else {
1421 // The next activity is already visible, so hide the previous
1422 // activity's windows right now so we can show the new one ASAP.
1423 // We only do this if the previous is finishing, which should mean
1424 // it is on top of the one being resumed so hiding it quickly
1425 // is good. Otherwise, we want to do the normal route of allowing
1426 // the resumed activity to be shown so we can decide if the
1427 // previous should actually be hidden depending on whether the
1428 // new one is found to be full-screen or not.
1429 if (prev.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001430 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001431 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1432 + prev + ", waitingVisible="
1433 + (prev != null ? prev.waitingVisible : null)
1434 + ", nowVisible=" + next.nowVisible);
1435 } else {
1436 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1437 + prev + ", waitingVisible="
1438 + (prev != null ? prev.waitingVisible : null)
1439 + ", nowVisible=" + next.nowVisible);
1440 }
1441 }
1442 }
1443
Dianne Hackborne7f97212011-02-24 14:40:20 -08001444 // Launching this app's activity, make sure the app is no longer
1445 // considered stopped.
1446 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07001447 // TODO: Apply to the correct userId
Dianne Hackborne7f97212011-02-24 14:40:20 -08001448 AppGlobals.getPackageManager().setPackageStoppedState(
1449 next.packageName, false);
1450 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001451 } catch (IllegalArgumentException e) {
1452 Slog.w(TAG, "Failed trying to unstop package "
1453 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001454 }
1455
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001456 // We are starting up the next activity, so tell the window manager
1457 // that the previous one will be hidden soon. This way it can know
1458 // to ignore it when computing the desired screen orientation.
1459 if (prev != null) {
1460 if (prev.finishing) {
1461 if (DEBUG_TRANSITION) Slog.v(TAG,
1462 "Prepare close transition: prev=" + prev);
1463 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001464 mService.mWindowManager.prepareAppTransition(
1465 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001466 } else {
1467 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1468 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001469 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001470 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001471 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1472 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001473 } else {
1474 if (DEBUG_TRANSITION) Slog.v(TAG,
1475 "Prepare open transition: prev=" + prev);
1476 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001477 mService.mWindowManager.prepareAppTransition(
1478 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001479 } else {
1480 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1481 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001482 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001483 }
1484 }
1485 if (false) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001486 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1487 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001488 }
1489 } else if (mHistory.size() > 1) {
1490 if (DEBUG_TRANSITION) Slog.v(TAG,
1491 "Prepare open transition: no previous");
1492 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001493 mService.mWindowManager.prepareAppTransition(
1494 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001495 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001496 mService.mWindowManager.prepareAppTransition(
1497 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001498 }
1499 }
1500
1501 if (next.app != null && next.app.thread != null) {
1502 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1503
1504 // This activity is now becoming visible.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001505 mService.mWindowManager.setAppVisibility(next.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001506
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001507 // schedule launch ticks to collect information about slow apps.
1508 next.startLaunchTickingLocked();
1509
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001510 ActivityRecord lastResumedActivity = mResumedActivity;
1511 ActivityState lastState = next.state;
1512
1513 mService.updateCpuStats();
1514
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001515 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001516 next.state = ActivityState.RESUMED;
1517 mResumedActivity = next;
1518 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001519 if (mMainStack) {
1520 mService.addRecentTaskLocked(next.task);
1521 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001522 mService.updateLruProcessLocked(next.app, true, true);
1523 updateLRUListLocked(next);
1524
1525 // Have the window manager re-evaluate the orientation of
1526 // the screen based on the new activity order.
1527 boolean updated = false;
1528 if (mMainStack) {
1529 synchronized (mService) {
1530 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1531 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001532 next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001533 if (config != null) {
1534 next.frozenBeforeDestroy = true;
1535 }
Dianne Hackborn813075a62011-11-14 17:45:19 -08001536 updated = mService.updateConfigurationLocked(config, next, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001537 }
1538 }
1539 if (!updated) {
1540 // The configuration update wasn't able to keep the existing
1541 // instance of the activity, and instead started a new one.
1542 // We should be all done, but let's just make sure our activity
1543 // is still at the top and schedule another run if something
1544 // weird happened.
1545 ActivityRecord nextNext = topRunningActivityLocked(null);
1546 if (DEBUG_SWITCH) Slog.i(TAG,
1547 "Activity config changed during resume: " + next
1548 + ", new next: " + nextNext);
1549 if (nextNext != next) {
1550 // Do over!
1551 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1552 }
1553 if (mMainStack) {
1554 mService.setFocusedActivityLocked(next);
1555 }
1556 ensureActivitiesVisibleLocked(null, 0);
1557 mService.mWindowManager.executeAppTransition();
1558 mNoAnimActivities.clear();
1559 return true;
1560 }
1561
1562 try {
1563 // Deliver all pending results.
1564 ArrayList a = next.results;
1565 if (a != null) {
1566 final int N = a.size();
1567 if (!next.finishing && N > 0) {
1568 if (DEBUG_RESULTS) Slog.v(
1569 TAG, "Delivering results to " + next
1570 + ": " + a);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001571 next.app.thread.scheduleSendResult(next.appToken, a);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001572 }
1573 }
1574
1575 if (next.newIntents != null) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001576 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001577 }
1578
1579 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
1580 System.identityHashCode(next),
1581 next.task.taskId, next.shortComponentName);
1582
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001583 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001584 showAskCompatModeDialogLocked(next);
Dianne Hackborn905577f2011-09-07 18:31:28 -07001585 next.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001586 next.app.thread.scheduleResumeActivity(next.appToken,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001587 mService.isNextTransitionForward());
1588
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001589 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001590
1591 } catch (Exception e) {
1592 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001593 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1594 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001595 next.state = lastState;
1596 mResumedActivity = lastResumedActivity;
1597 Slog.i(TAG, "Restarting because process died: " + next);
1598 if (!next.hasBeenLaunched) {
1599 next.hasBeenLaunched = true;
1600 } else {
1601 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1602 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001603 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001604 mService.compatibilityInfoForPackageLocked(
1605 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001606 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001607 next.labelRes, next.icon, next.windowFlags,
1608 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001609 }
1610 }
1611 startSpecificActivityLocked(next, true, false);
1612 return true;
1613 }
1614
1615 // From this point on, if something goes wrong there is no way
1616 // to recover the activity.
1617 try {
1618 next.visible = true;
1619 completeResumeLocked(next);
1620 } catch (Exception e) {
1621 // If any exception gets thrown, toss away this
1622 // activity and try the next one.
1623 Slog.w(TAG, "Exception thrown during resume of " + next, e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001624 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001625 "resume-exception");
1626 return true;
1627 }
1628
1629 // Didn't need to use the icicle, and it is now out of date.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001630 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Resumed activity; didn't need icicle of: " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001631 next.icicle = null;
1632 next.haveState = false;
1633 next.stopped = false;
1634
1635 } else {
1636 // Whoops, need to restart this activity!
1637 if (!next.hasBeenLaunched) {
1638 next.hasBeenLaunched = true;
1639 } else {
1640 if (SHOW_APP_STARTING_PREVIEW) {
1641 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001642 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001643 mService.compatibilityInfoForPackageLocked(
1644 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001645 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001646 next.labelRes, next.icon, next.windowFlags,
1647 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001648 }
1649 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1650 }
1651 startSpecificActivityLocked(next, true, true);
1652 }
1653
1654 return true;
1655 }
1656
1657 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001658 boolean doResume, boolean keepCurTransition) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001659 final int NH = mHistory.size();
1660
1661 int addPos = -1;
1662
1663 if (!newTask) {
1664 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001665 boolean startIt = true;
1666 for (int i = NH-1; i >= 0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001667 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001668 if (p.finishing) {
1669 continue;
1670 }
1671 if (p.task == r.task) {
1672 // Here it is! Now, if this is not yet visible to the
1673 // user, then just add it without starting; it will
1674 // get started when the user navigates back to it.
1675 addPos = i+1;
1676 if (!startIt) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001677 if (DEBUG_ADD_REMOVE) {
1678 RuntimeException here = new RuntimeException("here");
1679 here.fillInStackTrace();
1680 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos,
1681 here);
1682 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001683 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001684 r.putInHistory();
Dianne Hackbornbe707852011-11-11 14:32:10 -08001685 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001686 r.info.screenOrientation, r.fullscreen);
1687 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001688 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001689 }
1690 return;
1691 }
1692 break;
1693 }
1694 if (p.fullscreen) {
1695 startIt = false;
1696 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001697 }
1698 }
1699
1700 // Place a new activity at top of stack, so it is next to interact
1701 // with the user.
1702 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001703 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001704 }
1705
1706 // If we are not placing the new activity frontmost, we do not want
1707 // to deliver the onUserLeaving callback to the actual frontmost
1708 // activity
1709 if (addPos < NH) {
1710 mUserLeaving = false;
1711 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1712 }
1713
1714 // Slot the activity into the history stack and proceed
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001715 if (DEBUG_ADD_REMOVE) {
1716 RuntimeException here = new RuntimeException("here");
1717 here.fillInStackTrace();
1718 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos, here);
1719 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001720 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001721 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001722 r.frontOfTask = newTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001723 if (NH > 0) {
1724 // We want to show the starting preview window if we are
1725 // switching to a new task, or the next activity's process is
1726 // not currently running.
1727 boolean showStartingIcon = newTask;
1728 ProcessRecord proc = r.app;
1729 if (proc == null) {
1730 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1731 }
1732 if (proc == null || proc.thread == null) {
1733 showStartingIcon = true;
1734 }
1735 if (DEBUG_TRANSITION) Slog.v(TAG,
1736 "Prepare open transition: starting " + r);
1737 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001738 mService.mWindowManager.prepareAppTransition(
1739 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001740 mNoAnimActivities.add(r);
1741 } else if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
1742 mService.mWindowManager.prepareAppTransition(
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001743 WindowManagerPolicy.TRANSIT_TASK_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001744 mNoAnimActivities.remove(r);
1745 } else {
1746 mService.mWindowManager.prepareAppTransition(newTask
1747 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001748 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001749 mNoAnimActivities.remove(r);
1750 }
1751 mService.mWindowManager.addAppToken(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001752 addPos, r.appToken, r.task.taskId, r.info.screenOrientation, r.fullscreen);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001753 boolean doShow = true;
1754 if (newTask) {
1755 // Even though this activity is starting fresh, we still need
1756 // to reset it to make sure we apply affinities to move any
1757 // existing activities from other tasks in to it.
1758 // If the caller has requested that the target task be
1759 // reset, then do so.
1760 if ((r.intent.getFlags()
1761 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1762 resetTaskIfNeededLocked(r, r);
1763 doShow = topRunningNonDelayedActivityLocked(null) == r;
1764 }
1765 }
1766 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1767 // Figure out if we are transitioning from another activity that is
1768 // "has the same starting icon" as the next one. This allows the
1769 // window manager to keep the previous window it had previously
1770 // created, if it still had one.
1771 ActivityRecord prev = mResumedActivity;
1772 if (prev != null) {
1773 // We don't want to reuse the previous starting preview if:
1774 // (1) The current activity is in a different task.
1775 if (prev.task != r.task) prev = null;
1776 // (2) The current activity is already displayed.
1777 else if (prev.nowVisible) prev = null;
1778 }
1779 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001780 r.appToken, r.packageName, r.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001781 mService.compatibilityInfoForPackageLocked(
1782 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001783 r.labelRes, r.icon, r.windowFlags,
1784 prev != null ? prev.appToken : null, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001785 }
1786 } else {
1787 // If this is the first activity, don't do any fancy animations,
1788 // because there is nothing for it to animate on top of.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001789 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001790 r.info.screenOrientation, r.fullscreen);
1791 }
1792 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001793 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001794 }
1795
1796 if (doResume) {
1797 resumeTopActivityLocked(null);
1798 }
1799 }
1800
Dianne Hackbornbe707852011-11-11 14:32:10 -08001801 final void validateAppTokensLocked() {
1802 mValidateAppTokens.clear();
1803 mValidateAppTokens.ensureCapacity(mHistory.size());
1804 for (int i=0; i<mHistory.size(); i++) {
1805 mValidateAppTokens.add(mHistory.get(i).appToken);
1806 }
1807 mService.mWindowManager.validateAppTokens(mValidateAppTokens);
1808 }
1809
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001810 /**
1811 * Perform a reset of the given task, if needed as part of launching it.
1812 * Returns the new HistoryRecord at the top of the task.
1813 */
1814 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1815 ActivityRecord newActivity) {
1816 boolean forceReset = (newActivity.info.flags
1817 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001818 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1819 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001820 if ((newActivity.info.flags
1821 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1822 forceReset = true;
1823 }
1824 }
1825
1826 final TaskRecord task = taskTop.task;
1827
1828 // We are going to move through the history list so that we can look
1829 // at each activity 'target' with 'below' either the interesting
1830 // activity immediately below it in the stack or null.
1831 ActivityRecord target = null;
1832 int targetI = 0;
1833 int taskTopI = -1;
1834 int replyChainEnd = -1;
1835 int lastReparentPos = -1;
1836 for (int i=mHistory.size()-1; i>=-1; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001837 ActivityRecord below = i >= 0 ? mHistory.get(i) : null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001838
1839 if (below != null && below.finishing) {
1840 continue;
1841 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001842 // Don't check any lower in the stack if we're crossing a user boundary.
1843 if (below != null && below.userId != taskTop.userId) {
1844 break;
1845 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001846 if (target == null) {
1847 target = below;
1848 targetI = i;
1849 // If we were in the middle of a reply chain before this
1850 // task, it doesn't appear like the root of the chain wants
1851 // anything interesting, so drop it.
1852 replyChainEnd = -1;
1853 continue;
1854 }
1855
1856 final int flags = target.info.flags;
1857
1858 final boolean finishOnTaskLaunch =
1859 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1860 final boolean allowTaskReparenting =
1861 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1862
1863 if (target.task == task) {
1864 // We are inside of the task being reset... we'll either
1865 // finish this activity, push it out for another task,
1866 // or leave it as-is. We only do this
1867 // for activities that are not the root of the task (since
1868 // if we finish the root, we may no longer have the task!).
1869 if (taskTopI < 0) {
1870 taskTopI = targetI;
1871 }
1872 if (below != null && below.task == task) {
1873 final boolean clearWhenTaskReset =
1874 (target.intent.getFlags()
1875 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
1876 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
1877 // If this activity is sending a reply to a previous
1878 // activity, we can't do anything with it now until
1879 // we reach the start of the reply chain.
1880 // XXX note that we are assuming the result is always
1881 // to the previous activity, which is almost always
1882 // the case but we really shouldn't count on.
1883 if (replyChainEnd < 0) {
1884 replyChainEnd = targetI;
1885 }
1886 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
1887 && target.taskAffinity != null
1888 && !target.taskAffinity.equals(task.affinity)) {
1889 // If this activity has an affinity for another
1890 // task, then we need to move it out of here. We will
1891 // move it as far out of the way as possible, to the
1892 // bottom of the activity stack. This also keeps it
1893 // correctly ordered with any activities we previously
1894 // moved.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001895 ActivityRecord p = mHistory.get(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001896 if (target.taskAffinity != null
1897 && target.taskAffinity.equals(p.task.affinity)) {
1898 // If the activity currently at the bottom has the
1899 // same task affinity as the one we are moving,
1900 // then merge it into the same task.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001901 target.setTask(p.task, p.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001902 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1903 + " out to bottom task " + p.task);
1904 } else {
1905 mService.mCurTask++;
1906 if (mService.mCurTask <= 0) {
1907 mService.mCurTask = 1;
1908 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001909 target.setTask(new TaskRecord(mService.mCurTask, target.info, null),
1910 null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001911 target.task.affinityIntent = target.intent;
1912 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1913 + " out to new task " + target.task);
1914 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001915 mService.mWindowManager.setAppGroupId(target.appToken, task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001916 if (replyChainEnd < 0) {
1917 replyChainEnd = targetI;
1918 }
1919 int dstPos = 0;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001920 ThumbnailHolder curThumbHolder = target.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001921 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001922 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001923 if (p.finishing) {
1924 continue;
1925 }
1926 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
1927 + " out to target's task " + target.task);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001928 p.setTask(target.task, curThumbHolder, false);
1929 curThumbHolder = p.thumbHolder;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001930 if (DEBUG_ADD_REMOVE) {
1931 RuntimeException here = new RuntimeException("here");
1932 here.fillInStackTrace();
1933 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
1934 + dstPos, here);
1935 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001936 mHistory.remove(srcPos);
1937 mHistory.add(dstPos, p);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001938 mService.mWindowManager.moveAppToken(dstPos, p.appToken);
1939 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001940 dstPos++;
1941 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001942 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001943 }
1944 i++;
1945 }
1946 if (taskTop == p) {
1947 taskTop = below;
1948 }
1949 if (taskTopI == replyChainEnd) {
1950 taskTopI = -1;
1951 }
1952 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001953 } else if (forceReset || finishOnTaskLaunch
1954 || clearWhenTaskReset) {
1955 // If the activity should just be removed -- either
1956 // because it asks for it, or the task should be
1957 // cleared -- then finish it and anything that is
1958 // part of its reply chain.
1959 if (clearWhenTaskReset) {
1960 // In this case, we want to finish this activity
1961 // and everything above it, so be sneaky and pretend
1962 // like these are all in the reply chain.
1963 replyChainEnd = targetI+1;
1964 while (replyChainEnd < mHistory.size() &&
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001965 (mHistory.get(
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001966 replyChainEnd)).task == task) {
1967 replyChainEnd++;
1968 }
1969 replyChainEnd--;
1970 } else if (replyChainEnd < 0) {
1971 replyChainEnd = targetI;
1972 }
1973 ActivityRecord p = null;
1974 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001975 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001976 if (p.finishing) {
1977 continue;
1978 }
1979 if (finishActivityLocked(p, srcPos,
1980 Activity.RESULT_CANCELED, null, "reset")) {
1981 replyChainEnd--;
1982 srcPos--;
1983 }
1984 }
1985 if (taskTop == p) {
1986 taskTop = below;
1987 }
1988 if (taskTopI == replyChainEnd) {
1989 taskTopI = -1;
1990 }
1991 replyChainEnd = -1;
1992 } else {
1993 // If we were in the middle of a chain, well the
1994 // activity that started it all doesn't want anything
1995 // special, so leave it all as-is.
1996 replyChainEnd = -1;
1997 }
1998 } else {
1999 // Reached the bottom of the task -- any reply chain
2000 // should be left as-is.
2001 replyChainEnd = -1;
2002 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002003
2004 } else if (target.resultTo != null && (below == null
2005 || below.task == target.task)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002006 // If this activity is sending a reply to a previous
2007 // activity, we can't do anything with it now until
2008 // we reach the start of the reply chain.
2009 // XXX note that we are assuming the result is always
2010 // to the previous activity, which is almost always
2011 // the case but we really shouldn't count on.
2012 if (replyChainEnd < 0) {
2013 replyChainEnd = targetI;
2014 }
2015
2016 } else if (taskTopI >= 0 && allowTaskReparenting
2017 && task.affinity != null
2018 && task.affinity.equals(target.taskAffinity)) {
2019 // We are inside of another task... if this activity has
2020 // an affinity for our task, then either remove it if we are
2021 // clearing or move it over to our task. Note that
2022 // we currently punt on the case where we are resetting a
2023 // task that is not at the top but who has activities above
2024 // with an affinity to it... this is really not a normal
2025 // case, and we will need to later pull that task to the front
2026 // and usually at that point we will do the reset and pick
2027 // up those remaining activities. (This only happens if
2028 // someone starts an activity in a new task from an activity
2029 // in a task that is not currently on top.)
2030 if (forceReset || finishOnTaskLaunch) {
2031 if (replyChainEnd < 0) {
2032 replyChainEnd = targetI;
2033 }
2034 ActivityRecord p = null;
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002035 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index "
2036 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002037 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002038 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002039 if (p.finishing) {
2040 continue;
2041 }
2042 if (finishActivityLocked(p, srcPos,
2043 Activity.RESULT_CANCELED, null, "reset")) {
2044 taskTopI--;
2045 lastReparentPos--;
2046 replyChainEnd--;
2047 srcPos--;
2048 }
2049 }
2050 replyChainEnd = -1;
2051 } else {
2052 if (replyChainEnd < 0) {
2053 replyChainEnd = targetI;
2054 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002055 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting task at index "
2056 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002057 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002058 ActivityRecord p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002059 if (p.finishing) {
2060 continue;
2061 }
2062 if (lastReparentPos < 0) {
2063 lastReparentPos = taskTopI;
2064 taskTop = p;
2065 } else {
2066 lastReparentPos--;
2067 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002068 if (DEBUG_ADD_REMOVE) {
2069 RuntimeException here = new RuntimeException("here");
2070 here.fillInStackTrace();
2071 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2072 + lastReparentPos, here);
2073 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002074 mHistory.remove(srcPos);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002075 p.setTask(task, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002076 mHistory.add(lastReparentPos, p);
2077 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002078 + " from " + srcPos + " to " + lastReparentPos
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002079 + " in to resetting task " + task);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002080 mService.mWindowManager.moveAppToken(lastReparentPos, p.appToken);
2081 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002082 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002083 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002084 }
2085 }
2086 replyChainEnd = -1;
2087
2088 // Now we've moved it in to place... but what if this is
2089 // a singleTop activity and we have put it on top of another
2090 // instance of the same activity? Then we drop the instance
2091 // below so it remains singleTop.
2092 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2093 for (int j=lastReparentPos-1; j>=0; j--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002094 ActivityRecord p = mHistory.get(j);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002095 if (p.finishing) {
2096 continue;
2097 }
2098 if (p.intent.getComponent().equals(target.intent.getComponent())) {
2099 if (finishActivityLocked(p, j,
2100 Activity.RESULT_CANCELED, null, "replace")) {
2101 taskTopI--;
2102 lastReparentPos--;
2103 }
2104 }
2105 }
2106 }
2107 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002108
2109 } else if (below != null && below.task != target.task) {
2110 // We hit the botton of a task; the reply chain can't
2111 // pass through it.
2112 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002113 }
2114
2115 target = below;
2116 targetI = i;
2117 }
2118
2119 return taskTop;
2120 }
2121
2122 /**
2123 * Perform clear operation as requested by
2124 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2125 * stack to the given task, then look for
2126 * an instance of that activity in the stack and, if found, finish all
2127 * activities on top of it and return the instance.
2128 *
2129 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002130 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002131 * or null if none was found.
2132 */
2133 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002134 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002135 int i = mHistory.size();
2136
2137 // First find the requested task.
2138 while (i > 0) {
2139 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002140 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002141 if (r.task.taskId == taskId) {
2142 i++;
2143 break;
2144 }
2145 }
2146
2147 // Now clear it.
2148 while (i > 0) {
2149 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002150 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002151 if (r.finishing) {
2152 continue;
2153 }
2154 if (r.task.taskId != taskId) {
2155 return null;
2156 }
2157 if (r.realActivity.equals(newR.realActivity)) {
2158 // Here it is! Now finish everything in front...
2159 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002160 while (i < (mHistory.size()-1)) {
2161 i++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002162 r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002163 if (r.task.taskId != taskId) {
2164 break;
2165 }
2166 if (r.finishing) {
2167 continue;
2168 }
2169 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2170 null, "clear")) {
2171 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002172 }
2173 }
2174
2175 // Finally, if this is a normal launch mode (that is, not
2176 // expecting onNewIntent()), then we will finish the current
2177 // instance of the activity so a new fresh one can be started.
2178 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2179 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
2180 if (!ret.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002181 int index = indexOfTokenLocked(ret.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002182 if (index >= 0) {
2183 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
2184 null, "clear");
2185 }
2186 return null;
2187 }
2188 }
2189
2190 return ret;
2191 }
2192 }
2193
2194 return null;
2195 }
2196
2197 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002198 * Completely remove all activities associated with an existing
2199 * task starting at a specified index.
2200 */
2201 private final void performClearTaskAtIndexLocked(int taskId, int i) {
Dianne Hackborneabd3282011-10-13 16:26:49 -07002202 while (i < mHistory.size()) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002203 ActivityRecord r = mHistory.get(i);
2204 if (r.task.taskId != taskId) {
2205 // Whoops hit the end.
2206 return;
2207 }
2208 if (r.finishing) {
2209 i++;
2210 continue;
2211 }
2212 if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2213 null, "clear")) {
2214 i++;
2215 }
2216 }
2217 }
2218
2219 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002220 * Completely remove all activities associated with an existing task.
2221 */
2222 private final void performClearTaskLocked(int taskId) {
2223 int i = mHistory.size();
2224
2225 // First find the requested task.
2226 while (i > 0) {
2227 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002228 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002229 if (r.task.taskId == taskId) {
2230 i++;
2231 break;
2232 }
2233 }
2234
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002235 // Now find the start and clear it.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002236 while (i > 0) {
2237 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002238 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002239 if (r.finishing) {
2240 continue;
2241 }
2242 if (r.task.taskId != taskId) {
2243 // We hit the bottom. Now finish it all...
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002244 performClearTaskAtIndexLocked(taskId, i+1);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002245 return;
2246 }
2247 }
2248 }
2249
2250 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002251 * Find the activity in the history stack within the given task. Returns
2252 * the index within the history at which it's found, or < 0 if not found.
2253 */
2254 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2255 int i = mHistory.size();
2256 while (i > 0) {
2257 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002258 ActivityRecord candidate = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002259 if (candidate.task.taskId != task) {
2260 break;
2261 }
2262 if (candidate.realActivity.equals(r.realActivity)) {
2263 return i;
2264 }
2265 }
2266
2267 return -1;
2268 }
2269
2270 /**
2271 * Reorder the history stack so that the activity at the given index is
2272 * brought to the front.
2273 */
2274 private final ActivityRecord moveActivityToFrontLocked(int where) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002275 ActivityRecord newTop = mHistory.remove(where);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002276 int top = mHistory.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002277 ActivityRecord oldTop = mHistory.get(top-1);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002278 if (DEBUG_ADD_REMOVE) {
2279 RuntimeException here = new RuntimeException("here");
2280 here.fillInStackTrace();
2281 Slog.i(TAG, "Removing and adding activity " + newTop + " to stack at "
2282 + top, here);
2283 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002284 mHistory.add(top, newTop);
2285 oldTop.frontOfTask = false;
2286 newTop.frontOfTask = true;
2287 return newTop;
2288 }
2289
2290 final int startActivityLocked(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002291 Intent intent, String resolvedType, ActivityInfo aInfo, IBinder resultTo,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002292 String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002293 int callingPid, int callingUid, int startFlags, Bundle options,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002294 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002295
Dianne Hackborna4972e92012-03-14 10:38:05 -07002296 int err = ActivityManager.START_SUCCESS;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002297
2298 ProcessRecord callerApp = null;
2299 if (caller != null) {
2300 callerApp = mService.getRecordForAppLocked(caller);
2301 if (callerApp != null) {
2302 callingPid = callerApp.pid;
2303 callingUid = callerApp.info.uid;
2304 } else {
2305 Slog.w(TAG, "Unable to find app for caller " + caller
2306 + " (pid=" + callingPid + ") when starting: "
2307 + intent.toString());
Dianne Hackborna4972e92012-03-14 10:38:05 -07002308 err = ActivityManager.START_PERMISSION_DENIED;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002309 }
2310 }
2311
Dianne Hackborna4972e92012-03-14 10:38:05 -07002312 if (err == ActivityManager.START_SUCCESS) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08002313 Slog.i(TAG, "START {" + intent.toShortString(true, true, true, false)
2314 + "} from pid " + (callerApp != null ? callerApp.pid : callingPid));
Dianne Hackbornefb58102010-10-14 16:47:34 -07002315 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002316
2317 ActivityRecord sourceRecord = null;
2318 ActivityRecord resultRecord = null;
2319 if (resultTo != null) {
2320 int index = indexOfTokenLocked(resultTo);
2321 if (DEBUG_RESULTS) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002322 TAG, "Will send result to " + resultTo + " (index " + index + ")");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002323 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002324 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002325 if (requestCode >= 0 && !sourceRecord.finishing) {
2326 resultRecord = sourceRecord;
2327 }
2328 }
2329 }
2330
2331 int launchFlags = intent.getFlags();
2332
2333 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2334 && sourceRecord != null) {
2335 // Transfer the result target from the source activity to the new
2336 // one being started, including any failures.
2337 if (requestCode >= 0) {
Dianne Hackborna4972e92012-03-14 10:38:05 -07002338 return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002339 }
2340 resultRecord = sourceRecord.resultTo;
2341 resultWho = sourceRecord.resultWho;
2342 requestCode = sourceRecord.requestCode;
2343 sourceRecord.resultTo = null;
2344 if (resultRecord != null) {
2345 resultRecord.removeResultsLocked(
2346 sourceRecord, resultWho, requestCode);
2347 }
2348 }
2349
Dianne Hackborna4972e92012-03-14 10:38:05 -07002350 if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002351 // We couldn't find a class that can handle the given Intent.
2352 // That's the end of that!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002353 err = ActivityManager.START_INTENT_NOT_RESOLVED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002354 }
2355
Dianne Hackborna4972e92012-03-14 10:38:05 -07002356 if (err == ActivityManager.START_SUCCESS && aInfo == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002357 // We couldn't find the specific class specified in the Intent.
2358 // Also the end of the line.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002359 err = ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002360 }
2361
Dianne Hackborna4972e92012-03-14 10:38:05 -07002362 if (err != ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002363 if (resultRecord != null) {
2364 sendActivityResultLocked(-1,
2365 resultRecord, resultWho, requestCode,
2366 Activity.RESULT_CANCELED, null);
2367 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002368 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002369 return err;
2370 }
2371
2372 final int perm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002373 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002374 if (perm != PackageManager.PERMISSION_GRANTED) {
2375 if (resultRecord != null) {
2376 sendActivityResultLocked(-1,
2377 resultRecord, resultWho, requestCode,
2378 Activity.RESULT_CANCELED, null);
2379 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002380 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002381 String msg;
2382 if (!aInfo.exported) {
2383 msg = "Permission Denial: starting " + intent.toString()
2384 + " from " + callerApp + " (pid=" + callingPid
2385 + ", uid=" + callingUid + ")"
2386 + " not exported from uid " + aInfo.applicationInfo.uid;
2387 } else {
2388 msg = "Permission Denial: starting " + intent.toString()
2389 + " from " + callerApp + " (pid=" + callingPid
2390 + ", uid=" + callingUid + ")"
2391 + " requires " + aInfo.permission;
2392 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002393 Slog.w(TAG, msg);
2394 throw new SecurityException(msg);
2395 }
2396
2397 if (mMainStack) {
2398 if (mService.mController != null) {
2399 boolean abort = false;
2400 try {
2401 // The Intent we give to the watcher has the extra data
2402 // stripped off, since it can contain private information.
2403 Intent watchIntent = intent.cloneFilter();
2404 abort = !mService.mController.activityStarting(watchIntent,
2405 aInfo.applicationInfo.packageName);
2406 } catch (RemoteException e) {
2407 mService.mController = null;
2408 }
2409
2410 if (abort) {
2411 if (resultRecord != null) {
2412 sendActivityResultLocked(-1,
2413 resultRecord, resultWho, requestCode,
2414 Activity.RESULT_CANCELED, null);
2415 }
2416 // We pretend to the caller that it was really started, but
2417 // they will just get a cancel result.
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002418 mDismissKeyguardOnNextActivity = false;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002419 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002420 }
2421 }
2422 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002423
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002424 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2425 intent, resolvedType, aInfo, mService.mConfiguration,
2426 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002427 if (outActivity != null) {
2428 outActivity[0] = r;
2429 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002430
2431 if (mMainStack) {
2432 if (mResumedActivity == null
2433 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2434 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2435 PendingActivityLaunch pal = new PendingActivityLaunch();
2436 pal.r = r;
2437 pal.sourceRecord = sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002438 pal.startFlags = startFlags;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002439 mService.mPendingActivityLaunches.add(pal);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002440 mDismissKeyguardOnNextActivity = false;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002441 return ActivityManager.START_SWITCHES_CANCELED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002442 }
2443 }
2444
2445 if (mService.mDidAppSwitch) {
2446 // This is the second allowed switch since we stopped switches,
2447 // so now just generally allow switches. Use case: user presses
2448 // home (switches disabled, switch to home, mDidAppSwitch now true);
2449 // user taps a home icon (coming from home so allowed, we hit here
2450 // and now allow anyone to switch again).
2451 mService.mAppSwitchesAllowedTime = 0;
2452 } else {
2453 mService.mDidAppSwitch = true;
2454 }
2455
2456 mService.doPendingActivityLaunchesLocked(false);
2457 }
2458
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002459 err = startActivityUncheckedLocked(r, sourceRecord,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002460 startFlags, true);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002461 if (mDismissKeyguardOnNextActivity && mPausingActivity == null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002462 // Someone asked to have the keyguard dismissed on the next
2463 // activity start, but we are not actually doing an activity
2464 // switch... just dismiss the keyguard now, because we
2465 // probably want to see whatever is behind it.
2466 mDismissKeyguardOnNextActivity = false;
2467 mService.mWindowManager.dismissKeyguard();
2468 }
2469 return err;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002470 }
2471
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002472 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2473 if ((launchFlags &
2474 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2475 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2476 // Caller wants to appear on home activity, so before starting
2477 // their own activity we will bring home to the front.
2478 moveHomeToFrontLocked();
2479 }
2480 }
2481
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002482 final int startActivityUncheckedLocked(ActivityRecord r,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002483 ActivityRecord sourceRecord, int startFlags, boolean doResume) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002484 final Intent intent = r.intent;
2485 final int callingUid = r.launchedFromUid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002486 final int userId = r.userId;
2487
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002488 int launchFlags = intent.getFlags();
2489
2490 // We'll invoke onUserLeaving before onPause only if the launching
2491 // activity did not explicitly state that this is an automated launch.
2492 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2493 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2494 "startActivity() => mUserLeaving=" + mUserLeaving);
2495
2496 // If the caller has asked not to resume at this point, we make note
2497 // of this in the record so that we can skip it when trying to find
2498 // the top running activity.
2499 if (!doResume) {
2500 r.delayedResume = true;
2501 }
2502
2503 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2504 != 0 ? r : null;
2505
2506 // If the onlyIfNeeded flag is set, then we can do this if the activity
2507 // being launched is the same as the one making the call... or, as
2508 // a special case, if we do not know the caller then we count the
2509 // current top activity as the caller.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002510 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002511 ActivityRecord checkedCaller = sourceRecord;
2512 if (checkedCaller == null) {
2513 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2514 }
2515 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2516 // Caller is not the same as launcher, so always needed.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002517 startFlags &= ~ActivityManager.START_FLAG_ONLY_IF_NEEDED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002518 }
2519 }
2520
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002521 if (sourceRecord == null) {
2522 // This activity is not being started from another... in this
2523 // case we -always- start a new task.
2524 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2525 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2526 + intent);
2527 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2528 }
2529 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2530 // The original activity who is starting us is running as a single
2531 // instance... this new activity it is starting must go on its
2532 // own task.
2533 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2534 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2535 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2536 // The activity being started is a single instance... it always
2537 // gets launched into its own task.
2538 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2539 }
2540
2541 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2542 // For whatever reason this activity is being launched into a new
2543 // task... yet the caller has requested a result back. Well, that
2544 // is pretty messed up, so instead immediately send back a cancel
2545 // and let the new task continue launched as normal without a
2546 // dependency on its originator.
2547 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2548 sendActivityResultLocked(-1,
2549 r.resultTo, r.resultWho, r.requestCode,
2550 Activity.RESULT_CANCELED, null);
2551 r.resultTo = null;
2552 }
2553
2554 boolean addingToTask = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002555 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002556 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2557 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2558 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2559 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2560 // If bring to front is requested, and no result is requested, and
2561 // we can find a task that was started with this same
2562 // component, then instead of launching bring that one to the front.
2563 if (r.resultTo == null) {
2564 // See if there is a task to bring to the front. If this is
2565 // a SINGLE_INSTANCE activity, there can be one and only one
2566 // instance of it in the history, and it is always in its own
2567 // unique task, so we do a special search.
2568 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2569 ? findTaskLocked(intent, r.info)
2570 : findActivityLocked(intent, r.info);
2571 if (taskTop != null) {
2572 if (taskTop.task.intent == null) {
2573 // This task was started because of movement of
2574 // the activity based on affinity... now that we
2575 // are actually launching it, we can assign the
2576 // base intent.
2577 taskTop.task.setIntent(intent, r.info);
2578 }
2579 // If the target task is not in the front, then we need
2580 // to bring it to the front... except... well, with
2581 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2582 // to have the same behavior as if a new instance was
2583 // being started, which means not bringing it to the front
2584 // if the caller is not itself in the front.
2585 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002586 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002587 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2588 boolean callerAtFront = sourceRecord == null
2589 || curTop.task == sourceRecord.task;
2590 if (callerAtFront) {
2591 // We really do want to push this one into the
2592 // user's face, right now.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002593 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002594 moveTaskToFrontLocked(taskTop.task, r);
2595 }
2596 }
2597 // If the caller has requested that the target task be
2598 // reset, then do so.
2599 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2600 taskTop = resetTaskIfNeededLocked(taskTop, r);
2601 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002602 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002603 // We don't need to start a new activity, and
2604 // the client said not to do anything if that
2605 // is the case, so this is it! And for paranoia, make
2606 // sure we have correctly resumed the top activity.
2607 if (doResume) {
2608 resumeTopActivityLocked(null);
2609 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002610 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002611 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002612 if ((launchFlags &
2613 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2614 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2615 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002616 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002617 // not be too hard...
2618 reuseTask = taskTop.task;
2619 performClearTaskLocked(taskTop.task.taskId);
2620 reuseTask.setIntent(r.intent, r.info);
2621 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002622 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2623 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2624 // In this situation we want to remove all activities
2625 // from the task up to the one being started. In most
2626 // cases this means we are resetting the task to its
2627 // initial state.
2628 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002629 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002630 if (top != null) {
2631 if (top.frontOfTask) {
2632 // Activity aliases may mean we use different
2633 // intents for the top activity, so make sure
2634 // the task now has the identity of the new
2635 // intent.
2636 top.task.setIntent(r.intent, r.info);
2637 }
2638 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002639 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002640 } else {
2641 // A special case: we need to
2642 // start the activity because it is not currently
2643 // running, and the caller has asked to clear the
2644 // current task to have this activity at the top.
2645 addingToTask = true;
2646 // Now pretend like this activity is being started
2647 // by the top of its task, so it is put in the
2648 // right place.
2649 sourceRecord = taskTop;
2650 }
2651 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2652 // In this case the top activity on the task is the
2653 // same as the one being launched, so we take that
2654 // as a request to bring the task to the foreground.
2655 // If the top activity in the task is the root
2656 // activity, deliver this new intent to it if it
2657 // desires.
2658 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2659 && taskTop.realActivity.equals(r.realActivity)) {
2660 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2661 if (taskTop.frontOfTask) {
2662 taskTop.task.setIntent(r.intent, r.info);
2663 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002664 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002665 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2666 // In this case we are launching the root activity
2667 // of the task, but with a different intent. We
2668 // should start a new instance on top.
2669 addingToTask = true;
2670 sourceRecord = taskTop;
2671 }
2672 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2673 // In this case an activity is being launched in to an
2674 // existing task, without resetting that task. This
2675 // is typically the situation of launching an activity
2676 // from a notification or shortcut. We want to place
2677 // the new activity on top of the current task.
2678 addingToTask = true;
2679 sourceRecord = taskTop;
2680 } else if (!taskTop.task.rootWasReset) {
2681 // In this case we are launching in to an existing task
2682 // that has not yet been started from its front door.
2683 // The current task has been brought to the front.
2684 // Ideally, we'd probably like to place this new task
2685 // at the bottom of its stack, but that's a little hard
2686 // to do with the current organization of the code so
2687 // for now we'll just drop it.
2688 taskTop.task.setIntent(r.intent, r.info);
2689 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002690 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002691 // We didn't do anything... but it was needed (a.k.a., client
2692 // don't use that intent!) And for paranoia, make
2693 // sure we have correctly resumed the top activity.
2694 if (doResume) {
2695 resumeTopActivityLocked(null);
2696 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002697 return ActivityManager.START_TASK_TO_FRONT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002698 }
2699 }
2700 }
2701 }
2702
2703 //String uri = r.intent.toURI();
2704 //Intent intent2 = new Intent(uri);
2705 //Slog.i(TAG, "Given intent: " + r.intent);
2706 //Slog.i(TAG, "URI is: " + uri);
2707 //Slog.i(TAG, "To intent: " + intent2);
2708
2709 if (r.packageName != null) {
2710 // If the activity being launched is the same as the one currently
2711 // at the top, then we need to check if it should only be launched
2712 // once.
2713 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2714 if (top != null && r.resultTo == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002715 if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002716 if (top.app != null && top.app.thread != null) {
2717 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2718 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2719 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2720 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2721 // For paranoia, make sure we have correctly
2722 // resumed the top activity.
2723 if (doResume) {
2724 resumeTopActivityLocked(null);
2725 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002726 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002727 // We don't need to start a new activity, and
2728 // the client said not to do anything if that
2729 // is the case, so this is it!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002730 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002731 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002732 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002733 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002734 }
2735 }
2736 }
2737 }
2738
2739 } else {
2740 if (r.resultTo != null) {
2741 sendActivityResultLocked(-1,
2742 r.resultTo, r.resultWho, r.requestCode,
2743 Activity.RESULT_CANCELED, null);
2744 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002745 return ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002746 }
2747
2748 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002749 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002750
2751 // Should this be considered a new task?
2752 if (r.resultTo == null && !addingToTask
2753 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002754 if (reuseTask == null) {
2755 // todo: should do better management of integers.
2756 mService.mCurTask++;
2757 if (mService.mCurTask <= 0) {
2758 mService.mCurTask = 1;
2759 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002760 r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002761 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2762 + " in new task " + r.task);
2763 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002764 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002765 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002766 newTask = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002767 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002768
2769 } else if (sourceRecord != null) {
2770 if (!addingToTask &&
2771 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2772 // In this case, we are adding the activity to an existing
2773 // task, but the caller has asked to clear that task if the
2774 // activity is already running.
2775 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002776 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002777 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002778 if (top != null) {
2779 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002780 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002781 // For paranoia, make sure we have correctly
2782 // resumed the top activity.
2783 if (doResume) {
2784 resumeTopActivityLocked(null);
2785 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002786 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002787 }
2788 } else if (!addingToTask &&
2789 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2790 // In this case, we are launching an activity in our own task
2791 // that may already be running somewhere in the history, and
2792 // we want to shuffle it to the front of the stack if so.
2793 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2794 if (where >= 0) {
2795 ActivityRecord top = moveActivityToFrontLocked(where);
2796 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002797 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002798 if (doResume) {
2799 resumeTopActivityLocked(null);
2800 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002801 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002802 }
2803 }
2804 // An existing activity is starting this new activity, so we want
2805 // to keep the new one in the same task as the one that is starting
2806 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002807 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002808 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2809 + " in existing task " + r.task);
2810
2811 } else {
2812 // This not being started from an existing activity, and not part
2813 // of a new task... just put it in the top task, though these days
2814 // this case should never happen.
2815 final int N = mHistory.size();
2816 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002817 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002818 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002819 ? prev.task
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002820 : new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002821 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2822 + " in new guessed " + r.task);
2823 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002824
Dianne Hackborn39792d22010-08-19 18:01:52 -07002825 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002826 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002827
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002828 if (newTask) {
2829 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
2830 }
2831 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002832 startActivityLocked(r, newTask, doResume, keepCurTransition);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002833 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002834 }
2835
Dianne Hackborna4972e92012-03-14 10:38:05 -07002836 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
2837 String profileFile, ParcelFileDescriptor profileFd) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002838 // Collect information about the target of the Intent.
2839 ActivityInfo aInfo;
2840 try {
2841 ResolveInfo rInfo =
2842 AppGlobals.getPackageManager().resolveIntent(
2843 intent, resolvedType,
2844 PackageManager.MATCH_DEFAULT_ONLY
2845 | ActivityManagerService.STOCK_PM_FLAGS);
2846 aInfo = rInfo != null ? rInfo.activityInfo : null;
2847 } catch (RemoteException e) {
2848 aInfo = null;
2849 }
2850
2851 if (aInfo != null) {
2852 // Store the found target back into the intent, because now that
2853 // we have it we never want to do this again. For example, if the
2854 // user navigates back to this point in the history, we should
2855 // always restart the exact same activity.
2856 intent.setComponent(new ComponentName(
2857 aInfo.applicationInfo.packageName, aInfo.name));
2858
2859 // Don't debug things in the system process
Dianne Hackborna4972e92012-03-14 10:38:05 -07002860 if ((startFlags&ActivityManager.START_FLAG_DEBUG) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002861 if (!aInfo.processName.equals("system")) {
2862 mService.setDebugApp(aInfo.processName, true, false);
2863 }
2864 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002865
Dianne Hackborna4972e92012-03-14 10:38:05 -07002866 if ((startFlags&ActivityManager.START_FLAG_OPENGL_TRACES) != 0) {
Siva Velusamy92a8b222012-03-09 16:24:04 -08002867 if (!aInfo.processName.equals("system")) {
2868 mService.setOpenGlTraceApp(aInfo.applicationInfo, aInfo.processName);
2869 }
2870 }
2871
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002872 if (profileFile != null) {
2873 if (!aInfo.processName.equals("system")) {
2874 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002875 profileFile, profileFd,
2876 (startFlags&ActivityManager.START_FLAG_AUTO_STOP_PROFILER) != 0);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002877 }
2878 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002879 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002880 return aInfo;
2881 }
2882
2883 final int startActivityMayWait(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002884 Intent intent, String resolvedType, IBinder resultTo,
2885 String resultWho, int requestCode, int startFlags, String profileFile,
2886 ParcelFileDescriptor profileFd, WaitResult outResult, Configuration config,
2887 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002888 // Refuse possible leaked file descriptors
2889 if (intent != null && intent.hasFileDescriptors()) {
2890 throw new IllegalArgumentException("File descriptors passed in Intent");
2891 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002892 boolean componentSpecified = intent.getComponent() != null;
2893
2894 // Don't modify the client's object!
2895 intent = new Intent(intent);
2896
2897 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002898 ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,
2899 profileFile, profileFd);
Amith Yamasani742a6712011-05-04 14:49:28 -07002900 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002901
2902 synchronized (mService) {
2903 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002904 if (callingUid >= 0) {
2905 callingPid = -1;
2906 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002907 callingPid = Binder.getCallingPid();
2908 callingUid = Binder.getCallingUid();
2909 } else {
2910 callingPid = callingUid = -1;
2911 }
2912
2913 mConfigWillChange = config != null
2914 && mService.mConfiguration.diff(config) != 0;
2915 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2916 "Starting activity when config will change = " + mConfigWillChange);
2917
2918 final long origId = Binder.clearCallingIdentity();
2919
2920 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07002921 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002922 // This may be a heavy-weight process! Check to see if we already
2923 // have another, different heavy-weight process running.
2924 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
2925 if (mService.mHeavyWeightProcess != null &&
2926 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
2927 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
2928 int realCallingPid = callingPid;
2929 int realCallingUid = callingUid;
2930 if (caller != null) {
2931 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
2932 if (callerApp != null) {
2933 realCallingPid = callerApp.pid;
2934 realCallingUid = callerApp.info.uid;
2935 } else {
2936 Slog.w(TAG, "Unable to find app for caller " + caller
2937 + " (pid=" + realCallingPid + ") when starting: "
2938 + intent.toString());
Dianne Hackborna4972e92012-03-14 10:38:05 -07002939 return ActivityManager.START_PERMISSION_DENIED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002940 }
2941 }
2942
2943 IIntentSender target = mService.getIntentSenderLocked(
Dianne Hackborna4972e92012-03-14 10:38:05 -07002944 ActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002945 realCallingUid, null, null, 0, new Intent[] { intent },
2946 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002947 | PendingIntent.FLAG_ONE_SHOT);
2948
2949 Intent newIntent = new Intent();
2950 if (requestCode >= 0) {
2951 // Caller is requesting a result.
2952 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
2953 }
2954 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
2955 new IntentSender(target));
2956 if (mService.mHeavyWeightProcess.activities.size() > 0) {
2957 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
2958 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
2959 hist.packageName);
2960 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
2961 hist.task.taskId);
2962 }
2963 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
2964 aInfo.packageName);
2965 newIntent.setFlags(intent.getFlags());
2966 newIntent.setClassName("android",
2967 HeavyWeightSwitcherActivity.class.getName());
2968 intent = newIntent;
2969 resolvedType = null;
2970 caller = null;
2971 callingUid = Binder.getCallingUid();
2972 callingPid = Binder.getCallingPid();
2973 componentSpecified = true;
2974 try {
2975 ResolveInfo rInfo =
2976 AppGlobals.getPackageManager().resolveIntent(
2977 intent, null,
2978 PackageManager.MATCH_DEFAULT_ONLY
2979 | ActivityManagerService.STOCK_PM_FLAGS);
2980 aInfo = rInfo != null ? rInfo.activityInfo : null;
Amith Yamasani742a6712011-05-04 14:49:28 -07002981 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002982 } catch (RemoteException e) {
2983 aInfo = null;
2984 }
2985 }
2986 }
2987 }
2988
2989 int res = startActivityLocked(caller, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002990 aInfo, resultTo, resultWho, requestCode, callingPid, callingUid,
2991 startFlags, options, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002992
2993 if (mConfigWillChange && mMainStack) {
2994 // If the caller also wants to switch to a new configuration,
2995 // do so now. This allows a clean switch, as we are waiting
2996 // for the current activity to pause (so we will not destroy
2997 // it), and have not yet started the next activity.
2998 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
2999 "updateConfiguration()");
3000 mConfigWillChange = false;
3001 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3002 "Updating to new configuration after starting activity.");
Dianne Hackborn813075a62011-11-14 17:45:19 -08003003 mService.updateConfigurationLocked(config, null, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003004 }
3005
3006 Binder.restoreCallingIdentity(origId);
3007
3008 if (outResult != null) {
3009 outResult.result = res;
Dianne Hackborna4972e92012-03-14 10:38:05 -07003010 if (res == ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003011 mWaitingActivityLaunched.add(outResult);
3012 do {
3013 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003014 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003015 } catch (InterruptedException e) {
3016 }
3017 } while (!outResult.timeout && outResult.who == null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003018 } else if (res == ActivityManager.START_TASK_TO_FRONT) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003019 ActivityRecord r = this.topRunningActivityLocked(null);
3020 if (r.nowVisible) {
3021 outResult.timeout = false;
3022 outResult.who = new ComponentName(r.info.packageName, r.info.name);
3023 outResult.totalTime = 0;
3024 outResult.thisTime = 0;
3025 } else {
3026 outResult.thisTime = SystemClock.uptimeMillis();
3027 mWaitingActivityVisible.add(outResult);
3028 do {
3029 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003030 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003031 } catch (InterruptedException e) {
3032 }
3033 } while (!outResult.timeout && outResult.who == null);
3034 }
3035 }
3036 }
3037
3038 return res;
3039 }
3040 }
3041
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003042 final int startActivities(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003043 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
3044 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003045 if (intents == null) {
3046 throw new NullPointerException("intents is null");
3047 }
3048 if (resolvedTypes == null) {
3049 throw new NullPointerException("resolvedTypes is null");
3050 }
3051 if (intents.length != resolvedTypes.length) {
3052 throw new IllegalArgumentException("intents are length different than resolvedTypes");
3053 }
3054
3055 ActivityRecord[] outActivity = new ActivityRecord[1];
3056
3057 int callingPid;
3058 if (callingUid >= 0) {
3059 callingPid = -1;
3060 } else if (caller == null) {
3061 callingPid = Binder.getCallingPid();
3062 callingUid = Binder.getCallingUid();
3063 } else {
3064 callingPid = callingUid = -1;
3065 }
3066 final long origId = Binder.clearCallingIdentity();
3067 try {
3068 synchronized (mService) {
3069
3070 for (int i=0; i<intents.length; i++) {
3071 Intent intent = intents[i];
3072 if (intent == null) {
3073 continue;
3074 }
3075
3076 // Refuse possible leaked file descriptors
3077 if (intent != null && intent.hasFileDescriptors()) {
3078 throw new IllegalArgumentException("File descriptors passed in Intent");
3079 }
3080
3081 boolean componentSpecified = intent.getComponent() != null;
3082
3083 // Don't modify the client's object!
3084 intent = new Intent(intent);
3085
3086 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003087 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i],
3088 0, null, null);
Amith Yamasani742a6712011-05-04 14:49:28 -07003089 // TODO: New, check if this is correct
3090 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003091
3092 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
3093 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
3094 throw new IllegalArgumentException(
3095 "FLAG_CANT_SAVE_STATE not supported here");
3096 }
3097
3098 int res = startActivityLocked(caller, intent, resolvedTypes[i],
Dianne Hackborna4972e92012-03-14 10:38:05 -07003099 aInfo, resultTo, null, -1, callingPid, callingUid,
3100 0, options, componentSpecified, outActivity);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003101 if (res < 0) {
3102 return res;
3103 }
3104
Dianne Hackbornbe707852011-11-11 14:32:10 -08003105 resultTo = outActivity[0] != null ? outActivity[0].appToken : null;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003106 }
3107 }
3108 } finally {
3109 Binder.restoreCallingIdentity(origId);
3110 }
3111
Dianne Hackborna4972e92012-03-14 10:38:05 -07003112 return ActivityManager.START_SUCCESS;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003113 }
3114
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003115 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
3116 long thisTime, long totalTime) {
3117 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
3118 WaitResult w = mWaitingActivityLaunched.get(i);
3119 w.timeout = timeout;
3120 if (r != null) {
3121 w.who = new ComponentName(r.info.packageName, r.info.name);
3122 }
3123 w.thisTime = thisTime;
3124 w.totalTime = totalTime;
3125 }
3126 mService.notifyAll();
3127 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003128
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003129 void reportActivityVisibleLocked(ActivityRecord r) {
3130 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
3131 WaitResult w = mWaitingActivityVisible.get(i);
3132 w.timeout = false;
3133 if (r != null) {
3134 w.who = new ComponentName(r.info.packageName, r.info.name);
3135 }
3136 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
3137 w.thisTime = w.totalTime;
3138 }
3139 mService.notifyAll();
Dianne Hackborn90c52de2011-09-23 12:57:44 -07003140
3141 if (mDismissKeyguardOnNextActivity) {
3142 mDismissKeyguardOnNextActivity = false;
3143 mService.mWindowManager.dismissKeyguard();
3144 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003145 }
3146
3147 void sendActivityResultLocked(int callingUid, ActivityRecord r,
3148 String resultWho, int requestCode, int resultCode, Intent data) {
3149
3150 if (callingUid > 0) {
3151 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003152 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003153 }
3154
3155 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3156 + " : who=" + resultWho + " req=" + requestCode
3157 + " res=" + resultCode + " data=" + data);
3158 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3159 try {
3160 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3161 list.add(new ResultInfo(resultWho, requestCode,
3162 resultCode, data));
Dianne Hackbornbe707852011-11-11 14:32:10 -08003163 r.app.thread.scheduleSendResult(r.appToken, list);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003164 return;
3165 } catch (Exception e) {
3166 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3167 }
3168 }
3169
3170 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3171 }
3172
3173 private final void stopActivityLocked(ActivityRecord r) {
3174 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3175 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3176 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3177 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003178 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003179 "no-history");
3180 }
3181 } else if (r.app != null && r.app.thread != null) {
3182 if (mMainStack) {
3183 if (mService.mFocusedActivity == r) {
3184 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3185 }
3186 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003187 r.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003188 try {
3189 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003190 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3191 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003192 r.state = ActivityState.STOPPING;
3193 if (DEBUG_VISBILITY) Slog.v(
3194 TAG, "Stopping visible=" + r.visible + " for " + r);
3195 if (!r.visible) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003196 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003197 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003198 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003199 if (mService.isSleeping()) {
3200 r.setSleeping(true);
3201 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003202 } catch (Exception e) {
3203 // Maybe just ignore exceptions here... if the process
3204 // has crashed, our death notification will clean things
3205 // up.
3206 Slog.w(TAG, "Exception thrown during pause", e);
3207 // Just in case, assume it to be stopped.
3208 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003209 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003210 r.state = ActivityState.STOPPED;
3211 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003212 destroyActivityLocked(r, true, false, "stop-except");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003213 }
3214 }
3215 }
3216 }
3217
3218 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3219 boolean remove) {
3220 int N = mStoppingActivities.size();
3221 if (N <= 0) return null;
3222
3223 ArrayList<ActivityRecord> stops = null;
3224
3225 final boolean nowVisible = mResumedActivity != null
3226 && mResumedActivity.nowVisible
3227 && !mResumedActivity.waitingVisible;
3228 for (int i=0; i<N; i++) {
3229 ActivityRecord s = mStoppingActivities.get(i);
3230 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3231 + nowVisible + " waitingVisible=" + s.waitingVisible
3232 + " finishing=" + s.finishing);
3233 if (s.waitingVisible && nowVisible) {
3234 mWaitingVisibleActivities.remove(s);
3235 s.waitingVisible = false;
3236 if (s.finishing) {
3237 // If this activity is finishing, it is sitting on top of
3238 // everyone else but we now know it is no longer needed...
3239 // so get rid of it. Otherwise, we need to go through the
3240 // normal flow and hide it once we determine that it is
3241 // hidden by the activities in front of it.
3242 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003243 mService.mWindowManager.setAppVisibility(s.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003244 }
3245 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003246 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003247 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3248 if (stops == null) {
3249 stops = new ArrayList<ActivityRecord>();
3250 }
3251 stops.add(s);
3252 mStoppingActivities.remove(i);
3253 N--;
3254 i--;
3255 }
3256 }
3257
3258 return stops;
3259 }
3260
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003261 final void scheduleIdleLocked() {
3262 Message msg = Message.obtain();
3263 msg.what = IDLE_NOW_MSG;
3264 mHandler.sendMessage(msg);
3265 }
3266
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003267 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003268 Configuration config) {
3269 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3270
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003271 ActivityRecord res = null;
3272
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003273 ArrayList<ActivityRecord> stops = null;
3274 ArrayList<ActivityRecord> finishes = null;
3275 ArrayList<ActivityRecord> thumbnails = null;
3276 int NS = 0;
3277 int NF = 0;
3278 int NT = 0;
3279 IApplicationThread sendThumbnail = null;
3280 boolean booting = false;
3281 boolean enableScreen = false;
3282
3283 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003284 ActivityRecord r = ActivityRecord.forToken(token);
3285 if (r != null) {
3286 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003287 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003288 }
3289
3290 // Get the activity record.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003291 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003292 if (index >= 0) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003293 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003294
3295 if (fromTimeout) {
3296 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3297 }
3298
3299 // This is a hack to semi-deal with a race condition
3300 // in the client where it can be constructed with a
3301 // newer configuration from when we asked it to launch.
3302 // We'll update with whatever configuration it now says
3303 // it used to launch.
3304 if (config != null) {
3305 r.configuration = config;
3306 }
3307
3308 // No longer need to keep the device awake.
3309 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3310 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3311 mLaunchingActivity.release();
3312 }
3313
3314 // We are now idle. If someone is waiting for a thumbnail from
3315 // us, we can now deliver.
3316 r.idle = true;
3317 mService.scheduleAppGcsLocked();
3318 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3319 sendThumbnail = r.app.thread;
3320 r.thumbnailNeeded = false;
3321 }
3322
3323 // If this activity is fullscreen, set up to hide those under it.
3324
3325 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3326 ensureActivitiesVisibleLocked(null, 0);
3327
3328 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3329 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003330 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003331 mService.mBooted = true;
3332 enableScreen = true;
3333 }
3334 }
3335
3336 } else if (fromTimeout) {
3337 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3338 }
3339
3340 // Atomically retrieve all of the other things to do.
3341 stops = processStoppingActivitiesLocked(true);
3342 NS = stops != null ? stops.size() : 0;
3343 if ((NF=mFinishingActivities.size()) > 0) {
3344 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3345 mFinishingActivities.clear();
3346 }
3347 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3348 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3349 mService.mCancelledThumbnails.clear();
3350 }
3351
3352 if (mMainStack) {
3353 booting = mService.mBooting;
3354 mService.mBooting = false;
3355 }
3356 }
3357
3358 int i;
3359
3360 // Send thumbnail if requested.
3361 if (sendThumbnail != null) {
3362 try {
3363 sendThumbnail.requestThumbnail(token);
3364 } catch (Exception e) {
3365 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3366 mService.sendPendingThumbnail(null, token, null, null, true);
3367 }
3368 }
3369
3370 // Stop any activities that are scheduled to do so but have been
3371 // waiting for the next one to start.
3372 for (i=0; i<NS; i++) {
3373 ActivityRecord r = (ActivityRecord)stops.get(i);
3374 synchronized (mService) {
3375 if (r.finishing) {
3376 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY);
3377 } else {
3378 stopActivityLocked(r);
3379 }
3380 }
3381 }
3382
3383 // Finish any activities that are scheduled to do so but have been
3384 // waiting for the next one to start.
3385 for (i=0; i<NF; i++) {
3386 ActivityRecord r = (ActivityRecord)finishes.get(i);
3387 synchronized (mService) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003388 destroyActivityLocked(r, true, false, "finish-idle");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003389 }
3390 }
3391
3392 // Report back to any thumbnail receivers.
3393 for (i=0; i<NT; i++) {
3394 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3395 mService.sendPendingThumbnail(r, null, null, null, true);
3396 }
3397
3398 if (booting) {
3399 mService.finishBooting();
3400 }
3401
3402 mService.trimApplications();
3403 //dump();
3404 //mWindowManager.dump();
3405
3406 if (enableScreen) {
3407 mService.enableScreenAfterBoot();
3408 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003409
3410 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003411 }
3412
3413 /**
3414 * @return Returns true if the activity is being finished, false if for
3415 * some reason it is being left as-is.
3416 */
3417 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
3418 Intent resultData, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003419 int index = indexOfTokenLocked(token);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003420 if (DEBUG_RESULTS) Slog.v(
3421 TAG, "Finishing activity @" + index + ": token=" + token
3422 + ", result=" + resultCode + ", data=" + resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003423 if (index < 0) {
3424 return false;
3425 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003426 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003427
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003428 finishActivityLocked(r, index, resultCode, resultData, reason);
3429 return true;
3430 }
3431
Dianne Hackborn5c607432012-02-28 14:44:19 -08003432 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
3433 // send the result
3434 ActivityRecord resultTo = r.resultTo;
3435 if (resultTo != null) {
3436 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3437 + " who=" + r.resultWho + " req=" + r.requestCode
3438 + " res=" + resultCode + " data=" + resultData);
3439 if (r.info.applicationInfo.uid > 0) {
3440 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3441 resultTo.packageName, resultData,
3442 resultTo.getUriPermissionsLocked());
3443 }
3444 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3445 resultData);
3446 r.resultTo = null;
3447 }
3448 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3449
3450 // Make sure this HistoryRecord is not holding on to other resources,
3451 // because clients have remote IPC references to this object so we
3452 // can't assume that will go away and want to avoid circular IPC refs.
3453 r.results = null;
3454 r.pendingResults = null;
3455 r.newIntents = null;
3456 r.icicle = null;
3457 }
3458
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003459 /**
3460 * @return Returns true if this activity has been removed from the history
3461 * list, or false if it is still in the list and will be removed later.
3462 */
3463 final boolean finishActivityLocked(ActivityRecord r, int index,
3464 int resultCode, Intent resultData, String reason) {
3465 if (r.finishing) {
3466 Slog.w(TAG, "Duplicate finish request for " + r);
3467 return false;
3468 }
3469
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003470 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003471 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3472 System.identityHashCode(r),
3473 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003474 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003475 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003476 if (next.task == r.task) {
3477 if (r.frontOfTask) {
3478 // The next activity is now the front of the task.
3479 next.frontOfTask = true;
3480 }
3481 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3482 // If the caller asked that this activity (and all above it)
3483 // be cleared when the task is reset, don't lose that information,
3484 // but propagate it up to the next activity.
3485 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3486 }
3487 }
3488 }
3489
3490 r.pauseKeyDispatchingLocked();
3491 if (mMainStack) {
3492 if (mService.mFocusedActivity == r) {
3493 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3494 }
3495 }
3496
Dianne Hackborn5c607432012-02-28 14:44:19 -08003497 finishActivityResultsLocked(r, resultCode, resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003498
3499 if (mService.mPendingThumbnails.size() > 0) {
3500 // There are clients waiting to receive thumbnails so, in case
3501 // this is an activity that someone is waiting for, add it
3502 // to the pending list so we can correctly update the clients.
3503 mService.mCancelledThumbnails.add(r);
3504 }
3505
3506 if (mResumedActivity == r) {
3507 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003508 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003509 if (DEBUG_TRANSITION) Slog.v(TAG,
3510 "Prepare close transition: finishing " + r);
3511 mService.mWindowManager.prepareAppTransition(endTask
3512 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003513 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003514
3515 // Tell window manager to prepare for this one to be removed.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003516 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003517
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003518 if (mPausingActivity == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003519 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3520 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3521 startPausingLocked(false, false);
3522 }
3523
3524 } else if (r.state != ActivityState.PAUSING) {
3525 // If the activity is PAUSING, we will complete the finish once
3526 // it is done pausing; else we can just directly finish it here.
3527 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3528 return finishCurrentActivityLocked(r, index,
3529 FINISH_AFTER_PAUSE) == null;
3530 } else {
3531 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3532 }
3533
3534 return false;
3535 }
3536
3537 private static final int FINISH_IMMEDIATELY = 0;
3538 private static final int FINISH_AFTER_PAUSE = 1;
3539 private static final int FINISH_AFTER_VISIBLE = 2;
3540
3541 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3542 int mode) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003543 final int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003544 if (index < 0) {
3545 return null;
3546 }
3547
3548 return finishCurrentActivityLocked(r, index, mode);
3549 }
3550
3551 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3552 int index, int mode) {
3553 // First things first: if this activity is currently visible,
3554 // and the resumed activity is not yet visible, then hold off on
3555 // finishing until the resumed one becomes visible.
3556 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3557 if (!mStoppingActivities.contains(r)) {
3558 mStoppingActivities.add(r);
3559 if (mStoppingActivities.size() > 3) {
3560 // If we already have a few activities waiting to stop,
3561 // then give up on things going idle and start clearing
3562 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003563 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003564 } else {
3565 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003566 }
3567 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003568 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3569 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003570 r.state = ActivityState.STOPPING;
3571 mService.updateOomAdjLocked();
3572 return r;
3573 }
3574
3575 // make sure the record is cleaned out of other places.
3576 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003577 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003578 mWaitingVisibleActivities.remove(r);
3579 if (mResumedActivity == r) {
3580 mResumedActivity = null;
3581 }
3582 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003583 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003584 r.state = ActivityState.FINISHING;
3585
3586 if (mode == FINISH_IMMEDIATELY
3587 || prevState == ActivityState.STOPPED
3588 || prevState == ActivityState.INITIALIZING) {
3589 // If this activity is already stopped, we can just finish
3590 // it right now.
Dianne Hackborn28695e02011-11-02 21:59:51 -07003591 return destroyActivityLocked(r, true, true, "finish-imm") ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003592 } else {
3593 // Need to go through the full pause cycle to get this
3594 // activity into the stopped state and then finish it.
3595 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3596 mFinishingActivities.add(r);
3597 resumeTopActivityLocked(null);
3598 }
3599 return r;
3600 }
3601
3602 /**
3603 * Perform the common clean-up of an activity record. This is called both
3604 * as part of destroyActivityLocked() (when destroying the client-side
3605 * representation) and cleaning things up as a result of its hosting
3606 * processing going away, in which case there is no remaining client-side
3607 * state to destroy so only the cleanup here is needed.
3608 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003609 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3610 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003611 if (mResumedActivity == r) {
3612 mResumedActivity = null;
3613 }
3614 if (mService.mFocusedActivity == r) {
3615 mService.mFocusedActivity = null;
3616 }
3617
3618 r.configDestroy = false;
3619 r.frozenBeforeDestroy = false;
3620
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003621 if (setState) {
3622 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3623 r.state = ActivityState.DESTROYED;
3624 }
3625
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003626 // Make sure this record is no longer in the pending finishes list.
3627 // This could happen, for example, if we are trimming activities
3628 // down to the max limit while they are still waiting to finish.
3629 mFinishingActivities.remove(r);
3630 mWaitingVisibleActivities.remove(r);
3631
3632 // Remove any pending results.
3633 if (r.finishing && r.pendingResults != null) {
3634 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3635 PendingIntentRecord rec = apr.get();
3636 if (rec != null) {
3637 mService.cancelIntentSenderLocked(rec, false);
3638 }
3639 }
3640 r.pendingResults = null;
3641 }
3642
3643 if (cleanServices) {
3644 cleanUpActivityServicesLocked(r);
3645 }
3646
3647 if (mService.mPendingThumbnails.size() > 0) {
3648 // There are clients waiting to receive thumbnails so, in case
3649 // this is an activity that someone is waiting for, add it
3650 // to the pending list so we can correctly update the clients.
3651 mService.mCancelledThumbnails.add(r);
3652 }
3653
3654 // Get rid of any pending idle timeouts.
3655 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
3656 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003657 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003658 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003659 }
3660
Dianne Hackborn5c607432012-02-28 14:44:19 -08003661 final void removeActivityFromHistoryLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003662 if (r.state != ActivityState.DESTROYED) {
Dianne Hackborn5c607432012-02-28 14:44:19 -08003663 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003664 r.makeFinishing();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003665 if (DEBUG_ADD_REMOVE) {
3666 RuntimeException here = new RuntimeException("here");
3667 here.fillInStackTrace();
3668 Slog.i(TAG, "Removing activity " + r + " from stack");
3669 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003670 mHistory.remove(r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003671 r.takeFromHistory();
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003672 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3673 + " (removed from history)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003674 r.state = ActivityState.DESTROYED;
Dianne Hackbornbe707852011-11-11 14:32:10 -08003675 mService.mWindowManager.removeAppToken(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003676 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003677 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003678 }
3679 cleanUpActivityServicesLocked(r);
3680 r.removeUriPermissionsLocked();
3681 }
3682 }
3683
3684 /**
3685 * Perform clean-up of service connections in an activity record.
3686 */
3687 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3688 // Throw away any services that have been bound by this activity.
3689 if (r.connections != null) {
3690 Iterator<ConnectionRecord> it = r.connections.iterator();
3691 while (it.hasNext()) {
3692 ConnectionRecord c = it.next();
3693 mService.removeConnectionLocked(c, null, r);
3694 }
3695 r.connections = null;
3696 }
3697 }
3698
Dianne Hackborn28695e02011-11-02 21:59:51 -07003699 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003700 for (int i=mHistory.size()-1; i>=0; i--) {
3701 ActivityRecord r = mHistory.get(i);
3702 if (owner != null && r.app != owner) {
3703 continue;
3704 }
3705 // We can destroy this one if we have its icicle saved and
3706 // it is not in the process of pausing/stopping/finishing.
3707 if (r.app != null && r.haveState && !r.visible && r.stopped && !r.finishing
3708 && r.state != ActivityState.DESTROYING
3709 && r.state != ActivityState.DESTROYED) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003710 destroyActivityLocked(r, true, oomAdj, "trim");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003711 }
3712 }
3713 }
3714
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003715 /**
3716 * Destroy the current CLIENT SIDE instance of an activity. This may be
3717 * called both when actually finishing an activity, or when performing
3718 * a configuration switch where we destroy the current client-side object
3719 * but then create a new client-side object for this same HistoryRecord.
3720 */
3721 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackborn28695e02011-11-02 21:59:51 -07003722 boolean removeFromApp, boolean oomAdj, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003723 if (DEBUG_SWITCH) Slog.v(
3724 TAG, "Removing activity: token=" + r
3725 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3726 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3727 System.identityHashCode(r),
Dianne Hackborn28695e02011-11-02 21:59:51 -07003728 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003729
3730 boolean removedFromHistory = false;
3731
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003732 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003733
3734 final boolean hadApp = r.app != null;
3735
3736 if (hadApp) {
3737 if (removeFromApp) {
3738 int idx = r.app.activities.indexOf(r);
3739 if (idx >= 0) {
3740 r.app.activities.remove(idx);
3741 }
3742 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
3743 mService.mHeavyWeightProcess = null;
3744 mService.mHandler.sendEmptyMessage(
3745 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
3746 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003747 if (r.app.activities.size() == 0) {
3748 // No longer have activities, so update location in
3749 // LRU list.
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003750 mService.updateLruProcessLocked(r.app, oomAdj, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003751 }
3752 }
3753
3754 boolean skipDestroy = false;
3755
3756 try {
3757 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003758 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003759 r.configChangeFlags);
3760 } catch (Exception e) {
3761 // We can just ignore exceptions here... if the process
3762 // has crashed, our death notification will clean things
3763 // up.
3764 //Slog.w(TAG, "Exception thrown during finish", e);
3765 if (r.finishing) {
3766 removeActivityFromHistoryLocked(r);
3767 removedFromHistory = true;
3768 skipDestroy = true;
3769 }
3770 }
3771
3772 r.app = null;
3773 r.nowVisible = false;
3774
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003775 // If the activity is finishing, we need to wait on removing it
3776 // from the list to give it a chance to do its cleanup. During
3777 // that time it may make calls back with its token so we need to
3778 // be able to find it on the list and so we don't want to remove
3779 // it from the list yet. Otherwise, we can just immediately put
3780 // it in the destroyed state since we are not removing it from the
3781 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003782 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003783 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
3784 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003785 r.state = ActivityState.DESTROYING;
3786 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
3787 msg.obj = r;
3788 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
3789 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003790 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3791 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003792 r.state = ActivityState.DESTROYED;
3793 }
3794 } else {
3795 // remove this record from the history.
3796 if (r.finishing) {
3797 removeActivityFromHistoryLocked(r);
3798 removedFromHistory = true;
3799 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003800 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3801 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003802 r.state = ActivityState.DESTROYED;
3803 }
3804 }
3805
3806 r.configChangeFlags = 0;
3807
3808 if (!mLRUActivities.remove(r) && hadApp) {
3809 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
3810 }
3811
3812 return removedFromHistory;
3813 }
3814
3815 final void activityDestroyed(IBinder token) {
3816 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003817 ActivityRecord r = ActivityRecord.forToken(token);
3818 if (r != null) {
3819 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
3820 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003821
Dianne Hackbornbe707852011-11-11 14:32:10 -08003822 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003823 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003824 if (r.state == ActivityState.DESTROYING) {
3825 final long origId = Binder.clearCallingIdentity();
3826 removeActivityFromHistoryLocked(r);
3827 Binder.restoreCallingIdentity(origId);
3828 }
3829 }
3830 }
3831 }
3832
3833 private static void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
3834 int i = list.size();
3835 if (localLOGV) Slog.v(
3836 TAG, "Removing app " + app + " from list " + list
3837 + " with " + i + " entries");
3838 while (i > 0) {
3839 i--;
3840 ActivityRecord r = (ActivityRecord)list.get(i);
3841 if (localLOGV) Slog.v(
3842 TAG, "Record #" + i + " " + r + ": app=" + r.app);
3843 if (r.app == app) {
3844 if (localLOGV) Slog.v(TAG, "Removing this entry!");
3845 list.remove(i);
3846 }
3847 }
3848 }
3849
3850 void removeHistoryRecordsForAppLocked(ProcessRecord app) {
3851 removeHistoryRecordsForAppLocked(mLRUActivities, app);
3852 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003853 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003854 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
3855 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
3856 }
3857
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003858 /**
3859 * Move the current home activity's task (if one exists) to the front
3860 * of the stack.
3861 */
3862 final void moveHomeToFrontLocked() {
3863 TaskRecord homeTask = null;
3864 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003865 ActivityRecord hr = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003866 if (hr.isHomeActivity) {
3867 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003868 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003869 }
3870 }
3871 if (homeTask != null) {
3872 moveTaskToFrontLocked(homeTask, null);
3873 }
3874 }
3875
3876
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003877 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason) {
3878 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
3879
3880 final int task = tr.taskId;
3881 int top = mHistory.size()-1;
3882
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003883 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003884 // nothing to do!
3885 return;
3886 }
3887
Dianne Hackbornbe707852011-11-11 14:32:10 -08003888 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003889
3890 // Applying the affinities may have removed entries from the history,
3891 // so get the size again.
3892 top = mHistory.size()-1;
3893 int pos = top;
3894
3895 // Shift all activities with this task up to the top
3896 // of the stack, keeping them in the same internal order.
3897 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003898 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003899 if (localLOGV) Slog.v(
3900 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003901 if (r.task.taskId == task) {
3902 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003903 if (DEBUG_ADD_REMOVE) {
3904 RuntimeException here = new RuntimeException("here");
3905 here.fillInStackTrace();
3906 Slog.i(TAG, "Removing and adding activity " + r + " to stack at " + top, here);
3907 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003908 mHistory.remove(pos);
3909 mHistory.add(top, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003910 moved.add(0, r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003911 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003912 }
3913 pos--;
3914 }
3915
3916 if (DEBUG_TRANSITION) Slog.v(TAG,
3917 "Prepare to front transition: task=" + tr);
3918 if (reason != null &&
3919 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003920 mService.mWindowManager.prepareAppTransition(
3921 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003922 ActivityRecord r = topRunningActivityLocked(null);
3923 if (r != null) {
3924 mNoAnimActivities.add(r);
3925 }
3926 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003927 mService.mWindowManager.prepareAppTransition(
3928 WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003929 }
3930
3931 mService.mWindowManager.moveAppTokensToTop(moved);
3932 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003933 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003934 }
3935
3936 finishTaskMoveLocked(task);
3937 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
3938 }
3939
3940 private final void finishTaskMoveLocked(int task) {
3941 resumeTopActivityLocked(null);
3942 }
3943
3944 /**
3945 * Worker method for rearranging history stack. Implements the function of moving all
3946 * activities for a specific task (gathering them if disjoint) into a single group at the
3947 * bottom of the stack.
3948 *
3949 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
3950 * to premeptively cancel the move.
3951 *
3952 * @param task The taskId to collect and move to the bottom.
3953 * @return Returns true if the move completed, false if not.
3954 */
3955 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
3956 Slog.i(TAG, "moveTaskToBack: " + task);
3957
3958 // If we have a watcher, preflight the move before committing to it. First check
3959 // for *other* available tasks, but if none are available, then try again allowing the
3960 // current task to be selected.
3961 if (mMainStack && mService.mController != null) {
3962 ActivityRecord next = topRunningActivityLocked(null, task);
3963 if (next == null) {
3964 next = topRunningActivityLocked(null, 0);
3965 }
3966 if (next != null) {
3967 // ask watcher if this is allowed
3968 boolean moveOK = true;
3969 try {
3970 moveOK = mService.mController.activityResuming(next.packageName);
3971 } catch (RemoteException e) {
3972 mService.mController = null;
3973 }
3974 if (!moveOK) {
3975 return false;
3976 }
3977 }
3978 }
3979
Dianne Hackbornbe707852011-11-11 14:32:10 -08003980 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003981
3982 if (DEBUG_TRANSITION) Slog.v(TAG,
3983 "Prepare to back transition: task=" + task);
3984
3985 final int N = mHistory.size();
3986 int bottom = 0;
3987 int pos = 0;
3988
3989 // Shift all activities with this task down to the bottom
3990 // of the stack, keeping them in the same internal order.
3991 while (pos < N) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003992 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003993 if (localLOGV) Slog.v(
3994 TAG, "At " + pos + " ckp " + r.task + ": " + r);
3995 if (r.task.taskId == task) {
3996 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003997 if (DEBUG_ADD_REMOVE) {
3998 RuntimeException here = new RuntimeException("here");
3999 here.fillInStackTrace();
4000 Slog.i(TAG, "Removing and adding activity " + r + " to stack at "
4001 + bottom, here);
4002 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004003 mHistory.remove(pos);
4004 mHistory.add(bottom, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004005 moved.add(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004006 bottom++;
4007 }
4008 pos++;
4009 }
4010
4011 if (reason != null &&
4012 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004013 mService.mWindowManager.prepareAppTransition(
4014 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004015 ActivityRecord r = topRunningActivityLocked(null);
4016 if (r != null) {
4017 mNoAnimActivities.add(r);
4018 }
4019 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004020 mService.mWindowManager.prepareAppTransition(
4021 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004022 }
4023 mService.mWindowManager.moveAppTokensToBottom(moved);
4024 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004025 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004026 }
4027
4028 finishTaskMoveLocked(task);
4029 return true;
4030 }
4031
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004032 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
4033 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4034 ActivityRecord resumed = mResumedActivity;
4035 if (resumed != null && resumed.thumbHolder == tr) {
4036 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
4037 } else {
4038 info.mainThumbnail = tr.lastThumbnail;
4039 }
4040 return info;
4041 }
4042
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004043 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex,
4044 boolean taskRequired) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004045 TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
4046 if (info.root == null) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004047 if (taskRequired) {
4048 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
4049 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004050 return null;
4051 }
4052
4053 if (subTaskIndex < 0) {
4054 // Just remove the entire task.
4055 performClearTaskAtIndexLocked(taskId, info.rootIndex);
4056 return info.root;
4057 }
4058
4059 if (subTaskIndex >= info.subtasks.size()) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004060 if (taskRequired) {
4061 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
4062 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004063 return null;
4064 }
4065
4066 // Remove all of this task's activies starting at the sub task.
4067 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
4068 performClearTaskAtIndexLocked(taskId, subtask.index);
4069 return subtask.activity;
4070 }
4071
4072 public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
4073 ActivityRecord resumed = mResumedActivity;
4074 final TaskAccessInfo thumbs = new TaskAccessInfo();
4075 // How many different sub-thumbnails?
4076 final int NA = mHistory.size();
4077 int j = 0;
4078 ThumbnailHolder holder = null;
4079 while (j < NA) {
4080 ActivityRecord ar = mHistory.get(j);
4081 if (!ar.finishing && ar.task.taskId == taskId) {
4082 holder = ar.thumbHolder;
4083 break;
4084 }
4085 j++;
4086 }
4087
4088 if (j >= NA) {
4089 return thumbs;
4090 }
4091
4092 thumbs.root = mHistory.get(j);
4093 thumbs.rootIndex = j;
4094
4095 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
4096 thumbs.subtasks = subtasks;
4097 ActivityRecord lastActivity = null;
4098 while (j < NA) {
4099 ActivityRecord ar = mHistory.get(j);
4100 j++;
4101 if (ar.finishing) {
4102 continue;
4103 }
4104 if (ar.task.taskId != taskId) {
4105 break;
4106 }
4107 lastActivity = ar;
4108 if (ar.thumbHolder != holder && holder != null) {
4109 thumbs.numSubThumbbails++;
4110 holder = ar.thumbHolder;
4111 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
4112 sub.thumbnail = holder.lastThumbnail;
4113 sub.activity = ar;
4114 sub.index = j-1;
4115 subtasks.add(sub);
4116 }
4117 }
4118 if (lastActivity != null && subtasks.size() > 0) {
4119 if (resumed == lastActivity) {
4120 TaskAccessInfo.SubTask sub = subtasks.get(subtasks.size()-1);
4121 sub.thumbnail = lastActivity.stack.screenshotActivities(lastActivity);
4122 }
4123 }
4124 if (thumbs.numSubThumbbails > 0) {
4125 thumbs.retriever = new IThumbnailRetriever.Stub() {
4126 public Bitmap getThumbnail(int index) {
4127 if (index < 0 || index >= thumbs.subtasks.size()) {
4128 return null;
4129 }
4130 return thumbs.subtasks.get(index).thumbnail;
4131 }
4132 };
4133 }
4134 return thumbs;
4135 }
4136
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004137 private final void logStartActivity(int tag, ActivityRecord r,
4138 TaskRecord task) {
4139 EventLog.writeEvent(tag,
4140 System.identityHashCode(r), task.taskId,
4141 r.shortComponentName, r.intent.getAction(),
4142 r.intent.getType(), r.intent.getDataString(),
4143 r.intent.getFlags());
4144 }
4145
4146 /**
4147 * Make sure the given activity matches the current configuration. Returns
4148 * false if the activity had to be destroyed. Returns true if the
4149 * configuration is the same, or the activity will remain running as-is
4150 * for whatever reason. Ensures the HistoryRecord is updated with the
4151 * correct configuration and all other bookkeeping is handled.
4152 */
4153 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
4154 int globalChanges) {
4155 if (mConfigWillChange) {
4156 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4157 "Skipping config check (will change): " + r);
4158 return true;
4159 }
4160
4161 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4162 "Ensuring correct configuration: " + r);
4163
4164 // Short circuit: if the two configurations are the exact same
4165 // object (the common case), then there is nothing to do.
4166 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004167 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004168 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4169 "Configuration unchanged in " + r);
4170 return true;
4171 }
4172
4173 // We don't worry about activities that are finishing.
4174 if (r.finishing) {
4175 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4176 "Configuration doesn't matter in finishing " + r);
4177 r.stopFreezingScreenLocked(false);
4178 return true;
4179 }
4180
4181 // Okay we now are going to make this activity have the new config.
4182 // But then we need to figure out how it needs to deal with that.
4183 Configuration oldConfig = r.configuration;
4184 r.configuration = newConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004185
4186 // Determine what has changed. May be nothing, if this is a config
4187 // that has come back from the app after going idle. In that case
4188 // we just want to leave the official config object now in the
4189 // activity and do nothing else.
4190 final int changes = oldConfig.diff(newConfig);
4191 if (changes == 0 && !r.forceNewConfig) {
4192 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4193 "Configuration no differences in " + r);
4194 return true;
4195 }
4196
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004197 // If the activity isn't currently running, just leave the new
4198 // configuration and it will pick that up next time it starts.
4199 if (r.app == null || r.app.thread == null) {
4200 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4201 "Configuration doesn't matter not running " + r);
4202 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004203 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004204 return true;
4205 }
4206
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004207 // Figure out how to handle the changes between the configurations.
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004208 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4209 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
4210 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07004211 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004212 + ", newConfig=" + newConfig);
4213 }
Dianne Hackborne6676352011-06-01 16:51:20 -07004214 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004215 // Aha, the activity isn't handling the change, so DIE DIE DIE.
4216 r.configChangeFlags |= changes;
4217 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004218 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004219 if (r.app == null || r.app.thread == null) {
4220 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4221 "Switch is destroying non-running " + r);
Dianne Hackborn28695e02011-11-02 21:59:51 -07004222 destroyActivityLocked(r, true, false, "config");
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004223 } else if (r.state == ActivityState.PAUSING) {
4224 // A little annoying: we are waiting for this activity to
4225 // finish pausing. Let's not do anything now, but just
4226 // flag that it needs to be restarted when done pausing.
4227 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4228 "Switch is skipping already pausing " + r);
4229 r.configDestroy = true;
4230 return true;
4231 } else if (r.state == ActivityState.RESUMED) {
4232 // Try to optimize this case: the configuration is changing
4233 // and we need to restart the top, resumed activity.
4234 // Instead of doing the normal handshaking, just say
4235 // "restart!".
4236 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4237 "Switch is restarting resumed " + r);
4238 relaunchActivityLocked(r, r.configChangeFlags, true);
4239 r.configChangeFlags = 0;
4240 } else {
4241 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4242 "Switch is restarting non-resumed " + r);
4243 relaunchActivityLocked(r, r.configChangeFlags, false);
4244 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004245 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004246
4247 // All done... tell the caller we weren't able to keep this
4248 // activity around.
4249 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004250 }
4251
4252 // Default case: the activity can handle this new configuration, so
4253 // hand it over. Note that we don't need to give it the new
4254 // configuration, since we always send configuration changes to all
4255 // process when they happen so it can just use whatever configuration
4256 // it last got.
4257 if (r.app != null && r.app.thread != null) {
4258 try {
4259 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004260 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004261 } catch (RemoteException e) {
4262 // If process died, whatever.
4263 }
4264 }
4265 r.stopFreezingScreenLocked(false);
4266
4267 return true;
4268 }
4269
4270 private final boolean relaunchActivityLocked(ActivityRecord r,
4271 int changes, boolean andResume) {
4272 List<ResultInfo> results = null;
4273 List<Intent> newIntents = null;
4274 if (andResume) {
4275 results = r.results;
4276 newIntents = r.newIntents;
4277 }
4278 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4279 + " with results=" + results + " newIntents=" + newIntents
4280 + " andResume=" + andResume);
4281 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
4282 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
4283 r.task.taskId, r.shortComponentName);
4284
4285 r.startFreezingScreenLocked(r.app, 0);
4286
4287 try {
4288 if (DEBUG_SWITCH) Slog.i(TAG, "Switch is restarting resumed " + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004289 r.forceNewConfig = false;
Dianne Hackbornbe707852011-11-11 14:32:10 -08004290 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004291 changes, !andResume, new Configuration(mService.mConfiguration));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004292 // Note: don't need to call pauseIfSleepingLocked() here, because
4293 // the caller will only pass in 'andResume' if this activity is
4294 // currently resumed, which implies we aren't sleeping.
4295 } catch (RemoteException e) {
4296 return false;
4297 }
4298
4299 if (andResume) {
4300 r.results = null;
4301 r.newIntents = null;
4302 if (mMainStack) {
4303 mService.reportResumedActivityLocked(r);
4304 }
4305 }
4306
4307 return true;
4308 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004309
4310 public void dismissKeyguardOnNextActivityLocked() {
4311 mDismissKeyguardOnNextActivity = true;
4312 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004313}