blob: 7e8df356e2a439122815705e2dab07dd2504bdeb [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 Hackborn7a2195c2012-03-19 17:38:00 -070025import android.app.ActivityOptions;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070026import android.app.AppGlobals;
27import android.app.IActivityManager;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070028import android.app.IThumbnailRetriever;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070029import android.app.IApplicationThread;
30import android.app.PendingIntent;
31import android.app.ResultInfo;
32import android.app.IActivityManager.WaitResult;
33import android.content.ComponentName;
34import android.content.Context;
35import android.content.IIntentSender;
36import android.content.Intent;
37import android.content.IntentSender;
38import android.content.pm.ActivityInfo;
39import android.content.pm.ApplicationInfo;
40import android.content.pm.PackageManager;
41import android.content.pm.ResolveInfo;
42import android.content.res.Configuration;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -080043import android.content.res.Resources;
44import android.graphics.Bitmap;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070045import android.net.Uri;
46import android.os.Binder;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070047import android.os.Bundle;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070048import android.os.Handler;
49import android.os.IBinder;
50import android.os.Message;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070051import android.os.ParcelFileDescriptor;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070052import android.os.PowerManager;
53import android.os.RemoteException;
54import android.os.SystemClock;
Amith Yamasani742a6712011-05-04 14:49:28 -070055import android.os.UserId;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070056import android.util.EventLog;
57import android.util.Log;
58import android.util.Slog;
59import android.view.WindowManagerPolicy;
60
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070061import java.io.IOException;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070062import java.lang.ref.WeakReference;
63import java.util.ArrayList;
64import java.util.Iterator;
65import java.util.List;
66
67/**
68 * State and management of a single stack of activities.
69 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070070final class ActivityStack {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070071 static final String TAG = ActivityManagerService.TAG;
Dianne Hackbornb961cd22011-06-21 12:13:37 -070072 static final boolean localLOGV = ActivityManagerService.localLOGV;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070073 static final boolean DEBUG_SWITCH = ActivityManagerService.DEBUG_SWITCH;
74 static final boolean DEBUG_PAUSE = ActivityManagerService.DEBUG_PAUSE;
75 static final boolean DEBUG_VISBILITY = ActivityManagerService.DEBUG_VISBILITY;
76 static final boolean DEBUG_USER_LEAVING = ActivityManagerService.DEBUG_USER_LEAVING;
77 static final boolean DEBUG_TRANSITION = ActivityManagerService.DEBUG_TRANSITION;
78 static final boolean DEBUG_RESULTS = ActivityManagerService.DEBUG_RESULTS;
79 static final boolean DEBUG_CONFIGURATION = ActivityManagerService.DEBUG_CONFIGURATION;
80 static final boolean DEBUG_TASKS = ActivityManagerService.DEBUG_TASKS;
81
Dianne Hackbornce86ba82011-07-13 19:33:41 -070082 static final boolean DEBUG_STATES = false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070083 static final boolean DEBUG_ADD_REMOVE = false;
84 static final boolean DEBUG_SAVED_STATE = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070085
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070086 static final boolean VALIDATE_TOKENS = ActivityManagerService.VALIDATE_TOKENS;
87
88 // How long we wait until giving up on the last activity telling us it
89 // is idle.
90 static final int IDLE_TIMEOUT = 10*1000;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -070091
92 // Ticks during which we check progress while waiting for an app to launch.
93 static final int LAUNCH_TICK = 500;
94
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070095 // How long we wait until giving up on the last activity to pause. This
96 // is short because it directly impacts the responsiveness of starting the
97 // next activity.
98 static final int PAUSE_TIMEOUT = 500;
99
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800100 // How long we can hold the sleep wake lock before giving up.
101 static final int SLEEP_TIMEOUT = 5*1000;
102
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700103 // How long we can hold the launch wake lock before giving up.
104 static final int LAUNCH_TIMEOUT = 10*1000;
105
106 // How long we wait until giving up on an activity telling us it has
107 // finished destroying itself.
108 static final int DESTROY_TIMEOUT = 10*1000;
109
110 // How long until we reset a task when the user returns to it. Currently
Dianne Hackborn621e17d2010-11-22 15:59:56 -0800111 // disabled.
112 static final long ACTIVITY_INACTIVE_RESET_TIME = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700113
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700114 // How long between activity launches that we consider safe to not warn
115 // the user about an unexpected activity being launched on top.
116 static final long START_WARN_TIME = 5*1000;
117
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700118 // Set to false to disable the preview that is shown while a new activity
119 // is being started.
120 static final boolean SHOW_APP_STARTING_PREVIEW = true;
121
122 enum ActivityState {
123 INITIALIZING,
124 RESUMED,
125 PAUSING,
126 PAUSED,
127 STOPPING,
128 STOPPED,
129 FINISHING,
130 DESTROYING,
131 DESTROYED
132 }
133
134 final ActivityManagerService mService;
135 final boolean mMainStack;
136
137 final Context mContext;
138
139 /**
140 * The back history of all previous (and possibly still
141 * running) activities. It contains HistoryRecord objects.
142 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700143 final ArrayList<ActivityRecord> mHistory = new ArrayList<ActivityRecord>();
Dianne Hackbornbe707852011-11-11 14:32:10 -0800144
145 /**
146 * Used for validating app tokens with window manager.
147 */
148 final ArrayList<IBinder> mValidateAppTokens = new ArrayList<IBinder>();
149
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700150 /**
151 * List of running activities, sorted by recent usage.
152 * The first entry in the list is the least recently used.
153 * It contains HistoryRecord objects.
154 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700155 final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700156
157 /**
158 * List of activities that are waiting for a new activity
159 * to become visible before completing whatever operation they are
160 * supposed to do.
161 */
162 final ArrayList<ActivityRecord> mWaitingVisibleActivities
163 = new ArrayList<ActivityRecord>();
164
165 /**
166 * List of activities that are ready to be stopped, but waiting
167 * for the next activity to settle down before doing so. It contains
168 * HistoryRecord objects.
169 */
170 final ArrayList<ActivityRecord> mStoppingActivities
171 = new ArrayList<ActivityRecord>();
172
173 /**
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800174 * List of activities that are in the process of going to sleep.
175 */
176 final ArrayList<ActivityRecord> mGoingToSleepActivities
177 = new ArrayList<ActivityRecord>();
178
179 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700180 * Animations that for the current transition have requested not to
181 * be considered for the transition animation.
182 */
183 final ArrayList<ActivityRecord> mNoAnimActivities
184 = new ArrayList<ActivityRecord>();
185
186 /**
187 * List of activities that are ready to be finished, but waiting
188 * for the previous activity to settle down before doing so. It contains
189 * HistoryRecord objects.
190 */
191 final ArrayList<ActivityRecord> mFinishingActivities
192 = new ArrayList<ActivityRecord>();
193
194 /**
195 * List of people waiting to find out about the next launched activity.
196 */
197 final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched
198 = new ArrayList<IActivityManager.WaitResult>();
199
200 /**
201 * List of people waiting to find out about the next visible activity.
202 */
203 final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible
204 = new ArrayList<IActivityManager.WaitResult>();
205
206 /**
207 * Set when the system is going to sleep, until we have
208 * successfully paused the current activity and released our wake lock.
209 * At that point the system is allowed to actually sleep.
210 */
211 final PowerManager.WakeLock mGoingToSleep;
212
213 /**
214 * We don't want to allow the device to go to sleep while in the process
215 * of launching an activity. This is primarily to allow alarm intent
216 * receivers to launch an activity and get that to run before the device
217 * goes back to sleep.
218 */
219 final PowerManager.WakeLock mLaunchingActivity;
220
221 /**
222 * When we are in the process of pausing an activity, before starting the
223 * next one, this variable holds the activity that is currently being paused.
224 */
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800225 ActivityRecord mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700226
227 /**
228 * This is the last activity that we put into the paused state. This is
229 * used to determine if we need to do an activity transition while sleeping,
230 * when we normally hold the top activity paused.
231 */
232 ActivityRecord mLastPausedActivity = null;
233
234 /**
235 * Current activity that is resumed, or null if there is none.
236 */
237 ActivityRecord mResumedActivity = null;
238
239 /**
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700240 * This is the last activity that has been started. It is only used to
241 * identify when multiple activities are started at once so that the user
242 * can be warned they may not be in the activity they think they are.
243 */
244 ActivityRecord mLastStartedActivity = null;
245
246 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700247 * Set when we know we are going to be calling updateConfiguration()
248 * soon, so want to skip intermediate config checks.
249 */
250 boolean mConfigWillChange;
251
252 /**
253 * Set to indicate whether to issue an onUserLeaving callback when a
254 * newly launched activity is being brought in front of us.
255 */
256 boolean mUserLeaving = false;
257
258 long mInitialStartTime = 0;
259
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800260 /**
261 * Set when we have taken too long waiting to go to sleep.
262 */
263 boolean mSleepTimeout = false;
264
Dianne Hackborn90c52de2011-09-23 12:57:44 -0700265 /**
266 * Dismiss the keyguard after the next activity is displayed?
267 */
268 boolean mDismissKeyguardOnNextActivity = false;
269
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800270 int mThumbnailWidth = -1;
271 int mThumbnailHeight = -1;
272
Amith Yamasani742a6712011-05-04 14:49:28 -0700273 private int mCurrentUser;
274
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800275 static final int SLEEP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG;
276 static final int PAUSE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 1;
277 static final int IDLE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 2;
278 static final int IDLE_NOW_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 3;
279 static final int LAUNCH_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 4;
280 static final int DESTROY_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 5;
281 static final int RESUME_TOP_ACTIVITY_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 6;
Dianne Hackborn29ba7e62012-03-16 15:03:36 -0700282 static final int LAUNCH_TICK_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 7;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700283
284 final Handler mHandler = new Handler() {
285 //public Handler() {
286 // if (localLOGV) Slog.v(TAG, "Handler started!");
287 //}
288
289 public void handleMessage(Message msg) {
290 switch (msg.what) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800291 case SLEEP_TIMEOUT_MSG: {
Dianne Hackborn8e8d65f2011-08-11 19:36:18 -0700292 synchronized (mService) {
293 if (mService.isSleeping()) {
294 Slog.w(TAG, "Sleep timeout! Sleeping now.");
295 mSleepTimeout = true;
296 checkReadyForSleepLocked();
297 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800298 }
299 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700300 case PAUSE_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800301 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700302 // We don't at this point know if the activity is fullscreen,
303 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800304 Slog.w(TAG, "Activity pause timeout for " + r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700305 synchronized (mService) {
306 if (r.app != null) {
307 mService.logAppTooSlow(r.app, r.pauseTime,
308 "pausing " + r);
309 }
310 }
311
Dianne Hackbornbe707852011-11-11 14:32:10 -0800312 activityPaused(r != null ? r.appToken : null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700313 } break;
314 case IDLE_TIMEOUT_MSG: {
315 if (mService.mDidDexOpt) {
316 mService.mDidDexOpt = false;
317 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
318 nmsg.obj = msg.obj;
319 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
320 return;
321 }
322 // We don't at this point know if the activity is fullscreen,
323 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800324 ActivityRecord r = (ActivityRecord)msg.obj;
325 Slog.w(TAG, "Activity idle timeout for " + r);
326 activityIdleInternal(r != null ? r.appToken : null, true, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700327 } break;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700328 case LAUNCH_TICK_MSG: {
329 ActivityRecord r = (ActivityRecord)msg.obj;
330 synchronized (mService) {
331 if (r.continueLaunchTickingLocked()) {
332 mService.logAppTooSlow(r.app, r.launchTickTime,
333 "launching " + r);
334 }
335 }
336 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700337 case DESTROY_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800338 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700339 // We don't at this point know if the activity is fullscreen,
340 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800341 Slog.w(TAG, "Activity destroy timeout for " + r);
342 activityDestroyed(r != null ? r.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700343 } break;
344 case IDLE_NOW_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800345 ActivityRecord r = (ActivityRecord)msg.obj;
346 activityIdleInternal(r != null ? r.appToken : null, false, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700347 } break;
348 case LAUNCH_TIMEOUT_MSG: {
349 if (mService.mDidDexOpt) {
350 mService.mDidDexOpt = false;
351 Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
352 mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
353 return;
354 }
355 synchronized (mService) {
356 if (mLaunchingActivity.isHeld()) {
357 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
358 mLaunchingActivity.release();
359 }
360 }
361 } break;
362 case RESUME_TOP_ACTIVITY_MSG: {
363 synchronized (mService) {
364 resumeTopActivityLocked(null);
365 }
366 } break;
367 }
368 }
369 };
370
371 ActivityStack(ActivityManagerService service, Context context, boolean mainStack) {
372 mService = service;
373 mContext = context;
374 mMainStack = mainStack;
375 PowerManager pm =
376 (PowerManager)context.getSystemService(Context.POWER_SERVICE);
377 mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
378 mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
379 mLaunchingActivity.setReferenceCounted(false);
380 }
381
382 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700383 // TODO: Don't look for any tasks from other users
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700384 int i = mHistory.size()-1;
385 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700386 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700387 if (!r.finishing && r != notTop) {
388 return r;
389 }
390 i--;
391 }
392 return null;
393 }
394
395 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700396 // TODO: Don't look for any tasks from other users
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700397 int i = mHistory.size()-1;
398 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700399 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700400 if (!r.finishing && !r.delayedResume && r != notTop) {
401 return r;
402 }
403 i--;
404 }
405 return null;
406 }
407
408 /**
409 * This is a simplified version of topRunningActivityLocked that provides a number of
410 * optional skip-over modes. It is intended for use with the ActivityController hook only.
411 *
412 * @param token If non-null, any history records matching this token will be skipped.
413 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
414 *
415 * @return Returns the HistoryRecord of the next activity on the stack.
416 */
417 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700418 // TODO: Don't look for any tasks from other users
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700419 int i = mHistory.size()-1;
420 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700421 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700422 // Note: the taskId check depends on real taskId fields being non-zero
Dianne Hackbornbe707852011-11-11 14:32:10 -0800423 if (!r.finishing && (token != r.appToken) && (taskId != r.task.taskId)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700424 return r;
425 }
426 i--;
427 }
428 return null;
429 }
430
431 final int indexOfTokenLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800432 return mHistory.indexOf(ActivityRecord.forToken(token));
433 }
434
435 final int indexOfActivityLocked(ActivityRecord r) {
436 return mHistory.indexOf(r);
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700437 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700438
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700439 final ActivityRecord isInStackLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800440 ActivityRecord r = ActivityRecord.forToken(token);
441 if (mHistory.contains(r)) {
442 return r;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700443 }
444 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700445 }
446
447 private final boolean updateLRUListLocked(ActivityRecord r) {
448 final boolean hadit = mLRUActivities.remove(r);
449 mLRUActivities.add(r);
450 return hadit;
451 }
452
453 /**
454 * Returns the top activity in any existing task matching the given
455 * Intent. Returns null if no such task is found.
456 */
457 private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
458 ComponentName cls = intent.getComponent();
459 if (info.targetActivity != null) {
460 cls = new ComponentName(info.packageName, info.targetActivity);
461 }
462
463 TaskRecord cp = null;
464
Amith Yamasani742a6712011-05-04 14:49:28 -0700465 final int userId = UserId.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700466 final int N = mHistory.size();
467 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700468 ActivityRecord r = mHistory.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -0700469 if (!r.finishing && r.task != cp && r.userId == userId
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700470 && r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
471 cp = r.task;
472 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
473 // + "/aff=" + r.task.affinity + " to new cls="
474 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
475 if (r.task.affinity != null) {
476 if (r.task.affinity.equals(info.taskAffinity)) {
477 //Slog.i(TAG, "Found matching affinity!");
478 return r;
479 }
480 } else if (r.task.intent != null
481 && r.task.intent.getComponent().equals(cls)) {
482 //Slog.i(TAG, "Found matching class!");
483 //dump();
484 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
485 return r;
486 } else if (r.task.affinityIntent != null
487 && r.task.affinityIntent.getComponent().equals(cls)) {
488 //Slog.i(TAG, "Found matching class!");
489 //dump();
490 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
491 return r;
492 }
493 }
494 }
495
496 return null;
497 }
498
499 /**
500 * Returns the first activity (starting from the top of the stack) that
501 * is the same as the given activity. Returns null if no such activity
502 * is found.
503 */
504 private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
505 ComponentName cls = intent.getComponent();
506 if (info.targetActivity != null) {
507 cls = new ComponentName(info.packageName, info.targetActivity);
508 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700509 final int userId = UserId.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700510
511 final int N = mHistory.size();
512 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700513 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700514 if (!r.finishing) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700515 if (r.intent.getComponent().equals(cls) && r.userId == userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700516 //Slog.i(TAG, "Found matching class!");
517 //dump();
518 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
519 return r;
520 }
521 }
522 }
523
524 return null;
525 }
526
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700527 final void showAskCompatModeDialogLocked(ActivityRecord r) {
528 Message msg = Message.obtain();
529 msg.what = ActivityManagerService.SHOW_COMPAT_MODE_DIALOG_MSG;
530 msg.obj = r.task.askedCompatMode ? null : r;
531 mService.mHandler.sendMessage(msg);
532 }
533
Amith Yamasani742a6712011-05-04 14:49:28 -0700534 /*
535 * Move the activities around in the stack to bring a user to the foreground.
536 * @return whether there are any activities for the specified user.
537 */
538 final boolean switchUser(int userId) {
539 synchronized (mService) {
540 mCurrentUser = userId;
541
542 // Only one activity? Nothing to do...
543 if (mHistory.size() < 2)
544 return false;
545
546 boolean haveActivities = false;
547 // Check if the top activity is from the new user.
548 ActivityRecord top = mHistory.get(mHistory.size() - 1);
549 if (top.userId == userId) return true;
550 // Otherwise, move the user's activities to the top.
551 int N = mHistory.size();
552 int i = 0;
553 while (i < N) {
554 ActivityRecord r = mHistory.get(i);
555 if (r.userId == userId) {
556 ActivityRecord moveToTop = mHistory.remove(i);
557 mHistory.add(moveToTop);
558 // No need to check the top one now
559 N--;
560 haveActivities = true;
561 } else {
562 i++;
563 }
564 }
565 // Transition from the old top to the new top
566 resumeTopActivityLocked(top);
567 return haveActivities;
568 }
569 }
570
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700571 final boolean realStartActivityLocked(ActivityRecord r,
572 ProcessRecord app, boolean andResume, boolean checkConfig)
573 throws RemoteException {
574
575 r.startFreezingScreenLocked(app, 0);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800576 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700577
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700578 // schedule launch ticks to collect information about slow apps.
579 r.startLaunchTickingLocked();
580
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700581 // Have the window manager re-evaluate the orientation of
582 // the screen based on the new activity order. Note that
583 // as a result of this, it can call back into the activity
584 // manager with a new orientation. We don't care about that,
585 // because the activity is not currently running so we are
586 // just restarting it anyway.
587 if (checkConfig) {
588 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
589 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -0800590 r.mayFreezeScreenLocked(app) ? r.appToken : null);
Dianne Hackborn813075a62011-11-14 17:45:19 -0800591 mService.updateConfigurationLocked(config, r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700592 }
593
594 r.app = app;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700595 app.waitingToKill = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700596
597 if (localLOGV) Slog.v(TAG, "Launching: " + r);
598
599 int idx = app.activities.indexOf(r);
600 if (idx < 0) {
601 app.activities.add(r);
602 }
603 mService.updateLruProcessLocked(app, true, true);
604
605 try {
606 if (app.thread == null) {
607 throw new RemoteException();
608 }
609 List<ResultInfo> results = null;
610 List<Intent> newIntents = null;
611 if (andResume) {
612 results = r.results;
613 newIntents = r.newIntents;
614 }
615 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
616 + " icicle=" + r.icicle
617 + " with results=" + results + " newIntents=" + newIntents
618 + " andResume=" + andResume);
619 if (andResume) {
620 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
621 System.identityHashCode(r),
622 r.task.taskId, r.shortComponentName);
623 }
624 if (r.isHomeActivity) {
625 mService.mHomeProcess = app;
626 }
627 mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800628 r.sleeping = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400629 r.forceNewConfig = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700630 showAskCompatModeDialogLocked(r);
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700631 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700632 String profileFile = null;
633 ParcelFileDescriptor profileFd = null;
634 boolean profileAutoStop = false;
635 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
636 if (mService.mProfileProc == null || mService.mProfileProc == app) {
637 mService.mProfileProc = app;
638 profileFile = mService.mProfileFile;
639 profileFd = mService.mProfileFd;
640 profileAutoStop = mService.mAutoStopProfiler;
641 }
642 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -0700643 app.hasShownUi = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700644 app.pendingUiClean = true;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700645 if (profileFd != null) {
646 try {
647 profileFd = profileFd.dup();
648 } catch (IOException e) {
649 profileFd = null;
650 }
651 }
Dianne Hackbornbe707852011-11-11 14:32:10 -0800652 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
Dianne Hackborn813075a62011-11-14 17:45:19 -0800653 System.identityHashCode(r), r.info,
654 new Configuration(mService.mConfiguration),
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700655 r.compat, r.icicle, results, newIntents, !andResume,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700656 mService.isNextTransitionForward(), profileFile, profileFd,
657 profileAutoStop);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700658
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700659 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700660 // This may be a heavy-weight process! Note that the package
661 // manager will ensure that only activity can run in the main
662 // process of the .apk, which is the only thing that will be
663 // considered heavy-weight.
664 if (app.processName.equals(app.info.packageName)) {
665 if (mService.mHeavyWeightProcess != null
666 && mService.mHeavyWeightProcess != app) {
667 Log.w(TAG, "Starting new heavy weight process " + app
668 + " when already running "
669 + mService.mHeavyWeightProcess);
670 }
671 mService.mHeavyWeightProcess = app;
672 Message msg = mService.mHandler.obtainMessage(
673 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
674 msg.obj = r;
675 mService.mHandler.sendMessage(msg);
676 }
677 }
678
679 } catch (RemoteException e) {
680 if (r.launchFailed) {
681 // This is the second time we failed -- finish activity
682 // and give up.
683 Slog.e(TAG, "Second failure launching "
684 + r.intent.getComponent().flattenToShortString()
685 + ", giving up", e);
686 mService.appDiedLocked(app, app.pid, app.thread);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800687 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700688 "2nd-crash");
689 return false;
690 }
691
692 // This is the first time we failed -- restart process and
693 // retry.
694 app.activities.remove(r);
695 throw e;
696 }
697
698 r.launchFailed = false;
699 if (updateLRUListLocked(r)) {
700 Slog.w(TAG, "Activity " + r
701 + " being launched, but already in LRU list");
702 }
703
704 if (andResume) {
705 // As part of the process of launching, ActivityThread also performs
706 // a resume.
707 r.state = ActivityState.RESUMED;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700708 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
709 + " (starting new instance)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700710 r.stopped = false;
711 mResumedActivity = r;
712 r.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -0800713 if (mMainStack) {
714 mService.addRecentTaskLocked(r.task);
715 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700716 completeResumeLocked(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800717 checkReadyForSleepLocked();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700718 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Launch completed; removing icicle of " + r.icicle);
719 r.icicle = null;
720 r.haveState = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700721 } else {
722 // This activity is not starting in the resumed state... which
723 // should look like we asked it to pause+stop (but remain visible),
724 // and it has done so and reported back the current icicle and
725 // other state.
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700726 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
727 + " (starting in stopped state)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700728 r.state = ActivityState.STOPPED;
729 r.stopped = true;
730 }
731
732 // Launch the new version setup screen if needed. We do this -after-
733 // launching the initial activity (that is, home), so that it can have
734 // a chance to initialize itself while in the background, making the
735 // switch back to it faster and look better.
736 if (mMainStack) {
737 mService.startSetupActivityLocked();
738 }
739
740 return true;
741 }
742
743 private final void startSpecificActivityLocked(ActivityRecord r,
744 boolean andResume, boolean checkConfig) {
745 // Is this activity's application already running?
746 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
747 r.info.applicationInfo.uid);
748
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700749 if (r.launchTime == 0) {
750 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700751 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700752 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700753 }
754 } else if (mInitialStartTime == 0) {
755 mInitialStartTime = SystemClock.uptimeMillis();
756 }
757
758 if (app != null && app.thread != null) {
759 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700760 app.addPackage(r.info.packageName);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700761 realStartActivityLocked(r, app, andResume, checkConfig);
762 return;
763 } catch (RemoteException e) {
764 Slog.w(TAG, "Exception when starting activity "
765 + r.intent.getComponent().flattenToShortString(), e);
766 }
767
768 // If a dead object exception was thrown -- fall through to
769 // restart the application.
770 }
771
772 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800773 "activity", r.intent.getComponent(), false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700774 }
775
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800776 void stopIfSleepingLocked() {
777 if (mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700778 if (!mGoingToSleep.isHeld()) {
779 mGoingToSleep.acquire();
780 if (mLaunchingActivity.isHeld()) {
781 mLaunchingActivity.release();
782 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
783 }
784 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800785 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
786 Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
787 mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
788 checkReadyForSleepLocked();
789 }
790 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700791
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800792 void awakeFromSleepingLocked() {
793 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
794 mSleepTimeout = false;
795 if (mGoingToSleep.isHeld()) {
796 mGoingToSleep.release();
797 }
798 // Ensure activities are no longer sleeping.
799 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700800 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800801 r.setSleeping(false);
802 }
803 mGoingToSleepActivities.clear();
804 }
805
806 void activitySleptLocked(ActivityRecord r) {
807 mGoingToSleepActivities.remove(r);
808 checkReadyForSleepLocked();
809 }
810
811 void checkReadyForSleepLocked() {
812 if (!mService.isSleeping()) {
813 // Do not care.
814 return;
815 }
816
817 if (!mSleepTimeout) {
818 if (mResumedActivity != null) {
819 // Still have something resumed; can't sleep until it is paused.
820 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700821 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
822 startPausingLocked(false, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800823 return;
824 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800825 if (mPausingActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800826 // Still waiting for something to pause; can't sleep yet.
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800827 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800828 return;
829 }
830
831 if (mStoppingActivities.size() > 0) {
832 // Still need to tell some activities to stop; can't sleep yet.
833 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
834 + mStoppingActivities.size() + " activities");
Dianne Hackborn80a7ac12011-09-22 18:32:52 -0700835 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800836 return;
837 }
838
839 ensureActivitiesVisibleLocked(null, 0);
840
841 // Make sure any stopped but visible activities are now sleeping.
842 // This ensures that the activity's onStop() is called.
843 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700844 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800845 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
846 r.setSleeping(true);
847 }
848 }
849
850 if (mGoingToSleepActivities.size() > 0) {
851 // Still need to tell some activities to sleep; can't sleep yet.
852 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
853 + mGoingToSleepActivities.size() + " activities");
854 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700855 }
856 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800857
858 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
859
860 if (mGoingToSleep.isHeld()) {
861 mGoingToSleep.release();
862 }
863 if (mService.mShuttingDown) {
864 mService.notifyAll();
865 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700866 }
867
Dianne Hackbornd2835932010-12-13 16:28:46 -0800868 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -0800869 if (who.noDisplay) {
870 return null;
871 }
872
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800873 Resources res = mService.mContext.getResources();
874 int w = mThumbnailWidth;
875 int h = mThumbnailHeight;
876 if (w < 0) {
877 mThumbnailWidth = w =
878 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
879 mThumbnailHeight = h =
880 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
881 }
882
883 if (w > 0) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800884 return mService.mWindowManager.screenshotApplications(who.appToken, w, h);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800885 }
886 return null;
887 }
888
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700889 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800890 if (mPausingActivity != null) {
891 RuntimeException e = new RuntimeException();
892 Slog.e(TAG, "Trying to pause when pause is already pending for "
893 + mPausingActivity, e);
894 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700895 ActivityRecord prev = mResumedActivity;
896 if (prev == null) {
897 RuntimeException e = new RuntimeException();
898 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
899 resumeTopActivityLocked(null);
900 return;
901 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700902 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
903 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700904 mResumedActivity = null;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800905 mPausingActivity = prev;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700906 mLastPausedActivity = prev;
907 prev.state = ActivityState.PAUSING;
908 prev.task.touchActiveTime();
Dianne Hackbornf26fd992011-04-08 18:14:09 -0700909 prev.updateThumbnail(screenshotActivities(prev), null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700910
911 mService.updateCpuStats();
912
913 if (prev.app != null && prev.app.thread != null) {
914 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
915 try {
916 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
917 System.identityHashCode(prev),
918 prev.shortComponentName);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800919 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
920 userLeaving, prev.configChangeFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700921 if (mMainStack) {
922 mService.updateUsageStats(prev, false);
923 }
924 } catch (Exception e) {
925 // Ignore exception, if process died other code will cleanup.
926 Slog.w(TAG, "Exception thrown during pause", e);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800927 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700928 mLastPausedActivity = null;
929 }
930 } else {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800931 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700932 mLastPausedActivity = null;
933 }
934
935 // If we are not going to sleep, we want to ensure the device is
936 // awake until the next activity is started.
937 if (!mService.mSleeping && !mService.mShuttingDown) {
938 mLaunchingActivity.acquire();
939 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
940 // To be safe, don't allow the wake lock to be held for too long.
941 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
942 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
943 }
944 }
945
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800946
947 if (mPausingActivity != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700948 // Have the window manager pause its key dispatching until the new
949 // activity has started. If we're pausing the activity just because
950 // the screen is being turned off and the UI is sleeping, don't interrupt
951 // key dispatch; the same activity will pick it up again on wakeup.
952 if (!uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800953 prev.pauseKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700954 } else {
955 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
956 }
957
958 // Schedule a pause timeout in case the app doesn't respond.
959 // We don't give it much time because this directly impacts the
960 // responsiveness seen by the user.
961 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
962 msg.obj = prev;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700963 prev.pauseTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700964 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
965 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
966 } else {
967 // This activity failed to schedule the
968 // pause, so just treat it as being paused now.
969 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800970 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700971 }
972 }
973
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800974 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700975 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800976 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700977
978 ActivityRecord r = null;
979
980 synchronized (mService) {
981 int index = indexOfTokenLocked(token);
982 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700983 r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700984 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800985 if (mPausingActivity == r) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700986 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
987 + (timeout ? " (due to timeout)" : " (pause complete)"));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700988 r.state = ActivityState.PAUSED;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800989 completePauseLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700990 } else {
991 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
992 System.identityHashCode(r), r.shortComponentName,
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800993 mPausingActivity != null
994 ? mPausingActivity.shortComponentName : "(none)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700995 }
996 }
997 }
998 }
999
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001000 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
1001 CharSequence description) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001002 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Saving icicle of " + r + ": " + icicle);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001003 r.icicle = icicle;
1004 r.haveState = true;
1005 r.updateThumbnail(thumbnail, description);
1006 r.stopped = true;
1007 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
1008 r.state = ActivityState.STOPPED;
1009 if (!r.finishing) {
1010 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07001011 destroyActivityLocked(r, true, false, "stop-config");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001012 resumeTopActivityLocked(null);
Dianne Hackborn50685602011-12-01 12:23:37 -08001013 } else {
1014 // Now that this process has stopped, we may want to consider
1015 // it to be the previous app to try to keep around in case
1016 // the user wants to return to it.
1017 ProcessRecord fgApp = null;
1018 if (mResumedActivity != null) {
1019 fgApp = mResumedActivity.app;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001020 } else if (mPausingActivity != null) {
1021 fgApp = mPausingActivity.app;
Dianne Hackborn50685602011-12-01 12:23:37 -08001022 }
1023 if (r.app != null && fgApp != null && r.app != fgApp
1024 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
1025 && r.app != mService.mHomeProcess) {
1026 mService.mPreviousProcess = r.app;
1027 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
1028 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001029 }
1030 }
1031 }
1032
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001033 private final void completePauseLocked() {
1034 ActivityRecord prev = mPausingActivity;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001035 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
1036
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001037 if (prev != null) {
1038 if (prev.finishing) {
1039 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
1040 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE);
1041 } else if (prev.app != null) {
1042 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
1043 if (prev.waitingVisible) {
1044 prev.waitingVisible = false;
1045 mWaitingVisibleActivities.remove(prev);
1046 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
1047 TAG, "Complete pause, no longer waiting: " + prev);
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001048 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001049 if (prev.configDestroy) {
1050 // The previous is being paused because the configuration
1051 // is changing, which means it is actually stopping...
1052 // To juggle the fact that we are also starting a new
1053 // instance right now, we need to first completely stop
1054 // the current instance before starting the new one.
1055 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
1056 destroyActivityLocked(prev, true, false, "pause-config");
1057 } else {
1058 mStoppingActivities.add(prev);
1059 if (mStoppingActivities.size() > 3) {
1060 // If we already have a few activities waiting to stop,
1061 // then give up on things going idle and start clearing
1062 // them out.
1063 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
1064 scheduleIdleLocked();
1065 } else {
1066 checkReadyForSleepLocked();
1067 }
1068 }
1069 } else {
1070 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
1071 prev = null;
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001072 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001073 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001074 }
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001075
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001076 if (!mService.isSleeping()) {
1077 resumeTopActivityLocked(prev);
1078 } else {
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001079 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001080 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001081
1082 if (prev != null) {
1083 prev.resumeKeyDispatchingLocked();
1084 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001085
1086 if (prev.app != null && prev.cpuTimeAtResume > 0
1087 && mService.mBatteryStatsService.isOnBattery()) {
1088 long diff = 0;
1089 synchronized (mService.mProcessStatsThread) {
1090 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
1091 - prev.cpuTimeAtResume;
1092 }
1093 if (diff > 0) {
1094 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
1095 synchronized (bsi) {
1096 BatteryStatsImpl.Uid.Proc ps =
1097 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
1098 prev.info.packageName);
1099 if (ps != null) {
1100 ps.addForegroundTimeLocked(diff);
1101 }
1102 }
1103 }
1104 }
1105 prev.cpuTimeAtResume = 0; // reset it
1106 }
1107
1108 /**
1109 * Once we know that we have asked an application to put an activity in
1110 * the resumed state (either by launching it or explicitly telling it),
1111 * this function updates the rest of our state to match that fact.
1112 */
1113 private final void completeResumeLocked(ActivityRecord next) {
1114 next.idle = false;
1115 next.results = null;
1116 next.newIntents = null;
1117
1118 // schedule an idle timeout in case the app doesn't do it for us.
1119 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1120 msg.obj = next;
1121 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
1122
1123 if (false) {
1124 // The activity was never told to pause, so just keep
1125 // things going as-is. To maintain our own state,
1126 // we need to emulate it coming back and saying it is
1127 // idle.
1128 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
1129 msg.obj = next;
1130 mHandler.sendMessage(msg);
1131 }
1132
1133 if (mMainStack) {
1134 mService.reportResumedActivityLocked(next);
1135 }
1136
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001137 next.clearThumbnail();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001138 if (mMainStack) {
1139 mService.setFocusedActivityLocked(next);
1140 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001141 next.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001142 ensureActivitiesVisibleLocked(null, 0);
1143 mService.mWindowManager.executeAppTransition();
1144 mNoAnimActivities.clear();
1145
1146 // Mark the point when the activity is resuming
1147 // TODO: To be more accurate, the mark should be before the onCreate,
1148 // not after the onResume. But for subsequent starts, onResume is fine.
1149 if (next.app != null) {
1150 synchronized (mService.mProcessStatsThread) {
1151 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1152 }
1153 } else {
1154 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1155 }
1156 }
1157
1158 /**
1159 * Make sure that all activities that need to be visible (that is, they
1160 * currently can be seen by the user) actually are.
1161 */
1162 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1163 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1164 if (DEBUG_VISBILITY) Slog.v(
1165 TAG, "ensureActivitiesVisible behind " + top
1166 + " configChanges=0x" + Integer.toHexString(configChanges));
1167
1168 // If the top activity is not fullscreen, then we need to
1169 // make sure any activities under it are now visible.
1170 final int count = mHistory.size();
1171 int i = count-1;
1172 while (mHistory.get(i) != top) {
1173 i--;
1174 }
1175 ActivityRecord r;
1176 boolean behindFullscreen = false;
1177 for (; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001178 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001179 if (DEBUG_VISBILITY) Slog.v(
1180 TAG, "Make visible? " + r + " finishing=" + r.finishing
1181 + " state=" + r.state);
1182 if (r.finishing) {
1183 continue;
1184 }
1185
1186 final boolean doThisProcess = onlyThisProcess == null
1187 || onlyThisProcess.equals(r.processName);
1188
1189 // First: if this is not the current activity being started, make
1190 // sure it matches the current configuration.
1191 if (r != starting && doThisProcess) {
1192 ensureActivityConfigurationLocked(r, 0);
1193 }
1194
1195 if (r.app == null || r.app.thread == null) {
1196 if (onlyThisProcess == null
1197 || onlyThisProcess.equals(r.processName)) {
1198 // This activity needs to be visible, but isn't even
1199 // running... get it started, but don't resume it
1200 // at this point.
1201 if (DEBUG_VISBILITY) Slog.v(
1202 TAG, "Start and freeze screen for " + r);
1203 if (r != starting) {
1204 r.startFreezingScreenLocked(r.app, configChanges);
1205 }
1206 if (!r.visible) {
1207 if (DEBUG_VISBILITY) Slog.v(
1208 TAG, "Starting and making visible: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001209 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001210 }
1211 if (r != starting) {
1212 startSpecificActivityLocked(r, false, false);
1213 }
1214 }
1215
1216 } else if (r.visible) {
1217 // If this activity is already visible, then there is nothing
1218 // else to do here.
1219 if (DEBUG_VISBILITY) Slog.v(
1220 TAG, "Skipping: already visible at " + r);
1221 r.stopFreezingScreenLocked(false);
1222
1223 } else if (onlyThisProcess == null) {
1224 // This activity is not currently visible, but is running.
1225 // Tell it to become visible.
1226 r.visible = true;
1227 if (r.state != ActivityState.RESUMED && r != starting) {
1228 // If this activity is paused, tell it
1229 // to now show its window.
1230 if (DEBUG_VISBILITY) Slog.v(
1231 TAG, "Making visible and scheduling visibility: " + r);
1232 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001233 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001234 r.sleeping = false;
Dianne Hackborn905577f2011-09-07 18:31:28 -07001235 r.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001236 r.app.thread.scheduleWindowVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001237 r.stopFreezingScreenLocked(false);
1238 } catch (Exception e) {
1239 // Just skip on any failure; we'll make it
1240 // visible when it next restarts.
1241 Slog.w(TAG, "Exception thrown making visibile: "
1242 + r.intent.getComponent(), e);
1243 }
1244 }
1245 }
1246
1247 // Aggregate current change flags.
1248 configChanges |= r.configChangeFlags;
1249
1250 if (r.fullscreen) {
1251 // At this point, nothing else needs to be shown
1252 if (DEBUG_VISBILITY) Slog.v(
1253 TAG, "Stopping: fullscreen at " + r);
1254 behindFullscreen = true;
1255 i--;
1256 break;
1257 }
1258 }
1259
1260 // Now for any activities that aren't visible to the user, make
1261 // sure they no longer are keeping the screen frozen.
1262 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001263 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001264 if (DEBUG_VISBILITY) Slog.v(
1265 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1266 + " state=" + r.state
1267 + " behindFullscreen=" + behindFullscreen);
1268 if (!r.finishing) {
1269 if (behindFullscreen) {
1270 if (r.visible) {
1271 if (DEBUG_VISBILITY) Slog.v(
1272 TAG, "Making invisible: " + r);
1273 r.visible = false;
1274 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001275 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001276 if ((r.state == ActivityState.STOPPING
1277 || r.state == ActivityState.STOPPED)
1278 && r.app != null && r.app.thread != null) {
1279 if (DEBUG_VISBILITY) Slog.v(
1280 TAG, "Scheduling invisibility: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001281 r.app.thread.scheduleWindowVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001282 }
1283 } catch (Exception e) {
1284 // Just skip on any failure; we'll make it
1285 // visible when it next restarts.
1286 Slog.w(TAG, "Exception thrown making hidden: "
1287 + r.intent.getComponent(), e);
1288 }
1289 } else {
1290 if (DEBUG_VISBILITY) Slog.v(
1291 TAG, "Already invisible: " + r);
1292 }
1293 } else if (r.fullscreen) {
1294 if (DEBUG_VISBILITY) Slog.v(
1295 TAG, "Now behindFullscreen: " + r);
1296 behindFullscreen = true;
1297 }
1298 }
1299 i--;
1300 }
1301 }
1302
1303 /**
1304 * Version of ensureActivitiesVisible that can easily be called anywhere.
1305 */
1306 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1307 int configChanges) {
1308 ActivityRecord r = topRunningActivityLocked(null);
1309 if (r != null) {
1310 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1311 }
1312 }
1313
1314 /**
1315 * Ensure that the top activity in the stack is resumed.
1316 *
1317 * @param prev The previously resumed activity, for when in the process
1318 * of pausing; can be null to call from elsewhere.
1319 *
1320 * @return Returns true if something is being resumed, or false if
1321 * nothing happened.
1322 */
1323 final boolean resumeTopActivityLocked(ActivityRecord prev) {
1324 // Find the first activity that is not finishing.
1325 ActivityRecord next = topRunningActivityLocked(null);
1326
1327 // Remember how we'll process this pause/resume situation, and ensure
1328 // that the state is reset however we wind up proceeding.
1329 final boolean userLeaving = mUserLeaving;
1330 mUserLeaving = false;
1331
1332 if (next == null) {
1333 // There are no more activities! Let's just start up the
1334 // Launcher...
1335 if (mMainStack) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001336 return mService.startHomeActivityLocked(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001337 }
1338 }
1339
1340 next.delayedResume = false;
1341
1342 // If the top activity is the resumed one, nothing to do.
1343 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1344 // Make sure we have executed any pending transitions, since there
1345 // should be nothing left to do at this point.
1346 mService.mWindowManager.executeAppTransition();
1347 mNoAnimActivities.clear();
1348 return false;
1349 }
1350
1351 // If we are sleeping, and there is no resumed activity, and the top
1352 // activity is paused, well that is the state we want.
1353 if ((mService.mSleeping || mService.mShuttingDown)
1354 && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
1355 // Make sure we have executed any pending transitions, since there
1356 // should be nothing left to do at this point.
1357 mService.mWindowManager.executeAppTransition();
1358 mNoAnimActivities.clear();
1359 return false;
1360 }
1361
1362 // The activity may be waiting for stop, but that is no longer
1363 // appropriate for it.
1364 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001365 mGoingToSleepActivities.remove(next);
1366 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001367 mWaitingVisibleActivities.remove(next);
1368
1369 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1370
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001371 // If we are currently pausing an activity, then don't do anything
1372 // until that is done.
1373 if (mPausingActivity != null) {
1374 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
1375 return false;
1376 }
1377
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001378 // Okay we are now going to start a switch, to 'next'. We may first
1379 // have to pause the current activity, but this is an important point
1380 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001381 // XXX "App Redirected" dialog is getting too many false positives
1382 // at this point, so turn off for now.
1383 if (false) {
1384 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1385 long now = SystemClock.uptimeMillis();
1386 final boolean inTime = mLastStartedActivity.startTime != 0
1387 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1388 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1389 final int nextUid = next.info.applicationInfo.uid;
1390 if (inTime && lastUid != nextUid
1391 && lastUid != next.launchedFromUid
1392 && mService.checkPermission(
1393 android.Manifest.permission.STOP_APP_SWITCHES,
1394 -1, next.launchedFromUid)
1395 != PackageManager.PERMISSION_GRANTED) {
1396 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1397 } else {
1398 next.startTime = now;
1399 mLastStartedActivity = next;
1400 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001401 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001402 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001403 mLastStartedActivity = next;
1404 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001405 }
1406
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001407 // We need to start pausing the current activity so the top one
1408 // can be resumed...
1409 if (mResumedActivity != null) {
1410 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
1411 startPausingLocked(userLeaving, false);
1412 return true;
1413 }
1414
1415 if (prev != null && prev != next) {
1416 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1417 prev.waitingVisible = true;
1418 mWaitingVisibleActivities.add(prev);
1419 if (DEBUG_SWITCH) Slog.v(
1420 TAG, "Resuming top, waiting visible to hide: " + prev);
1421 } else {
1422 // The next activity is already visible, so hide the previous
1423 // activity's windows right now so we can show the new one ASAP.
1424 // We only do this if the previous is finishing, which should mean
1425 // it is on top of the one being resumed so hiding it quickly
1426 // is good. Otherwise, we want to do the normal route of allowing
1427 // the resumed activity to be shown so we can decide if the
1428 // previous should actually be hidden depending on whether the
1429 // new one is found to be full-screen or not.
1430 if (prev.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001431 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001432 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1433 + prev + ", waitingVisible="
1434 + (prev != null ? prev.waitingVisible : null)
1435 + ", nowVisible=" + next.nowVisible);
1436 } else {
1437 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1438 + prev + ", waitingVisible="
1439 + (prev != null ? prev.waitingVisible : null)
1440 + ", nowVisible=" + next.nowVisible);
1441 }
1442 }
1443 }
1444
Dianne Hackborne7f97212011-02-24 14:40:20 -08001445 // Launching this app's activity, make sure the app is no longer
1446 // considered stopped.
1447 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07001448 // TODO: Apply to the correct userId
Dianne Hackborne7f97212011-02-24 14:40:20 -08001449 AppGlobals.getPackageManager().setPackageStoppedState(
1450 next.packageName, false);
1451 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001452 } catch (IllegalArgumentException e) {
1453 Slog.w(TAG, "Failed trying to unstop package "
1454 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001455 }
1456
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001457 // We are starting up the next activity, so tell the window manager
1458 // that the previous one will be hidden soon. This way it can know
1459 // to ignore it when computing the desired screen orientation.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001460 boolean noAnim = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001461 if (prev != null) {
1462 if (prev.finishing) {
1463 if (DEBUG_TRANSITION) Slog.v(TAG,
1464 "Prepare close transition: prev=" + prev);
1465 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001466 mService.mWindowManager.prepareAppTransition(
1467 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001468 } else {
1469 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1470 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001471 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001472 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001473 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1474 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001475 } else {
1476 if (DEBUG_TRANSITION) Slog.v(TAG,
1477 "Prepare open transition: prev=" + prev);
1478 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001479 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001480 mService.mWindowManager.prepareAppTransition(
1481 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001482 } else {
1483 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1484 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001485 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001486 }
1487 }
1488 if (false) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001489 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1490 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001491 }
1492 } else if (mHistory.size() > 1) {
1493 if (DEBUG_TRANSITION) Slog.v(TAG,
1494 "Prepare open transition: no previous");
1495 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001496 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001497 mService.mWindowManager.prepareAppTransition(
1498 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001499 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001500 mService.mWindowManager.prepareAppTransition(
1501 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001502 }
1503 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001504 if (!noAnim) {
1505 next.applyOptionsLocked();
1506 } else {
1507 next.clearOptionsLocked();
1508 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001509
1510 if (next.app != null && next.app.thread != null) {
1511 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1512
1513 // This activity is now becoming visible.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001514 mService.mWindowManager.setAppVisibility(next.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001515
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001516 // schedule launch ticks to collect information about slow apps.
1517 next.startLaunchTickingLocked();
1518
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001519 ActivityRecord lastResumedActivity = mResumedActivity;
1520 ActivityState lastState = next.state;
1521
1522 mService.updateCpuStats();
1523
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001524 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001525 next.state = ActivityState.RESUMED;
1526 mResumedActivity = next;
1527 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001528 if (mMainStack) {
1529 mService.addRecentTaskLocked(next.task);
1530 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001531 mService.updateLruProcessLocked(next.app, true, true);
1532 updateLRUListLocked(next);
1533
1534 // Have the window manager re-evaluate the orientation of
1535 // the screen based on the new activity order.
1536 boolean updated = false;
1537 if (mMainStack) {
1538 synchronized (mService) {
1539 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1540 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001541 next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001542 if (config != null) {
1543 next.frozenBeforeDestroy = true;
1544 }
Dianne Hackborn813075a62011-11-14 17:45:19 -08001545 updated = mService.updateConfigurationLocked(config, next, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001546 }
1547 }
1548 if (!updated) {
1549 // The configuration update wasn't able to keep the existing
1550 // instance of the activity, and instead started a new one.
1551 // We should be all done, but let's just make sure our activity
1552 // is still at the top and schedule another run if something
1553 // weird happened.
1554 ActivityRecord nextNext = topRunningActivityLocked(null);
1555 if (DEBUG_SWITCH) Slog.i(TAG,
1556 "Activity config changed during resume: " + next
1557 + ", new next: " + nextNext);
1558 if (nextNext != next) {
1559 // Do over!
1560 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1561 }
1562 if (mMainStack) {
1563 mService.setFocusedActivityLocked(next);
1564 }
1565 ensureActivitiesVisibleLocked(null, 0);
1566 mService.mWindowManager.executeAppTransition();
1567 mNoAnimActivities.clear();
1568 return true;
1569 }
1570
1571 try {
1572 // Deliver all pending results.
1573 ArrayList a = next.results;
1574 if (a != null) {
1575 final int N = a.size();
1576 if (!next.finishing && N > 0) {
1577 if (DEBUG_RESULTS) Slog.v(
1578 TAG, "Delivering results to " + next
1579 + ": " + a);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001580 next.app.thread.scheduleSendResult(next.appToken, a);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001581 }
1582 }
1583
1584 if (next.newIntents != null) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001585 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001586 }
1587
1588 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
1589 System.identityHashCode(next),
1590 next.task.taskId, next.shortComponentName);
1591
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001592 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001593 showAskCompatModeDialogLocked(next);
Dianne Hackborn905577f2011-09-07 18:31:28 -07001594 next.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001595 next.app.thread.scheduleResumeActivity(next.appToken,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001596 mService.isNextTransitionForward());
1597
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001598 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001599
1600 } catch (Exception e) {
1601 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001602 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1603 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001604 next.state = lastState;
1605 mResumedActivity = lastResumedActivity;
1606 Slog.i(TAG, "Restarting because process died: " + next);
1607 if (!next.hasBeenLaunched) {
1608 next.hasBeenLaunched = true;
1609 } else {
1610 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1611 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001612 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001613 mService.compatibilityInfoForPackageLocked(
1614 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001615 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001616 next.labelRes, next.icon, next.windowFlags,
1617 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001618 }
1619 }
1620 startSpecificActivityLocked(next, true, false);
1621 return true;
1622 }
1623
1624 // From this point on, if something goes wrong there is no way
1625 // to recover the activity.
1626 try {
1627 next.visible = true;
1628 completeResumeLocked(next);
1629 } catch (Exception e) {
1630 // If any exception gets thrown, toss away this
1631 // activity and try the next one.
1632 Slog.w(TAG, "Exception thrown during resume of " + next, e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001633 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001634 "resume-exception");
1635 return true;
1636 }
1637
1638 // Didn't need to use the icicle, and it is now out of date.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001639 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Resumed activity; didn't need icicle of: " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001640 next.icicle = null;
1641 next.haveState = false;
1642 next.stopped = false;
1643
1644 } else {
1645 // Whoops, need to restart this activity!
1646 if (!next.hasBeenLaunched) {
1647 next.hasBeenLaunched = true;
1648 } else {
1649 if (SHOW_APP_STARTING_PREVIEW) {
1650 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001651 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001652 mService.compatibilityInfoForPackageLocked(
1653 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001654 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001655 next.labelRes, next.icon, next.windowFlags,
1656 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001657 }
1658 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1659 }
1660 startSpecificActivityLocked(next, true, true);
1661 }
1662
1663 return true;
1664 }
1665
1666 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001667 boolean doResume, boolean keepCurTransition, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001668 final int NH = mHistory.size();
1669
1670 int addPos = -1;
1671
1672 if (!newTask) {
1673 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001674 boolean startIt = true;
1675 for (int i = NH-1; i >= 0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001676 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001677 if (p.finishing) {
1678 continue;
1679 }
1680 if (p.task == r.task) {
1681 // Here it is! Now, if this is not yet visible to the
1682 // user, then just add it without starting; it will
1683 // get started when the user navigates back to it.
1684 addPos = i+1;
1685 if (!startIt) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001686 if (DEBUG_ADD_REMOVE) {
1687 RuntimeException here = new RuntimeException("here");
1688 here.fillInStackTrace();
1689 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos,
1690 here);
1691 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001692 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001693 r.putInHistory();
Dianne Hackbornbe707852011-11-11 14:32:10 -08001694 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001695 r.info.screenOrientation, r.fullscreen);
1696 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001697 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001698 }
1699 return;
1700 }
1701 break;
1702 }
1703 if (p.fullscreen) {
1704 startIt = false;
1705 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001706 }
1707 }
1708
1709 // Place a new activity at top of stack, so it is next to interact
1710 // with the user.
1711 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001712 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001713 }
1714
1715 // If we are not placing the new activity frontmost, we do not want
1716 // to deliver the onUserLeaving callback to the actual frontmost
1717 // activity
1718 if (addPos < NH) {
1719 mUserLeaving = false;
1720 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1721 }
1722
1723 // Slot the activity into the history stack and proceed
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001724 if (DEBUG_ADD_REMOVE) {
1725 RuntimeException here = new RuntimeException("here");
1726 here.fillInStackTrace();
1727 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos, here);
1728 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001729 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001730 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001731 r.frontOfTask = newTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001732 if (NH > 0) {
1733 // We want to show the starting preview window if we are
1734 // switching to a new task, or the next activity's process is
1735 // not currently running.
1736 boolean showStartingIcon = newTask;
1737 ProcessRecord proc = r.app;
1738 if (proc == null) {
1739 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1740 }
1741 if (proc == null || proc.thread == null) {
1742 showStartingIcon = true;
1743 }
1744 if (DEBUG_TRANSITION) Slog.v(TAG,
1745 "Prepare open transition: starting " + r);
1746 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001747 mService.mWindowManager.prepareAppTransition(
1748 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001749 mNoAnimActivities.add(r);
1750 } else if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
1751 mService.mWindowManager.prepareAppTransition(
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001752 WindowManagerPolicy.TRANSIT_TASK_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001753 mNoAnimActivities.remove(r);
1754 } else {
1755 mService.mWindowManager.prepareAppTransition(newTask
1756 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001757 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001758 mNoAnimActivities.remove(r);
1759 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001760 r.updateOptionsLocked(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001761 mService.mWindowManager.addAppToken(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001762 addPos, r.appToken, r.task.taskId, r.info.screenOrientation, r.fullscreen);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001763 boolean doShow = true;
1764 if (newTask) {
1765 // Even though this activity is starting fresh, we still need
1766 // to reset it to make sure we apply affinities to move any
1767 // existing activities from other tasks in to it.
1768 // If the caller has requested that the target task be
1769 // reset, then do so.
1770 if ((r.intent.getFlags()
1771 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1772 resetTaskIfNeededLocked(r, r);
1773 doShow = topRunningNonDelayedActivityLocked(null) == r;
1774 }
1775 }
1776 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1777 // Figure out if we are transitioning from another activity that is
1778 // "has the same starting icon" as the next one. This allows the
1779 // window manager to keep the previous window it had previously
1780 // created, if it still had one.
1781 ActivityRecord prev = mResumedActivity;
1782 if (prev != null) {
1783 // We don't want to reuse the previous starting preview if:
1784 // (1) The current activity is in a different task.
1785 if (prev.task != r.task) prev = null;
1786 // (2) The current activity is already displayed.
1787 else if (prev.nowVisible) prev = null;
1788 }
1789 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001790 r.appToken, r.packageName, r.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001791 mService.compatibilityInfoForPackageLocked(
1792 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001793 r.labelRes, r.icon, r.windowFlags,
1794 prev != null ? prev.appToken : null, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001795 }
1796 } else {
1797 // If this is the first activity, don't do any fancy animations,
1798 // because there is nothing for it to animate on top of.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001799 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001800 r.info.screenOrientation, r.fullscreen);
1801 }
1802 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001803 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001804 }
1805
1806 if (doResume) {
1807 resumeTopActivityLocked(null);
1808 }
1809 }
1810
Dianne Hackbornbe707852011-11-11 14:32:10 -08001811 final void validateAppTokensLocked() {
1812 mValidateAppTokens.clear();
1813 mValidateAppTokens.ensureCapacity(mHistory.size());
1814 for (int i=0; i<mHistory.size(); i++) {
1815 mValidateAppTokens.add(mHistory.get(i).appToken);
1816 }
1817 mService.mWindowManager.validateAppTokens(mValidateAppTokens);
1818 }
1819
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001820 /**
1821 * Perform a reset of the given task, if needed as part of launching it.
1822 * Returns the new HistoryRecord at the top of the task.
1823 */
1824 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1825 ActivityRecord newActivity) {
1826 boolean forceReset = (newActivity.info.flags
1827 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001828 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1829 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001830 if ((newActivity.info.flags
1831 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1832 forceReset = true;
1833 }
1834 }
1835
1836 final TaskRecord task = taskTop.task;
1837
1838 // We are going to move through the history list so that we can look
1839 // at each activity 'target' with 'below' either the interesting
1840 // activity immediately below it in the stack or null.
1841 ActivityRecord target = null;
1842 int targetI = 0;
1843 int taskTopI = -1;
1844 int replyChainEnd = -1;
1845 int lastReparentPos = -1;
1846 for (int i=mHistory.size()-1; i>=-1; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001847 ActivityRecord below = i >= 0 ? mHistory.get(i) : null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001848
1849 if (below != null && below.finishing) {
1850 continue;
1851 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001852 // Don't check any lower in the stack if we're crossing a user boundary.
1853 if (below != null && below.userId != taskTop.userId) {
1854 break;
1855 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001856 if (target == null) {
1857 target = below;
1858 targetI = i;
1859 // If we were in the middle of a reply chain before this
1860 // task, it doesn't appear like the root of the chain wants
1861 // anything interesting, so drop it.
1862 replyChainEnd = -1;
1863 continue;
1864 }
1865
1866 final int flags = target.info.flags;
1867
1868 final boolean finishOnTaskLaunch =
1869 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1870 final boolean allowTaskReparenting =
1871 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1872
1873 if (target.task == task) {
1874 // We are inside of the task being reset... we'll either
1875 // finish this activity, push it out for another task,
1876 // or leave it as-is. We only do this
1877 // for activities that are not the root of the task (since
1878 // if we finish the root, we may no longer have the task!).
1879 if (taskTopI < 0) {
1880 taskTopI = targetI;
1881 }
1882 if (below != null && below.task == task) {
1883 final boolean clearWhenTaskReset =
1884 (target.intent.getFlags()
1885 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
1886 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
1887 // If this activity is sending a reply to a previous
1888 // activity, we can't do anything with it now until
1889 // we reach the start of the reply chain.
1890 // XXX note that we are assuming the result is always
1891 // to the previous activity, which is almost always
1892 // the case but we really shouldn't count on.
1893 if (replyChainEnd < 0) {
1894 replyChainEnd = targetI;
1895 }
1896 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
1897 && target.taskAffinity != null
1898 && !target.taskAffinity.equals(task.affinity)) {
1899 // If this activity has an affinity for another
1900 // task, then we need to move it out of here. We will
1901 // move it as far out of the way as possible, to the
1902 // bottom of the activity stack. This also keeps it
1903 // correctly ordered with any activities we previously
1904 // moved.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001905 ActivityRecord p = mHistory.get(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001906 if (target.taskAffinity != null
1907 && target.taskAffinity.equals(p.task.affinity)) {
1908 // If the activity currently at the bottom has the
1909 // same task affinity as the one we are moving,
1910 // then merge it into the same task.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001911 target.setTask(p.task, p.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001912 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1913 + " out to bottom task " + p.task);
1914 } else {
1915 mService.mCurTask++;
1916 if (mService.mCurTask <= 0) {
1917 mService.mCurTask = 1;
1918 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001919 target.setTask(new TaskRecord(mService.mCurTask, target.info, null),
1920 null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001921 target.task.affinityIntent = target.intent;
1922 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1923 + " out to new task " + target.task);
1924 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001925 mService.mWindowManager.setAppGroupId(target.appToken, task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001926 if (replyChainEnd < 0) {
1927 replyChainEnd = targetI;
1928 }
1929 int dstPos = 0;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001930 ThumbnailHolder curThumbHolder = target.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001931 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001932 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001933 if (p.finishing) {
1934 continue;
1935 }
1936 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
1937 + " out to target's task " + target.task);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001938 p.setTask(target.task, curThumbHolder, false);
1939 curThumbHolder = p.thumbHolder;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001940 if (DEBUG_ADD_REMOVE) {
1941 RuntimeException here = new RuntimeException("here");
1942 here.fillInStackTrace();
1943 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
1944 + dstPos, here);
1945 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001946 mHistory.remove(srcPos);
1947 mHistory.add(dstPos, p);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001948 mService.mWindowManager.moveAppToken(dstPos, p.appToken);
1949 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001950 dstPos++;
1951 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001952 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001953 }
1954 i++;
1955 }
1956 if (taskTop == p) {
1957 taskTop = below;
1958 }
1959 if (taskTopI == replyChainEnd) {
1960 taskTopI = -1;
1961 }
1962 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001963 } else if (forceReset || finishOnTaskLaunch
1964 || clearWhenTaskReset) {
1965 // If the activity should just be removed -- either
1966 // because it asks for it, or the task should be
1967 // cleared -- then finish it and anything that is
1968 // part of its reply chain.
1969 if (clearWhenTaskReset) {
1970 // In this case, we want to finish this activity
1971 // and everything above it, so be sneaky and pretend
1972 // like these are all in the reply chain.
1973 replyChainEnd = targetI+1;
1974 while (replyChainEnd < mHistory.size() &&
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001975 (mHistory.get(
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001976 replyChainEnd)).task == task) {
1977 replyChainEnd++;
1978 }
1979 replyChainEnd--;
1980 } else if (replyChainEnd < 0) {
1981 replyChainEnd = targetI;
1982 }
1983 ActivityRecord p = null;
1984 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001985 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001986 if (p.finishing) {
1987 continue;
1988 }
1989 if (finishActivityLocked(p, srcPos,
1990 Activity.RESULT_CANCELED, null, "reset")) {
1991 replyChainEnd--;
1992 srcPos--;
1993 }
1994 }
1995 if (taskTop == p) {
1996 taskTop = below;
1997 }
1998 if (taskTopI == replyChainEnd) {
1999 taskTopI = -1;
2000 }
2001 replyChainEnd = -1;
2002 } else {
2003 // If we were in the middle of a chain, well the
2004 // activity that started it all doesn't want anything
2005 // special, so leave it all as-is.
2006 replyChainEnd = -1;
2007 }
2008 } else {
2009 // Reached the bottom of the task -- any reply chain
2010 // should be left as-is.
2011 replyChainEnd = -1;
2012 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002013
2014 } else if (target.resultTo != null && (below == null
2015 || below.task == target.task)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002016 // If this activity is sending a reply to a previous
2017 // activity, we can't do anything with it now until
2018 // we reach the start of the reply chain.
2019 // XXX note that we are assuming the result is always
2020 // to the previous activity, which is almost always
2021 // the case but we really shouldn't count on.
2022 if (replyChainEnd < 0) {
2023 replyChainEnd = targetI;
2024 }
2025
2026 } else if (taskTopI >= 0 && allowTaskReparenting
2027 && task.affinity != null
2028 && task.affinity.equals(target.taskAffinity)) {
2029 // We are inside of another task... if this activity has
2030 // an affinity for our task, then either remove it if we are
2031 // clearing or move it over to our task. Note that
2032 // we currently punt on the case where we are resetting a
2033 // task that is not at the top but who has activities above
2034 // with an affinity to it... this is really not a normal
2035 // case, and we will need to later pull that task to the front
2036 // and usually at that point we will do the reset and pick
2037 // up those remaining activities. (This only happens if
2038 // someone starts an activity in a new task from an activity
2039 // in a task that is not currently on top.)
2040 if (forceReset || finishOnTaskLaunch) {
2041 if (replyChainEnd < 0) {
2042 replyChainEnd = targetI;
2043 }
2044 ActivityRecord p = null;
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002045 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index "
2046 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002047 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002048 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002049 if (p.finishing) {
2050 continue;
2051 }
2052 if (finishActivityLocked(p, srcPos,
2053 Activity.RESULT_CANCELED, null, "reset")) {
2054 taskTopI--;
2055 lastReparentPos--;
2056 replyChainEnd--;
2057 srcPos--;
2058 }
2059 }
2060 replyChainEnd = -1;
2061 } else {
2062 if (replyChainEnd < 0) {
2063 replyChainEnd = targetI;
2064 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002065 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting task at index "
2066 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002067 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002068 ActivityRecord p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002069 if (p.finishing) {
2070 continue;
2071 }
2072 if (lastReparentPos < 0) {
2073 lastReparentPos = taskTopI;
2074 taskTop = p;
2075 } else {
2076 lastReparentPos--;
2077 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002078 if (DEBUG_ADD_REMOVE) {
2079 RuntimeException here = new RuntimeException("here");
2080 here.fillInStackTrace();
2081 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2082 + lastReparentPos, here);
2083 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002084 mHistory.remove(srcPos);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002085 p.setTask(task, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002086 mHistory.add(lastReparentPos, p);
2087 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002088 + " from " + srcPos + " to " + lastReparentPos
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002089 + " in to resetting task " + task);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002090 mService.mWindowManager.moveAppToken(lastReparentPos, p.appToken);
2091 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002092 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002093 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002094 }
2095 }
2096 replyChainEnd = -1;
2097
2098 // Now we've moved it in to place... but what if this is
2099 // a singleTop activity and we have put it on top of another
2100 // instance of the same activity? Then we drop the instance
2101 // below so it remains singleTop.
2102 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2103 for (int j=lastReparentPos-1; j>=0; j--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002104 ActivityRecord p = mHistory.get(j);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002105 if (p.finishing) {
2106 continue;
2107 }
2108 if (p.intent.getComponent().equals(target.intent.getComponent())) {
2109 if (finishActivityLocked(p, j,
2110 Activity.RESULT_CANCELED, null, "replace")) {
2111 taskTopI--;
2112 lastReparentPos--;
2113 }
2114 }
2115 }
2116 }
2117 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002118
2119 } else if (below != null && below.task != target.task) {
2120 // We hit the botton of a task; the reply chain can't
2121 // pass through it.
2122 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002123 }
2124
2125 target = below;
2126 targetI = i;
2127 }
2128
2129 return taskTop;
2130 }
2131
2132 /**
2133 * Perform clear operation as requested by
2134 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2135 * stack to the given task, then look for
2136 * an instance of that activity in the stack and, if found, finish all
2137 * activities on top of it and return the instance.
2138 *
2139 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002140 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002141 * or null if none was found.
2142 */
2143 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002144 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002145 int i = mHistory.size();
2146
2147 // First find the requested task.
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.task.taskId == taskId) {
2152 i++;
2153 break;
2154 }
2155 }
2156
2157 // Now clear it.
2158 while (i > 0) {
2159 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002160 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002161 if (r.finishing) {
2162 continue;
2163 }
2164 if (r.task.taskId != taskId) {
2165 return null;
2166 }
2167 if (r.realActivity.equals(newR.realActivity)) {
2168 // Here it is! Now finish everything in front...
2169 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002170 while (i < (mHistory.size()-1)) {
2171 i++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002172 r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002173 if (r.task.taskId != taskId) {
2174 break;
2175 }
2176 if (r.finishing) {
2177 continue;
2178 }
2179 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2180 null, "clear")) {
2181 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002182 }
2183 }
2184
2185 // Finally, if this is a normal launch mode (that is, not
2186 // expecting onNewIntent()), then we will finish the current
2187 // instance of the activity so a new fresh one can be started.
2188 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2189 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
2190 if (!ret.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002191 int index = indexOfTokenLocked(ret.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002192 if (index >= 0) {
2193 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
2194 null, "clear");
2195 }
2196 return null;
2197 }
2198 }
2199
2200 return ret;
2201 }
2202 }
2203
2204 return null;
2205 }
2206
2207 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002208 * Completely remove all activities associated with an existing
2209 * task starting at a specified index.
2210 */
2211 private final void performClearTaskAtIndexLocked(int taskId, int i) {
Dianne Hackborneabd3282011-10-13 16:26:49 -07002212 while (i < mHistory.size()) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002213 ActivityRecord r = mHistory.get(i);
2214 if (r.task.taskId != taskId) {
2215 // Whoops hit the end.
2216 return;
2217 }
2218 if (r.finishing) {
2219 i++;
2220 continue;
2221 }
2222 if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2223 null, "clear")) {
2224 i++;
2225 }
2226 }
2227 }
2228
2229 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002230 * Completely remove all activities associated with an existing task.
2231 */
2232 private final void performClearTaskLocked(int taskId) {
2233 int i = mHistory.size();
2234
2235 // First find the requested task.
2236 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.task.taskId == taskId) {
2240 i++;
2241 break;
2242 }
2243 }
2244
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002245 // Now find the start and clear it.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002246 while (i > 0) {
2247 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002248 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002249 if (r.finishing) {
2250 continue;
2251 }
2252 if (r.task.taskId != taskId) {
2253 // We hit the bottom. Now finish it all...
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002254 performClearTaskAtIndexLocked(taskId, i+1);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002255 return;
2256 }
2257 }
2258 }
2259
2260 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002261 * Find the activity in the history stack within the given task. Returns
2262 * the index within the history at which it's found, or < 0 if not found.
2263 */
2264 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2265 int i = mHistory.size();
2266 while (i > 0) {
2267 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002268 ActivityRecord candidate = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002269 if (candidate.task.taskId != task) {
2270 break;
2271 }
2272 if (candidate.realActivity.equals(r.realActivity)) {
2273 return i;
2274 }
2275 }
2276
2277 return -1;
2278 }
2279
2280 /**
2281 * Reorder the history stack so that the activity at the given index is
2282 * brought to the front.
2283 */
2284 private final ActivityRecord moveActivityToFrontLocked(int where) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002285 ActivityRecord newTop = mHistory.remove(where);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002286 int top = mHistory.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002287 ActivityRecord oldTop = mHistory.get(top-1);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002288 if (DEBUG_ADD_REMOVE) {
2289 RuntimeException here = new RuntimeException("here");
2290 here.fillInStackTrace();
2291 Slog.i(TAG, "Removing and adding activity " + newTop + " to stack at "
2292 + top, here);
2293 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002294 mHistory.add(top, newTop);
2295 oldTop.frontOfTask = false;
2296 newTop.frontOfTask = true;
2297 return newTop;
2298 }
2299
2300 final int startActivityLocked(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002301 Intent intent, String resolvedType, ActivityInfo aInfo, IBinder resultTo,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002302 String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002303 int callingPid, int callingUid, int startFlags, Bundle options,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002304 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002305
Dianne Hackborna4972e92012-03-14 10:38:05 -07002306 int err = ActivityManager.START_SUCCESS;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002307
2308 ProcessRecord callerApp = null;
2309 if (caller != null) {
2310 callerApp = mService.getRecordForAppLocked(caller);
2311 if (callerApp != null) {
2312 callingPid = callerApp.pid;
2313 callingUid = callerApp.info.uid;
2314 } else {
2315 Slog.w(TAG, "Unable to find app for caller " + caller
2316 + " (pid=" + callingPid + ") when starting: "
2317 + intent.toString());
Dianne Hackborna4972e92012-03-14 10:38:05 -07002318 err = ActivityManager.START_PERMISSION_DENIED;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002319 }
2320 }
2321
Dianne Hackborna4972e92012-03-14 10:38:05 -07002322 if (err == ActivityManager.START_SUCCESS) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08002323 Slog.i(TAG, "START {" + intent.toShortString(true, true, true, false)
2324 + "} from pid " + (callerApp != null ? callerApp.pid : callingPid));
Dianne Hackbornefb58102010-10-14 16:47:34 -07002325 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002326
2327 ActivityRecord sourceRecord = null;
2328 ActivityRecord resultRecord = null;
2329 if (resultTo != null) {
2330 int index = indexOfTokenLocked(resultTo);
2331 if (DEBUG_RESULTS) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002332 TAG, "Will send result to " + resultTo + " (index " + index + ")");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002333 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002334 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002335 if (requestCode >= 0 && !sourceRecord.finishing) {
2336 resultRecord = sourceRecord;
2337 }
2338 }
2339 }
2340
2341 int launchFlags = intent.getFlags();
2342
2343 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2344 && sourceRecord != null) {
2345 // Transfer the result target from the source activity to the new
2346 // one being started, including any failures.
2347 if (requestCode >= 0) {
Dianne Hackborna4972e92012-03-14 10:38:05 -07002348 return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002349 }
2350 resultRecord = sourceRecord.resultTo;
2351 resultWho = sourceRecord.resultWho;
2352 requestCode = sourceRecord.requestCode;
2353 sourceRecord.resultTo = null;
2354 if (resultRecord != null) {
2355 resultRecord.removeResultsLocked(
2356 sourceRecord, resultWho, requestCode);
2357 }
2358 }
2359
Dianne Hackborna4972e92012-03-14 10:38:05 -07002360 if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002361 // We couldn't find a class that can handle the given Intent.
2362 // That's the end of that!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002363 err = ActivityManager.START_INTENT_NOT_RESOLVED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002364 }
2365
Dianne Hackborna4972e92012-03-14 10:38:05 -07002366 if (err == ActivityManager.START_SUCCESS && aInfo == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002367 // We couldn't find the specific class specified in the Intent.
2368 // Also the end of the line.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002369 err = ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002370 }
2371
Dianne Hackborna4972e92012-03-14 10:38:05 -07002372 if (err != ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002373 if (resultRecord != null) {
2374 sendActivityResultLocked(-1,
2375 resultRecord, resultWho, requestCode,
2376 Activity.RESULT_CANCELED, null);
2377 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002378 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002379 return err;
2380 }
2381
2382 final int perm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002383 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002384 if (perm != PackageManager.PERMISSION_GRANTED) {
2385 if (resultRecord != null) {
2386 sendActivityResultLocked(-1,
2387 resultRecord, resultWho, requestCode,
2388 Activity.RESULT_CANCELED, null);
2389 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002390 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002391 String msg;
2392 if (!aInfo.exported) {
2393 msg = "Permission Denial: starting " + intent.toString()
2394 + " from " + callerApp + " (pid=" + callingPid
2395 + ", uid=" + callingUid + ")"
2396 + " not exported from uid " + aInfo.applicationInfo.uid;
2397 } else {
2398 msg = "Permission Denial: starting " + intent.toString()
2399 + " from " + callerApp + " (pid=" + callingPid
2400 + ", uid=" + callingUid + ")"
2401 + " requires " + aInfo.permission;
2402 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002403 Slog.w(TAG, msg);
2404 throw new SecurityException(msg);
2405 }
2406
2407 if (mMainStack) {
2408 if (mService.mController != null) {
2409 boolean abort = false;
2410 try {
2411 // The Intent we give to the watcher has the extra data
2412 // stripped off, since it can contain private information.
2413 Intent watchIntent = intent.cloneFilter();
2414 abort = !mService.mController.activityStarting(watchIntent,
2415 aInfo.applicationInfo.packageName);
2416 } catch (RemoteException e) {
2417 mService.mController = null;
2418 }
2419
2420 if (abort) {
2421 if (resultRecord != null) {
2422 sendActivityResultLocked(-1,
2423 resultRecord, resultWho, requestCode,
2424 Activity.RESULT_CANCELED, null);
2425 }
2426 // We pretend to the caller that it was really started, but
2427 // they will just get a cancel result.
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002428 mDismissKeyguardOnNextActivity = false;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002429 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002430 }
2431 }
2432 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002433
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002434 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2435 intent, resolvedType, aInfo, mService.mConfiguration,
2436 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002437 if (outActivity != null) {
2438 outActivity[0] = r;
2439 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002440
2441 if (mMainStack) {
2442 if (mResumedActivity == null
2443 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2444 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2445 PendingActivityLaunch pal = new PendingActivityLaunch();
2446 pal.r = r;
2447 pal.sourceRecord = sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002448 pal.startFlags = startFlags;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002449 mService.mPendingActivityLaunches.add(pal);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002450 mDismissKeyguardOnNextActivity = false;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002451 return ActivityManager.START_SWITCHES_CANCELED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002452 }
2453 }
2454
2455 if (mService.mDidAppSwitch) {
2456 // This is the second allowed switch since we stopped switches,
2457 // so now just generally allow switches. Use case: user presses
2458 // home (switches disabled, switch to home, mDidAppSwitch now true);
2459 // user taps a home icon (coming from home so allowed, we hit here
2460 // and now allow anyone to switch again).
2461 mService.mAppSwitchesAllowedTime = 0;
2462 } else {
2463 mService.mDidAppSwitch = true;
2464 }
2465
2466 mService.doPendingActivityLaunchesLocked(false);
2467 }
2468
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002469 err = startActivityUncheckedLocked(r, sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002470 startFlags, true, options);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002471 if (mDismissKeyguardOnNextActivity && mPausingActivity == null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002472 // Someone asked to have the keyguard dismissed on the next
2473 // activity start, but we are not actually doing an activity
2474 // switch... just dismiss the keyguard now, because we
2475 // probably want to see whatever is behind it.
2476 mDismissKeyguardOnNextActivity = false;
2477 mService.mWindowManager.dismissKeyguard();
2478 }
2479 return err;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002480 }
2481
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002482 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2483 if ((launchFlags &
2484 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2485 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2486 // Caller wants to appear on home activity, so before starting
2487 // their own activity we will bring home to the front.
2488 moveHomeToFrontLocked();
2489 }
2490 }
2491
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002492 final int startActivityUncheckedLocked(ActivityRecord r,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002493 ActivityRecord sourceRecord, int startFlags, boolean doResume,
2494 Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002495 final Intent intent = r.intent;
2496 final int callingUid = r.launchedFromUid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002497 final int userId = r.userId;
2498
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002499 int launchFlags = intent.getFlags();
2500
2501 // We'll invoke onUserLeaving before onPause only if the launching
2502 // activity did not explicitly state that this is an automated launch.
2503 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2504 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2505 "startActivity() => mUserLeaving=" + mUserLeaving);
2506
2507 // If the caller has asked not to resume at this point, we make note
2508 // of this in the record so that we can skip it when trying to find
2509 // the top running activity.
2510 if (!doResume) {
2511 r.delayedResume = true;
2512 }
2513
2514 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2515 != 0 ? r : null;
2516
2517 // If the onlyIfNeeded flag is set, then we can do this if the activity
2518 // being launched is the same as the one making the call... or, as
2519 // a special case, if we do not know the caller then we count the
2520 // current top activity as the caller.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002521 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002522 ActivityRecord checkedCaller = sourceRecord;
2523 if (checkedCaller == null) {
2524 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2525 }
2526 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2527 // Caller is not the same as launcher, so always needed.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002528 startFlags &= ~ActivityManager.START_FLAG_ONLY_IF_NEEDED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002529 }
2530 }
2531
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002532 if (sourceRecord == null) {
2533 // This activity is not being started from another... in this
2534 // case we -always- start a new task.
2535 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2536 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2537 + intent);
2538 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2539 }
2540 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2541 // The original activity who is starting us is running as a single
2542 // instance... this new activity it is starting must go on its
2543 // own task.
2544 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2545 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2546 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2547 // The activity being started is a single instance... it always
2548 // gets launched into its own task.
2549 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2550 }
2551
2552 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2553 // For whatever reason this activity is being launched into a new
2554 // task... yet the caller has requested a result back. Well, that
2555 // is pretty messed up, so instead immediately send back a cancel
2556 // and let the new task continue launched as normal without a
2557 // dependency on its originator.
2558 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2559 sendActivityResultLocked(-1,
2560 r.resultTo, r.resultWho, r.requestCode,
2561 Activity.RESULT_CANCELED, null);
2562 r.resultTo = null;
2563 }
2564
2565 boolean addingToTask = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002566 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002567 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2568 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2569 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2570 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2571 // If bring to front is requested, and no result is requested, and
2572 // we can find a task that was started with this same
2573 // component, then instead of launching bring that one to the front.
2574 if (r.resultTo == null) {
2575 // See if there is a task to bring to the front. If this is
2576 // a SINGLE_INSTANCE activity, there can be one and only one
2577 // instance of it in the history, and it is always in its own
2578 // unique task, so we do a special search.
2579 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2580 ? findTaskLocked(intent, r.info)
2581 : findActivityLocked(intent, r.info);
2582 if (taskTop != null) {
2583 if (taskTop.task.intent == null) {
2584 // This task was started because of movement of
2585 // the activity based on affinity... now that we
2586 // are actually launching it, we can assign the
2587 // base intent.
2588 taskTop.task.setIntent(intent, r.info);
2589 }
2590 // If the target task is not in the front, then we need
2591 // to bring it to the front... except... well, with
2592 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2593 // to have the same behavior as if a new instance was
2594 // being started, which means not bringing it to the front
2595 // if the caller is not itself in the front.
2596 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002597 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002598 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2599 boolean callerAtFront = sourceRecord == null
2600 || curTop.task == sourceRecord.task;
2601 if (callerAtFront) {
2602 // We really do want to push this one into the
2603 // user's face, right now.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002604 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002605 r.updateOptionsLocked(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002606 moveTaskToFrontLocked(taskTop.task, r);
2607 }
2608 }
2609 // If the caller has requested that the target task be
2610 // reset, then do so.
2611 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2612 taskTop = resetTaskIfNeededLocked(taskTop, r);
2613 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002614 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002615 // We don't need to start a new activity, and
2616 // the client said not to do anything if that
2617 // is the case, so this is it! And for paranoia, make
2618 // sure we have correctly resumed the top activity.
2619 if (doResume) {
2620 resumeTopActivityLocked(null);
2621 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002622 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002623 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002624 if ((launchFlags &
2625 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2626 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2627 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002628 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002629 // not be too hard...
2630 reuseTask = taskTop.task;
2631 performClearTaskLocked(taskTop.task.taskId);
2632 reuseTask.setIntent(r.intent, r.info);
2633 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002634 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2635 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2636 // In this situation we want to remove all activities
2637 // from the task up to the one being started. In most
2638 // cases this means we are resetting the task to its
2639 // initial state.
2640 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002641 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002642 if (top != null) {
2643 if (top.frontOfTask) {
2644 // Activity aliases may mean we use different
2645 // intents for the top activity, so make sure
2646 // the task now has the identity of the new
2647 // intent.
2648 top.task.setIntent(r.intent, r.info);
2649 }
2650 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002651 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002652 } else {
2653 // A special case: we need to
2654 // start the activity because it is not currently
2655 // running, and the caller has asked to clear the
2656 // current task to have this activity at the top.
2657 addingToTask = true;
2658 // Now pretend like this activity is being started
2659 // by the top of its task, so it is put in the
2660 // right place.
2661 sourceRecord = taskTop;
2662 }
2663 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2664 // In this case the top activity on the task is the
2665 // same as the one being launched, so we take that
2666 // as a request to bring the task to the foreground.
2667 // If the top activity in the task is the root
2668 // activity, deliver this new intent to it if it
2669 // desires.
2670 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2671 && taskTop.realActivity.equals(r.realActivity)) {
2672 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2673 if (taskTop.frontOfTask) {
2674 taskTop.task.setIntent(r.intent, r.info);
2675 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002676 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002677 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2678 // In this case we are launching the root activity
2679 // of the task, but with a different intent. We
2680 // should start a new instance on top.
2681 addingToTask = true;
2682 sourceRecord = taskTop;
2683 }
2684 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2685 // In this case an activity is being launched in to an
2686 // existing task, without resetting that task. This
2687 // is typically the situation of launching an activity
2688 // from a notification or shortcut. We want to place
2689 // the new activity on top of the current task.
2690 addingToTask = true;
2691 sourceRecord = taskTop;
2692 } else if (!taskTop.task.rootWasReset) {
2693 // In this case we are launching in to an existing task
2694 // that has not yet been started from its front door.
2695 // The current task has been brought to the front.
2696 // Ideally, we'd probably like to place this new task
2697 // at the bottom of its stack, but that's a little hard
2698 // to do with the current organization of the code so
2699 // for now we'll just drop it.
2700 taskTop.task.setIntent(r.intent, r.info);
2701 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002702 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002703 // We didn't do anything... but it was needed (a.k.a., client
2704 // don't use that intent!) And for paranoia, make
2705 // sure we have correctly resumed the top activity.
2706 if (doResume) {
2707 resumeTopActivityLocked(null);
2708 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002709 return ActivityManager.START_TASK_TO_FRONT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002710 }
2711 }
2712 }
2713 }
2714
2715 //String uri = r.intent.toURI();
2716 //Intent intent2 = new Intent(uri);
2717 //Slog.i(TAG, "Given intent: " + r.intent);
2718 //Slog.i(TAG, "URI is: " + uri);
2719 //Slog.i(TAG, "To intent: " + intent2);
2720
2721 if (r.packageName != null) {
2722 // If the activity being launched is the same as the one currently
2723 // at the top, then we need to check if it should only be launched
2724 // once.
2725 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2726 if (top != null && r.resultTo == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002727 if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002728 if (top.app != null && top.app.thread != null) {
2729 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2730 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2731 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2732 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2733 // For paranoia, make sure we have correctly
2734 // resumed the top activity.
2735 if (doResume) {
2736 resumeTopActivityLocked(null);
2737 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002738 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002739 // We don't need to start a new activity, and
2740 // the client said not to do anything if that
2741 // is the case, so this is it!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002742 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002743 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002744 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002745 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002746 }
2747 }
2748 }
2749 }
2750
2751 } else {
2752 if (r.resultTo != null) {
2753 sendActivityResultLocked(-1,
2754 r.resultTo, r.resultWho, r.requestCode,
2755 Activity.RESULT_CANCELED, null);
2756 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002757 return ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002758 }
2759
2760 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002761 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002762
2763 // Should this be considered a new task?
2764 if (r.resultTo == null && !addingToTask
2765 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002766 if (reuseTask == null) {
2767 // todo: should do better management of integers.
2768 mService.mCurTask++;
2769 if (mService.mCurTask <= 0) {
2770 mService.mCurTask = 1;
2771 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002772 r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002773 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2774 + " in new task " + r.task);
2775 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002776 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002777 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002778 newTask = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002779 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002780
2781 } else if (sourceRecord != null) {
2782 if (!addingToTask &&
2783 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2784 // In this case, we are adding the activity to an existing
2785 // task, but the caller has asked to clear that task if the
2786 // activity is already running.
2787 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002788 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002789 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002790 if (top != null) {
2791 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002792 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002793 // For paranoia, make sure we have correctly
2794 // resumed the top activity.
2795 if (doResume) {
2796 resumeTopActivityLocked(null);
2797 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002798 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002799 }
2800 } else if (!addingToTask &&
2801 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2802 // In this case, we are launching an activity in our own task
2803 // that may already be running somewhere in the history, and
2804 // we want to shuffle it to the front of the stack if so.
2805 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2806 if (where >= 0) {
2807 ActivityRecord top = moveActivityToFrontLocked(where);
2808 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002809 top.updateOptionsLocked(options);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002810 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002811 if (doResume) {
2812 resumeTopActivityLocked(null);
2813 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002814 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002815 }
2816 }
2817 // An existing activity is starting this new activity, so we want
2818 // to keep the new one in the same task as the one that is starting
2819 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002820 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002821 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2822 + " in existing task " + r.task);
2823
2824 } else {
2825 // This not being started from an existing activity, and not part
2826 // of a new task... just put it in the top task, though these days
2827 // this case should never happen.
2828 final int N = mHistory.size();
2829 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002830 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002831 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002832 ? prev.task
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002833 : new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002834 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2835 + " in new guessed " + r.task);
2836 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002837
Dianne Hackborn39792d22010-08-19 18:01:52 -07002838 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002839 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002840
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002841 if (newTask) {
2842 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
2843 }
2844 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002845 startActivityLocked(r, newTask, doResume, keepCurTransition, options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002846 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002847 }
2848
Dianne Hackborna4972e92012-03-14 10:38:05 -07002849 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
2850 String profileFile, ParcelFileDescriptor profileFd) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002851 // Collect information about the target of the Intent.
2852 ActivityInfo aInfo;
2853 try {
2854 ResolveInfo rInfo =
2855 AppGlobals.getPackageManager().resolveIntent(
2856 intent, resolvedType,
2857 PackageManager.MATCH_DEFAULT_ONLY
2858 | ActivityManagerService.STOCK_PM_FLAGS);
2859 aInfo = rInfo != null ? rInfo.activityInfo : null;
2860 } catch (RemoteException e) {
2861 aInfo = null;
2862 }
2863
2864 if (aInfo != null) {
2865 // Store the found target back into the intent, because now that
2866 // we have it we never want to do this again. For example, if the
2867 // user navigates back to this point in the history, we should
2868 // always restart the exact same activity.
2869 intent.setComponent(new ComponentName(
2870 aInfo.applicationInfo.packageName, aInfo.name));
2871
2872 // Don't debug things in the system process
Dianne Hackborna4972e92012-03-14 10:38:05 -07002873 if ((startFlags&ActivityManager.START_FLAG_DEBUG) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002874 if (!aInfo.processName.equals("system")) {
2875 mService.setDebugApp(aInfo.processName, true, false);
2876 }
2877 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002878
Dianne Hackborna4972e92012-03-14 10:38:05 -07002879 if ((startFlags&ActivityManager.START_FLAG_OPENGL_TRACES) != 0) {
Siva Velusamy92a8b222012-03-09 16:24:04 -08002880 if (!aInfo.processName.equals("system")) {
2881 mService.setOpenGlTraceApp(aInfo.applicationInfo, aInfo.processName);
2882 }
2883 }
2884
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002885 if (profileFile != null) {
2886 if (!aInfo.processName.equals("system")) {
2887 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002888 profileFile, profileFd,
2889 (startFlags&ActivityManager.START_FLAG_AUTO_STOP_PROFILER) != 0);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002890 }
2891 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002892 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002893 return aInfo;
2894 }
2895
2896 final int startActivityMayWait(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002897 Intent intent, String resolvedType, IBinder resultTo,
2898 String resultWho, int requestCode, int startFlags, String profileFile,
2899 ParcelFileDescriptor profileFd, WaitResult outResult, Configuration config,
2900 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002901 // Refuse possible leaked file descriptors
2902 if (intent != null && intent.hasFileDescriptors()) {
2903 throw new IllegalArgumentException("File descriptors passed in Intent");
2904 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002905 boolean componentSpecified = intent.getComponent() != null;
2906
2907 // Don't modify the client's object!
2908 intent = new Intent(intent);
2909
2910 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002911 ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,
2912 profileFile, profileFd);
Amith Yamasani742a6712011-05-04 14:49:28 -07002913 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002914
2915 synchronized (mService) {
2916 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002917 if (callingUid >= 0) {
2918 callingPid = -1;
2919 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002920 callingPid = Binder.getCallingPid();
2921 callingUid = Binder.getCallingUid();
2922 } else {
2923 callingPid = callingUid = -1;
2924 }
2925
2926 mConfigWillChange = config != null
2927 && mService.mConfiguration.diff(config) != 0;
2928 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2929 "Starting activity when config will change = " + mConfigWillChange);
2930
2931 final long origId = Binder.clearCallingIdentity();
2932
2933 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07002934 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002935 // This may be a heavy-weight process! Check to see if we already
2936 // have another, different heavy-weight process running.
2937 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
2938 if (mService.mHeavyWeightProcess != null &&
2939 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
2940 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
2941 int realCallingPid = callingPid;
2942 int realCallingUid = callingUid;
2943 if (caller != null) {
2944 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
2945 if (callerApp != null) {
2946 realCallingPid = callerApp.pid;
2947 realCallingUid = callerApp.info.uid;
2948 } else {
2949 Slog.w(TAG, "Unable to find app for caller " + caller
2950 + " (pid=" + realCallingPid + ") when starting: "
2951 + intent.toString());
Dianne Hackborna4972e92012-03-14 10:38:05 -07002952 return ActivityManager.START_PERMISSION_DENIED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002953 }
2954 }
2955
2956 IIntentSender target = mService.getIntentSenderLocked(
Dianne Hackborna4972e92012-03-14 10:38:05 -07002957 ActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002958 realCallingUid, null, null, 0, new Intent[] { intent },
2959 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002960 | PendingIntent.FLAG_ONE_SHOT, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002961
2962 Intent newIntent = new Intent();
2963 if (requestCode >= 0) {
2964 // Caller is requesting a result.
2965 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
2966 }
2967 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
2968 new IntentSender(target));
2969 if (mService.mHeavyWeightProcess.activities.size() > 0) {
2970 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
2971 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
2972 hist.packageName);
2973 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
2974 hist.task.taskId);
2975 }
2976 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
2977 aInfo.packageName);
2978 newIntent.setFlags(intent.getFlags());
2979 newIntent.setClassName("android",
2980 HeavyWeightSwitcherActivity.class.getName());
2981 intent = newIntent;
2982 resolvedType = null;
2983 caller = null;
2984 callingUid = Binder.getCallingUid();
2985 callingPid = Binder.getCallingPid();
2986 componentSpecified = true;
2987 try {
2988 ResolveInfo rInfo =
2989 AppGlobals.getPackageManager().resolveIntent(
2990 intent, null,
2991 PackageManager.MATCH_DEFAULT_ONLY
2992 | ActivityManagerService.STOCK_PM_FLAGS);
2993 aInfo = rInfo != null ? rInfo.activityInfo : null;
Amith Yamasani742a6712011-05-04 14:49:28 -07002994 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002995 } catch (RemoteException e) {
2996 aInfo = null;
2997 }
2998 }
2999 }
3000 }
3001
3002 int res = startActivityLocked(caller, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003003 aInfo, resultTo, resultWho, requestCode, callingPid, callingUid,
3004 startFlags, options, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003005
3006 if (mConfigWillChange && mMainStack) {
3007 // If the caller also wants to switch to a new configuration,
3008 // do so now. This allows a clean switch, as we are waiting
3009 // for the current activity to pause (so we will not destroy
3010 // it), and have not yet started the next activity.
3011 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
3012 "updateConfiguration()");
3013 mConfigWillChange = false;
3014 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3015 "Updating to new configuration after starting activity.");
Dianne Hackborn813075a62011-11-14 17:45:19 -08003016 mService.updateConfigurationLocked(config, null, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003017 }
3018
3019 Binder.restoreCallingIdentity(origId);
3020
3021 if (outResult != null) {
3022 outResult.result = res;
Dianne Hackborna4972e92012-03-14 10:38:05 -07003023 if (res == ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003024 mWaitingActivityLaunched.add(outResult);
3025 do {
3026 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003027 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003028 } catch (InterruptedException e) {
3029 }
3030 } while (!outResult.timeout && outResult.who == null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003031 } else if (res == ActivityManager.START_TASK_TO_FRONT) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003032 ActivityRecord r = this.topRunningActivityLocked(null);
3033 if (r.nowVisible) {
3034 outResult.timeout = false;
3035 outResult.who = new ComponentName(r.info.packageName, r.info.name);
3036 outResult.totalTime = 0;
3037 outResult.thisTime = 0;
3038 } else {
3039 outResult.thisTime = SystemClock.uptimeMillis();
3040 mWaitingActivityVisible.add(outResult);
3041 do {
3042 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003043 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003044 } catch (InterruptedException e) {
3045 }
3046 } while (!outResult.timeout && outResult.who == null);
3047 }
3048 }
3049 }
3050
3051 return res;
3052 }
3053 }
3054
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003055 final int startActivities(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003056 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
3057 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003058 if (intents == null) {
3059 throw new NullPointerException("intents is null");
3060 }
3061 if (resolvedTypes == null) {
3062 throw new NullPointerException("resolvedTypes is null");
3063 }
3064 if (intents.length != resolvedTypes.length) {
3065 throw new IllegalArgumentException("intents are length different than resolvedTypes");
3066 }
3067
3068 ActivityRecord[] outActivity = new ActivityRecord[1];
3069
3070 int callingPid;
3071 if (callingUid >= 0) {
3072 callingPid = -1;
3073 } else if (caller == null) {
3074 callingPid = Binder.getCallingPid();
3075 callingUid = Binder.getCallingUid();
3076 } else {
3077 callingPid = callingUid = -1;
3078 }
3079 final long origId = Binder.clearCallingIdentity();
3080 try {
3081 synchronized (mService) {
3082
3083 for (int i=0; i<intents.length; i++) {
3084 Intent intent = intents[i];
3085 if (intent == null) {
3086 continue;
3087 }
3088
3089 // Refuse possible leaked file descriptors
3090 if (intent != null && intent.hasFileDescriptors()) {
3091 throw new IllegalArgumentException("File descriptors passed in Intent");
3092 }
3093
3094 boolean componentSpecified = intent.getComponent() != null;
3095
3096 // Don't modify the client's object!
3097 intent = new Intent(intent);
3098
3099 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003100 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i],
3101 0, null, null);
Amith Yamasani742a6712011-05-04 14:49:28 -07003102 // TODO: New, check if this is correct
3103 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003104
3105 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
3106 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
3107 throw new IllegalArgumentException(
3108 "FLAG_CANT_SAVE_STATE not supported here");
3109 }
3110
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003111 Bundle theseOptions;
3112 if (options != null && i == intents.length-1) {
3113 theseOptions = options;
3114 } else {
3115 theseOptions = null;
3116 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003117 int res = startActivityLocked(caller, intent, resolvedTypes[i],
Dianne Hackborna4972e92012-03-14 10:38:05 -07003118 aInfo, resultTo, null, -1, callingPid, callingUid,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003119 0, theseOptions, componentSpecified, outActivity);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003120 if (res < 0) {
3121 return res;
3122 }
3123
Dianne Hackbornbe707852011-11-11 14:32:10 -08003124 resultTo = outActivity[0] != null ? outActivity[0].appToken : null;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003125 }
3126 }
3127 } finally {
3128 Binder.restoreCallingIdentity(origId);
3129 }
3130
Dianne Hackborna4972e92012-03-14 10:38:05 -07003131 return ActivityManager.START_SUCCESS;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003132 }
3133
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003134 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
3135 long thisTime, long totalTime) {
3136 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
3137 WaitResult w = mWaitingActivityLaunched.get(i);
3138 w.timeout = timeout;
3139 if (r != null) {
3140 w.who = new ComponentName(r.info.packageName, r.info.name);
3141 }
3142 w.thisTime = thisTime;
3143 w.totalTime = totalTime;
3144 }
3145 mService.notifyAll();
3146 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003147
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003148 void reportActivityVisibleLocked(ActivityRecord r) {
3149 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
3150 WaitResult w = mWaitingActivityVisible.get(i);
3151 w.timeout = false;
3152 if (r != null) {
3153 w.who = new ComponentName(r.info.packageName, r.info.name);
3154 }
3155 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
3156 w.thisTime = w.totalTime;
3157 }
3158 mService.notifyAll();
Dianne Hackborn90c52de2011-09-23 12:57:44 -07003159
3160 if (mDismissKeyguardOnNextActivity) {
3161 mDismissKeyguardOnNextActivity = false;
3162 mService.mWindowManager.dismissKeyguard();
3163 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003164 }
3165
3166 void sendActivityResultLocked(int callingUid, ActivityRecord r,
3167 String resultWho, int requestCode, int resultCode, Intent data) {
3168
3169 if (callingUid > 0) {
3170 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003171 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003172 }
3173
3174 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3175 + " : who=" + resultWho + " req=" + requestCode
3176 + " res=" + resultCode + " data=" + data);
3177 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3178 try {
3179 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3180 list.add(new ResultInfo(resultWho, requestCode,
3181 resultCode, data));
Dianne Hackbornbe707852011-11-11 14:32:10 -08003182 r.app.thread.scheduleSendResult(r.appToken, list);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003183 return;
3184 } catch (Exception e) {
3185 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3186 }
3187 }
3188
3189 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3190 }
3191
3192 private final void stopActivityLocked(ActivityRecord r) {
3193 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3194 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3195 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3196 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003197 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003198 "no-history");
3199 }
3200 } else if (r.app != null && r.app.thread != null) {
3201 if (mMainStack) {
3202 if (mService.mFocusedActivity == r) {
3203 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3204 }
3205 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003206 r.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003207 try {
3208 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003209 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3210 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003211 r.state = ActivityState.STOPPING;
3212 if (DEBUG_VISBILITY) Slog.v(
3213 TAG, "Stopping visible=" + r.visible + " for " + r);
3214 if (!r.visible) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003215 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003216 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003217 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003218 if (mService.isSleeping()) {
3219 r.setSleeping(true);
3220 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003221 } catch (Exception e) {
3222 // Maybe just ignore exceptions here... if the process
3223 // has crashed, our death notification will clean things
3224 // up.
3225 Slog.w(TAG, "Exception thrown during pause", e);
3226 // Just in case, assume it to be stopped.
3227 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003228 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003229 r.state = ActivityState.STOPPED;
3230 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003231 destroyActivityLocked(r, true, false, "stop-except");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003232 }
3233 }
3234 }
3235 }
3236
3237 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3238 boolean remove) {
3239 int N = mStoppingActivities.size();
3240 if (N <= 0) return null;
3241
3242 ArrayList<ActivityRecord> stops = null;
3243
3244 final boolean nowVisible = mResumedActivity != null
3245 && mResumedActivity.nowVisible
3246 && !mResumedActivity.waitingVisible;
3247 for (int i=0; i<N; i++) {
3248 ActivityRecord s = mStoppingActivities.get(i);
3249 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3250 + nowVisible + " waitingVisible=" + s.waitingVisible
3251 + " finishing=" + s.finishing);
3252 if (s.waitingVisible && nowVisible) {
3253 mWaitingVisibleActivities.remove(s);
3254 s.waitingVisible = false;
3255 if (s.finishing) {
3256 // If this activity is finishing, it is sitting on top of
3257 // everyone else but we now know it is no longer needed...
3258 // so get rid of it. Otherwise, we need to go through the
3259 // normal flow and hide it once we determine that it is
3260 // hidden by the activities in front of it.
3261 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003262 mService.mWindowManager.setAppVisibility(s.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003263 }
3264 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003265 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003266 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3267 if (stops == null) {
3268 stops = new ArrayList<ActivityRecord>();
3269 }
3270 stops.add(s);
3271 mStoppingActivities.remove(i);
3272 N--;
3273 i--;
3274 }
3275 }
3276
3277 return stops;
3278 }
3279
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003280 final void scheduleIdleLocked() {
3281 Message msg = Message.obtain();
3282 msg.what = IDLE_NOW_MSG;
3283 mHandler.sendMessage(msg);
3284 }
3285
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003286 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003287 Configuration config) {
3288 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3289
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003290 ActivityRecord res = null;
3291
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003292 ArrayList<ActivityRecord> stops = null;
3293 ArrayList<ActivityRecord> finishes = null;
3294 ArrayList<ActivityRecord> thumbnails = null;
3295 int NS = 0;
3296 int NF = 0;
3297 int NT = 0;
3298 IApplicationThread sendThumbnail = null;
3299 boolean booting = false;
3300 boolean enableScreen = false;
3301
3302 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003303 ActivityRecord r = ActivityRecord.forToken(token);
3304 if (r != null) {
3305 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003306 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003307 }
3308
3309 // Get the activity record.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003310 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003311 if (index >= 0) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003312 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003313
3314 if (fromTimeout) {
3315 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3316 }
3317
3318 // This is a hack to semi-deal with a race condition
3319 // in the client where it can be constructed with a
3320 // newer configuration from when we asked it to launch.
3321 // We'll update with whatever configuration it now says
3322 // it used to launch.
3323 if (config != null) {
3324 r.configuration = config;
3325 }
3326
3327 // No longer need to keep the device awake.
3328 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3329 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3330 mLaunchingActivity.release();
3331 }
3332
3333 // We are now idle. If someone is waiting for a thumbnail from
3334 // us, we can now deliver.
3335 r.idle = true;
3336 mService.scheduleAppGcsLocked();
3337 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3338 sendThumbnail = r.app.thread;
3339 r.thumbnailNeeded = false;
3340 }
3341
3342 // If this activity is fullscreen, set up to hide those under it.
3343
3344 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3345 ensureActivitiesVisibleLocked(null, 0);
3346
3347 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3348 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003349 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003350 mService.mBooted = true;
3351 enableScreen = true;
3352 }
3353 }
3354
3355 } else if (fromTimeout) {
3356 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3357 }
3358
3359 // Atomically retrieve all of the other things to do.
3360 stops = processStoppingActivitiesLocked(true);
3361 NS = stops != null ? stops.size() : 0;
3362 if ((NF=mFinishingActivities.size()) > 0) {
3363 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3364 mFinishingActivities.clear();
3365 }
3366 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3367 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3368 mService.mCancelledThumbnails.clear();
3369 }
3370
3371 if (mMainStack) {
3372 booting = mService.mBooting;
3373 mService.mBooting = false;
3374 }
3375 }
3376
3377 int i;
3378
3379 // Send thumbnail if requested.
3380 if (sendThumbnail != null) {
3381 try {
3382 sendThumbnail.requestThumbnail(token);
3383 } catch (Exception e) {
3384 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3385 mService.sendPendingThumbnail(null, token, null, null, true);
3386 }
3387 }
3388
3389 // Stop any activities that are scheduled to do so but have been
3390 // waiting for the next one to start.
3391 for (i=0; i<NS; i++) {
3392 ActivityRecord r = (ActivityRecord)stops.get(i);
3393 synchronized (mService) {
3394 if (r.finishing) {
3395 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY);
3396 } else {
3397 stopActivityLocked(r);
3398 }
3399 }
3400 }
3401
3402 // Finish any activities that are scheduled to do so but have been
3403 // waiting for the next one to start.
3404 for (i=0; i<NF; i++) {
3405 ActivityRecord r = (ActivityRecord)finishes.get(i);
3406 synchronized (mService) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003407 destroyActivityLocked(r, true, false, "finish-idle");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003408 }
3409 }
3410
3411 // Report back to any thumbnail receivers.
3412 for (i=0; i<NT; i++) {
3413 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3414 mService.sendPendingThumbnail(r, null, null, null, true);
3415 }
3416
3417 if (booting) {
3418 mService.finishBooting();
3419 }
3420
3421 mService.trimApplications();
3422 //dump();
3423 //mWindowManager.dump();
3424
3425 if (enableScreen) {
3426 mService.enableScreenAfterBoot();
3427 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003428
3429 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003430 }
3431
3432 /**
3433 * @return Returns true if the activity is being finished, false if for
3434 * some reason it is being left as-is.
3435 */
3436 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
3437 Intent resultData, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003438 int index = indexOfTokenLocked(token);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003439 if (DEBUG_RESULTS) Slog.v(
3440 TAG, "Finishing activity @" + index + ": token=" + token
3441 + ", result=" + resultCode + ", data=" + resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003442 if (index < 0) {
3443 return false;
3444 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003445 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003446
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003447 finishActivityLocked(r, index, resultCode, resultData, reason);
3448 return true;
3449 }
3450
Dianne Hackborn5c607432012-02-28 14:44:19 -08003451 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
3452 // send the result
3453 ActivityRecord resultTo = r.resultTo;
3454 if (resultTo != null) {
3455 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3456 + " who=" + r.resultWho + " req=" + r.requestCode
3457 + " res=" + resultCode + " data=" + resultData);
3458 if (r.info.applicationInfo.uid > 0) {
3459 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3460 resultTo.packageName, resultData,
3461 resultTo.getUriPermissionsLocked());
3462 }
3463 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3464 resultData);
3465 r.resultTo = null;
3466 }
3467 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3468
3469 // Make sure this HistoryRecord is not holding on to other resources,
3470 // because clients have remote IPC references to this object so we
3471 // can't assume that will go away and want to avoid circular IPC refs.
3472 r.results = null;
3473 r.pendingResults = null;
3474 r.newIntents = null;
3475 r.icicle = null;
3476 }
3477
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003478 /**
3479 * @return Returns true if this activity has been removed from the history
3480 * list, or false if it is still in the list and will be removed later.
3481 */
3482 final boolean finishActivityLocked(ActivityRecord r, int index,
3483 int resultCode, Intent resultData, String reason) {
3484 if (r.finishing) {
3485 Slog.w(TAG, "Duplicate finish request for " + r);
3486 return false;
3487 }
3488
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003489 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003490 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3491 System.identityHashCode(r),
3492 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003493 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003494 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003495 if (next.task == r.task) {
3496 if (r.frontOfTask) {
3497 // The next activity is now the front of the task.
3498 next.frontOfTask = true;
3499 }
3500 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3501 // If the caller asked that this activity (and all above it)
3502 // be cleared when the task is reset, don't lose that information,
3503 // but propagate it up to the next activity.
3504 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3505 }
3506 }
3507 }
3508
3509 r.pauseKeyDispatchingLocked();
3510 if (mMainStack) {
3511 if (mService.mFocusedActivity == r) {
3512 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3513 }
3514 }
3515
Dianne Hackborn5c607432012-02-28 14:44:19 -08003516 finishActivityResultsLocked(r, resultCode, resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003517
3518 if (mService.mPendingThumbnails.size() > 0) {
3519 // There are clients waiting to receive thumbnails so, in case
3520 // this is an activity that someone is waiting for, add it
3521 // to the pending list so we can correctly update the clients.
3522 mService.mCancelledThumbnails.add(r);
3523 }
3524
3525 if (mResumedActivity == r) {
3526 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003527 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003528 if (DEBUG_TRANSITION) Slog.v(TAG,
3529 "Prepare close transition: finishing " + r);
3530 mService.mWindowManager.prepareAppTransition(endTask
3531 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003532 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003533
3534 // Tell window manager to prepare for this one to be removed.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003535 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003536
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003537 if (mPausingActivity == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003538 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3539 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3540 startPausingLocked(false, false);
3541 }
3542
3543 } else if (r.state != ActivityState.PAUSING) {
3544 // If the activity is PAUSING, we will complete the finish once
3545 // it is done pausing; else we can just directly finish it here.
3546 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3547 return finishCurrentActivityLocked(r, index,
3548 FINISH_AFTER_PAUSE) == null;
3549 } else {
3550 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3551 }
3552
3553 return false;
3554 }
3555
3556 private static final int FINISH_IMMEDIATELY = 0;
3557 private static final int FINISH_AFTER_PAUSE = 1;
3558 private static final int FINISH_AFTER_VISIBLE = 2;
3559
3560 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3561 int mode) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003562 final int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003563 if (index < 0) {
3564 return null;
3565 }
3566
3567 return finishCurrentActivityLocked(r, index, mode);
3568 }
3569
3570 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3571 int index, int mode) {
3572 // First things first: if this activity is currently visible,
3573 // and the resumed activity is not yet visible, then hold off on
3574 // finishing until the resumed one becomes visible.
3575 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3576 if (!mStoppingActivities.contains(r)) {
3577 mStoppingActivities.add(r);
3578 if (mStoppingActivities.size() > 3) {
3579 // If we already have a few activities waiting to stop,
3580 // then give up on things going idle and start clearing
3581 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003582 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003583 } else {
3584 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003585 }
3586 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003587 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3588 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003589 r.state = ActivityState.STOPPING;
3590 mService.updateOomAdjLocked();
3591 return r;
3592 }
3593
3594 // make sure the record is cleaned out of other places.
3595 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003596 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003597 mWaitingVisibleActivities.remove(r);
3598 if (mResumedActivity == r) {
3599 mResumedActivity = null;
3600 }
3601 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003602 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003603 r.state = ActivityState.FINISHING;
3604
3605 if (mode == FINISH_IMMEDIATELY
3606 || prevState == ActivityState.STOPPED
3607 || prevState == ActivityState.INITIALIZING) {
3608 // If this activity is already stopped, we can just finish
3609 // it right now.
Dianne Hackborn28695e02011-11-02 21:59:51 -07003610 return destroyActivityLocked(r, true, true, "finish-imm") ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003611 } else {
3612 // Need to go through the full pause cycle to get this
3613 // activity into the stopped state and then finish it.
3614 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3615 mFinishingActivities.add(r);
3616 resumeTopActivityLocked(null);
3617 }
3618 return r;
3619 }
3620
3621 /**
3622 * Perform the common clean-up of an activity record. This is called both
3623 * as part of destroyActivityLocked() (when destroying the client-side
3624 * representation) and cleaning things up as a result of its hosting
3625 * processing going away, in which case there is no remaining client-side
3626 * state to destroy so only the cleanup here is needed.
3627 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003628 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3629 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003630 if (mResumedActivity == r) {
3631 mResumedActivity = null;
3632 }
3633 if (mService.mFocusedActivity == r) {
3634 mService.mFocusedActivity = null;
3635 }
3636
3637 r.configDestroy = false;
3638 r.frozenBeforeDestroy = false;
3639
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003640 if (setState) {
3641 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3642 r.state = ActivityState.DESTROYED;
3643 }
3644
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003645 // Make sure this record is no longer in the pending finishes list.
3646 // This could happen, for example, if we are trimming activities
3647 // down to the max limit while they are still waiting to finish.
3648 mFinishingActivities.remove(r);
3649 mWaitingVisibleActivities.remove(r);
3650
3651 // Remove any pending results.
3652 if (r.finishing && r.pendingResults != null) {
3653 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3654 PendingIntentRecord rec = apr.get();
3655 if (rec != null) {
3656 mService.cancelIntentSenderLocked(rec, false);
3657 }
3658 }
3659 r.pendingResults = null;
3660 }
3661
3662 if (cleanServices) {
3663 cleanUpActivityServicesLocked(r);
3664 }
3665
3666 if (mService.mPendingThumbnails.size() > 0) {
3667 // There are clients waiting to receive thumbnails so, in case
3668 // this is an activity that someone is waiting for, add it
3669 // to the pending list so we can correctly update the clients.
3670 mService.mCancelledThumbnails.add(r);
3671 }
3672
3673 // Get rid of any pending idle timeouts.
3674 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
3675 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003676 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003677 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003678 }
3679
Dianne Hackborn5c607432012-02-28 14:44:19 -08003680 final void removeActivityFromHistoryLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003681 if (r.state != ActivityState.DESTROYED) {
Dianne Hackborn5c607432012-02-28 14:44:19 -08003682 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003683 r.makeFinishing();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003684 if (DEBUG_ADD_REMOVE) {
3685 RuntimeException here = new RuntimeException("here");
3686 here.fillInStackTrace();
3687 Slog.i(TAG, "Removing activity " + r + " from stack");
3688 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003689 mHistory.remove(r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003690 r.takeFromHistory();
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003691 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3692 + " (removed from history)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003693 r.state = ActivityState.DESTROYED;
Dianne Hackbornbe707852011-11-11 14:32:10 -08003694 mService.mWindowManager.removeAppToken(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003695 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003696 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003697 }
3698 cleanUpActivityServicesLocked(r);
3699 r.removeUriPermissionsLocked();
3700 }
3701 }
3702
3703 /**
3704 * Perform clean-up of service connections in an activity record.
3705 */
3706 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3707 // Throw away any services that have been bound by this activity.
3708 if (r.connections != null) {
3709 Iterator<ConnectionRecord> it = r.connections.iterator();
3710 while (it.hasNext()) {
3711 ConnectionRecord c = it.next();
3712 mService.removeConnectionLocked(c, null, r);
3713 }
3714 r.connections = null;
3715 }
3716 }
3717
Dianne Hackborn28695e02011-11-02 21:59:51 -07003718 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003719 for (int i=mHistory.size()-1; i>=0; i--) {
3720 ActivityRecord r = mHistory.get(i);
3721 if (owner != null && r.app != owner) {
3722 continue;
3723 }
3724 // We can destroy this one if we have its icicle saved and
3725 // it is not in the process of pausing/stopping/finishing.
3726 if (r.app != null && r.haveState && !r.visible && r.stopped && !r.finishing
3727 && r.state != ActivityState.DESTROYING
3728 && r.state != ActivityState.DESTROYED) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003729 destroyActivityLocked(r, true, oomAdj, "trim");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003730 }
3731 }
3732 }
3733
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003734 /**
3735 * Destroy the current CLIENT SIDE instance of an activity. This may be
3736 * called both when actually finishing an activity, or when performing
3737 * a configuration switch where we destroy the current client-side object
3738 * but then create a new client-side object for this same HistoryRecord.
3739 */
3740 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackborn28695e02011-11-02 21:59:51 -07003741 boolean removeFromApp, boolean oomAdj, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003742 if (DEBUG_SWITCH) Slog.v(
3743 TAG, "Removing activity: token=" + r
3744 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3745 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3746 System.identityHashCode(r),
Dianne Hackborn28695e02011-11-02 21:59:51 -07003747 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003748
3749 boolean removedFromHistory = false;
3750
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003751 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003752
3753 final boolean hadApp = r.app != null;
3754
3755 if (hadApp) {
3756 if (removeFromApp) {
3757 int idx = r.app.activities.indexOf(r);
3758 if (idx >= 0) {
3759 r.app.activities.remove(idx);
3760 }
3761 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
3762 mService.mHeavyWeightProcess = null;
3763 mService.mHandler.sendEmptyMessage(
3764 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
3765 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003766 if (r.app.activities.size() == 0) {
3767 // No longer have activities, so update location in
3768 // LRU list.
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003769 mService.updateLruProcessLocked(r.app, oomAdj, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003770 }
3771 }
3772
3773 boolean skipDestroy = false;
3774
3775 try {
3776 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003777 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003778 r.configChangeFlags);
3779 } catch (Exception e) {
3780 // We can just ignore exceptions here... if the process
3781 // has crashed, our death notification will clean things
3782 // up.
3783 //Slog.w(TAG, "Exception thrown during finish", e);
3784 if (r.finishing) {
3785 removeActivityFromHistoryLocked(r);
3786 removedFromHistory = true;
3787 skipDestroy = true;
3788 }
3789 }
3790
3791 r.app = null;
3792 r.nowVisible = false;
3793
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003794 // If the activity is finishing, we need to wait on removing it
3795 // from the list to give it a chance to do its cleanup. During
3796 // that time it may make calls back with its token so we need to
3797 // be able to find it on the list and so we don't want to remove
3798 // it from the list yet. Otherwise, we can just immediately put
3799 // it in the destroyed state since we are not removing it from the
3800 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003801 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003802 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
3803 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003804 r.state = ActivityState.DESTROYING;
3805 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
3806 msg.obj = r;
3807 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
3808 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003809 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3810 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003811 r.state = ActivityState.DESTROYED;
3812 }
3813 } else {
3814 // remove this record from the history.
3815 if (r.finishing) {
3816 removeActivityFromHistoryLocked(r);
3817 removedFromHistory = true;
3818 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003819 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3820 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003821 r.state = ActivityState.DESTROYED;
3822 }
3823 }
3824
3825 r.configChangeFlags = 0;
3826
3827 if (!mLRUActivities.remove(r) && hadApp) {
3828 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
3829 }
3830
3831 return removedFromHistory;
3832 }
3833
3834 final void activityDestroyed(IBinder token) {
3835 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003836 ActivityRecord r = ActivityRecord.forToken(token);
3837 if (r != null) {
3838 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
3839 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003840
Dianne Hackbornbe707852011-11-11 14:32:10 -08003841 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003842 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003843 if (r.state == ActivityState.DESTROYING) {
3844 final long origId = Binder.clearCallingIdentity();
3845 removeActivityFromHistoryLocked(r);
3846 Binder.restoreCallingIdentity(origId);
3847 }
3848 }
3849 }
3850 }
3851
3852 private static void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
3853 int i = list.size();
3854 if (localLOGV) Slog.v(
3855 TAG, "Removing app " + app + " from list " + list
3856 + " with " + i + " entries");
3857 while (i > 0) {
3858 i--;
3859 ActivityRecord r = (ActivityRecord)list.get(i);
3860 if (localLOGV) Slog.v(
3861 TAG, "Record #" + i + " " + r + ": app=" + r.app);
3862 if (r.app == app) {
3863 if (localLOGV) Slog.v(TAG, "Removing this entry!");
3864 list.remove(i);
3865 }
3866 }
3867 }
3868
3869 void removeHistoryRecordsForAppLocked(ProcessRecord app) {
3870 removeHistoryRecordsForAppLocked(mLRUActivities, app);
3871 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003872 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003873 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
3874 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
3875 }
3876
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003877 /**
3878 * Move the current home activity's task (if one exists) to the front
3879 * of the stack.
3880 */
3881 final void moveHomeToFrontLocked() {
3882 TaskRecord homeTask = null;
3883 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003884 ActivityRecord hr = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003885 if (hr.isHomeActivity) {
3886 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003887 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003888 }
3889 }
3890 if (homeTask != null) {
3891 moveTaskToFrontLocked(homeTask, null);
3892 }
3893 }
3894
3895
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003896 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason) {
3897 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
3898
3899 final int task = tr.taskId;
3900 int top = mHistory.size()-1;
3901
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003902 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003903 // nothing to do!
3904 return;
3905 }
3906
Dianne Hackbornbe707852011-11-11 14:32:10 -08003907 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003908
3909 // Applying the affinities may have removed entries from the history,
3910 // so get the size again.
3911 top = mHistory.size()-1;
3912 int pos = top;
3913
3914 // Shift all activities with this task up to the top
3915 // of the stack, keeping them in the same internal order.
3916 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003917 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003918 if (localLOGV) Slog.v(
3919 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003920 if (r.task.taskId == task) {
3921 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003922 if (DEBUG_ADD_REMOVE) {
3923 RuntimeException here = new RuntimeException("here");
3924 here.fillInStackTrace();
3925 Slog.i(TAG, "Removing and adding activity " + r + " to stack at " + top, here);
3926 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003927 mHistory.remove(pos);
3928 mHistory.add(top, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003929 moved.add(0, r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003930 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003931 }
3932 pos--;
3933 }
3934
3935 if (DEBUG_TRANSITION) Slog.v(TAG,
3936 "Prepare to front transition: task=" + tr);
3937 if (reason != null &&
3938 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003939 mService.mWindowManager.prepareAppTransition(
3940 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003941 ActivityRecord r = topRunningActivityLocked(null);
3942 if (r != null) {
3943 mNoAnimActivities.add(r);
3944 }
3945 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003946 mService.mWindowManager.prepareAppTransition(
3947 WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003948 }
3949
3950 mService.mWindowManager.moveAppTokensToTop(moved);
3951 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003952 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003953 }
3954
3955 finishTaskMoveLocked(task);
3956 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
3957 }
3958
3959 private final void finishTaskMoveLocked(int task) {
3960 resumeTopActivityLocked(null);
3961 }
3962
3963 /**
3964 * Worker method for rearranging history stack. Implements the function of moving all
3965 * activities for a specific task (gathering them if disjoint) into a single group at the
3966 * bottom of the stack.
3967 *
3968 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
3969 * to premeptively cancel the move.
3970 *
3971 * @param task The taskId to collect and move to the bottom.
3972 * @return Returns true if the move completed, false if not.
3973 */
3974 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
3975 Slog.i(TAG, "moveTaskToBack: " + task);
3976
3977 // If we have a watcher, preflight the move before committing to it. First check
3978 // for *other* available tasks, but if none are available, then try again allowing the
3979 // current task to be selected.
3980 if (mMainStack && mService.mController != null) {
3981 ActivityRecord next = topRunningActivityLocked(null, task);
3982 if (next == null) {
3983 next = topRunningActivityLocked(null, 0);
3984 }
3985 if (next != null) {
3986 // ask watcher if this is allowed
3987 boolean moveOK = true;
3988 try {
3989 moveOK = mService.mController.activityResuming(next.packageName);
3990 } catch (RemoteException e) {
3991 mService.mController = null;
3992 }
3993 if (!moveOK) {
3994 return false;
3995 }
3996 }
3997 }
3998
Dianne Hackbornbe707852011-11-11 14:32:10 -08003999 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004000
4001 if (DEBUG_TRANSITION) Slog.v(TAG,
4002 "Prepare to back transition: task=" + task);
4003
4004 final int N = mHistory.size();
4005 int bottom = 0;
4006 int pos = 0;
4007
4008 // Shift all activities with this task down to the bottom
4009 // of the stack, keeping them in the same internal order.
4010 while (pos < N) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004011 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004012 if (localLOGV) Slog.v(
4013 TAG, "At " + pos + " ckp " + r.task + ": " + r);
4014 if (r.task.taskId == task) {
4015 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004016 if (DEBUG_ADD_REMOVE) {
4017 RuntimeException here = new RuntimeException("here");
4018 here.fillInStackTrace();
4019 Slog.i(TAG, "Removing and adding activity " + r + " to stack at "
4020 + bottom, here);
4021 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004022 mHistory.remove(pos);
4023 mHistory.add(bottom, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004024 moved.add(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004025 bottom++;
4026 }
4027 pos++;
4028 }
4029
4030 if (reason != null &&
4031 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004032 mService.mWindowManager.prepareAppTransition(
4033 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004034 ActivityRecord r = topRunningActivityLocked(null);
4035 if (r != null) {
4036 mNoAnimActivities.add(r);
4037 }
4038 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004039 mService.mWindowManager.prepareAppTransition(
4040 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004041 }
4042 mService.mWindowManager.moveAppTokensToBottom(moved);
4043 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004044 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004045 }
4046
4047 finishTaskMoveLocked(task);
4048 return true;
4049 }
4050
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004051 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
4052 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4053 ActivityRecord resumed = mResumedActivity;
4054 if (resumed != null && resumed.thumbHolder == tr) {
4055 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
4056 } else {
4057 info.mainThumbnail = tr.lastThumbnail;
4058 }
4059 return info;
4060 }
4061
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004062 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex,
4063 boolean taskRequired) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004064 TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
4065 if (info.root == null) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004066 if (taskRequired) {
4067 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
4068 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004069 return null;
4070 }
4071
4072 if (subTaskIndex < 0) {
4073 // Just remove the entire task.
4074 performClearTaskAtIndexLocked(taskId, info.rootIndex);
4075 return info.root;
4076 }
4077
4078 if (subTaskIndex >= info.subtasks.size()) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004079 if (taskRequired) {
4080 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
4081 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004082 return null;
4083 }
4084
4085 // Remove all of this task's activies starting at the sub task.
4086 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
4087 performClearTaskAtIndexLocked(taskId, subtask.index);
4088 return subtask.activity;
4089 }
4090
4091 public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
4092 ActivityRecord resumed = mResumedActivity;
4093 final TaskAccessInfo thumbs = new TaskAccessInfo();
4094 // How many different sub-thumbnails?
4095 final int NA = mHistory.size();
4096 int j = 0;
4097 ThumbnailHolder holder = null;
4098 while (j < NA) {
4099 ActivityRecord ar = mHistory.get(j);
4100 if (!ar.finishing && ar.task.taskId == taskId) {
4101 holder = ar.thumbHolder;
4102 break;
4103 }
4104 j++;
4105 }
4106
4107 if (j >= NA) {
4108 return thumbs;
4109 }
4110
4111 thumbs.root = mHistory.get(j);
4112 thumbs.rootIndex = j;
4113
4114 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
4115 thumbs.subtasks = subtasks;
4116 ActivityRecord lastActivity = null;
4117 while (j < NA) {
4118 ActivityRecord ar = mHistory.get(j);
4119 j++;
4120 if (ar.finishing) {
4121 continue;
4122 }
4123 if (ar.task.taskId != taskId) {
4124 break;
4125 }
4126 lastActivity = ar;
4127 if (ar.thumbHolder != holder && holder != null) {
4128 thumbs.numSubThumbbails++;
4129 holder = ar.thumbHolder;
4130 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
4131 sub.thumbnail = holder.lastThumbnail;
4132 sub.activity = ar;
4133 sub.index = j-1;
4134 subtasks.add(sub);
4135 }
4136 }
4137 if (lastActivity != null && subtasks.size() > 0) {
4138 if (resumed == lastActivity) {
4139 TaskAccessInfo.SubTask sub = subtasks.get(subtasks.size()-1);
4140 sub.thumbnail = lastActivity.stack.screenshotActivities(lastActivity);
4141 }
4142 }
4143 if (thumbs.numSubThumbbails > 0) {
4144 thumbs.retriever = new IThumbnailRetriever.Stub() {
4145 public Bitmap getThumbnail(int index) {
4146 if (index < 0 || index >= thumbs.subtasks.size()) {
4147 return null;
4148 }
4149 return thumbs.subtasks.get(index).thumbnail;
4150 }
4151 };
4152 }
4153 return thumbs;
4154 }
4155
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004156 private final void logStartActivity(int tag, ActivityRecord r,
4157 TaskRecord task) {
4158 EventLog.writeEvent(tag,
4159 System.identityHashCode(r), task.taskId,
4160 r.shortComponentName, r.intent.getAction(),
4161 r.intent.getType(), r.intent.getDataString(),
4162 r.intent.getFlags());
4163 }
4164
4165 /**
4166 * Make sure the given activity matches the current configuration. Returns
4167 * false if the activity had to be destroyed. Returns true if the
4168 * configuration is the same, or the activity will remain running as-is
4169 * for whatever reason. Ensures the HistoryRecord is updated with the
4170 * correct configuration and all other bookkeeping is handled.
4171 */
4172 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
4173 int globalChanges) {
4174 if (mConfigWillChange) {
4175 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4176 "Skipping config check (will change): " + r);
4177 return true;
4178 }
4179
4180 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4181 "Ensuring correct configuration: " + r);
4182
4183 // Short circuit: if the two configurations are the exact same
4184 // object (the common case), then there is nothing to do.
4185 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004186 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004187 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4188 "Configuration unchanged in " + r);
4189 return true;
4190 }
4191
4192 // We don't worry about activities that are finishing.
4193 if (r.finishing) {
4194 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4195 "Configuration doesn't matter in finishing " + r);
4196 r.stopFreezingScreenLocked(false);
4197 return true;
4198 }
4199
4200 // Okay we now are going to make this activity have the new config.
4201 // But then we need to figure out how it needs to deal with that.
4202 Configuration oldConfig = r.configuration;
4203 r.configuration = newConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004204
4205 // Determine what has changed. May be nothing, if this is a config
4206 // that has come back from the app after going idle. In that case
4207 // we just want to leave the official config object now in the
4208 // activity and do nothing else.
4209 final int changes = oldConfig.diff(newConfig);
4210 if (changes == 0 && !r.forceNewConfig) {
4211 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4212 "Configuration no differences in " + r);
4213 return true;
4214 }
4215
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004216 // If the activity isn't currently running, just leave the new
4217 // configuration and it will pick that up next time it starts.
4218 if (r.app == null || r.app.thread == null) {
4219 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4220 "Configuration doesn't matter not running " + r);
4221 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004222 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004223 return true;
4224 }
4225
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004226 // Figure out how to handle the changes between the configurations.
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004227 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4228 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
4229 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07004230 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004231 + ", newConfig=" + newConfig);
4232 }
Dianne Hackborne6676352011-06-01 16:51:20 -07004233 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004234 // Aha, the activity isn't handling the change, so DIE DIE DIE.
4235 r.configChangeFlags |= changes;
4236 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004237 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004238 if (r.app == null || r.app.thread == null) {
4239 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4240 "Switch is destroying non-running " + r);
Dianne Hackborn28695e02011-11-02 21:59:51 -07004241 destroyActivityLocked(r, true, false, "config");
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004242 } else if (r.state == ActivityState.PAUSING) {
4243 // A little annoying: we are waiting for this activity to
4244 // finish pausing. Let's not do anything now, but just
4245 // flag that it needs to be restarted when done pausing.
4246 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4247 "Switch is skipping already pausing " + r);
4248 r.configDestroy = true;
4249 return true;
4250 } else if (r.state == ActivityState.RESUMED) {
4251 // Try to optimize this case: the configuration is changing
4252 // and we need to restart the top, resumed activity.
4253 // Instead of doing the normal handshaking, just say
4254 // "restart!".
4255 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4256 "Switch is restarting resumed " + r);
4257 relaunchActivityLocked(r, r.configChangeFlags, true);
4258 r.configChangeFlags = 0;
4259 } else {
4260 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4261 "Switch is restarting non-resumed " + r);
4262 relaunchActivityLocked(r, r.configChangeFlags, false);
4263 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004264 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004265
4266 // All done... tell the caller we weren't able to keep this
4267 // activity around.
4268 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004269 }
4270
4271 // Default case: the activity can handle this new configuration, so
4272 // hand it over. Note that we don't need to give it the new
4273 // configuration, since we always send configuration changes to all
4274 // process when they happen so it can just use whatever configuration
4275 // it last got.
4276 if (r.app != null && r.app.thread != null) {
4277 try {
4278 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004279 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004280 } catch (RemoteException e) {
4281 // If process died, whatever.
4282 }
4283 }
4284 r.stopFreezingScreenLocked(false);
4285
4286 return true;
4287 }
4288
4289 private final boolean relaunchActivityLocked(ActivityRecord r,
4290 int changes, boolean andResume) {
4291 List<ResultInfo> results = null;
4292 List<Intent> newIntents = null;
4293 if (andResume) {
4294 results = r.results;
4295 newIntents = r.newIntents;
4296 }
4297 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4298 + " with results=" + results + " newIntents=" + newIntents
4299 + " andResume=" + andResume);
4300 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
4301 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
4302 r.task.taskId, r.shortComponentName);
4303
4304 r.startFreezingScreenLocked(r.app, 0);
4305
4306 try {
4307 if (DEBUG_SWITCH) Slog.i(TAG, "Switch is restarting resumed " + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004308 r.forceNewConfig = false;
Dianne Hackbornbe707852011-11-11 14:32:10 -08004309 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004310 changes, !andResume, new Configuration(mService.mConfiguration));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004311 // Note: don't need to call pauseIfSleepingLocked() here, because
4312 // the caller will only pass in 'andResume' if this activity is
4313 // currently resumed, which implies we aren't sleeping.
4314 } catch (RemoteException e) {
4315 return false;
4316 }
4317
4318 if (andResume) {
4319 r.results = null;
4320 r.newIntents = null;
4321 if (mMainStack) {
4322 mService.reportResumedActivityLocked(r);
4323 }
4324 }
4325
4326 return true;
4327 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004328
4329 public void dismissKeyguardOnNextActivityLocked() {
4330 mDismissKeyguardOnNextActivity = true;
4331 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004332}