blob: 86d3a1a05c3dc7fcc523a9fee8db67dfe363d0f9 [file] [log] [blame]
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
19import com.android.internal.app.HeavyWeightSwitcherActivity;
20import com.android.internal.os.BatteryStatsImpl;
21import com.android.server.am.ActivityManagerService.PendingActivityLaunch;
22
23import android.app.Activity;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070024import android.app.ActivityManager;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070025import android.app.AppGlobals;
26import android.app.IActivityManager;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070027import android.app.IThumbnailRetriever;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070028import static android.app.IActivityManager.START_CLASS_NOT_FOUND;
29import static android.app.IActivityManager.START_DELIVERED_TO_TOP;
30import static android.app.IActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
31import static android.app.IActivityManager.START_INTENT_NOT_RESOLVED;
32import static android.app.IActivityManager.START_PERMISSION_DENIED;
33import static android.app.IActivityManager.START_RETURN_INTENT_TO_CALLER;
34import static android.app.IActivityManager.START_SUCCESS;
35import static android.app.IActivityManager.START_SWITCHES_CANCELED;
36import static android.app.IActivityManager.START_TASK_TO_FRONT;
37import android.app.IApplicationThread;
38import android.app.PendingIntent;
39import android.app.ResultInfo;
40import android.app.IActivityManager.WaitResult;
41import android.content.ComponentName;
42import android.content.Context;
43import android.content.IIntentSender;
44import android.content.Intent;
45import android.content.IntentSender;
46import android.content.pm.ActivityInfo;
47import android.content.pm.ApplicationInfo;
48import android.content.pm.PackageManager;
49import android.content.pm.ResolveInfo;
50import android.content.res.Configuration;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -080051import android.content.res.Resources;
52import android.graphics.Bitmap;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070053import android.net.Uri;
54import android.os.Binder;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070055import android.os.Bundle;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070056import android.os.Handler;
57import android.os.IBinder;
58import android.os.Message;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070059import android.os.ParcelFileDescriptor;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070060import android.os.PowerManager;
61import android.os.RemoteException;
62import android.os.SystemClock;
63import android.util.EventLog;
64import android.util.Log;
65import android.util.Slog;
66import android.view.WindowManagerPolicy;
67
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070068import java.io.IOException;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070069import java.lang.ref.WeakReference;
70import java.util.ArrayList;
71import java.util.Iterator;
72import java.util.List;
73
74/**
75 * State and management of a single stack of activities.
76 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070077final class ActivityStack {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070078 static final String TAG = ActivityManagerService.TAG;
Dianne Hackbornb961cd22011-06-21 12:13:37 -070079 static final boolean localLOGV = ActivityManagerService.localLOGV;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070080 static final boolean DEBUG_SWITCH = ActivityManagerService.DEBUG_SWITCH;
81 static final boolean DEBUG_PAUSE = ActivityManagerService.DEBUG_PAUSE;
82 static final boolean DEBUG_VISBILITY = ActivityManagerService.DEBUG_VISBILITY;
83 static final boolean DEBUG_USER_LEAVING = ActivityManagerService.DEBUG_USER_LEAVING;
84 static final boolean DEBUG_TRANSITION = ActivityManagerService.DEBUG_TRANSITION;
85 static final boolean DEBUG_RESULTS = ActivityManagerService.DEBUG_RESULTS;
86 static final boolean DEBUG_CONFIGURATION = ActivityManagerService.DEBUG_CONFIGURATION;
87 static final boolean DEBUG_TASKS = ActivityManagerService.DEBUG_TASKS;
88
Dianne Hackbornce86ba82011-07-13 19:33:41 -070089 static final boolean DEBUG_STATES = false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070090 static final boolean DEBUG_ADD_REMOVE = false;
91 static final boolean DEBUG_SAVED_STATE = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070092
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070093 static final boolean VALIDATE_TOKENS = ActivityManagerService.VALIDATE_TOKENS;
94
95 // How long we wait until giving up on the last activity telling us it
96 // is idle.
97 static final int IDLE_TIMEOUT = 10*1000;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -070098
99 // Ticks during which we check progress while waiting for an app to launch.
100 static final int LAUNCH_TICK = 500;
101
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700102 // How long we wait until giving up on the last activity to pause. This
103 // is short because it directly impacts the responsiveness of starting the
104 // next activity.
105 static final int PAUSE_TIMEOUT = 500;
106
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800107 // How long we can hold the sleep wake lock before giving up.
108 static final int SLEEP_TIMEOUT = 5*1000;
109
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700110 // How long we can hold the launch wake lock before giving up.
111 static final int LAUNCH_TIMEOUT = 10*1000;
112
113 // How long we wait until giving up on an activity telling us it has
114 // finished destroying itself.
115 static final int DESTROY_TIMEOUT = 10*1000;
116
117 // How long until we reset a task when the user returns to it. Currently
Dianne Hackborn621e17d2010-11-22 15:59:56 -0800118 // disabled.
119 static final long ACTIVITY_INACTIVE_RESET_TIME = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700120
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700121 // How long between activity launches that we consider safe to not warn
122 // the user about an unexpected activity being launched on top.
123 static final long START_WARN_TIME = 5*1000;
124
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700125 // Set to false to disable the preview that is shown while a new activity
126 // is being started.
127 static final boolean SHOW_APP_STARTING_PREVIEW = true;
128
129 enum ActivityState {
130 INITIALIZING,
131 RESUMED,
132 PAUSING,
133 PAUSED,
134 STOPPING,
135 STOPPED,
136 FINISHING,
137 DESTROYING,
138 DESTROYED
139 }
140
141 final ActivityManagerService mService;
142 final boolean mMainStack;
143
144 final Context mContext;
145
146 /**
147 * The back history of all previous (and possibly still
148 * running) activities. It contains HistoryRecord objects.
149 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700150 final ArrayList<ActivityRecord> mHistory = new ArrayList<ActivityRecord>();
Dianne Hackbornbe707852011-11-11 14:32:10 -0800151
152 /**
153 * Used for validating app tokens with window manager.
154 */
155 final ArrayList<IBinder> mValidateAppTokens = new ArrayList<IBinder>();
156
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700157 /**
158 * List of running activities, sorted by recent usage.
159 * The first entry in the list is the least recently used.
160 * It contains HistoryRecord objects.
161 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700162 final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700163
164 /**
165 * List of activities that are waiting for a new activity
166 * to become visible before completing whatever operation they are
167 * supposed to do.
168 */
169 final ArrayList<ActivityRecord> mWaitingVisibleActivities
170 = new ArrayList<ActivityRecord>();
171
172 /**
173 * List of activities that are ready to be stopped, but waiting
174 * for the next activity to settle down before doing so. It contains
175 * HistoryRecord objects.
176 */
177 final ArrayList<ActivityRecord> mStoppingActivities
178 = new ArrayList<ActivityRecord>();
179
180 /**
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800181 * List of activities that are in the process of going to sleep.
182 */
183 final ArrayList<ActivityRecord> mGoingToSleepActivities
184 = new ArrayList<ActivityRecord>();
185
186 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700187 * Animations that for the current transition have requested not to
188 * be considered for the transition animation.
189 */
190 final ArrayList<ActivityRecord> mNoAnimActivities
191 = new ArrayList<ActivityRecord>();
192
193 /**
194 * List of activities that are ready to be finished, but waiting
195 * for the previous activity to settle down before doing so. It contains
196 * HistoryRecord objects.
197 */
198 final ArrayList<ActivityRecord> mFinishingActivities
199 = new ArrayList<ActivityRecord>();
200
201 /**
202 * List of people waiting to find out about the next launched activity.
203 */
204 final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched
205 = new ArrayList<IActivityManager.WaitResult>();
206
207 /**
208 * List of people waiting to find out about the next visible activity.
209 */
210 final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible
211 = new ArrayList<IActivityManager.WaitResult>();
212
213 /**
214 * Set when the system is going to sleep, until we have
215 * successfully paused the current activity and released our wake lock.
216 * At that point the system is allowed to actually sleep.
217 */
218 final PowerManager.WakeLock mGoingToSleep;
219
220 /**
221 * We don't want to allow the device to go to sleep while in the process
222 * of launching an activity. This is primarily to allow alarm intent
223 * receivers to launch an activity and get that to run before the device
224 * goes back to sleep.
225 */
226 final PowerManager.WakeLock mLaunchingActivity;
227
228 /**
229 * When we are in the process of pausing an activity, before starting the
230 * next one, this variable holds the activity that is currently being paused.
231 */
232 ActivityRecord mPausingActivity = null;
233
234 /**
235 * This is the last activity that we put into the paused state. This is
236 * used to determine if we need to do an activity transition while sleeping,
237 * when we normally hold the top activity paused.
238 */
239 ActivityRecord mLastPausedActivity = null;
240
241 /**
242 * Current activity that is resumed, or null if there is none.
243 */
244 ActivityRecord mResumedActivity = null;
245
246 /**
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700247 * This is the last activity that has been started. It is only used to
248 * identify when multiple activities are started at once so that the user
249 * can be warned they may not be in the activity they think they are.
250 */
251 ActivityRecord mLastStartedActivity = null;
252
253 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700254 * Set when we know we are going to be calling updateConfiguration()
255 * soon, so want to skip intermediate config checks.
256 */
257 boolean mConfigWillChange;
258
259 /**
260 * Set to indicate whether to issue an onUserLeaving callback when a
261 * newly launched activity is being brought in front of us.
262 */
263 boolean mUserLeaving = false;
264
265 long mInitialStartTime = 0;
266
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800267 /**
268 * Set when we have taken too long waiting to go to sleep.
269 */
270 boolean mSleepTimeout = false;
271
Dianne Hackborn90c52de2011-09-23 12:57:44 -0700272 /**
273 * Dismiss the keyguard after the next activity is displayed?
274 */
275 boolean mDismissKeyguardOnNextActivity = false;
276
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800277 int mThumbnailWidth = -1;
278 int mThumbnailHeight = -1;
279
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800280 static final int SLEEP_TIMEOUT_MSG = 8;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700281 static final int PAUSE_TIMEOUT_MSG = 9;
282 static final int IDLE_TIMEOUT_MSG = 10;
283 static final int IDLE_NOW_MSG = 11;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700284 static final int LAUNCH_TICK_MSG = 12;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700285 static final int LAUNCH_TIMEOUT_MSG = 16;
286 static final int DESTROY_TIMEOUT_MSG = 17;
287 static final int RESUME_TOP_ACTIVITY_MSG = 19;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700288
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700289 final Handler mHandler = new Handler() {
290 //public Handler() {
291 // if (localLOGV) Slog.v(TAG, "Handler started!");
292 //}
293
294 public void handleMessage(Message msg) {
295 switch (msg.what) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800296 case SLEEP_TIMEOUT_MSG: {
Dianne Hackborn8e8d65f2011-08-11 19:36:18 -0700297 synchronized (mService) {
298 if (mService.isSleeping()) {
299 Slog.w(TAG, "Sleep timeout! Sleeping now.");
300 mSleepTimeout = true;
301 checkReadyForSleepLocked();
302 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800303 }
304 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700305 case PAUSE_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800306 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700307 // We don't at this point know if the activity is fullscreen,
308 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800309 Slog.w(TAG, "Activity pause timeout for " + r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700310 synchronized (mService) {
311 if (r.app != null) {
312 mService.logAppTooSlow(r.app, r.pauseTime,
313 "pausing " + r);
314 }
315 }
316
Dianne Hackbornbe707852011-11-11 14:32:10 -0800317 activityPaused(r != null ? r.appToken : null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700318 } break;
319 case IDLE_TIMEOUT_MSG: {
320 if (mService.mDidDexOpt) {
321 mService.mDidDexOpt = false;
322 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
323 nmsg.obj = msg.obj;
324 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
325 return;
326 }
327 // We don't at this point know if the activity is fullscreen,
328 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800329 ActivityRecord r = (ActivityRecord)msg.obj;
330 Slog.w(TAG, "Activity idle timeout for " + r);
331 activityIdleInternal(r != null ? r.appToken : null, true, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700332 } break;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700333 case LAUNCH_TICK_MSG: {
334 ActivityRecord r = (ActivityRecord)msg.obj;
335 synchronized (mService) {
336 if (r.continueLaunchTickingLocked()) {
337 mService.logAppTooSlow(r.app, r.launchTickTime,
338 "launching " + r);
339 }
340 }
341 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700342 case DESTROY_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800343 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700344 // We don't at this point know if the activity is fullscreen,
345 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800346 Slog.w(TAG, "Activity destroy timeout for " + r);
347 activityDestroyed(r != null ? r.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700348 } break;
349 case IDLE_NOW_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800350 ActivityRecord r = (ActivityRecord)msg.obj;
351 activityIdleInternal(r != null ? r.appToken : null, false, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700352 } break;
353 case LAUNCH_TIMEOUT_MSG: {
354 if (mService.mDidDexOpt) {
355 mService.mDidDexOpt = false;
356 Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
357 mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
358 return;
359 }
360 synchronized (mService) {
361 if (mLaunchingActivity.isHeld()) {
362 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
363 mLaunchingActivity.release();
364 }
365 }
366 } break;
367 case RESUME_TOP_ACTIVITY_MSG: {
368 synchronized (mService) {
369 resumeTopActivityLocked(null);
370 }
371 } break;
372 }
373 }
374 };
375
376 ActivityStack(ActivityManagerService service, Context context, boolean mainStack) {
377 mService = service;
378 mContext = context;
379 mMainStack = mainStack;
380 PowerManager pm =
381 (PowerManager)context.getSystemService(Context.POWER_SERVICE);
382 mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
383 mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
384 mLaunchingActivity.setReferenceCounted(false);
385 }
386
387 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
388 int i = mHistory.size()-1;
389 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700390 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700391 if (!r.finishing && r != notTop) {
392 return r;
393 }
394 i--;
395 }
396 return null;
397 }
398
399 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
400 int i = mHistory.size()-1;
401 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700402 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700403 if (!r.finishing && !r.delayedResume && r != notTop) {
404 return r;
405 }
406 i--;
407 }
408 return null;
409 }
410
411 /**
412 * This is a simplified version of topRunningActivityLocked that provides a number of
413 * optional skip-over modes. It is intended for use with the ActivityController hook only.
414 *
415 * @param token If non-null, any history records matching this token will be skipped.
416 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
417 *
418 * @return Returns the HistoryRecord of the next activity on the stack.
419 */
420 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
421 int i = mHistory.size()-1;
422 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700423 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700424 // Note: the taskId check depends on real taskId fields being non-zero
Dianne Hackbornbe707852011-11-11 14:32:10 -0800425 if (!r.finishing && (token != r.appToken) && (taskId != r.task.taskId)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700426 return r;
427 }
428 i--;
429 }
430 return null;
431 }
432
433 final int indexOfTokenLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800434 return mHistory.indexOf(ActivityRecord.forToken(token));
435 }
436
437 final int indexOfActivityLocked(ActivityRecord r) {
438 return mHistory.indexOf(r);
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700439 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700440
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700441 final ActivityRecord isInStackLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800442 ActivityRecord r = ActivityRecord.forToken(token);
443 if (mHistory.contains(r)) {
444 return r;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700445 }
446 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700447 }
448
449 private final boolean updateLRUListLocked(ActivityRecord r) {
450 final boolean hadit = mLRUActivities.remove(r);
451 mLRUActivities.add(r);
452 return hadit;
453 }
454
455 /**
456 * Returns the top activity in any existing task matching the given
457 * Intent. Returns null if no such task is found.
458 */
459 private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
460 ComponentName cls = intent.getComponent();
461 if (info.targetActivity != null) {
462 cls = new ComponentName(info.packageName, info.targetActivity);
463 }
464
465 TaskRecord cp = null;
466
467 final int N = mHistory.size();
468 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700469 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700470 if (!r.finishing && r.task != cp
471 && r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
472 cp = r.task;
473 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
474 // + "/aff=" + r.task.affinity + " to new cls="
475 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
476 if (r.task.affinity != null) {
477 if (r.task.affinity.equals(info.taskAffinity)) {
478 //Slog.i(TAG, "Found matching affinity!");
479 return r;
480 }
481 } else if (r.task.intent != null
482 && r.task.intent.getComponent().equals(cls)) {
483 //Slog.i(TAG, "Found matching class!");
484 //dump();
485 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
486 return r;
487 } else if (r.task.affinityIntent != null
488 && r.task.affinityIntent.getComponent().equals(cls)) {
489 //Slog.i(TAG, "Found matching class!");
490 //dump();
491 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
492 return r;
493 }
494 }
495 }
496
497 return null;
498 }
499
500 /**
501 * Returns the first activity (starting from the top of the stack) that
502 * is the same as the given activity. Returns null if no such activity
503 * is found.
504 */
505 private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
506 ComponentName cls = intent.getComponent();
507 if (info.targetActivity != null) {
508 cls = new ComponentName(info.packageName, info.targetActivity);
509 }
510
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) {
515 if (r.intent.getComponent().equals(cls)) {
516 //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
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700534 final boolean realStartActivityLocked(ActivityRecord r,
535 ProcessRecord app, boolean andResume, boolean checkConfig)
536 throws RemoteException {
537
538 r.startFreezingScreenLocked(app, 0);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800539 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700540
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700541 // schedule launch ticks to collect information about slow apps.
542 r.startLaunchTickingLocked();
543
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700544 // Have the window manager re-evaluate the orientation of
545 // the screen based on the new activity order. Note that
546 // as a result of this, it can call back into the activity
547 // manager with a new orientation. We don't care about that,
548 // because the activity is not currently running so we are
549 // just restarting it anyway.
550 if (checkConfig) {
551 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
552 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -0800553 r.mayFreezeScreenLocked(app) ? r.appToken : null);
Dianne Hackborn813075a62011-11-14 17:45:19 -0800554 mService.updateConfigurationLocked(config, r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700555 }
556
557 r.app = app;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700558 app.waitingToKill = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700559
560 if (localLOGV) Slog.v(TAG, "Launching: " + r);
561
562 int idx = app.activities.indexOf(r);
563 if (idx < 0) {
564 app.activities.add(r);
565 }
566 mService.updateLruProcessLocked(app, true, true);
567
568 try {
569 if (app.thread == null) {
570 throw new RemoteException();
571 }
572 List<ResultInfo> results = null;
573 List<Intent> newIntents = null;
574 if (andResume) {
575 results = r.results;
576 newIntents = r.newIntents;
577 }
578 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
579 + " icicle=" + r.icicle
580 + " with results=" + results + " newIntents=" + newIntents
581 + " andResume=" + andResume);
582 if (andResume) {
583 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
584 System.identityHashCode(r),
585 r.task.taskId, r.shortComponentName);
586 }
587 if (r.isHomeActivity) {
588 mService.mHomeProcess = app;
589 }
590 mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800591 r.sleeping = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400592 r.forceNewConfig = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700593 showAskCompatModeDialogLocked(r);
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700594 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700595 String profileFile = null;
596 ParcelFileDescriptor profileFd = null;
597 boolean profileAutoStop = false;
598 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
599 if (mService.mProfileProc == null || mService.mProfileProc == app) {
600 mService.mProfileProc = app;
601 profileFile = mService.mProfileFile;
602 profileFd = mService.mProfileFd;
603 profileAutoStop = mService.mAutoStopProfiler;
604 }
605 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -0700606 app.hasShownUi = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700607 app.pendingUiClean = true;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700608 if (profileFd != null) {
609 try {
610 profileFd = profileFd.dup();
611 } catch (IOException e) {
612 profileFd = null;
613 }
614 }
Dianne Hackbornbe707852011-11-11 14:32:10 -0800615 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
Dianne Hackborn813075a62011-11-14 17:45:19 -0800616 System.identityHashCode(r), r.info,
617 new Configuration(mService.mConfiguration),
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700618 r.compat, r.icicle, results, newIntents, !andResume,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700619 mService.isNextTransitionForward(), profileFile, profileFd,
620 profileAutoStop);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700621
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700622 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700623 // This may be a heavy-weight process! Note that the package
624 // manager will ensure that only activity can run in the main
625 // process of the .apk, which is the only thing that will be
626 // considered heavy-weight.
627 if (app.processName.equals(app.info.packageName)) {
628 if (mService.mHeavyWeightProcess != null
629 && mService.mHeavyWeightProcess != app) {
630 Log.w(TAG, "Starting new heavy weight process " + app
631 + " when already running "
632 + mService.mHeavyWeightProcess);
633 }
634 mService.mHeavyWeightProcess = app;
635 Message msg = mService.mHandler.obtainMessage(
636 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
637 msg.obj = r;
638 mService.mHandler.sendMessage(msg);
639 }
640 }
641
642 } catch (RemoteException e) {
643 if (r.launchFailed) {
644 // This is the second time we failed -- finish activity
645 // and give up.
646 Slog.e(TAG, "Second failure launching "
647 + r.intent.getComponent().flattenToShortString()
648 + ", giving up", e);
649 mService.appDiedLocked(app, app.pid, app.thread);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800650 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700651 "2nd-crash");
652 return false;
653 }
654
655 // This is the first time we failed -- restart process and
656 // retry.
657 app.activities.remove(r);
658 throw e;
659 }
660
661 r.launchFailed = false;
662 if (updateLRUListLocked(r)) {
663 Slog.w(TAG, "Activity " + r
664 + " being launched, but already in LRU list");
665 }
666
667 if (andResume) {
668 // As part of the process of launching, ActivityThread also performs
669 // a resume.
670 r.state = ActivityState.RESUMED;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700671 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
672 + " (starting new instance)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700673 r.stopped = false;
674 mResumedActivity = r;
675 r.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -0800676 if (mMainStack) {
677 mService.addRecentTaskLocked(r.task);
678 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700679 completeResumeLocked(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800680 checkReadyForSleepLocked();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700681 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Launch completed; removing icicle of " + r.icicle);
682 r.icicle = null;
683 r.haveState = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700684 } else {
685 // This activity is not starting in the resumed state... which
686 // should look like we asked it to pause+stop (but remain visible),
687 // and it has done so and reported back the current icicle and
688 // other state.
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700689 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
690 + " (starting in stopped state)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700691 r.state = ActivityState.STOPPED;
692 r.stopped = true;
693 }
694
695 // Launch the new version setup screen if needed. We do this -after-
696 // launching the initial activity (that is, home), so that it can have
697 // a chance to initialize itself while in the background, making the
698 // switch back to it faster and look better.
699 if (mMainStack) {
700 mService.startSetupActivityLocked();
701 }
702
703 return true;
704 }
705
706 private final void startSpecificActivityLocked(ActivityRecord r,
707 boolean andResume, boolean checkConfig) {
708 // Is this activity's application already running?
709 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
710 r.info.applicationInfo.uid);
711
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700712 if (r.launchTime == 0) {
713 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700714 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700715 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700716 }
717 } else if (mInitialStartTime == 0) {
718 mInitialStartTime = SystemClock.uptimeMillis();
719 }
720
721 if (app != null && app.thread != null) {
722 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700723 app.addPackage(r.info.packageName);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700724 realStartActivityLocked(r, app, andResume, checkConfig);
725 return;
726 } catch (RemoteException e) {
727 Slog.w(TAG, "Exception when starting activity "
728 + r.intent.getComponent().flattenToShortString(), e);
729 }
730
731 // If a dead object exception was thrown -- fall through to
732 // restart the application.
733 }
734
735 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
736 "activity", r.intent.getComponent(), false);
737 }
738
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800739 void stopIfSleepingLocked() {
740 if (mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700741 if (!mGoingToSleep.isHeld()) {
742 mGoingToSleep.acquire();
743 if (mLaunchingActivity.isHeld()) {
744 mLaunchingActivity.release();
745 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
746 }
747 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800748 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
749 Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
750 mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
751 checkReadyForSleepLocked();
752 }
753 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700754
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800755 void awakeFromSleepingLocked() {
756 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
757 mSleepTimeout = false;
758 if (mGoingToSleep.isHeld()) {
759 mGoingToSleep.release();
760 }
761 // Ensure activities are no longer sleeping.
762 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700763 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800764 r.setSleeping(false);
765 }
766 mGoingToSleepActivities.clear();
767 }
768
769 void activitySleptLocked(ActivityRecord r) {
770 mGoingToSleepActivities.remove(r);
771 checkReadyForSleepLocked();
772 }
773
774 void checkReadyForSleepLocked() {
775 if (!mService.isSleeping()) {
776 // Do not care.
777 return;
778 }
779
780 if (!mSleepTimeout) {
781 if (mResumedActivity != null) {
782 // Still have something resumed; can't sleep until it is paused.
783 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700784 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
785 startPausingLocked(false, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800786 return;
787 }
788 if (mPausingActivity != null) {
789 // Still waiting for something to pause; can't sleep yet.
790 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
791 return;
792 }
793
794 if (mStoppingActivities.size() > 0) {
795 // Still need to tell some activities to stop; can't sleep yet.
796 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
797 + mStoppingActivities.size() + " activities");
Dianne Hackborn80a7ac12011-09-22 18:32:52 -0700798 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800799 return;
800 }
801
802 ensureActivitiesVisibleLocked(null, 0);
803
804 // Make sure any stopped but visible activities are now sleeping.
805 // This ensures that the activity's onStop() is called.
806 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700807 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800808 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
809 r.setSleeping(true);
810 }
811 }
812
813 if (mGoingToSleepActivities.size() > 0) {
814 // Still need to tell some activities to sleep; can't sleep yet.
815 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
816 + mGoingToSleepActivities.size() + " activities");
817 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700818 }
819 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800820
821 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
822
823 if (mGoingToSleep.isHeld()) {
824 mGoingToSleep.release();
825 }
826 if (mService.mShuttingDown) {
827 mService.notifyAll();
828 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700829 }
830
Dianne Hackbornd2835932010-12-13 16:28:46 -0800831 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -0800832 if (who.noDisplay) {
833 return null;
834 }
835
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800836 Resources res = mService.mContext.getResources();
837 int w = mThumbnailWidth;
838 int h = mThumbnailHeight;
839 if (w < 0) {
840 mThumbnailWidth = w =
841 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
842 mThumbnailHeight = h =
843 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
844 }
845
846 if (w > 0) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800847 return mService.mWindowManager.screenshotApplications(who.appToken, w, h);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800848 }
849 return null;
850 }
851
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700852 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
853 if (mPausingActivity != null) {
854 RuntimeException e = new RuntimeException();
855 Slog.e(TAG, "Trying to pause when pause is already pending for "
856 + mPausingActivity, e);
857 }
858 ActivityRecord prev = mResumedActivity;
859 if (prev == null) {
860 RuntimeException e = new RuntimeException();
861 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
862 resumeTopActivityLocked(null);
863 return;
864 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700865 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
866 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700867 mResumedActivity = null;
868 mPausingActivity = prev;
869 mLastPausedActivity = prev;
870 prev.state = ActivityState.PAUSING;
871 prev.task.touchActiveTime();
Dianne Hackbornf26fd992011-04-08 18:14:09 -0700872 prev.updateThumbnail(screenshotActivities(prev), null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700873
874 mService.updateCpuStats();
875
876 if (prev.app != null && prev.app.thread != null) {
877 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
878 try {
879 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
880 System.identityHashCode(prev),
881 prev.shortComponentName);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800882 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
883 userLeaving, prev.configChangeFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700884 if (mMainStack) {
885 mService.updateUsageStats(prev, false);
886 }
887 } catch (Exception e) {
888 // Ignore exception, if process died other code will cleanup.
889 Slog.w(TAG, "Exception thrown during pause", e);
890 mPausingActivity = null;
891 mLastPausedActivity = null;
892 }
893 } else {
894 mPausingActivity = null;
895 mLastPausedActivity = null;
896 }
897
898 // If we are not going to sleep, we want to ensure the device is
899 // awake until the next activity is started.
900 if (!mService.mSleeping && !mService.mShuttingDown) {
901 mLaunchingActivity.acquire();
902 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
903 // To be safe, don't allow the wake lock to be held for too long.
904 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
905 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
906 }
907 }
908
909
910 if (mPausingActivity != null) {
911 // Have the window manager pause its key dispatching until the new
912 // activity has started. If we're pausing the activity just because
913 // the screen is being turned off and the UI is sleeping, don't interrupt
914 // key dispatch; the same activity will pick it up again on wakeup.
915 if (!uiSleeping) {
916 prev.pauseKeyDispatchingLocked();
917 } else {
918 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
919 }
920
921 // Schedule a pause timeout in case the app doesn't respond.
922 // We don't give it much time because this directly impacts the
923 // responsiveness seen by the user.
924 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
925 msg.obj = prev;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700926 prev.pauseTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700927 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
928 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
929 } else {
930 // This activity failed to schedule the
931 // pause, so just treat it as being paused now.
932 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
933 resumeTopActivityLocked(null);
934 }
935 }
936
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800937 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700938 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800939 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700940
941 ActivityRecord r = null;
942
943 synchronized (mService) {
944 int index = indexOfTokenLocked(token);
945 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700946 r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700947 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
948 if (mPausingActivity == r) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700949 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
950 + (timeout ? " (due to timeout)" : " (pause complete)"));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700951 r.state = ActivityState.PAUSED;
952 completePauseLocked();
953 } else {
954 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
955 System.identityHashCode(r), r.shortComponentName,
956 mPausingActivity != null
957 ? mPausingActivity.shortComponentName : "(none)");
958 }
959 }
960 }
961 }
962
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700963 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
964 CharSequence description) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700965 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Saving icicle of " + r + ": " + icicle);
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700966 r.icicle = icicle;
967 r.haveState = true;
968 r.updateThumbnail(thumbnail, description);
969 r.stopped = true;
970 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
971 r.state = ActivityState.STOPPED;
972 if (!r.finishing) {
973 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -0700974 destroyActivityLocked(r, true, false, "stop-config");
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700975 resumeTopActivityLocked(null);
Dianne Hackborn50685602011-12-01 12:23:37 -0800976 } else {
977 // Now that this process has stopped, we may want to consider
978 // it to be the previous app to try to keep around in case
979 // the user wants to return to it.
980 ProcessRecord fgApp = null;
981 if (mResumedActivity != null) {
982 fgApp = mResumedActivity.app;
983 } else if (mPausingActivity != null) {
984 fgApp = mPausingActivity.app;
985 }
986 if (r.app != null && fgApp != null && r.app != fgApp
987 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
988 && r.app != mService.mHomeProcess) {
989 mService.mPreviousProcess = r.app;
990 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
991 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700992 }
993 }
994 }
995
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700996 private final void completePauseLocked() {
997 ActivityRecord prev = mPausingActivity;
998 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
999
1000 if (prev != null) {
1001 if (prev.finishing) {
1002 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
1003 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE);
1004 } else if (prev.app != null) {
1005 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
1006 if (prev.waitingVisible) {
1007 prev.waitingVisible = false;
1008 mWaitingVisibleActivities.remove(prev);
1009 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
1010 TAG, "Complete pause, no longer waiting: " + prev);
1011 }
1012 if (prev.configDestroy) {
1013 // The previous is being paused because the configuration
1014 // is changing, which means it is actually stopping...
1015 // To juggle the fact that we are also starting a new
1016 // instance right now, we need to first completely stop
1017 // the current instance before starting the new one.
1018 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
Dianne Hackborn28695e02011-11-02 21:59:51 -07001019 destroyActivityLocked(prev, true, false, "pause-config");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001020 } else {
1021 mStoppingActivities.add(prev);
1022 if (mStoppingActivities.size() > 3) {
1023 // If we already have a few activities waiting to stop,
1024 // then give up on things going idle and start clearing
1025 // them out.
1026 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07001027 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001028 } else {
1029 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001030 }
1031 }
1032 } else {
1033 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
1034 prev = null;
1035 }
1036 mPausingActivity = null;
1037 }
1038
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001039 if (!mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001040 resumeTopActivityLocked(prev);
1041 } else {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001042 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001043 }
1044
1045 if (prev != null) {
1046 prev.resumeKeyDispatchingLocked();
1047 }
1048
1049 if (prev.app != null && prev.cpuTimeAtResume > 0
1050 && mService.mBatteryStatsService.isOnBattery()) {
1051 long diff = 0;
1052 synchronized (mService.mProcessStatsThread) {
1053 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
1054 - prev.cpuTimeAtResume;
1055 }
1056 if (diff > 0) {
1057 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
1058 synchronized (bsi) {
1059 BatteryStatsImpl.Uid.Proc ps =
1060 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
1061 prev.info.packageName);
1062 if (ps != null) {
1063 ps.addForegroundTimeLocked(diff);
1064 }
1065 }
1066 }
1067 }
1068 prev.cpuTimeAtResume = 0; // reset it
1069 }
1070
1071 /**
1072 * Once we know that we have asked an application to put an activity in
1073 * the resumed state (either by launching it or explicitly telling it),
1074 * this function updates the rest of our state to match that fact.
1075 */
1076 private final void completeResumeLocked(ActivityRecord next) {
1077 next.idle = false;
1078 next.results = null;
1079 next.newIntents = null;
1080
1081 // schedule an idle timeout in case the app doesn't do it for us.
1082 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1083 msg.obj = next;
1084 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
1085
1086 if (false) {
1087 // The activity was never told to pause, so just keep
1088 // things going as-is. To maintain our own state,
1089 // we need to emulate it coming back and saying it is
1090 // idle.
1091 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
1092 msg.obj = next;
1093 mHandler.sendMessage(msg);
1094 }
1095
1096 if (mMainStack) {
1097 mService.reportResumedActivityLocked(next);
1098 }
1099
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001100 next.clearThumbnail();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001101 if (mMainStack) {
1102 mService.setFocusedActivityLocked(next);
1103 }
1104 next.resumeKeyDispatchingLocked();
1105 ensureActivitiesVisibleLocked(null, 0);
1106 mService.mWindowManager.executeAppTransition();
1107 mNoAnimActivities.clear();
1108
1109 // Mark the point when the activity is resuming
1110 // TODO: To be more accurate, the mark should be before the onCreate,
1111 // not after the onResume. But for subsequent starts, onResume is fine.
1112 if (next.app != null) {
1113 synchronized (mService.mProcessStatsThread) {
1114 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1115 }
1116 } else {
1117 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1118 }
1119 }
1120
1121 /**
1122 * Make sure that all activities that need to be visible (that is, they
1123 * currently can be seen by the user) actually are.
1124 */
1125 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1126 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1127 if (DEBUG_VISBILITY) Slog.v(
1128 TAG, "ensureActivitiesVisible behind " + top
1129 + " configChanges=0x" + Integer.toHexString(configChanges));
1130
1131 // If the top activity is not fullscreen, then we need to
1132 // make sure any activities under it are now visible.
1133 final int count = mHistory.size();
1134 int i = count-1;
1135 while (mHistory.get(i) != top) {
1136 i--;
1137 }
1138 ActivityRecord r;
1139 boolean behindFullscreen = false;
1140 for (; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001141 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001142 if (DEBUG_VISBILITY) Slog.v(
1143 TAG, "Make visible? " + r + " finishing=" + r.finishing
1144 + " state=" + r.state);
1145 if (r.finishing) {
1146 continue;
1147 }
1148
1149 final boolean doThisProcess = onlyThisProcess == null
1150 || onlyThisProcess.equals(r.processName);
1151
1152 // First: if this is not the current activity being started, make
1153 // sure it matches the current configuration.
1154 if (r != starting && doThisProcess) {
1155 ensureActivityConfigurationLocked(r, 0);
1156 }
1157
1158 if (r.app == null || r.app.thread == null) {
1159 if (onlyThisProcess == null
1160 || onlyThisProcess.equals(r.processName)) {
1161 // This activity needs to be visible, but isn't even
1162 // running... get it started, but don't resume it
1163 // at this point.
1164 if (DEBUG_VISBILITY) Slog.v(
1165 TAG, "Start and freeze screen for " + r);
1166 if (r != starting) {
1167 r.startFreezingScreenLocked(r.app, configChanges);
1168 }
1169 if (!r.visible) {
1170 if (DEBUG_VISBILITY) Slog.v(
1171 TAG, "Starting and making visible: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001172 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001173 }
1174 if (r != starting) {
1175 startSpecificActivityLocked(r, false, false);
1176 }
1177 }
1178
1179 } else if (r.visible) {
1180 // If this activity is already visible, then there is nothing
1181 // else to do here.
1182 if (DEBUG_VISBILITY) Slog.v(
1183 TAG, "Skipping: already visible at " + r);
1184 r.stopFreezingScreenLocked(false);
1185
1186 } else if (onlyThisProcess == null) {
1187 // This activity is not currently visible, but is running.
1188 // Tell it to become visible.
1189 r.visible = true;
1190 if (r.state != ActivityState.RESUMED && r != starting) {
1191 // If this activity is paused, tell it
1192 // to now show its window.
1193 if (DEBUG_VISBILITY) Slog.v(
1194 TAG, "Making visible and scheduling visibility: " + r);
1195 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001196 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001197 r.sleeping = false;
Dianne Hackborn905577f2011-09-07 18:31:28 -07001198 r.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001199 r.app.thread.scheduleWindowVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001200 r.stopFreezingScreenLocked(false);
1201 } catch (Exception e) {
1202 // Just skip on any failure; we'll make it
1203 // visible when it next restarts.
1204 Slog.w(TAG, "Exception thrown making visibile: "
1205 + r.intent.getComponent(), e);
1206 }
1207 }
1208 }
1209
1210 // Aggregate current change flags.
1211 configChanges |= r.configChangeFlags;
1212
1213 if (r.fullscreen) {
1214 // At this point, nothing else needs to be shown
1215 if (DEBUG_VISBILITY) Slog.v(
1216 TAG, "Stopping: fullscreen at " + r);
1217 behindFullscreen = true;
1218 i--;
1219 break;
1220 }
1221 }
1222
1223 // Now for any activities that aren't visible to the user, make
1224 // sure they no longer are keeping the screen frozen.
1225 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001226 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001227 if (DEBUG_VISBILITY) Slog.v(
1228 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1229 + " state=" + r.state
1230 + " behindFullscreen=" + behindFullscreen);
1231 if (!r.finishing) {
1232 if (behindFullscreen) {
1233 if (r.visible) {
1234 if (DEBUG_VISBILITY) Slog.v(
1235 TAG, "Making invisible: " + r);
1236 r.visible = false;
1237 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001238 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001239 if ((r.state == ActivityState.STOPPING
1240 || r.state == ActivityState.STOPPED)
1241 && r.app != null && r.app.thread != null) {
1242 if (DEBUG_VISBILITY) Slog.v(
1243 TAG, "Scheduling invisibility: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001244 r.app.thread.scheduleWindowVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001245 }
1246 } catch (Exception e) {
1247 // Just skip on any failure; we'll make it
1248 // visible when it next restarts.
1249 Slog.w(TAG, "Exception thrown making hidden: "
1250 + r.intent.getComponent(), e);
1251 }
1252 } else {
1253 if (DEBUG_VISBILITY) Slog.v(
1254 TAG, "Already invisible: " + r);
1255 }
1256 } else if (r.fullscreen) {
1257 if (DEBUG_VISBILITY) Slog.v(
1258 TAG, "Now behindFullscreen: " + r);
1259 behindFullscreen = true;
1260 }
1261 }
1262 i--;
1263 }
1264 }
1265
1266 /**
1267 * Version of ensureActivitiesVisible that can easily be called anywhere.
1268 */
1269 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1270 int configChanges) {
1271 ActivityRecord r = topRunningActivityLocked(null);
1272 if (r != null) {
1273 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1274 }
1275 }
1276
1277 /**
1278 * Ensure that the top activity in the stack is resumed.
1279 *
1280 * @param prev The previously resumed activity, for when in the process
1281 * of pausing; can be null to call from elsewhere.
1282 *
1283 * @return Returns true if something is being resumed, or false if
1284 * nothing happened.
1285 */
1286 final boolean resumeTopActivityLocked(ActivityRecord prev) {
1287 // Find the first activity that is not finishing.
1288 ActivityRecord next = topRunningActivityLocked(null);
1289
1290 // Remember how we'll process this pause/resume situation, and ensure
1291 // that the state is reset however we wind up proceeding.
1292 final boolean userLeaving = mUserLeaving;
1293 mUserLeaving = false;
1294
1295 if (next == null) {
1296 // There are no more activities! Let's just start up the
1297 // Launcher...
1298 if (mMainStack) {
1299 return mService.startHomeActivityLocked();
1300 }
1301 }
1302
1303 next.delayedResume = false;
1304
1305 // If the top activity is the resumed one, nothing to do.
1306 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1307 // Make sure we have executed any pending transitions, since there
1308 // should be nothing left to do at this point.
1309 mService.mWindowManager.executeAppTransition();
1310 mNoAnimActivities.clear();
1311 return false;
1312 }
1313
1314 // If we are sleeping, and there is no resumed activity, and the top
1315 // activity is paused, well that is the state we want.
1316 if ((mService.mSleeping || mService.mShuttingDown)
p13451dbad2872012-04-18 11:39:23 +09001317 && mLastPausedActivity == next
1318 && (next.state == ActivityState.PAUSED
1319 || next.state == ActivityState.STOPPED
1320 || next.state == ActivityState.STOPPING)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001321 // Make sure we have executed any pending transitions, since there
1322 // should be nothing left to do at this point.
1323 mService.mWindowManager.executeAppTransition();
1324 mNoAnimActivities.clear();
1325 return false;
1326 }
1327
1328 // The activity may be waiting for stop, but that is no longer
1329 // appropriate for it.
1330 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001331 mGoingToSleepActivities.remove(next);
1332 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001333 mWaitingVisibleActivities.remove(next);
1334
1335 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1336
1337 // If we are currently pausing an activity, then don't do anything
1338 // until that is done.
1339 if (mPausingActivity != null) {
1340 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
1341 return false;
1342 }
1343
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001344 // Okay we are now going to start a switch, to 'next'. We may first
1345 // have to pause the current activity, but this is an important point
1346 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001347 // XXX "App Redirected" dialog is getting too many false positives
1348 // at this point, so turn off for now.
1349 if (false) {
1350 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1351 long now = SystemClock.uptimeMillis();
1352 final boolean inTime = mLastStartedActivity.startTime != 0
1353 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1354 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1355 final int nextUid = next.info.applicationInfo.uid;
1356 if (inTime && lastUid != nextUid
1357 && lastUid != next.launchedFromUid
1358 && mService.checkPermission(
1359 android.Manifest.permission.STOP_APP_SWITCHES,
1360 -1, next.launchedFromUid)
1361 != PackageManager.PERMISSION_GRANTED) {
1362 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1363 } else {
1364 next.startTime = now;
1365 mLastStartedActivity = next;
1366 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001367 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001368 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001369 mLastStartedActivity = next;
1370 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001371 }
1372
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001373 // We need to start pausing the current activity so the top one
1374 // can be resumed...
1375 if (mResumedActivity != null) {
1376 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
1377 startPausingLocked(userLeaving, false);
1378 return true;
1379 }
1380
1381 if (prev != null && prev != next) {
1382 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1383 prev.waitingVisible = true;
1384 mWaitingVisibleActivities.add(prev);
1385 if (DEBUG_SWITCH) Slog.v(
1386 TAG, "Resuming top, waiting visible to hide: " + prev);
1387 } else {
1388 // The next activity is already visible, so hide the previous
1389 // activity's windows right now so we can show the new one ASAP.
1390 // We only do this if the previous is finishing, which should mean
1391 // it is on top of the one being resumed so hiding it quickly
1392 // is good. Otherwise, we want to do the normal route of allowing
1393 // the resumed activity to be shown so we can decide if the
1394 // previous should actually be hidden depending on whether the
1395 // new one is found to be full-screen or not.
1396 if (prev.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001397 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001398 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1399 + prev + ", waitingVisible="
1400 + (prev != null ? prev.waitingVisible : null)
1401 + ", nowVisible=" + next.nowVisible);
1402 } else {
1403 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1404 + prev + ", waitingVisible="
1405 + (prev != null ? prev.waitingVisible : null)
1406 + ", nowVisible=" + next.nowVisible);
1407 }
1408 }
1409 }
1410
Dianne Hackborne7f97212011-02-24 14:40:20 -08001411 // Launching this app's activity, make sure the app is no longer
1412 // considered stopped.
1413 try {
1414 AppGlobals.getPackageManager().setPackageStoppedState(
1415 next.packageName, false);
1416 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001417 } catch (IllegalArgumentException e) {
1418 Slog.w(TAG, "Failed trying to unstop package "
1419 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001420 }
1421
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001422 // We are starting up the next activity, so tell the window manager
1423 // that the previous one will be hidden soon. This way it can know
1424 // to ignore it when computing the desired screen orientation.
1425 if (prev != null) {
1426 if (prev.finishing) {
1427 if (DEBUG_TRANSITION) Slog.v(TAG,
1428 "Prepare close transition: prev=" + prev);
1429 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001430 mService.mWindowManager.prepareAppTransition(
1431 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001432 } else {
1433 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1434 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001435 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001436 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001437 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1438 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001439 } else {
1440 if (DEBUG_TRANSITION) Slog.v(TAG,
1441 "Prepare open transition: prev=" + prev);
1442 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001443 mService.mWindowManager.prepareAppTransition(
1444 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001445 } else {
1446 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1447 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001448 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001449 }
1450 }
1451 if (false) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001452 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1453 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001454 }
1455 } else if (mHistory.size() > 1) {
1456 if (DEBUG_TRANSITION) Slog.v(TAG,
1457 "Prepare open transition: no previous");
1458 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001459 mService.mWindowManager.prepareAppTransition(
1460 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001461 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001462 mService.mWindowManager.prepareAppTransition(
1463 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001464 }
1465 }
1466
1467 if (next.app != null && next.app.thread != null) {
1468 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1469
1470 // This activity is now becoming visible.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001471 mService.mWindowManager.setAppVisibility(next.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001472
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001473 // schedule launch ticks to collect information about slow apps.
1474 next.startLaunchTickingLocked();
1475
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001476 ActivityRecord lastResumedActivity = mResumedActivity;
1477 ActivityState lastState = next.state;
1478
1479 mService.updateCpuStats();
1480
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001481 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001482 next.state = ActivityState.RESUMED;
1483 mResumedActivity = next;
1484 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001485 if (mMainStack) {
1486 mService.addRecentTaskLocked(next.task);
1487 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001488 mService.updateLruProcessLocked(next.app, true, true);
1489 updateLRUListLocked(next);
1490
1491 // Have the window manager re-evaluate the orientation of
1492 // the screen based on the new activity order.
1493 boolean updated = false;
1494 if (mMainStack) {
1495 synchronized (mService) {
1496 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1497 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001498 next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001499 if (config != null) {
1500 next.frozenBeforeDestroy = true;
1501 }
Dianne Hackborn813075a62011-11-14 17:45:19 -08001502 updated = mService.updateConfigurationLocked(config, next, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001503 }
1504 }
1505 if (!updated) {
1506 // The configuration update wasn't able to keep the existing
1507 // instance of the activity, and instead started a new one.
1508 // We should be all done, but let's just make sure our activity
1509 // is still at the top and schedule another run if something
1510 // weird happened.
1511 ActivityRecord nextNext = topRunningActivityLocked(null);
1512 if (DEBUG_SWITCH) Slog.i(TAG,
1513 "Activity config changed during resume: " + next
1514 + ", new next: " + nextNext);
1515 if (nextNext != next) {
1516 // Do over!
1517 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1518 }
1519 if (mMainStack) {
1520 mService.setFocusedActivityLocked(next);
1521 }
1522 ensureActivitiesVisibleLocked(null, 0);
1523 mService.mWindowManager.executeAppTransition();
1524 mNoAnimActivities.clear();
1525 return true;
1526 }
1527
1528 try {
1529 // Deliver all pending results.
1530 ArrayList a = next.results;
1531 if (a != null) {
1532 final int N = a.size();
1533 if (!next.finishing && N > 0) {
1534 if (DEBUG_RESULTS) Slog.v(
1535 TAG, "Delivering results to " + next
1536 + ": " + a);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001537 next.app.thread.scheduleSendResult(next.appToken, a);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001538 }
1539 }
1540
1541 if (next.newIntents != null) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001542 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001543 }
1544
1545 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
1546 System.identityHashCode(next),
1547 next.task.taskId, next.shortComponentName);
1548
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001549 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001550 showAskCompatModeDialogLocked(next);
Dianne Hackborn905577f2011-09-07 18:31:28 -07001551 next.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001552 next.app.thread.scheduleResumeActivity(next.appToken,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001553 mService.isNextTransitionForward());
1554
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001555 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001556
1557 } catch (Exception e) {
1558 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001559 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1560 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001561 next.state = lastState;
1562 mResumedActivity = lastResumedActivity;
1563 Slog.i(TAG, "Restarting because process died: " + next);
1564 if (!next.hasBeenLaunched) {
1565 next.hasBeenLaunched = true;
1566 } else {
1567 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1568 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001569 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001570 mService.compatibilityInfoForPackageLocked(
1571 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001572 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001573 next.labelRes, next.icon, next.windowFlags,
1574 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001575 }
1576 }
1577 startSpecificActivityLocked(next, true, false);
1578 return true;
1579 }
1580
1581 // From this point on, if something goes wrong there is no way
1582 // to recover the activity.
1583 try {
1584 next.visible = true;
1585 completeResumeLocked(next);
1586 } catch (Exception e) {
1587 // If any exception gets thrown, toss away this
1588 // activity and try the next one.
1589 Slog.w(TAG, "Exception thrown during resume of " + next, e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001590 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001591 "resume-exception");
1592 return true;
1593 }
1594
1595 // Didn't need to use the icicle, and it is now out of date.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001596 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Resumed activity; didn't need icicle of: " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001597 next.icicle = null;
1598 next.haveState = false;
1599 next.stopped = false;
1600
1601 } else {
1602 // Whoops, need to restart this activity!
1603 if (!next.hasBeenLaunched) {
1604 next.hasBeenLaunched = true;
1605 } else {
1606 if (SHOW_APP_STARTING_PREVIEW) {
1607 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001608 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001609 mService.compatibilityInfoForPackageLocked(
1610 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001611 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001612 next.labelRes, next.icon, next.windowFlags,
1613 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001614 }
1615 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1616 }
1617 startSpecificActivityLocked(next, true, true);
1618 }
1619
1620 return true;
1621 }
1622
1623 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001624 boolean doResume, boolean keepCurTransition) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001625 final int NH = mHistory.size();
1626
1627 int addPos = -1;
1628
1629 if (!newTask) {
1630 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001631 boolean startIt = true;
1632 for (int i = NH-1; i >= 0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001633 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001634 if (p.finishing) {
1635 continue;
1636 }
1637 if (p.task == r.task) {
1638 // Here it is! Now, if this is not yet visible to the
1639 // user, then just add it without starting; it will
1640 // get started when the user navigates back to it.
1641 addPos = i+1;
1642 if (!startIt) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001643 if (DEBUG_ADD_REMOVE) {
1644 RuntimeException here = new RuntimeException("here");
1645 here.fillInStackTrace();
1646 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos,
1647 here);
1648 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001649 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001650 r.putInHistory();
Dianne Hackbornbe707852011-11-11 14:32:10 -08001651 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001652 r.info.screenOrientation, r.fullscreen);
1653 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001654 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001655 }
1656 return;
1657 }
1658 break;
1659 }
1660 if (p.fullscreen) {
1661 startIt = false;
1662 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001663 }
1664 }
1665
1666 // Place a new activity at top of stack, so it is next to interact
1667 // with the user.
1668 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001669 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001670 }
1671
1672 // If we are not placing the new activity frontmost, we do not want
1673 // to deliver the onUserLeaving callback to the actual frontmost
1674 // activity
1675 if (addPos < NH) {
1676 mUserLeaving = false;
1677 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1678 }
1679
1680 // Slot the activity into the history stack and proceed
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001681 if (DEBUG_ADD_REMOVE) {
1682 RuntimeException here = new RuntimeException("here");
1683 here.fillInStackTrace();
1684 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos, here);
1685 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001686 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001687 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001688 r.frontOfTask = newTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001689 if (NH > 0) {
1690 // We want to show the starting preview window if we are
1691 // switching to a new task, or the next activity's process is
1692 // not currently running.
1693 boolean showStartingIcon = newTask;
1694 ProcessRecord proc = r.app;
1695 if (proc == null) {
1696 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1697 }
1698 if (proc == null || proc.thread == null) {
1699 showStartingIcon = true;
1700 }
1701 if (DEBUG_TRANSITION) Slog.v(TAG,
1702 "Prepare open transition: starting " + r);
1703 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001704 mService.mWindowManager.prepareAppTransition(
1705 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001706 mNoAnimActivities.add(r);
1707 } else if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
1708 mService.mWindowManager.prepareAppTransition(
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001709 WindowManagerPolicy.TRANSIT_TASK_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001710 mNoAnimActivities.remove(r);
1711 } else {
1712 mService.mWindowManager.prepareAppTransition(newTask
1713 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001714 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001715 mNoAnimActivities.remove(r);
1716 }
1717 mService.mWindowManager.addAppToken(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001718 addPos, r.appToken, r.task.taskId, r.info.screenOrientation, r.fullscreen);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001719 boolean doShow = true;
1720 if (newTask) {
1721 // Even though this activity is starting fresh, we still need
1722 // to reset it to make sure we apply affinities to move any
1723 // existing activities from other tasks in to it.
1724 // If the caller has requested that the target task be
1725 // reset, then do so.
1726 if ((r.intent.getFlags()
1727 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1728 resetTaskIfNeededLocked(r, r);
1729 doShow = topRunningNonDelayedActivityLocked(null) == r;
1730 }
1731 }
1732 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1733 // Figure out if we are transitioning from another activity that is
1734 // "has the same starting icon" as the next one. This allows the
1735 // window manager to keep the previous window it had previously
1736 // created, if it still had one.
1737 ActivityRecord prev = mResumedActivity;
1738 if (prev != null) {
1739 // We don't want to reuse the previous starting preview if:
1740 // (1) The current activity is in a different task.
1741 if (prev.task != r.task) prev = null;
1742 // (2) The current activity is already displayed.
1743 else if (prev.nowVisible) prev = null;
1744 }
1745 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001746 r.appToken, r.packageName, r.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001747 mService.compatibilityInfoForPackageLocked(
1748 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001749 r.labelRes, r.icon, r.windowFlags,
1750 prev != null ? prev.appToken : null, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001751 }
1752 } else {
1753 // If this is the first activity, don't do any fancy animations,
1754 // because there is nothing for it to animate on top of.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001755 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001756 r.info.screenOrientation, r.fullscreen);
1757 }
1758 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001759 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001760 }
1761
1762 if (doResume) {
1763 resumeTopActivityLocked(null);
1764 }
1765 }
1766
Dianne Hackbornbe707852011-11-11 14:32:10 -08001767 final void validateAppTokensLocked() {
1768 mValidateAppTokens.clear();
1769 mValidateAppTokens.ensureCapacity(mHistory.size());
1770 for (int i=0; i<mHistory.size(); i++) {
1771 mValidateAppTokens.add(mHistory.get(i).appToken);
1772 }
1773 mService.mWindowManager.validateAppTokens(mValidateAppTokens);
1774 }
1775
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001776 /**
1777 * Perform a reset of the given task, if needed as part of launching it.
1778 * Returns the new HistoryRecord at the top of the task.
1779 */
1780 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1781 ActivityRecord newActivity) {
1782 boolean forceReset = (newActivity.info.flags
1783 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001784 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1785 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001786 if ((newActivity.info.flags
1787 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1788 forceReset = true;
1789 }
1790 }
1791
1792 final TaskRecord task = taskTop.task;
1793
1794 // We are going to move through the history list so that we can look
1795 // at each activity 'target' with 'below' either the interesting
1796 // activity immediately below it in the stack or null.
1797 ActivityRecord target = null;
1798 int targetI = 0;
1799 int taskTopI = -1;
1800 int replyChainEnd = -1;
1801 int lastReparentPos = -1;
1802 for (int i=mHistory.size()-1; i>=-1; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001803 ActivityRecord below = i >= 0 ? mHistory.get(i) : null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001804
1805 if (below != null && below.finishing) {
1806 continue;
1807 }
1808 if (target == null) {
1809 target = below;
1810 targetI = i;
1811 // If we were in the middle of a reply chain before this
1812 // task, it doesn't appear like the root of the chain wants
1813 // anything interesting, so drop it.
1814 replyChainEnd = -1;
1815 continue;
1816 }
1817
1818 final int flags = target.info.flags;
1819
1820 final boolean finishOnTaskLaunch =
1821 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1822 final boolean allowTaskReparenting =
1823 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1824
1825 if (target.task == task) {
1826 // We are inside of the task being reset... we'll either
1827 // finish this activity, push it out for another task,
1828 // or leave it as-is. We only do this
1829 // for activities that are not the root of the task (since
1830 // if we finish the root, we may no longer have the task!).
1831 if (taskTopI < 0) {
1832 taskTopI = targetI;
1833 }
1834 if (below != null && below.task == task) {
1835 final boolean clearWhenTaskReset =
1836 (target.intent.getFlags()
1837 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
1838 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
1839 // If this activity is sending a reply to a previous
1840 // activity, we can't do anything with it now until
1841 // we reach the start of the reply chain.
1842 // XXX note that we are assuming the result is always
1843 // to the previous activity, which is almost always
1844 // the case but we really shouldn't count on.
1845 if (replyChainEnd < 0) {
1846 replyChainEnd = targetI;
1847 }
1848 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
1849 && target.taskAffinity != null
1850 && !target.taskAffinity.equals(task.affinity)) {
1851 // If this activity has an affinity for another
1852 // task, then we need to move it out of here. We will
1853 // move it as far out of the way as possible, to the
1854 // bottom of the activity stack. This also keeps it
1855 // correctly ordered with any activities we previously
1856 // moved.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001857 ActivityRecord p = mHistory.get(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001858 if (target.taskAffinity != null
1859 && target.taskAffinity.equals(p.task.affinity)) {
1860 // If the activity currently at the bottom has the
1861 // same task affinity as the one we are moving,
1862 // then merge it into the same task.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001863 target.setTask(p.task, p.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001864 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1865 + " out to bottom task " + p.task);
1866 } else {
1867 mService.mCurTask++;
1868 if (mService.mCurTask <= 0) {
1869 mService.mCurTask = 1;
1870 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001871 target.setTask(new TaskRecord(mService.mCurTask, target.info, null),
1872 null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001873 target.task.affinityIntent = target.intent;
1874 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1875 + " out to new task " + target.task);
1876 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001877 mService.mWindowManager.setAppGroupId(target.appToken, task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001878 if (replyChainEnd < 0) {
1879 replyChainEnd = targetI;
1880 }
1881 int dstPos = 0;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001882 ThumbnailHolder curThumbHolder = target.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001883 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001884 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001885 if (p.finishing) {
1886 continue;
1887 }
1888 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
1889 + " out to target's task " + target.task);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001890 p.setTask(target.task, curThumbHolder, false);
1891 curThumbHolder = p.thumbHolder;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001892 if (DEBUG_ADD_REMOVE) {
1893 RuntimeException here = new RuntimeException("here");
1894 here.fillInStackTrace();
1895 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
1896 + dstPos, here);
1897 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001898 mHistory.remove(srcPos);
1899 mHistory.add(dstPos, p);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001900 mService.mWindowManager.moveAppToken(dstPos, p.appToken);
1901 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001902 dstPos++;
1903 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001904 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001905 }
1906 i++;
1907 }
1908 if (taskTop == p) {
1909 taskTop = below;
1910 }
1911 if (taskTopI == replyChainEnd) {
1912 taskTopI = -1;
1913 }
1914 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001915 } else if (forceReset || finishOnTaskLaunch
1916 || clearWhenTaskReset) {
1917 // If the activity should just be removed -- either
1918 // because it asks for it, or the task should be
1919 // cleared -- then finish it and anything that is
1920 // part of its reply chain.
1921 if (clearWhenTaskReset) {
1922 // In this case, we want to finish this activity
1923 // and everything above it, so be sneaky and pretend
1924 // like these are all in the reply chain.
1925 replyChainEnd = targetI+1;
1926 while (replyChainEnd < mHistory.size() &&
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001927 (mHistory.get(
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001928 replyChainEnd)).task == task) {
1929 replyChainEnd++;
1930 }
1931 replyChainEnd--;
1932 } else if (replyChainEnd < 0) {
1933 replyChainEnd = targetI;
1934 }
1935 ActivityRecord p = null;
1936 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001937 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001938 if (p.finishing) {
1939 continue;
1940 }
1941 if (finishActivityLocked(p, srcPos,
1942 Activity.RESULT_CANCELED, null, "reset")) {
1943 replyChainEnd--;
1944 srcPos--;
1945 }
1946 }
1947 if (taskTop == p) {
1948 taskTop = below;
1949 }
1950 if (taskTopI == replyChainEnd) {
1951 taskTopI = -1;
1952 }
1953 replyChainEnd = -1;
1954 } else {
1955 // If we were in the middle of a chain, well the
1956 // activity that started it all doesn't want anything
1957 // special, so leave it all as-is.
1958 replyChainEnd = -1;
1959 }
1960 } else {
1961 // Reached the bottom of the task -- any reply chain
1962 // should be left as-is.
1963 replyChainEnd = -1;
1964 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08001965
1966 } else if (target.resultTo != null && (below == null
1967 || below.task == target.task)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001968 // If this activity is sending a reply to a previous
1969 // activity, we can't do anything with it now until
1970 // we reach the start of the reply chain.
1971 // XXX note that we are assuming the result is always
1972 // to the previous activity, which is almost always
1973 // the case but we really shouldn't count on.
1974 if (replyChainEnd < 0) {
1975 replyChainEnd = targetI;
1976 }
1977
1978 } else if (taskTopI >= 0 && allowTaskReparenting
1979 && task.affinity != null
1980 && task.affinity.equals(target.taskAffinity)) {
1981 // We are inside of another task... if this activity has
1982 // an affinity for our task, then either remove it if we are
1983 // clearing or move it over to our task. Note that
1984 // we currently punt on the case where we are resetting a
1985 // task that is not at the top but who has activities above
1986 // with an affinity to it... this is really not a normal
1987 // case, and we will need to later pull that task to the front
1988 // and usually at that point we will do the reset and pick
1989 // up those remaining activities. (This only happens if
1990 // someone starts an activity in a new task from an activity
1991 // in a task that is not currently on top.)
1992 if (forceReset || finishOnTaskLaunch) {
1993 if (replyChainEnd < 0) {
1994 replyChainEnd = targetI;
1995 }
1996 ActivityRecord p = null;
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08001997 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index "
1998 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001999 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002000 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002001 if (p.finishing) {
2002 continue;
2003 }
2004 if (finishActivityLocked(p, srcPos,
2005 Activity.RESULT_CANCELED, null, "reset")) {
2006 taskTopI--;
2007 lastReparentPos--;
2008 replyChainEnd--;
2009 srcPos--;
2010 }
2011 }
2012 replyChainEnd = -1;
2013 } else {
2014 if (replyChainEnd < 0) {
2015 replyChainEnd = targetI;
2016 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002017 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting task at index "
2018 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002019 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002020 ActivityRecord p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002021 if (p.finishing) {
2022 continue;
2023 }
2024 if (lastReparentPos < 0) {
2025 lastReparentPos = taskTopI;
2026 taskTop = p;
2027 } else {
2028 lastReparentPos--;
2029 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002030 if (DEBUG_ADD_REMOVE) {
2031 RuntimeException here = new RuntimeException("here");
2032 here.fillInStackTrace();
2033 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2034 + lastReparentPos, here);
2035 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002036 mHistory.remove(srcPos);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002037 p.setTask(task, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002038 mHistory.add(lastReparentPos, p);
2039 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002040 + " from " + srcPos + " to " + lastReparentPos
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002041 + " in to resetting task " + task);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002042 mService.mWindowManager.moveAppToken(lastReparentPos, p.appToken);
2043 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002044 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002045 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002046 }
2047 }
2048 replyChainEnd = -1;
2049
2050 // Now we've moved it in to place... but what if this is
2051 // a singleTop activity and we have put it on top of another
2052 // instance of the same activity? Then we drop the instance
2053 // below so it remains singleTop.
2054 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2055 for (int j=lastReparentPos-1; j>=0; j--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002056 ActivityRecord p = mHistory.get(j);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002057 if (p.finishing) {
2058 continue;
2059 }
2060 if (p.intent.getComponent().equals(target.intent.getComponent())) {
2061 if (finishActivityLocked(p, j,
2062 Activity.RESULT_CANCELED, null, "replace")) {
2063 taskTopI--;
2064 lastReparentPos--;
2065 }
2066 }
2067 }
2068 }
2069 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002070
2071 } else if (below != null && below.task != target.task) {
2072 // We hit the botton of a task; the reply chain can't
2073 // pass through it.
2074 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002075 }
2076
2077 target = below;
2078 targetI = i;
2079 }
2080
2081 return taskTop;
2082 }
2083
2084 /**
2085 * Perform clear operation as requested by
2086 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2087 * stack to the given task, then look for
2088 * an instance of that activity in the stack and, if found, finish all
2089 * activities on top of it and return the instance.
2090 *
2091 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002092 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002093 * or null if none was found.
2094 */
2095 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002096 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002097 int i = mHistory.size();
2098
2099 // First find the requested task.
2100 while (i > 0) {
2101 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002102 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002103 if (r.task.taskId == taskId) {
2104 i++;
2105 break;
2106 }
2107 }
2108
2109 // Now clear it.
2110 while (i > 0) {
2111 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002112 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002113 if (r.finishing) {
2114 continue;
2115 }
2116 if (r.task.taskId != taskId) {
2117 return null;
2118 }
2119 if (r.realActivity.equals(newR.realActivity)) {
2120 // Here it is! Now finish everything in front...
2121 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002122 while (i < (mHistory.size()-1)) {
2123 i++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002124 r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002125 if (r.task.taskId != taskId) {
2126 break;
2127 }
2128 if (r.finishing) {
2129 continue;
2130 }
2131 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2132 null, "clear")) {
2133 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002134 }
2135 }
2136
2137 // Finally, if this is a normal launch mode (that is, not
2138 // expecting onNewIntent()), then we will finish the current
2139 // instance of the activity so a new fresh one can be started.
2140 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2141 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
2142 if (!ret.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002143 int index = indexOfTokenLocked(ret.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002144 if (index >= 0) {
2145 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
2146 null, "clear");
2147 }
2148 return null;
2149 }
2150 }
2151
2152 return ret;
2153 }
2154 }
2155
2156 return null;
2157 }
2158
2159 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002160 * Completely remove all activities associated with an existing
2161 * task starting at a specified index.
2162 */
2163 private final void performClearTaskAtIndexLocked(int taskId, int i) {
Dianne Hackborneabd3282011-10-13 16:26:49 -07002164 while (i < mHistory.size()) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002165 ActivityRecord r = mHistory.get(i);
2166 if (r.task.taskId != taskId) {
2167 // Whoops hit the end.
2168 return;
2169 }
2170 if (r.finishing) {
2171 i++;
2172 continue;
2173 }
2174 if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2175 null, "clear")) {
2176 i++;
2177 }
2178 }
2179 }
2180
2181 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002182 * Completely remove all activities associated with an existing task.
2183 */
2184 private final void performClearTaskLocked(int taskId) {
2185 int i = mHistory.size();
2186
2187 // First find the requested task.
2188 while (i > 0) {
2189 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002190 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002191 if (r.task.taskId == taskId) {
2192 i++;
2193 break;
2194 }
2195 }
2196
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002197 // Now find the start and clear it.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002198 while (i > 0) {
2199 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002200 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002201 if (r.finishing) {
2202 continue;
2203 }
2204 if (r.task.taskId != taskId) {
2205 // We hit the bottom. Now finish it all...
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002206 performClearTaskAtIndexLocked(taskId, i+1);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002207 return;
2208 }
2209 }
2210 }
2211
2212 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002213 * Find the activity in the history stack within the given task. Returns
2214 * the index within the history at which it's found, or < 0 if not found.
2215 */
2216 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2217 int i = mHistory.size();
2218 while (i > 0) {
2219 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002220 ActivityRecord candidate = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002221 if (candidate.task.taskId != task) {
2222 break;
2223 }
2224 if (candidate.realActivity.equals(r.realActivity)) {
2225 return i;
2226 }
2227 }
2228
2229 return -1;
2230 }
2231
2232 /**
2233 * Reorder the history stack so that the activity at the given index is
2234 * brought to the front.
2235 */
2236 private final ActivityRecord moveActivityToFrontLocked(int where) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002237 ActivityRecord newTop = mHistory.remove(where);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002238 int top = mHistory.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002239 ActivityRecord oldTop = mHistory.get(top-1);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002240 if (DEBUG_ADD_REMOVE) {
2241 RuntimeException here = new RuntimeException("here");
2242 here.fillInStackTrace();
2243 Slog.i(TAG, "Removing and adding activity " + newTop + " to stack at "
2244 + top, here);
2245 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002246 mHistory.add(top, newTop);
2247 oldTop.frontOfTask = false;
2248 newTop.frontOfTask = true;
2249 return newTop;
2250 }
2251
2252 final int startActivityLocked(IApplicationThread caller,
2253 Intent intent, String resolvedType,
2254 Uri[] grantedUriPermissions,
2255 int grantedMode, ActivityInfo aInfo, IBinder resultTo,
2256 String resultWho, int requestCode,
2257 int callingPid, int callingUid, boolean onlyIfNeeded,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002258 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002259
2260 int err = START_SUCCESS;
2261
2262 ProcessRecord callerApp = null;
2263 if (caller != null) {
2264 callerApp = mService.getRecordForAppLocked(caller);
2265 if (callerApp != null) {
2266 callingPid = callerApp.pid;
2267 callingUid = callerApp.info.uid;
2268 } else {
2269 Slog.w(TAG, "Unable to find app for caller " + caller
2270 + " (pid=" + callingPid + ") when starting: "
2271 + intent.toString());
2272 err = START_PERMISSION_DENIED;
2273 }
2274 }
2275
2276 if (err == START_SUCCESS) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002277 Slog.i(TAG, "START {" + intent.toShortString(true, true, true) + "} from pid "
Dianne Hackbornefb58102010-10-14 16:47:34 -07002278 + (callerApp != null ? callerApp.pid : callingPid));
2279 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002280
2281 ActivityRecord sourceRecord = null;
2282 ActivityRecord resultRecord = null;
2283 if (resultTo != null) {
2284 int index = indexOfTokenLocked(resultTo);
2285 if (DEBUG_RESULTS) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002286 TAG, "Will send result to " + resultTo + " (index " + index + ")");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002287 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002288 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002289 if (requestCode >= 0 && !sourceRecord.finishing) {
2290 resultRecord = sourceRecord;
2291 }
2292 }
2293 }
2294
2295 int launchFlags = intent.getFlags();
2296
2297 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2298 && sourceRecord != null) {
2299 // Transfer the result target from the source activity to the new
2300 // one being started, including any failures.
2301 if (requestCode >= 0) {
2302 return START_FORWARD_AND_REQUEST_CONFLICT;
2303 }
2304 resultRecord = sourceRecord.resultTo;
2305 resultWho = sourceRecord.resultWho;
2306 requestCode = sourceRecord.requestCode;
2307 sourceRecord.resultTo = null;
2308 if (resultRecord != null) {
2309 resultRecord.removeResultsLocked(
2310 sourceRecord, resultWho, requestCode);
2311 }
2312 }
2313
Dianne Hackbornefb58102010-10-14 16:47:34 -07002314 if (err == START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002315 // We couldn't find a class that can handle the given Intent.
2316 // That's the end of that!
2317 err = START_INTENT_NOT_RESOLVED;
2318 }
2319
2320 if (err == START_SUCCESS && aInfo == null) {
2321 // We couldn't find the specific class specified in the Intent.
2322 // Also the end of the line.
2323 err = START_CLASS_NOT_FOUND;
2324 }
2325
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002326 if (err != START_SUCCESS) {
2327 if (resultRecord != null) {
2328 sendActivityResultLocked(-1,
2329 resultRecord, resultWho, requestCode,
2330 Activity.RESULT_CANCELED, null);
2331 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002332 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002333 return err;
2334 }
2335
2336 final int perm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002337 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002338 if (perm != PackageManager.PERMISSION_GRANTED) {
2339 if (resultRecord != null) {
2340 sendActivityResultLocked(-1,
2341 resultRecord, resultWho, requestCode,
2342 Activity.RESULT_CANCELED, null);
2343 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002344 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002345 String msg;
2346 if (!aInfo.exported) {
2347 msg = "Permission Denial: starting " + intent.toString()
2348 + " from " + callerApp + " (pid=" + callingPid
2349 + ", uid=" + callingUid + ")"
2350 + " not exported from uid " + aInfo.applicationInfo.uid;
2351 } else {
2352 msg = "Permission Denial: starting " + intent.toString()
2353 + " from " + callerApp + " (pid=" + callingPid
2354 + ", uid=" + callingUid + ")"
2355 + " requires " + aInfo.permission;
2356 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002357 Slog.w(TAG, msg);
2358 throw new SecurityException(msg);
2359 }
2360
2361 if (mMainStack) {
2362 if (mService.mController != null) {
2363 boolean abort = false;
2364 try {
2365 // The Intent we give to the watcher has the extra data
2366 // stripped off, since it can contain private information.
2367 Intent watchIntent = intent.cloneFilter();
2368 abort = !mService.mController.activityStarting(watchIntent,
2369 aInfo.applicationInfo.packageName);
2370 } catch (RemoteException e) {
2371 mService.mController = null;
2372 }
2373
2374 if (abort) {
2375 if (resultRecord != null) {
2376 sendActivityResultLocked(-1,
2377 resultRecord, resultWho, requestCode,
2378 Activity.RESULT_CANCELED, null);
2379 }
2380 // We pretend to the caller that it was really started, but
2381 // they will just get a cancel result.
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002382 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002383 return START_SUCCESS;
2384 }
2385 }
2386 }
2387
2388 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2389 intent, resolvedType, aInfo, mService.mConfiguration,
2390 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002391 if (outActivity != null) {
2392 outActivity[0] = r;
2393 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002394
2395 if (mMainStack) {
2396 if (mResumedActivity == null
2397 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2398 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2399 PendingActivityLaunch pal = new PendingActivityLaunch();
2400 pal.r = r;
2401 pal.sourceRecord = sourceRecord;
2402 pal.grantedUriPermissions = grantedUriPermissions;
2403 pal.grantedMode = grantedMode;
2404 pal.onlyIfNeeded = onlyIfNeeded;
2405 mService.mPendingActivityLaunches.add(pal);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002406 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002407 return START_SWITCHES_CANCELED;
2408 }
2409 }
2410
2411 if (mService.mDidAppSwitch) {
2412 // This is the second allowed switch since we stopped switches,
2413 // so now just generally allow switches. Use case: user presses
2414 // home (switches disabled, switch to home, mDidAppSwitch now true);
2415 // user taps a home icon (coming from home so allowed, we hit here
2416 // and now allow anyone to switch again).
2417 mService.mAppSwitchesAllowedTime = 0;
2418 } else {
2419 mService.mDidAppSwitch = true;
2420 }
2421
2422 mService.doPendingActivityLaunchesLocked(false);
2423 }
2424
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002425 err = startActivityUncheckedLocked(r, sourceRecord,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002426 grantedUriPermissions, grantedMode, onlyIfNeeded, true);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002427 if (mDismissKeyguardOnNextActivity && mPausingActivity == null) {
2428 // Someone asked to have the keyguard dismissed on the next
2429 // activity start, but we are not actually doing an activity
2430 // switch... just dismiss the keyguard now, because we
2431 // probably want to see whatever is behind it.
2432 mDismissKeyguardOnNextActivity = false;
2433 mService.mWindowManager.dismissKeyguard();
2434 }
2435 return err;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002436 }
2437
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002438 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2439 if ((launchFlags &
2440 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2441 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2442 // Caller wants to appear on home activity, so before starting
2443 // their own activity we will bring home to the front.
2444 moveHomeToFrontLocked();
2445 }
2446 }
2447
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002448 final int startActivityUncheckedLocked(ActivityRecord r,
2449 ActivityRecord sourceRecord, Uri[] grantedUriPermissions,
2450 int grantedMode, boolean onlyIfNeeded, boolean doResume) {
2451 final Intent intent = r.intent;
2452 final int callingUid = r.launchedFromUid;
2453
2454 int launchFlags = intent.getFlags();
2455
2456 // We'll invoke onUserLeaving before onPause only if the launching
2457 // activity did not explicitly state that this is an automated launch.
2458 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2459 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2460 "startActivity() => mUserLeaving=" + mUserLeaving);
2461
2462 // If the caller has asked not to resume at this point, we make note
2463 // of this in the record so that we can skip it when trying to find
2464 // the top running activity.
2465 if (!doResume) {
2466 r.delayedResume = true;
2467 }
2468
2469 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2470 != 0 ? r : null;
2471
2472 // If the onlyIfNeeded flag is set, then we can do this if the activity
2473 // being launched is the same as the one making the call... or, as
2474 // a special case, if we do not know the caller then we count the
2475 // current top activity as the caller.
2476 if (onlyIfNeeded) {
2477 ActivityRecord checkedCaller = sourceRecord;
2478 if (checkedCaller == null) {
2479 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2480 }
2481 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2482 // Caller is not the same as launcher, so always needed.
2483 onlyIfNeeded = false;
2484 }
2485 }
2486
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002487 if (sourceRecord == null) {
2488 // This activity is not being started from another... in this
2489 // case we -always- start a new task.
2490 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2491 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2492 + intent);
2493 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2494 }
2495 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2496 // The original activity who is starting us is running as a single
2497 // instance... this new activity it is starting must go on its
2498 // own task.
2499 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2500 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2501 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2502 // The activity being started is a single instance... it always
2503 // gets launched into its own task.
2504 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2505 }
2506
2507 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2508 // For whatever reason this activity is being launched into a new
2509 // task... yet the caller has requested a result back. Well, that
2510 // is pretty messed up, so instead immediately send back a cancel
2511 // and let the new task continue launched as normal without a
2512 // dependency on its originator.
2513 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2514 sendActivityResultLocked(-1,
2515 r.resultTo, r.resultWho, r.requestCode,
2516 Activity.RESULT_CANCELED, null);
2517 r.resultTo = null;
2518 }
2519
2520 boolean addingToTask = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002521 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002522 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2523 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2524 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2525 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2526 // If bring to front is requested, and no result is requested, and
2527 // we can find a task that was started with this same
2528 // component, then instead of launching bring that one to the front.
2529 if (r.resultTo == null) {
2530 // See if there is a task to bring to the front. If this is
2531 // a SINGLE_INSTANCE activity, there can be one and only one
2532 // instance of it in the history, and it is always in its own
2533 // unique task, so we do a special search.
2534 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2535 ? findTaskLocked(intent, r.info)
2536 : findActivityLocked(intent, r.info);
2537 if (taskTop != null) {
2538 if (taskTop.task.intent == null) {
2539 // This task was started because of movement of
2540 // the activity based on affinity... now that we
2541 // are actually launching it, we can assign the
2542 // base intent.
2543 taskTop.task.setIntent(intent, r.info);
2544 }
2545 // If the target task is not in the front, then we need
2546 // to bring it to the front... except... well, with
2547 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2548 // to have the same behavior as if a new instance was
2549 // being started, which means not bringing it to the front
2550 // if the caller is not itself in the front.
2551 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002552 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002553 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2554 boolean callerAtFront = sourceRecord == null
2555 || curTop.task == sourceRecord.task;
2556 if (callerAtFront) {
2557 // We really do want to push this one into the
2558 // user's face, right now.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002559 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002560 moveTaskToFrontLocked(taskTop.task, r);
2561 }
2562 }
2563 // If the caller has requested that the target task be
2564 // reset, then do so.
2565 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2566 taskTop = resetTaskIfNeededLocked(taskTop, r);
2567 }
2568 if (onlyIfNeeded) {
2569 // We don't need to start a new activity, and
2570 // the client said not to do anything if that
2571 // is the case, so this is it! And for paranoia, make
2572 // sure we have correctly resumed the top activity.
2573 if (doResume) {
2574 resumeTopActivityLocked(null);
2575 }
2576 return START_RETURN_INTENT_TO_CALLER;
2577 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002578 if ((launchFlags &
2579 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2580 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2581 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002582 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002583 // not be too hard...
2584 reuseTask = taskTop.task;
2585 performClearTaskLocked(taskTop.task.taskId);
2586 reuseTask.setIntent(r.intent, r.info);
2587 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002588 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2589 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2590 // In this situation we want to remove all activities
2591 // from the task up to the one being started. In most
2592 // cases this means we are resetting the task to its
2593 // initial state.
2594 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002595 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002596 if (top != null) {
2597 if (top.frontOfTask) {
2598 // Activity aliases may mean we use different
2599 // intents for the top activity, so make sure
2600 // the task now has the identity of the new
2601 // intent.
2602 top.task.setIntent(r.intent, r.info);
2603 }
2604 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002605 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002606 } else {
2607 // A special case: we need to
2608 // start the activity because it is not currently
2609 // running, and the caller has asked to clear the
2610 // current task to have this activity at the top.
2611 addingToTask = true;
2612 // Now pretend like this activity is being started
2613 // by the top of its task, so it is put in the
2614 // right place.
2615 sourceRecord = taskTop;
2616 }
2617 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2618 // In this case the top activity on the task is the
2619 // same as the one being launched, so we take that
2620 // as a request to bring the task to the foreground.
2621 // If the top activity in the task is the root
2622 // activity, deliver this new intent to it if it
2623 // desires.
2624 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2625 && taskTop.realActivity.equals(r.realActivity)) {
2626 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2627 if (taskTop.frontOfTask) {
2628 taskTop.task.setIntent(r.intent, r.info);
2629 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002630 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002631 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2632 // In this case we are launching the root activity
2633 // of the task, but with a different intent. We
2634 // should start a new instance on top.
2635 addingToTask = true;
2636 sourceRecord = taskTop;
2637 }
2638 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2639 // In this case an activity is being launched in to an
2640 // existing task, without resetting that task. This
2641 // is typically the situation of launching an activity
2642 // from a notification or shortcut. We want to place
2643 // the new activity on top of the current task.
2644 addingToTask = true;
2645 sourceRecord = taskTop;
2646 } else if (!taskTop.task.rootWasReset) {
2647 // In this case we are launching in to an existing task
2648 // that has not yet been started from its front door.
2649 // The current task has been brought to the front.
2650 // Ideally, we'd probably like to place this new task
2651 // at the bottom of its stack, but that's a little hard
2652 // to do with the current organization of the code so
2653 // for now we'll just drop it.
2654 taskTop.task.setIntent(r.intent, r.info);
2655 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002656 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002657 // We didn't do anything... but it was needed (a.k.a., client
2658 // don't use that intent!) And for paranoia, make
2659 // sure we have correctly resumed the top activity.
2660 if (doResume) {
2661 resumeTopActivityLocked(null);
2662 }
2663 return START_TASK_TO_FRONT;
2664 }
2665 }
2666 }
2667 }
2668
2669 //String uri = r.intent.toURI();
2670 //Intent intent2 = new Intent(uri);
2671 //Slog.i(TAG, "Given intent: " + r.intent);
2672 //Slog.i(TAG, "URI is: " + uri);
2673 //Slog.i(TAG, "To intent: " + intent2);
2674
2675 if (r.packageName != null) {
2676 // If the activity being launched is the same as the one currently
2677 // at the top, then we need to check if it should only be launched
2678 // once.
2679 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2680 if (top != null && r.resultTo == null) {
2681 if (top.realActivity.equals(r.realActivity)) {
2682 if (top.app != null && top.app.thread != null) {
2683 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2684 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2685 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2686 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2687 // For paranoia, make sure we have correctly
2688 // resumed the top activity.
2689 if (doResume) {
2690 resumeTopActivityLocked(null);
2691 }
2692 if (onlyIfNeeded) {
2693 // We don't need to start a new activity, and
2694 // the client said not to do anything if that
2695 // is the case, so this is it!
2696 return START_RETURN_INTENT_TO_CALLER;
2697 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002698 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002699 return START_DELIVERED_TO_TOP;
2700 }
2701 }
2702 }
2703 }
2704
2705 } else {
2706 if (r.resultTo != null) {
2707 sendActivityResultLocked(-1,
2708 r.resultTo, r.resultWho, r.requestCode,
2709 Activity.RESULT_CANCELED, null);
2710 }
2711 return START_CLASS_NOT_FOUND;
2712 }
2713
2714 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002715 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002716
2717 // Should this be considered a new task?
2718 if (r.resultTo == null && !addingToTask
2719 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002720 if (reuseTask == null) {
2721 // todo: should do better management of integers.
2722 mService.mCurTask++;
2723 if (mService.mCurTask <= 0) {
2724 mService.mCurTask = 1;
2725 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002726 r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002727 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2728 + " in new task " + r.task);
2729 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002730 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002731 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002732 newTask = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002733 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002734
2735 } else if (sourceRecord != null) {
2736 if (!addingToTask &&
2737 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2738 // In this case, we are adding the activity to an existing
2739 // task, but the caller has asked to clear that task if the
2740 // activity is already running.
2741 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002742 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002743 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002744 if (top != null) {
2745 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002746 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002747 // For paranoia, make sure we have correctly
2748 // resumed the top activity.
2749 if (doResume) {
2750 resumeTopActivityLocked(null);
2751 }
2752 return START_DELIVERED_TO_TOP;
2753 }
2754 } else if (!addingToTask &&
2755 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2756 // In this case, we are launching an activity in our own task
2757 // that may already be running somewhere in the history, and
2758 // we want to shuffle it to the front of the stack if so.
2759 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2760 if (where >= 0) {
2761 ActivityRecord top = moveActivityToFrontLocked(where);
2762 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002763 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002764 if (doResume) {
2765 resumeTopActivityLocked(null);
2766 }
2767 return START_DELIVERED_TO_TOP;
2768 }
2769 }
2770 // An existing activity is starting this new activity, so we want
2771 // to keep the new one in the same task as the one that is starting
2772 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002773 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002774 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2775 + " in existing task " + r.task);
2776
2777 } else {
2778 // This not being started from an existing activity, and not part
2779 // of a new task... just put it in the top task, though these days
2780 // this case should never happen.
2781 final int N = mHistory.size();
2782 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002783 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002784 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002785 ? prev.task
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002786 : new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002787 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2788 + " in new guessed " + r.task);
2789 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002790
2791 if (grantedUriPermissions != null && callingUid > 0) {
2792 for (int i=0; i<grantedUriPermissions.length; i++) {
2793 mService.grantUriPermissionLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002794 grantedUriPermissions[i], grantedMode, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002795 }
2796 }
2797
2798 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002799 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002800
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002801 if (newTask) {
2802 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
2803 }
2804 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002805 startActivityLocked(r, newTask, doResume, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002806 return START_SUCCESS;
2807 }
2808
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002809 ActivityInfo resolveActivity(Intent intent, String resolvedType, boolean debug,
2810 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002811 // Collect information about the target of the Intent.
2812 ActivityInfo aInfo;
2813 try {
2814 ResolveInfo rInfo =
2815 AppGlobals.getPackageManager().resolveIntent(
2816 intent, resolvedType,
2817 PackageManager.MATCH_DEFAULT_ONLY
2818 | ActivityManagerService.STOCK_PM_FLAGS);
2819 aInfo = rInfo != null ? rInfo.activityInfo : null;
2820 } catch (RemoteException e) {
2821 aInfo = null;
2822 }
2823
2824 if (aInfo != null) {
2825 // Store the found target back into the intent, because now that
2826 // we have it we never want to do this again. For example, if the
2827 // user navigates back to this point in the history, we should
2828 // always restart the exact same activity.
2829 intent.setComponent(new ComponentName(
2830 aInfo.applicationInfo.packageName, aInfo.name));
2831
2832 // Don't debug things in the system process
2833 if (debug) {
2834 if (!aInfo.processName.equals("system")) {
2835 mService.setDebugApp(aInfo.processName, true, false);
2836 }
2837 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002838
2839 if (profileFile != null) {
2840 if (!aInfo.processName.equals("system")) {
2841 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
2842 profileFile, profileFd, autoStopProfiler);
2843 }
2844 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002845 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002846 return aInfo;
2847 }
2848
2849 final int startActivityMayWait(IApplicationThread caller, int callingUid,
2850 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2851 int grantedMode, IBinder resultTo,
2852 String resultWho, int requestCode, boolean onlyIfNeeded,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002853 boolean debug, String profileFile, ParcelFileDescriptor profileFd,
2854 boolean autoStopProfiler, WaitResult outResult, Configuration config) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002855 // Refuse possible leaked file descriptors
2856 if (intent != null && intent.hasFileDescriptors()) {
2857 throw new IllegalArgumentException("File descriptors passed in Intent");
2858 }
2859
2860 boolean componentSpecified = intent.getComponent() != null;
2861
2862 // Don't modify the client's object!
2863 intent = new Intent(intent);
2864
2865 // Collect information about the target of the Intent.
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002866 ActivityInfo aInfo = resolveActivity(intent, resolvedType, debug,
2867 profileFile, profileFd, autoStopProfiler);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002868
2869 synchronized (mService) {
2870 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002871 if (callingUid >= 0) {
2872 callingPid = -1;
2873 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002874 callingPid = Binder.getCallingPid();
2875 callingUid = Binder.getCallingUid();
2876 } else {
2877 callingPid = callingUid = -1;
2878 }
2879
2880 mConfigWillChange = config != null
2881 && mService.mConfiguration.diff(config) != 0;
2882 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2883 "Starting activity when config will change = " + mConfigWillChange);
2884
2885 final long origId = Binder.clearCallingIdentity();
2886
2887 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07002888 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002889 // This may be a heavy-weight process! Check to see if we already
2890 // have another, different heavy-weight process running.
2891 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
2892 if (mService.mHeavyWeightProcess != null &&
2893 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
2894 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
2895 int realCallingPid = callingPid;
2896 int realCallingUid = callingUid;
2897 if (caller != null) {
2898 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
2899 if (callerApp != null) {
2900 realCallingPid = callerApp.pid;
2901 realCallingUid = callerApp.info.uid;
2902 } else {
2903 Slog.w(TAG, "Unable to find app for caller " + caller
2904 + " (pid=" + realCallingPid + ") when starting: "
2905 + intent.toString());
2906 return START_PERMISSION_DENIED;
2907 }
2908 }
2909
2910 IIntentSender target = mService.getIntentSenderLocked(
2911 IActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002912 realCallingUid, null, null, 0, new Intent[] { intent },
2913 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002914 | PendingIntent.FLAG_ONE_SHOT);
2915
2916 Intent newIntent = new Intent();
2917 if (requestCode >= 0) {
2918 // Caller is requesting a result.
2919 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
2920 }
2921 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
2922 new IntentSender(target));
2923 if (mService.mHeavyWeightProcess.activities.size() > 0) {
2924 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
2925 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
2926 hist.packageName);
2927 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
2928 hist.task.taskId);
2929 }
2930 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
2931 aInfo.packageName);
2932 newIntent.setFlags(intent.getFlags());
2933 newIntent.setClassName("android",
2934 HeavyWeightSwitcherActivity.class.getName());
2935 intent = newIntent;
2936 resolvedType = null;
2937 caller = null;
2938 callingUid = Binder.getCallingUid();
2939 callingPid = Binder.getCallingPid();
2940 componentSpecified = true;
2941 try {
2942 ResolveInfo rInfo =
2943 AppGlobals.getPackageManager().resolveIntent(
2944 intent, null,
2945 PackageManager.MATCH_DEFAULT_ONLY
2946 | ActivityManagerService.STOCK_PM_FLAGS);
2947 aInfo = rInfo != null ? rInfo.activityInfo : null;
2948 } catch (RemoteException e) {
2949 aInfo = null;
2950 }
2951 }
2952 }
2953 }
2954
2955 int res = startActivityLocked(caller, intent, resolvedType,
2956 grantedUriPermissions, grantedMode, aInfo,
2957 resultTo, resultWho, requestCode, callingPid, callingUid,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002958 onlyIfNeeded, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002959
2960 if (mConfigWillChange && mMainStack) {
2961 // If the caller also wants to switch to a new configuration,
2962 // do so now. This allows a clean switch, as we are waiting
2963 // for the current activity to pause (so we will not destroy
2964 // it), and have not yet started the next activity.
2965 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
2966 "updateConfiguration()");
2967 mConfigWillChange = false;
2968 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2969 "Updating to new configuration after starting activity.");
Dianne Hackborn813075a62011-11-14 17:45:19 -08002970 mService.updateConfigurationLocked(config, null, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002971 }
2972
2973 Binder.restoreCallingIdentity(origId);
2974
2975 if (outResult != null) {
2976 outResult.result = res;
2977 if (res == IActivityManager.START_SUCCESS) {
2978 mWaitingActivityLaunched.add(outResult);
2979 do {
2980 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07002981 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002982 } catch (InterruptedException e) {
2983 }
2984 } while (!outResult.timeout && outResult.who == null);
2985 } else if (res == IActivityManager.START_TASK_TO_FRONT) {
2986 ActivityRecord r = this.topRunningActivityLocked(null);
2987 if (r.nowVisible) {
2988 outResult.timeout = false;
2989 outResult.who = new ComponentName(r.info.packageName, r.info.name);
2990 outResult.totalTime = 0;
2991 outResult.thisTime = 0;
2992 } else {
2993 outResult.thisTime = SystemClock.uptimeMillis();
2994 mWaitingActivityVisible.add(outResult);
2995 do {
2996 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07002997 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002998 } catch (InterruptedException e) {
2999 }
3000 } while (!outResult.timeout && outResult.who == null);
3001 }
3002 }
3003 }
3004
3005 return res;
3006 }
3007 }
3008
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003009 final int startActivities(IApplicationThread caller, int callingUid,
3010 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
3011 if (intents == null) {
3012 throw new NullPointerException("intents is null");
3013 }
3014 if (resolvedTypes == null) {
3015 throw new NullPointerException("resolvedTypes is null");
3016 }
3017 if (intents.length != resolvedTypes.length) {
3018 throw new IllegalArgumentException("intents are length different than resolvedTypes");
3019 }
3020
3021 ActivityRecord[] outActivity = new ActivityRecord[1];
3022
3023 int callingPid;
3024 if (callingUid >= 0) {
3025 callingPid = -1;
3026 } else if (caller == null) {
3027 callingPid = Binder.getCallingPid();
3028 callingUid = Binder.getCallingUid();
3029 } else {
3030 callingPid = callingUid = -1;
3031 }
3032 final long origId = Binder.clearCallingIdentity();
3033 try {
3034 synchronized (mService) {
3035
3036 for (int i=0; i<intents.length; i++) {
3037 Intent intent = intents[i];
3038 if (intent == null) {
3039 continue;
3040 }
3041
3042 // Refuse possible leaked file descriptors
3043 if (intent != null && intent.hasFileDescriptors()) {
3044 throw new IllegalArgumentException("File descriptors passed in Intent");
3045 }
3046
3047 boolean componentSpecified = intent.getComponent() != null;
3048
3049 // Don't modify the client's object!
3050 intent = new Intent(intent);
3051
3052 // Collect information about the target of the Intent.
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003053 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i], false,
3054 null, null, false);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003055
3056 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
3057 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
3058 throw new IllegalArgumentException(
3059 "FLAG_CANT_SAVE_STATE not supported here");
3060 }
3061
3062 int res = startActivityLocked(caller, intent, resolvedTypes[i],
3063 null, 0, aInfo, resultTo, null, -1, callingPid, callingUid,
3064 false, componentSpecified, outActivity);
3065 if (res < 0) {
3066 return res;
3067 }
3068
Dianne Hackbornbe707852011-11-11 14:32:10 -08003069 resultTo = outActivity[0] != null ? outActivity[0].appToken : null;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003070 }
3071 }
3072 } finally {
3073 Binder.restoreCallingIdentity(origId);
3074 }
3075
3076 return IActivityManager.START_SUCCESS;
3077 }
3078
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003079 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
3080 long thisTime, long totalTime) {
3081 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
3082 WaitResult w = mWaitingActivityLaunched.get(i);
3083 w.timeout = timeout;
3084 if (r != null) {
3085 w.who = new ComponentName(r.info.packageName, r.info.name);
3086 }
3087 w.thisTime = thisTime;
3088 w.totalTime = totalTime;
3089 }
3090 mService.notifyAll();
3091 }
3092
3093 void reportActivityVisibleLocked(ActivityRecord r) {
3094 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
3095 WaitResult w = mWaitingActivityVisible.get(i);
3096 w.timeout = false;
3097 if (r != null) {
3098 w.who = new ComponentName(r.info.packageName, r.info.name);
3099 }
3100 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
3101 w.thisTime = w.totalTime;
3102 }
3103 mService.notifyAll();
Dianne Hackborn90c52de2011-09-23 12:57:44 -07003104
3105 if (mDismissKeyguardOnNextActivity) {
3106 mDismissKeyguardOnNextActivity = false;
3107 mService.mWindowManager.dismissKeyguard();
3108 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003109 }
3110
3111 void sendActivityResultLocked(int callingUid, ActivityRecord r,
3112 String resultWho, int requestCode, int resultCode, Intent data) {
3113
3114 if (callingUid > 0) {
3115 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003116 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003117 }
3118
3119 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3120 + " : who=" + resultWho + " req=" + requestCode
3121 + " res=" + resultCode + " data=" + data);
3122 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3123 try {
3124 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3125 list.add(new ResultInfo(resultWho, requestCode,
3126 resultCode, data));
Dianne Hackbornbe707852011-11-11 14:32:10 -08003127 r.app.thread.scheduleSendResult(r.appToken, list);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003128 return;
3129 } catch (Exception e) {
3130 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3131 }
3132 }
3133
3134 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3135 }
3136
3137 private final void stopActivityLocked(ActivityRecord r) {
3138 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3139 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3140 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3141 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003142 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003143 "no-history");
3144 }
3145 } else if (r.app != null && r.app.thread != null) {
3146 if (mMainStack) {
3147 if (mService.mFocusedActivity == r) {
3148 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3149 }
3150 }
3151 r.resumeKeyDispatchingLocked();
3152 try {
3153 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003154 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3155 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003156 r.state = ActivityState.STOPPING;
3157 if (DEBUG_VISBILITY) Slog.v(
3158 TAG, "Stopping visible=" + r.visible + " for " + r);
3159 if (!r.visible) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003160 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003161 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003162 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003163 if (mService.isSleeping()) {
3164 r.setSleeping(true);
3165 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003166 } catch (Exception e) {
3167 // Maybe just ignore exceptions here... if the process
3168 // has crashed, our death notification will clean things
3169 // up.
3170 Slog.w(TAG, "Exception thrown during pause", e);
3171 // Just in case, assume it to be stopped.
3172 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003173 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003174 r.state = ActivityState.STOPPED;
3175 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003176 destroyActivityLocked(r, true, false, "stop-except");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003177 }
3178 }
3179 }
3180 }
3181
3182 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3183 boolean remove) {
3184 int N = mStoppingActivities.size();
3185 if (N <= 0) return null;
3186
3187 ArrayList<ActivityRecord> stops = null;
3188
3189 final boolean nowVisible = mResumedActivity != null
3190 && mResumedActivity.nowVisible
3191 && !mResumedActivity.waitingVisible;
3192 for (int i=0; i<N; i++) {
3193 ActivityRecord s = mStoppingActivities.get(i);
3194 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3195 + nowVisible + " waitingVisible=" + s.waitingVisible
3196 + " finishing=" + s.finishing);
3197 if (s.waitingVisible && nowVisible) {
3198 mWaitingVisibleActivities.remove(s);
3199 s.waitingVisible = false;
3200 if (s.finishing) {
3201 // If this activity is finishing, it is sitting on top of
3202 // everyone else but we now know it is no longer needed...
3203 // so get rid of it. Otherwise, we need to go through the
3204 // normal flow and hide it once we determine that it is
3205 // hidden by the activities in front of it.
3206 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003207 mService.mWindowManager.setAppVisibility(s.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003208 }
3209 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003210 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003211 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3212 if (stops == null) {
3213 stops = new ArrayList<ActivityRecord>();
3214 }
3215 stops.add(s);
3216 mStoppingActivities.remove(i);
3217 N--;
3218 i--;
3219 }
3220 }
3221
3222 return stops;
3223 }
3224
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003225 final void scheduleIdleLocked() {
3226 Message msg = Message.obtain();
3227 msg.what = IDLE_NOW_MSG;
3228 mHandler.sendMessage(msg);
3229 }
3230
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003231 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003232 Configuration config) {
3233 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3234
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003235 ActivityRecord res = null;
3236
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003237 ArrayList<ActivityRecord> stops = null;
3238 ArrayList<ActivityRecord> finishes = null;
3239 ArrayList<ActivityRecord> thumbnails = null;
3240 int NS = 0;
3241 int NF = 0;
3242 int NT = 0;
3243 IApplicationThread sendThumbnail = null;
3244 boolean booting = false;
3245 boolean enableScreen = false;
3246
3247 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003248 ActivityRecord r = ActivityRecord.forToken(token);
3249 if (r != null) {
3250 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003251 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003252 }
3253
3254 // Get the activity record.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003255 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003256 if (index >= 0) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003257 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003258
3259 if (fromTimeout) {
3260 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3261 }
3262
3263 // This is a hack to semi-deal with a race condition
3264 // in the client where it can be constructed with a
3265 // newer configuration from when we asked it to launch.
3266 // We'll update with whatever configuration it now says
3267 // it used to launch.
3268 if (config != null) {
3269 r.configuration = config;
3270 }
3271
3272 // No longer need to keep the device awake.
3273 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3274 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3275 mLaunchingActivity.release();
3276 }
3277
3278 // We are now idle. If someone is waiting for a thumbnail from
3279 // us, we can now deliver.
3280 r.idle = true;
3281 mService.scheduleAppGcsLocked();
3282 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3283 sendThumbnail = r.app.thread;
3284 r.thumbnailNeeded = false;
3285 }
3286
3287 // If this activity is fullscreen, set up to hide those under it.
3288
3289 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3290 ensureActivitiesVisibleLocked(null, 0);
3291
3292 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3293 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003294 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003295 mService.mBooted = true;
3296 enableScreen = true;
3297 }
3298 }
3299
3300 } else if (fromTimeout) {
3301 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3302 }
3303
3304 // Atomically retrieve all of the other things to do.
3305 stops = processStoppingActivitiesLocked(true);
3306 NS = stops != null ? stops.size() : 0;
3307 if ((NF=mFinishingActivities.size()) > 0) {
3308 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3309 mFinishingActivities.clear();
3310 }
3311 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3312 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3313 mService.mCancelledThumbnails.clear();
3314 }
3315
3316 if (mMainStack) {
3317 booting = mService.mBooting;
3318 mService.mBooting = false;
3319 }
3320 }
3321
3322 int i;
3323
3324 // Send thumbnail if requested.
3325 if (sendThumbnail != null) {
3326 try {
3327 sendThumbnail.requestThumbnail(token);
3328 } catch (Exception e) {
3329 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3330 mService.sendPendingThumbnail(null, token, null, null, true);
3331 }
3332 }
3333
3334 // Stop any activities that are scheduled to do so but have been
3335 // waiting for the next one to start.
3336 for (i=0; i<NS; i++) {
3337 ActivityRecord r = (ActivityRecord)stops.get(i);
3338 synchronized (mService) {
3339 if (r.finishing) {
3340 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY);
3341 } else {
3342 stopActivityLocked(r);
3343 }
3344 }
3345 }
3346
3347 // Finish any activities that are scheduled to do so but have been
3348 // waiting for the next one to start.
3349 for (i=0; i<NF; i++) {
3350 ActivityRecord r = (ActivityRecord)finishes.get(i);
3351 synchronized (mService) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003352 destroyActivityLocked(r, true, false, "finish-idle");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003353 }
3354 }
3355
3356 // Report back to any thumbnail receivers.
3357 for (i=0; i<NT; i++) {
3358 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3359 mService.sendPendingThumbnail(r, null, null, null, true);
3360 }
3361
3362 if (booting) {
3363 mService.finishBooting();
3364 }
3365
3366 mService.trimApplications();
3367 //dump();
3368 //mWindowManager.dump();
3369
3370 if (enableScreen) {
3371 mService.enableScreenAfterBoot();
3372 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003373
3374 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003375 }
3376
3377 /**
3378 * @return Returns true if the activity is being finished, false if for
3379 * some reason it is being left as-is.
3380 */
3381 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
3382 Intent resultData, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003383 int index = indexOfTokenLocked(token);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003384 if (DEBUG_RESULTS) Slog.v(
3385 TAG, "Finishing activity @" + index + ": token=" + token
3386 + ", result=" + resultCode + ", data=" + resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003387 if (index < 0) {
3388 return false;
3389 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003390 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003391
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003392 finishActivityLocked(r, index, resultCode, resultData, reason);
3393 return true;
3394 }
3395
Dianne Hackborn5c607432012-02-28 14:44:19 -08003396 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
3397 // send the result
3398 ActivityRecord resultTo = r.resultTo;
3399 if (resultTo != null) {
3400 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3401 + " who=" + r.resultWho + " req=" + r.requestCode
3402 + " res=" + resultCode + " data=" + resultData);
3403 if (r.info.applicationInfo.uid > 0) {
3404 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3405 resultTo.packageName, resultData,
3406 resultTo.getUriPermissionsLocked());
3407 }
3408 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3409 resultData);
3410 r.resultTo = null;
3411 }
3412 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3413
3414 // Make sure this HistoryRecord is not holding on to other resources,
3415 // because clients have remote IPC references to this object so we
3416 // can't assume that will go away and want to avoid circular IPC refs.
3417 r.results = null;
3418 r.pendingResults = null;
3419 r.newIntents = null;
3420 r.icicle = null;
3421 }
3422
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003423 /**
3424 * @return Returns true if this activity has been removed from the history
3425 * list, or false if it is still in the list and will be removed later.
3426 */
3427 final boolean finishActivityLocked(ActivityRecord r, int index,
3428 int resultCode, Intent resultData, String reason) {
3429 if (r.finishing) {
3430 Slog.w(TAG, "Duplicate finish request for " + r);
3431 return false;
3432 }
3433
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003434 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003435 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3436 System.identityHashCode(r),
3437 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003438 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003439 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003440 if (next.task == r.task) {
3441 if (r.frontOfTask) {
3442 // The next activity is now the front of the task.
3443 next.frontOfTask = true;
3444 }
3445 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3446 // If the caller asked that this activity (and all above it)
3447 // be cleared when the task is reset, don't lose that information,
3448 // but propagate it up to the next activity.
3449 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3450 }
3451 }
3452 }
3453
3454 r.pauseKeyDispatchingLocked();
3455 if (mMainStack) {
3456 if (mService.mFocusedActivity == r) {
3457 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3458 }
3459 }
3460
Dianne Hackborn5c607432012-02-28 14:44:19 -08003461 finishActivityResultsLocked(r, resultCode, resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003462
3463 if (mService.mPendingThumbnails.size() > 0) {
3464 // There are clients waiting to receive thumbnails so, in case
3465 // this is an activity that someone is waiting for, add it
3466 // to the pending list so we can correctly update the clients.
3467 mService.mCancelledThumbnails.add(r);
3468 }
3469
3470 if (mResumedActivity == r) {
3471 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003472 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003473 if (DEBUG_TRANSITION) Slog.v(TAG,
3474 "Prepare close transition: finishing " + r);
3475 mService.mWindowManager.prepareAppTransition(endTask
3476 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003477 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003478
3479 // Tell window manager to prepare for this one to be removed.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003480 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003481
3482 if (mPausingActivity == null) {
3483 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3484 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3485 startPausingLocked(false, false);
3486 }
3487
3488 } else if (r.state != ActivityState.PAUSING) {
3489 // If the activity is PAUSING, we will complete the finish once
3490 // it is done pausing; else we can just directly finish it here.
3491 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3492 return finishCurrentActivityLocked(r, index,
3493 FINISH_AFTER_PAUSE) == null;
3494 } else {
3495 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3496 }
3497
3498 return false;
3499 }
3500
3501 private static final int FINISH_IMMEDIATELY = 0;
3502 private static final int FINISH_AFTER_PAUSE = 1;
3503 private static final int FINISH_AFTER_VISIBLE = 2;
3504
3505 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3506 int mode) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003507 final int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003508 if (index < 0) {
3509 return null;
3510 }
3511
3512 return finishCurrentActivityLocked(r, index, mode);
3513 }
3514
3515 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3516 int index, int mode) {
3517 // First things first: if this activity is currently visible,
3518 // and the resumed activity is not yet visible, then hold off on
3519 // finishing until the resumed one becomes visible.
3520 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3521 if (!mStoppingActivities.contains(r)) {
3522 mStoppingActivities.add(r);
3523 if (mStoppingActivities.size() > 3) {
3524 // If we already have a few activities waiting to stop,
3525 // then give up on things going idle and start clearing
3526 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003527 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003528 } else {
3529 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003530 }
3531 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003532 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3533 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003534 r.state = ActivityState.STOPPING;
3535 mService.updateOomAdjLocked();
3536 return r;
3537 }
3538
3539 // make sure the record is cleaned out of other places.
3540 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003541 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003542 mWaitingVisibleActivities.remove(r);
3543 if (mResumedActivity == r) {
3544 mResumedActivity = null;
3545 }
3546 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003547 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003548 r.state = ActivityState.FINISHING;
3549
3550 if (mode == FINISH_IMMEDIATELY
3551 || prevState == ActivityState.STOPPED
3552 || prevState == ActivityState.INITIALIZING) {
3553 // If this activity is already stopped, we can just finish
3554 // it right now.
Dianne Hackborn28695e02011-11-02 21:59:51 -07003555 return destroyActivityLocked(r, true, true, "finish-imm") ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003556 } else {
3557 // Need to go through the full pause cycle to get this
3558 // activity into the stopped state and then finish it.
3559 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3560 mFinishingActivities.add(r);
3561 resumeTopActivityLocked(null);
3562 }
3563 return r;
3564 }
3565
3566 /**
3567 * Perform the common clean-up of an activity record. This is called both
3568 * as part of destroyActivityLocked() (when destroying the client-side
3569 * representation) and cleaning things up as a result of its hosting
3570 * processing going away, in which case there is no remaining client-side
3571 * state to destroy so only the cleanup here is needed.
3572 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003573 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3574 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003575 if (mResumedActivity == r) {
3576 mResumedActivity = null;
3577 }
3578 if (mService.mFocusedActivity == r) {
3579 mService.mFocusedActivity = null;
3580 }
3581
3582 r.configDestroy = false;
3583 r.frozenBeforeDestroy = false;
3584
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003585 if (setState) {
3586 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3587 r.state = ActivityState.DESTROYED;
3588 }
3589
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003590 // Make sure this record is no longer in the pending finishes list.
3591 // This could happen, for example, if we are trimming activities
3592 // down to the max limit while they are still waiting to finish.
3593 mFinishingActivities.remove(r);
3594 mWaitingVisibleActivities.remove(r);
3595
3596 // Remove any pending results.
3597 if (r.finishing && r.pendingResults != null) {
3598 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3599 PendingIntentRecord rec = apr.get();
3600 if (rec != null) {
3601 mService.cancelIntentSenderLocked(rec, false);
3602 }
3603 }
3604 r.pendingResults = null;
3605 }
3606
3607 if (cleanServices) {
3608 cleanUpActivityServicesLocked(r);
3609 }
3610
3611 if (mService.mPendingThumbnails.size() > 0) {
3612 // There are clients waiting to receive thumbnails so, in case
3613 // this is an activity that someone is waiting for, add it
3614 // to the pending list so we can correctly update the clients.
3615 mService.mCancelledThumbnails.add(r);
3616 }
3617
3618 // Get rid of any pending idle timeouts.
3619 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
3620 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003621 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003622 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003623 }
3624
Dianne Hackborn5c607432012-02-28 14:44:19 -08003625 final void removeActivityFromHistoryLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003626 if (r.state != ActivityState.DESTROYED) {
Dianne Hackborn5c607432012-02-28 14:44:19 -08003627 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003628 r.makeFinishing();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003629 if (DEBUG_ADD_REMOVE) {
3630 RuntimeException here = new RuntimeException("here");
3631 here.fillInStackTrace();
3632 Slog.i(TAG, "Removing activity " + r + " from stack");
3633 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003634 mHistory.remove(r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003635 r.takeFromHistory();
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003636 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3637 + " (removed from history)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003638 r.state = ActivityState.DESTROYED;
Dianne Hackbornbe707852011-11-11 14:32:10 -08003639 mService.mWindowManager.removeAppToken(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003640 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003641 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003642 }
3643 cleanUpActivityServicesLocked(r);
3644 r.removeUriPermissionsLocked();
3645 }
3646 }
3647
3648 /**
3649 * Perform clean-up of service connections in an activity record.
3650 */
3651 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3652 // Throw away any services that have been bound by this activity.
3653 if (r.connections != null) {
3654 Iterator<ConnectionRecord> it = r.connections.iterator();
3655 while (it.hasNext()) {
3656 ConnectionRecord c = it.next();
3657 mService.removeConnectionLocked(c, null, r);
3658 }
3659 r.connections = null;
3660 }
3661 }
3662
Dianne Hackborn28695e02011-11-02 21:59:51 -07003663 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003664 for (int i=mHistory.size()-1; i>=0; i--) {
3665 ActivityRecord r = mHistory.get(i);
3666 if (owner != null && r.app != owner) {
3667 continue;
3668 }
3669 // We can destroy this one if we have its icicle saved and
3670 // it is not in the process of pausing/stopping/finishing.
3671 if (r.app != null && r.haveState && !r.visible && r.stopped && !r.finishing
3672 && r.state != ActivityState.DESTROYING
3673 && r.state != ActivityState.DESTROYED) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003674 destroyActivityLocked(r, true, oomAdj, "trim");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003675 }
3676 }
3677 }
3678
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003679 /**
3680 * Destroy the current CLIENT SIDE instance of an activity. This may be
3681 * called both when actually finishing an activity, or when performing
3682 * a configuration switch where we destroy the current client-side object
3683 * but then create a new client-side object for this same HistoryRecord.
3684 */
3685 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackborn28695e02011-11-02 21:59:51 -07003686 boolean removeFromApp, boolean oomAdj, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003687 if (DEBUG_SWITCH) Slog.v(
3688 TAG, "Removing activity: token=" + r
3689 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3690 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3691 System.identityHashCode(r),
Dianne Hackborn28695e02011-11-02 21:59:51 -07003692 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003693
3694 boolean removedFromHistory = false;
3695
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003696 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003697
3698 final boolean hadApp = r.app != null;
3699
3700 if (hadApp) {
3701 if (removeFromApp) {
3702 int idx = r.app.activities.indexOf(r);
3703 if (idx >= 0) {
3704 r.app.activities.remove(idx);
3705 }
3706 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
3707 mService.mHeavyWeightProcess = null;
3708 mService.mHandler.sendEmptyMessage(
3709 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
3710 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003711 if (r.app.activities.size() == 0) {
3712 // No longer have activities, so update location in
3713 // LRU list.
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003714 mService.updateLruProcessLocked(r.app, oomAdj, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003715 }
3716 }
3717
3718 boolean skipDestroy = false;
3719
3720 try {
3721 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003722 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003723 r.configChangeFlags);
3724 } catch (Exception e) {
3725 // We can just ignore exceptions here... if the process
3726 // has crashed, our death notification will clean things
3727 // up.
3728 //Slog.w(TAG, "Exception thrown during finish", e);
3729 if (r.finishing) {
3730 removeActivityFromHistoryLocked(r);
3731 removedFromHistory = true;
3732 skipDestroy = true;
3733 }
3734 }
3735
3736 r.app = null;
3737 r.nowVisible = false;
3738
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003739 // If the activity is finishing, we need to wait on removing it
3740 // from the list to give it a chance to do its cleanup. During
3741 // that time it may make calls back with its token so we need to
3742 // be able to find it on the list and so we don't want to remove
3743 // it from the list yet. Otherwise, we can just immediately put
3744 // it in the destroyed state since we are not removing it from the
3745 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003746 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003747 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
3748 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003749 r.state = ActivityState.DESTROYING;
3750 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
3751 msg.obj = r;
3752 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
3753 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003754 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3755 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003756 r.state = ActivityState.DESTROYED;
3757 }
3758 } else {
3759 // remove this record from the history.
3760 if (r.finishing) {
3761 removeActivityFromHistoryLocked(r);
3762 removedFromHistory = true;
3763 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003764 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3765 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003766 r.state = ActivityState.DESTROYED;
3767 }
3768 }
3769
3770 r.configChangeFlags = 0;
3771
3772 if (!mLRUActivities.remove(r) && hadApp) {
3773 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
3774 }
3775
3776 return removedFromHistory;
3777 }
3778
3779 final void activityDestroyed(IBinder token) {
3780 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003781 ActivityRecord r = ActivityRecord.forToken(token);
3782 if (r != null) {
3783 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
3784 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003785
Dianne Hackbornbe707852011-11-11 14:32:10 -08003786 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003787 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003788 if (r.state == ActivityState.DESTROYING) {
3789 final long origId = Binder.clearCallingIdentity();
3790 removeActivityFromHistoryLocked(r);
3791 Binder.restoreCallingIdentity(origId);
3792 }
3793 }
3794 }
3795 }
3796
3797 private static void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
3798 int i = list.size();
3799 if (localLOGV) Slog.v(
3800 TAG, "Removing app " + app + " from list " + list
3801 + " with " + i + " entries");
3802 while (i > 0) {
3803 i--;
3804 ActivityRecord r = (ActivityRecord)list.get(i);
3805 if (localLOGV) Slog.v(
3806 TAG, "Record #" + i + " " + r + ": app=" + r.app);
3807 if (r.app == app) {
3808 if (localLOGV) Slog.v(TAG, "Removing this entry!");
3809 list.remove(i);
3810 }
3811 }
3812 }
3813
3814 void removeHistoryRecordsForAppLocked(ProcessRecord app) {
3815 removeHistoryRecordsForAppLocked(mLRUActivities, app);
3816 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003817 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003818 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
3819 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
3820 }
3821
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003822 /**
3823 * Move the current home activity's task (if one exists) to the front
3824 * of the stack.
3825 */
3826 final void moveHomeToFrontLocked() {
3827 TaskRecord homeTask = null;
3828 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003829 ActivityRecord hr = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003830 if (hr.isHomeActivity) {
3831 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003832 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003833 }
3834 }
3835 if (homeTask != null) {
3836 moveTaskToFrontLocked(homeTask, null);
3837 }
3838 }
3839
3840
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003841 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason) {
3842 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
3843
3844 final int task = tr.taskId;
3845 int top = mHistory.size()-1;
3846
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003847 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003848 // nothing to do!
3849 return;
3850 }
3851
Dianne Hackbornbe707852011-11-11 14:32:10 -08003852 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003853
3854 // Applying the affinities may have removed entries from the history,
3855 // so get the size again.
3856 top = mHistory.size()-1;
3857 int pos = top;
3858
3859 // Shift all activities with this task up to the top
3860 // of the stack, keeping them in the same internal order.
3861 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003862 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003863 if (localLOGV) Slog.v(
3864 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003865 if (r.task.taskId == task) {
3866 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003867 if (DEBUG_ADD_REMOVE) {
3868 RuntimeException here = new RuntimeException("here");
3869 here.fillInStackTrace();
3870 Slog.i(TAG, "Removing and adding activity " + r + " to stack at " + top, here);
3871 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003872 mHistory.remove(pos);
3873 mHistory.add(top, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003874 moved.add(0, r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003875 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003876 }
3877 pos--;
3878 }
3879
3880 if (DEBUG_TRANSITION) Slog.v(TAG,
3881 "Prepare to front transition: task=" + tr);
3882 if (reason != null &&
3883 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003884 mService.mWindowManager.prepareAppTransition(
3885 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003886 ActivityRecord r = topRunningActivityLocked(null);
3887 if (r != null) {
3888 mNoAnimActivities.add(r);
3889 }
3890 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003891 mService.mWindowManager.prepareAppTransition(
3892 WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003893 }
3894
3895 mService.mWindowManager.moveAppTokensToTop(moved);
3896 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003897 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003898 }
3899
3900 finishTaskMoveLocked(task);
3901 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
3902 }
3903
3904 private final void finishTaskMoveLocked(int task) {
3905 resumeTopActivityLocked(null);
3906 }
3907
3908 /**
3909 * Worker method for rearranging history stack. Implements the function of moving all
3910 * activities for a specific task (gathering them if disjoint) into a single group at the
3911 * bottom of the stack.
3912 *
3913 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
3914 * to premeptively cancel the move.
3915 *
3916 * @param task The taskId to collect and move to the bottom.
3917 * @return Returns true if the move completed, false if not.
3918 */
3919 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
3920 Slog.i(TAG, "moveTaskToBack: " + task);
3921
3922 // If we have a watcher, preflight the move before committing to it. First check
3923 // for *other* available tasks, but if none are available, then try again allowing the
3924 // current task to be selected.
3925 if (mMainStack && mService.mController != null) {
3926 ActivityRecord next = topRunningActivityLocked(null, task);
3927 if (next == null) {
3928 next = topRunningActivityLocked(null, 0);
3929 }
3930 if (next != null) {
3931 // ask watcher if this is allowed
3932 boolean moveOK = true;
3933 try {
3934 moveOK = mService.mController.activityResuming(next.packageName);
3935 } catch (RemoteException e) {
3936 mService.mController = null;
3937 }
3938 if (!moveOK) {
3939 return false;
3940 }
3941 }
3942 }
3943
Dianne Hackbornbe707852011-11-11 14:32:10 -08003944 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003945
3946 if (DEBUG_TRANSITION) Slog.v(TAG,
3947 "Prepare to back transition: task=" + task);
3948
3949 final int N = mHistory.size();
3950 int bottom = 0;
3951 int pos = 0;
3952
3953 // Shift all activities with this task down to the bottom
3954 // of the stack, keeping them in the same internal order.
3955 while (pos < N) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003956 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003957 if (localLOGV) Slog.v(
3958 TAG, "At " + pos + " ckp " + r.task + ": " + r);
3959 if (r.task.taskId == task) {
3960 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003961 if (DEBUG_ADD_REMOVE) {
3962 RuntimeException here = new RuntimeException("here");
3963 here.fillInStackTrace();
3964 Slog.i(TAG, "Removing and adding activity " + r + " to stack at "
3965 + bottom, here);
3966 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003967 mHistory.remove(pos);
3968 mHistory.add(bottom, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003969 moved.add(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003970 bottom++;
3971 }
3972 pos++;
3973 }
3974
3975 if (reason != null &&
3976 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003977 mService.mWindowManager.prepareAppTransition(
3978 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003979 ActivityRecord r = topRunningActivityLocked(null);
3980 if (r != null) {
3981 mNoAnimActivities.add(r);
3982 }
3983 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003984 mService.mWindowManager.prepareAppTransition(
3985 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003986 }
3987 mService.mWindowManager.moveAppTokensToBottom(moved);
3988 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003989 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003990 }
3991
3992 finishTaskMoveLocked(task);
3993 return true;
3994 }
3995
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003996 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
3997 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
3998 ActivityRecord resumed = mResumedActivity;
3999 if (resumed != null && resumed.thumbHolder == tr) {
4000 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
4001 } else {
4002 info.mainThumbnail = tr.lastThumbnail;
4003 }
4004 return info;
4005 }
4006
4007 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex) {
4008 TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
4009 if (info.root == null) {
4010 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
4011 return null;
4012 }
4013
4014 if (subTaskIndex < 0) {
4015 // Just remove the entire task.
4016 performClearTaskAtIndexLocked(taskId, info.rootIndex);
4017 return info.root;
4018 }
4019
4020 if (subTaskIndex >= info.subtasks.size()) {
4021 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
4022 return null;
4023 }
4024
4025 // Remove all of this task's activies starting at the sub task.
4026 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
4027 performClearTaskAtIndexLocked(taskId, subtask.index);
4028 return subtask.activity;
4029 }
4030
4031 public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
4032 ActivityRecord resumed = mResumedActivity;
4033 final TaskAccessInfo thumbs = new TaskAccessInfo();
4034 // How many different sub-thumbnails?
4035 final int NA = mHistory.size();
4036 int j = 0;
4037 ThumbnailHolder holder = null;
4038 while (j < NA) {
4039 ActivityRecord ar = mHistory.get(j);
4040 if (!ar.finishing && ar.task.taskId == taskId) {
4041 holder = ar.thumbHolder;
4042 break;
4043 }
4044 j++;
4045 }
4046
4047 if (j >= NA) {
4048 return thumbs;
4049 }
4050
4051 thumbs.root = mHistory.get(j);
4052 thumbs.rootIndex = j;
4053
4054 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
4055 thumbs.subtasks = subtasks;
4056 ActivityRecord lastActivity = null;
4057 while (j < NA) {
4058 ActivityRecord ar = mHistory.get(j);
4059 j++;
4060 if (ar.finishing) {
4061 continue;
4062 }
4063 if (ar.task.taskId != taskId) {
4064 break;
4065 }
4066 lastActivity = ar;
4067 if (ar.thumbHolder != holder && holder != null) {
4068 thumbs.numSubThumbbails++;
4069 holder = ar.thumbHolder;
4070 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
4071 sub.thumbnail = holder.lastThumbnail;
4072 sub.activity = ar;
4073 sub.index = j-1;
4074 subtasks.add(sub);
4075 }
4076 }
4077 if (lastActivity != null && subtasks.size() > 0) {
4078 if (resumed == lastActivity) {
4079 TaskAccessInfo.SubTask sub = subtasks.get(subtasks.size()-1);
4080 sub.thumbnail = lastActivity.stack.screenshotActivities(lastActivity);
4081 }
4082 }
4083 if (thumbs.numSubThumbbails > 0) {
4084 thumbs.retriever = new IThumbnailRetriever.Stub() {
4085 public Bitmap getThumbnail(int index) {
4086 if (index < 0 || index >= thumbs.subtasks.size()) {
4087 return null;
4088 }
4089 return thumbs.subtasks.get(index).thumbnail;
4090 }
4091 };
4092 }
4093 return thumbs;
4094 }
4095
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004096 private final void logStartActivity(int tag, ActivityRecord r,
4097 TaskRecord task) {
4098 EventLog.writeEvent(tag,
4099 System.identityHashCode(r), task.taskId,
4100 r.shortComponentName, r.intent.getAction(),
4101 r.intent.getType(), r.intent.getDataString(),
4102 r.intent.getFlags());
4103 }
4104
4105 /**
4106 * Make sure the given activity matches the current configuration. Returns
4107 * false if the activity had to be destroyed. Returns true if the
4108 * configuration is the same, or the activity will remain running as-is
4109 * for whatever reason. Ensures the HistoryRecord is updated with the
4110 * correct configuration and all other bookkeeping is handled.
4111 */
4112 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
4113 int globalChanges) {
4114 if (mConfigWillChange) {
4115 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4116 "Skipping config check (will change): " + r);
4117 return true;
4118 }
4119
4120 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4121 "Ensuring correct configuration: " + r);
4122
4123 // Short circuit: if the two configurations are the exact same
4124 // object (the common case), then there is nothing to do.
4125 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004126 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004127 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4128 "Configuration unchanged in " + r);
4129 return true;
4130 }
4131
4132 // We don't worry about activities that are finishing.
4133 if (r.finishing) {
4134 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4135 "Configuration doesn't matter in finishing " + r);
4136 r.stopFreezingScreenLocked(false);
4137 return true;
4138 }
4139
4140 // Okay we now are going to make this activity have the new config.
4141 // But then we need to figure out how it needs to deal with that.
4142 Configuration oldConfig = r.configuration;
4143 r.configuration = newConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004144
4145 // Determine what has changed. May be nothing, if this is a config
4146 // that has come back from the app after going idle. In that case
4147 // we just want to leave the official config object now in the
4148 // activity and do nothing else.
4149 final int changes = oldConfig.diff(newConfig);
4150 if (changes == 0 && !r.forceNewConfig) {
4151 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4152 "Configuration no differences in " + r);
4153 return true;
4154 }
4155
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004156 // If the activity isn't currently running, just leave the new
4157 // configuration and it will pick that up next time it starts.
4158 if (r.app == null || r.app.thread == null) {
4159 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4160 "Configuration doesn't matter not running " + r);
4161 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004162 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004163 return true;
4164 }
4165
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004166 // Figure out how to handle the changes between the configurations.
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004167 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4168 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
4169 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07004170 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004171 + ", newConfig=" + newConfig);
4172 }
Dianne Hackborne6676352011-06-01 16:51:20 -07004173 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004174 // Aha, the activity isn't handling the change, so DIE DIE DIE.
4175 r.configChangeFlags |= changes;
4176 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004177 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004178 if (r.app == null || r.app.thread == null) {
4179 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4180 "Switch is destroying non-running " + r);
Dianne Hackborn28695e02011-11-02 21:59:51 -07004181 destroyActivityLocked(r, true, false, "config");
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004182 } else if (r.state == ActivityState.PAUSING) {
4183 // A little annoying: we are waiting for this activity to
4184 // finish pausing. Let's not do anything now, but just
4185 // flag that it needs to be restarted when done pausing.
4186 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4187 "Switch is skipping already pausing " + r);
4188 r.configDestroy = true;
4189 return true;
4190 } else if (r.state == ActivityState.RESUMED) {
4191 // Try to optimize this case: the configuration is changing
4192 // and we need to restart the top, resumed activity.
4193 // Instead of doing the normal handshaking, just say
4194 // "restart!".
4195 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4196 "Switch is restarting resumed " + r);
4197 relaunchActivityLocked(r, r.configChangeFlags, true);
4198 r.configChangeFlags = 0;
4199 } else {
4200 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4201 "Switch is restarting non-resumed " + r);
4202 relaunchActivityLocked(r, r.configChangeFlags, false);
4203 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004204 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004205
4206 // All done... tell the caller we weren't able to keep this
4207 // activity around.
4208 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004209 }
4210
4211 // Default case: the activity can handle this new configuration, so
4212 // hand it over. Note that we don't need to give it the new
4213 // configuration, since we always send configuration changes to all
4214 // process when they happen so it can just use whatever configuration
4215 // it last got.
4216 if (r.app != null && r.app.thread != null) {
4217 try {
4218 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004219 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004220 } catch (RemoteException e) {
4221 // If process died, whatever.
4222 }
4223 }
4224 r.stopFreezingScreenLocked(false);
4225
4226 return true;
4227 }
4228
4229 private final boolean relaunchActivityLocked(ActivityRecord r,
4230 int changes, boolean andResume) {
4231 List<ResultInfo> results = null;
4232 List<Intent> newIntents = null;
4233 if (andResume) {
4234 results = r.results;
4235 newIntents = r.newIntents;
4236 }
4237 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4238 + " with results=" + results + " newIntents=" + newIntents
4239 + " andResume=" + andResume);
4240 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
4241 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
4242 r.task.taskId, r.shortComponentName);
4243
4244 r.startFreezingScreenLocked(r.app, 0);
4245
4246 try {
4247 if (DEBUG_SWITCH) Slog.i(TAG, "Switch is restarting resumed " + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004248 r.forceNewConfig = false;
Dianne Hackbornbe707852011-11-11 14:32:10 -08004249 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004250 changes, !andResume, new Configuration(mService.mConfiguration));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004251 // Note: don't need to call pauseIfSleepingLocked() here, because
4252 // the caller will only pass in 'andResume' if this activity is
4253 // currently resumed, which implies we aren't sleeping.
4254 } catch (RemoteException e) {
4255 return false;
4256 }
4257
4258 if (andResume) {
4259 r.results = null;
4260 r.newIntents = null;
4261 if (mMainStack) {
4262 mService.reportResumedActivityLocked(r);
4263 }
4264 }
4265
4266 return true;
4267 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004268
4269 public void dismissKeyguardOnNextActivityLocked() {
4270 mDismissKeyguardOnNextActivity = true;
4271 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004272}