blob: cc58eafe887280ef8ebc5122ec87e19afe7230de [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;
59import android.os.PowerManager;
60import android.os.RemoteException;
61import android.os.SystemClock;
62import android.util.EventLog;
63import android.util.Log;
64import android.util.Slog;
65import android.view.WindowManagerPolicy;
66
67import java.lang.ref.WeakReference;
68import java.util.ArrayList;
69import java.util.Iterator;
70import java.util.List;
71
72/**
73 * State and management of a single stack of activities.
74 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070075final class ActivityStack {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070076 static final String TAG = ActivityManagerService.TAG;
Dianne Hackbornb961cd22011-06-21 12:13:37 -070077 static final boolean localLOGV = ActivityManagerService.localLOGV;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070078 static final boolean DEBUG_SWITCH = ActivityManagerService.DEBUG_SWITCH;
79 static final boolean DEBUG_PAUSE = ActivityManagerService.DEBUG_PAUSE;
80 static final boolean DEBUG_VISBILITY = ActivityManagerService.DEBUG_VISBILITY;
81 static final boolean DEBUG_USER_LEAVING = ActivityManagerService.DEBUG_USER_LEAVING;
82 static final boolean DEBUG_TRANSITION = ActivityManagerService.DEBUG_TRANSITION;
83 static final boolean DEBUG_RESULTS = ActivityManagerService.DEBUG_RESULTS;
84 static final boolean DEBUG_CONFIGURATION = ActivityManagerService.DEBUG_CONFIGURATION;
85 static final boolean DEBUG_TASKS = ActivityManagerService.DEBUG_TASKS;
86
Dianne Hackbornce86ba82011-07-13 19:33:41 -070087 static final boolean DEBUG_STATES = false;
88
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070089 static final boolean VALIDATE_TOKENS = ActivityManagerService.VALIDATE_TOKENS;
90
91 // How long we wait until giving up on the last activity telling us it
92 // is idle.
93 static final int IDLE_TIMEOUT = 10*1000;
94
95 // How long we wait until giving up on the last activity to pause. This
96 // is short because it directly impacts the responsiveness of starting the
97 // next activity.
98 static final int PAUSE_TIMEOUT = 500;
99
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800100 // How long we can hold the sleep wake lock before giving up.
101 static final int SLEEP_TIMEOUT = 5*1000;
102
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700103 // How long we can hold the launch wake lock before giving up.
104 static final int LAUNCH_TIMEOUT = 10*1000;
105
106 // How long we wait until giving up on an activity telling us it has
107 // finished destroying itself.
108 static final int DESTROY_TIMEOUT = 10*1000;
109
110 // How long until we reset a task when the user returns to it. Currently
Dianne Hackborn621e17d2010-11-22 15:59:56 -0800111 // disabled.
112 static final long ACTIVITY_INACTIVE_RESET_TIME = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700113
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700114 // How long between activity launches that we consider safe to not warn
115 // the user about an unexpected activity being launched on top.
116 static final long START_WARN_TIME = 5*1000;
117
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700118 // Set to false to disable the preview that is shown while a new activity
119 // is being started.
120 static final boolean SHOW_APP_STARTING_PREVIEW = true;
121
122 enum ActivityState {
123 INITIALIZING,
124 RESUMED,
125 PAUSING,
126 PAUSED,
127 STOPPING,
128 STOPPED,
129 FINISHING,
130 DESTROYING,
131 DESTROYED
132 }
133
134 final ActivityManagerService mService;
135 final boolean mMainStack;
136
137 final Context mContext;
138
139 /**
140 * The back history of all previous (and possibly still
141 * running) activities. It contains HistoryRecord objects.
142 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700143 final ArrayList<ActivityRecord> mHistory = new ArrayList<ActivityRecord>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700144
145 /**
146 * List of running activities, sorted by recent usage.
147 * The first entry in the list is the least recently used.
148 * It contains HistoryRecord objects.
149 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700150 final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700151
152 /**
153 * List of activities that are waiting for a new activity
154 * to become visible before completing whatever operation they are
155 * supposed to do.
156 */
157 final ArrayList<ActivityRecord> mWaitingVisibleActivities
158 = new ArrayList<ActivityRecord>();
159
160 /**
161 * List of activities that are ready to be stopped, but waiting
162 * for the next activity to settle down before doing so. It contains
163 * HistoryRecord objects.
164 */
165 final ArrayList<ActivityRecord> mStoppingActivities
166 = new ArrayList<ActivityRecord>();
167
168 /**
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800169 * List of activities that are in the process of going to sleep.
170 */
171 final ArrayList<ActivityRecord> mGoingToSleepActivities
172 = new ArrayList<ActivityRecord>();
173
174 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700175 * Animations that for the current transition have requested not to
176 * be considered for the transition animation.
177 */
178 final ArrayList<ActivityRecord> mNoAnimActivities
179 = new ArrayList<ActivityRecord>();
180
181 /**
182 * List of activities that are ready to be finished, but waiting
183 * for the previous activity to settle down before doing so. It contains
184 * HistoryRecord objects.
185 */
186 final ArrayList<ActivityRecord> mFinishingActivities
187 = new ArrayList<ActivityRecord>();
188
189 /**
190 * List of people waiting to find out about the next launched activity.
191 */
192 final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched
193 = new ArrayList<IActivityManager.WaitResult>();
194
195 /**
196 * List of people waiting to find out about the next visible activity.
197 */
198 final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible
199 = new ArrayList<IActivityManager.WaitResult>();
200
201 /**
202 * Set when the system is going to sleep, until we have
203 * successfully paused the current activity and released our wake lock.
204 * At that point the system is allowed to actually sleep.
205 */
206 final PowerManager.WakeLock mGoingToSleep;
207
208 /**
209 * We don't want to allow the device to go to sleep while in the process
210 * of launching an activity. This is primarily to allow alarm intent
211 * receivers to launch an activity and get that to run before the device
212 * goes back to sleep.
213 */
214 final PowerManager.WakeLock mLaunchingActivity;
215
216 /**
217 * When we are in the process of pausing an activity, before starting the
218 * next one, this variable holds the activity that is currently being paused.
219 */
220 ActivityRecord mPausingActivity = null;
221
222 /**
223 * This is the last activity that we put into the paused state. This is
224 * used to determine if we need to do an activity transition while sleeping,
225 * when we normally hold the top activity paused.
226 */
227 ActivityRecord mLastPausedActivity = null;
228
229 /**
230 * Current activity that is resumed, or null if there is none.
231 */
232 ActivityRecord mResumedActivity = null;
233
234 /**
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700235 * This is the last activity that has been started. It is only used to
236 * identify when multiple activities are started at once so that the user
237 * can be warned they may not be in the activity they think they are.
238 */
239 ActivityRecord mLastStartedActivity = null;
240
241 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700242 * Set when we know we are going to be calling updateConfiguration()
243 * soon, so want to skip intermediate config checks.
244 */
245 boolean mConfigWillChange;
246
247 /**
248 * Set to indicate whether to issue an onUserLeaving callback when a
249 * newly launched activity is being brought in front of us.
250 */
251 boolean mUserLeaving = false;
252
253 long mInitialStartTime = 0;
254
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800255 /**
256 * Set when we have taken too long waiting to go to sleep.
257 */
258 boolean mSleepTimeout = false;
259
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800260 int mThumbnailWidth = -1;
261 int mThumbnailHeight = -1;
262
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800263 static final int SLEEP_TIMEOUT_MSG = 8;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700264 static final int PAUSE_TIMEOUT_MSG = 9;
265 static final int IDLE_TIMEOUT_MSG = 10;
266 static final int IDLE_NOW_MSG = 11;
267 static final int LAUNCH_TIMEOUT_MSG = 16;
268 static final int DESTROY_TIMEOUT_MSG = 17;
269 static final int RESUME_TOP_ACTIVITY_MSG = 19;
270
271 final Handler mHandler = new Handler() {
272 //public Handler() {
273 // if (localLOGV) Slog.v(TAG, "Handler started!");
274 //}
275
276 public void handleMessage(Message msg) {
277 switch (msg.what) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800278 case SLEEP_TIMEOUT_MSG: {
279 if (mService.isSleeping()) {
280 Slog.w(TAG, "Sleep timeout! Sleeping now.");
281 mSleepTimeout = true;
282 checkReadyForSleepLocked();
283 }
284 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700285 case PAUSE_TIMEOUT_MSG: {
286 IBinder token = (IBinder)msg.obj;
287 // We don't at this point know if the activity is fullscreen,
288 // so we need to be conservative and assume it isn't.
289 Slog.w(TAG, "Activity pause timeout for " + token);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800290 activityPaused(token, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700291 } break;
292 case IDLE_TIMEOUT_MSG: {
293 if (mService.mDidDexOpt) {
294 mService.mDidDexOpt = false;
295 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
296 nmsg.obj = msg.obj;
297 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
298 return;
299 }
300 // We don't at this point know if the activity is fullscreen,
301 // so we need to be conservative and assume it isn't.
302 IBinder token = (IBinder)msg.obj;
303 Slog.w(TAG, "Activity idle timeout for " + token);
304 activityIdleInternal(token, true, null);
305 } break;
306 case DESTROY_TIMEOUT_MSG: {
307 IBinder token = (IBinder)msg.obj;
308 // We don't at this point know if the activity is fullscreen,
309 // so we need to be conservative and assume it isn't.
310 Slog.w(TAG, "Activity destroy timeout for " + token);
311 activityDestroyed(token);
312 } break;
313 case IDLE_NOW_MSG: {
314 IBinder token = (IBinder)msg.obj;
315 activityIdleInternal(token, false, null);
316 } break;
317 case LAUNCH_TIMEOUT_MSG: {
318 if (mService.mDidDexOpt) {
319 mService.mDidDexOpt = false;
320 Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
321 mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
322 return;
323 }
324 synchronized (mService) {
325 if (mLaunchingActivity.isHeld()) {
326 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
327 mLaunchingActivity.release();
328 }
329 }
330 } break;
331 case RESUME_TOP_ACTIVITY_MSG: {
332 synchronized (mService) {
333 resumeTopActivityLocked(null);
334 }
335 } break;
336 }
337 }
338 };
339
340 ActivityStack(ActivityManagerService service, Context context, boolean mainStack) {
341 mService = service;
342 mContext = context;
343 mMainStack = mainStack;
344 PowerManager pm =
345 (PowerManager)context.getSystemService(Context.POWER_SERVICE);
346 mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
347 mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
348 mLaunchingActivity.setReferenceCounted(false);
349 }
350
351 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
352 int i = mHistory.size()-1;
353 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700354 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700355 if (!r.finishing && r != notTop) {
356 return r;
357 }
358 i--;
359 }
360 return null;
361 }
362
363 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
364 int i = mHistory.size()-1;
365 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700366 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700367 if (!r.finishing && !r.delayedResume && r != notTop) {
368 return r;
369 }
370 i--;
371 }
372 return null;
373 }
374
375 /**
376 * This is a simplified version of topRunningActivityLocked that provides a number of
377 * optional skip-over modes. It is intended for use with the ActivityController hook only.
378 *
379 * @param token If non-null, any history records matching this token will be skipped.
380 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
381 *
382 * @return Returns the HistoryRecord of the next activity on the stack.
383 */
384 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
385 int i = mHistory.size()-1;
386 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700387 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700388 // Note: the taskId check depends on real taskId fields being non-zero
389 if (!r.finishing && (token != r) && (taskId != r.task.taskId)) {
390 return r;
391 }
392 i--;
393 }
394 return null;
395 }
396
397 final int indexOfTokenLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700398 try {
399 ActivityRecord r = (ActivityRecord)token;
400 return mHistory.indexOf(r);
401 } catch (ClassCastException e) {
402 Slog.w(TAG, "Bad activity token: " + token, e);
403 return -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700404 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700405 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700406
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700407 final ActivityRecord isInStackLocked(IBinder token) {
408 try {
409 ActivityRecord r = (ActivityRecord)token;
410 if (mHistory.contains(r)) {
411 return r;
412 }
413 } catch (ClassCastException e) {
414 Slog.w(TAG, "Bad activity token: " + token, e);
415 }
416 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700417 }
418
419 private final boolean updateLRUListLocked(ActivityRecord r) {
420 final boolean hadit = mLRUActivities.remove(r);
421 mLRUActivities.add(r);
422 return hadit;
423 }
424
425 /**
426 * Returns the top activity in any existing task matching the given
427 * Intent. Returns null if no such task is found.
428 */
429 private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
430 ComponentName cls = intent.getComponent();
431 if (info.targetActivity != null) {
432 cls = new ComponentName(info.packageName, info.targetActivity);
433 }
434
435 TaskRecord cp = null;
436
437 final int N = mHistory.size();
438 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700439 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700440 if (!r.finishing && r.task != cp
441 && r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
442 cp = r.task;
443 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
444 // + "/aff=" + r.task.affinity + " to new cls="
445 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
446 if (r.task.affinity != null) {
447 if (r.task.affinity.equals(info.taskAffinity)) {
448 //Slog.i(TAG, "Found matching affinity!");
449 return r;
450 }
451 } else if (r.task.intent != null
452 && r.task.intent.getComponent().equals(cls)) {
453 //Slog.i(TAG, "Found matching class!");
454 //dump();
455 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
456 return r;
457 } else if (r.task.affinityIntent != null
458 && r.task.affinityIntent.getComponent().equals(cls)) {
459 //Slog.i(TAG, "Found matching class!");
460 //dump();
461 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
462 return r;
463 }
464 }
465 }
466
467 return null;
468 }
469
470 /**
471 * Returns the first activity (starting from the top of the stack) that
472 * is the same as the given activity. Returns null if no such activity
473 * is found.
474 */
475 private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
476 ComponentName cls = intent.getComponent();
477 if (info.targetActivity != null) {
478 cls = new ComponentName(info.packageName, info.targetActivity);
479 }
480
481 final int N = mHistory.size();
482 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700483 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700484 if (!r.finishing) {
485 if (r.intent.getComponent().equals(cls)) {
486 //Slog.i(TAG, "Found matching class!");
487 //dump();
488 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
489 return r;
490 }
491 }
492 }
493
494 return null;
495 }
496
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700497 final void showAskCompatModeDialogLocked(ActivityRecord r) {
498 Message msg = Message.obtain();
499 msg.what = ActivityManagerService.SHOW_COMPAT_MODE_DIALOG_MSG;
500 msg.obj = r.task.askedCompatMode ? null : r;
501 mService.mHandler.sendMessage(msg);
502 }
503
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700504 final boolean realStartActivityLocked(ActivityRecord r,
505 ProcessRecord app, boolean andResume, boolean checkConfig)
506 throws RemoteException {
507
508 r.startFreezingScreenLocked(app, 0);
509 mService.mWindowManager.setAppVisibility(r, true);
510
511 // Have the window manager re-evaluate the orientation of
512 // the screen based on the new activity order. Note that
513 // as a result of this, it can call back into the activity
514 // manager with a new orientation. We don't care about that,
515 // because the activity is not currently running so we are
516 // just restarting it anyway.
517 if (checkConfig) {
518 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
519 mService.mConfiguration,
520 r.mayFreezeScreenLocked(app) ? r : null);
Dianne Hackborn31ca8542011-07-19 14:58:28 -0700521 mService.updateConfigurationLocked(config, r, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700522 }
523
524 r.app = app;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700525 app.waitingToKill = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700526
527 if (localLOGV) Slog.v(TAG, "Launching: " + r);
528
529 int idx = app.activities.indexOf(r);
530 if (idx < 0) {
531 app.activities.add(r);
532 }
533 mService.updateLruProcessLocked(app, true, true);
534
535 try {
536 if (app.thread == null) {
537 throw new RemoteException();
538 }
539 List<ResultInfo> results = null;
540 List<Intent> newIntents = null;
541 if (andResume) {
542 results = r.results;
543 newIntents = r.newIntents;
544 }
545 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
546 + " icicle=" + r.icicle
547 + " with results=" + results + " newIntents=" + newIntents
548 + " andResume=" + andResume);
549 if (andResume) {
550 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
551 System.identityHashCode(r),
552 r.task.taskId, r.shortComponentName);
553 }
554 if (r.isHomeActivity) {
555 mService.mHomeProcess = app;
556 }
557 mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800558 r.sleeping = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400559 r.forceNewConfig = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700560 showAskCompatModeDialogLocked(r);
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700561 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -0700562 app.hasShownUi = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700563 app.thread.scheduleLaunchActivity(new Intent(r.intent), r,
564 System.identityHashCode(r),
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700565 r.info, r.compat, r.icicle, results, newIntents, !andResume,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700566 mService.isNextTransitionForward());
567
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700568 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700569 // This may be a heavy-weight process! Note that the package
570 // manager will ensure that only activity can run in the main
571 // process of the .apk, which is the only thing that will be
572 // considered heavy-weight.
573 if (app.processName.equals(app.info.packageName)) {
574 if (mService.mHeavyWeightProcess != null
575 && mService.mHeavyWeightProcess != app) {
576 Log.w(TAG, "Starting new heavy weight process " + app
577 + " when already running "
578 + mService.mHeavyWeightProcess);
579 }
580 mService.mHeavyWeightProcess = app;
581 Message msg = mService.mHandler.obtainMessage(
582 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
583 msg.obj = r;
584 mService.mHandler.sendMessage(msg);
585 }
586 }
587
588 } catch (RemoteException e) {
589 if (r.launchFailed) {
590 // This is the second time we failed -- finish activity
591 // and give up.
592 Slog.e(TAG, "Second failure launching "
593 + r.intent.getComponent().flattenToShortString()
594 + ", giving up", e);
595 mService.appDiedLocked(app, app.pid, app.thread);
596 requestFinishActivityLocked(r, Activity.RESULT_CANCELED, null,
597 "2nd-crash");
598 return false;
599 }
600
601 // This is the first time we failed -- restart process and
602 // retry.
603 app.activities.remove(r);
604 throw e;
605 }
606
607 r.launchFailed = false;
608 if (updateLRUListLocked(r)) {
609 Slog.w(TAG, "Activity " + r
610 + " being launched, but already in LRU list");
611 }
612
613 if (andResume) {
614 // As part of the process of launching, ActivityThread also performs
615 // a resume.
616 r.state = ActivityState.RESUMED;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700617 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
618 + " (starting new instance)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700619 r.stopped = false;
620 mResumedActivity = r;
621 r.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -0800622 if (mMainStack) {
623 mService.addRecentTaskLocked(r.task);
624 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700625 completeResumeLocked(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800626 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700627 } else {
628 // This activity is not starting in the resumed state... which
629 // should look like we asked it to pause+stop (but remain visible),
630 // and it has done so and reported back the current icicle and
631 // other state.
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700632 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
633 + " (starting in stopped state)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700634 r.state = ActivityState.STOPPED;
635 r.stopped = true;
636 }
637
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800638 r.icicle = null;
639 r.haveState = false;
640
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700641 // Launch the new version setup screen if needed. We do this -after-
642 // launching the initial activity (that is, home), so that it can have
643 // a chance to initialize itself while in the background, making the
644 // switch back to it faster and look better.
645 if (mMainStack) {
646 mService.startSetupActivityLocked();
647 }
648
649 return true;
650 }
651
652 private final void startSpecificActivityLocked(ActivityRecord r,
653 boolean andResume, boolean checkConfig) {
654 // Is this activity's application already running?
655 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
656 r.info.applicationInfo.uid);
657
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700658 if (r.launchTime == 0) {
659 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700660 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700661 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700662 }
663 } else if (mInitialStartTime == 0) {
664 mInitialStartTime = SystemClock.uptimeMillis();
665 }
666
667 if (app != null && app.thread != null) {
668 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700669 app.addPackage(r.info.packageName);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700670 realStartActivityLocked(r, app, andResume, checkConfig);
671 return;
672 } catch (RemoteException e) {
673 Slog.w(TAG, "Exception when starting activity "
674 + r.intent.getComponent().flattenToShortString(), e);
675 }
676
677 // If a dead object exception was thrown -- fall through to
678 // restart the application.
679 }
680
681 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
682 "activity", r.intent.getComponent(), false);
683 }
684
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800685 void stopIfSleepingLocked() {
686 if (mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700687 if (!mGoingToSleep.isHeld()) {
688 mGoingToSleep.acquire();
689 if (mLaunchingActivity.isHeld()) {
690 mLaunchingActivity.release();
691 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
692 }
693 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800694 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
695 Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
696 mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
697 checkReadyForSleepLocked();
698 }
699 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700700
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800701 void awakeFromSleepingLocked() {
702 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
703 mSleepTimeout = false;
704 if (mGoingToSleep.isHeld()) {
705 mGoingToSleep.release();
706 }
707 // Ensure activities are no longer sleeping.
708 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700709 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800710 r.setSleeping(false);
711 }
712 mGoingToSleepActivities.clear();
713 }
714
715 void activitySleptLocked(ActivityRecord r) {
716 mGoingToSleepActivities.remove(r);
717 checkReadyForSleepLocked();
718 }
719
720 void checkReadyForSleepLocked() {
721 if (!mService.isSleeping()) {
722 // Do not care.
723 return;
724 }
725
726 if (!mSleepTimeout) {
727 if (mResumedActivity != null) {
728 // Still have something resumed; can't sleep until it is paused.
729 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700730 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
731 startPausingLocked(false, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800732 return;
733 }
734 if (mPausingActivity != null) {
735 // Still waiting for something to pause; can't sleep yet.
736 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
737 return;
738 }
739
740 if (mStoppingActivities.size() > 0) {
741 // Still need to tell some activities to stop; can't sleep yet.
742 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
743 + mStoppingActivities.size() + " activities");
744 Message msg = Message.obtain();
745 msg.what = IDLE_NOW_MSG;
746 mHandler.sendMessage(msg);
747 return;
748 }
749
750 ensureActivitiesVisibleLocked(null, 0);
751
752 // Make sure any stopped but visible activities are now sleeping.
753 // This ensures that the activity's onStop() is called.
754 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700755 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800756 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
757 r.setSleeping(true);
758 }
759 }
760
761 if (mGoingToSleepActivities.size() > 0) {
762 // Still need to tell some activities to sleep; can't sleep yet.
763 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
764 + mGoingToSleepActivities.size() + " activities");
765 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700766 }
767 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800768
769 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
770
771 if (mGoingToSleep.isHeld()) {
772 mGoingToSleep.release();
773 }
774 if (mService.mShuttingDown) {
775 mService.notifyAll();
776 }
777
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700778 }
779
Dianne Hackbornd2835932010-12-13 16:28:46 -0800780 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -0800781 if (who.noDisplay) {
782 return null;
783 }
784
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800785 Resources res = mService.mContext.getResources();
786 int w = mThumbnailWidth;
787 int h = mThumbnailHeight;
788 if (w < 0) {
789 mThumbnailWidth = w =
790 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
791 mThumbnailHeight = h =
792 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
793 }
794
795 if (w > 0) {
Dianne Hackborn7c8a4b32010-12-15 14:58:00 -0800796 return mService.mWindowManager.screenshotApplications(who, w, h);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800797 }
798 return null;
799 }
800
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700801 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
802 if (mPausingActivity != null) {
803 RuntimeException e = new RuntimeException();
804 Slog.e(TAG, "Trying to pause when pause is already pending for "
805 + mPausingActivity, e);
806 }
807 ActivityRecord prev = mResumedActivity;
808 if (prev == null) {
809 RuntimeException e = new RuntimeException();
810 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
811 resumeTopActivityLocked(null);
812 return;
813 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700814 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
815 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700816 mResumedActivity = null;
817 mPausingActivity = prev;
818 mLastPausedActivity = prev;
819 prev.state = ActivityState.PAUSING;
820 prev.task.touchActiveTime();
Dianne Hackbornf26fd992011-04-08 18:14:09 -0700821 prev.updateThumbnail(screenshotActivities(prev), null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700822
823 mService.updateCpuStats();
824
825 if (prev.app != null && prev.app.thread != null) {
826 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
827 try {
828 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
829 System.identityHashCode(prev),
830 prev.shortComponentName);
831 prev.app.thread.schedulePauseActivity(prev, prev.finishing, userLeaving,
832 prev.configChangeFlags);
833 if (mMainStack) {
834 mService.updateUsageStats(prev, false);
835 }
836 } catch (Exception e) {
837 // Ignore exception, if process died other code will cleanup.
838 Slog.w(TAG, "Exception thrown during pause", e);
839 mPausingActivity = null;
840 mLastPausedActivity = null;
841 }
842 } else {
843 mPausingActivity = null;
844 mLastPausedActivity = null;
845 }
846
847 // If we are not going to sleep, we want to ensure the device is
848 // awake until the next activity is started.
849 if (!mService.mSleeping && !mService.mShuttingDown) {
850 mLaunchingActivity.acquire();
851 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
852 // To be safe, don't allow the wake lock to be held for too long.
853 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
854 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
855 }
856 }
857
858
859 if (mPausingActivity != null) {
860 // Have the window manager pause its key dispatching until the new
861 // activity has started. If we're pausing the activity just because
862 // the screen is being turned off and the UI is sleeping, don't interrupt
863 // key dispatch; the same activity will pick it up again on wakeup.
864 if (!uiSleeping) {
865 prev.pauseKeyDispatchingLocked();
866 } else {
867 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
868 }
869
870 // Schedule a pause timeout in case the app doesn't respond.
871 // We don't give it much time because this directly impacts the
872 // responsiveness seen by the user.
873 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
874 msg.obj = prev;
875 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
876 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
877 } else {
878 // This activity failed to schedule the
879 // pause, so just treat it as being paused now.
880 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
881 resumeTopActivityLocked(null);
882 }
883 }
884
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800885 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700886 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800887 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700888
889 ActivityRecord r = null;
890
891 synchronized (mService) {
892 int index = indexOfTokenLocked(token);
893 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700894 r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700895 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
896 if (mPausingActivity == r) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700897 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
898 + (timeout ? " (due to timeout)" : " (pause complete)"));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700899 r.state = ActivityState.PAUSED;
900 completePauseLocked();
901 } else {
902 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
903 System.identityHashCode(r), r.shortComponentName,
904 mPausingActivity != null
905 ? mPausingActivity.shortComponentName : "(none)");
906 }
907 }
908 }
909 }
910
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700911 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
912 CharSequence description) {
913 r.icicle = icicle;
914 r.haveState = true;
915 r.updateThumbnail(thumbnail, description);
916 r.stopped = true;
917 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
918 r.state = ActivityState.STOPPED;
919 if (!r.finishing) {
920 if (r.configDestroy) {
921 destroyActivityLocked(r, true, false);
922 resumeTopActivityLocked(null);
923 }
924 }
925 }
926
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700927 private final void completePauseLocked() {
928 ActivityRecord prev = mPausingActivity;
929 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
930
931 if (prev != null) {
932 if (prev.finishing) {
933 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
934 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE);
935 } else if (prev.app != null) {
936 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
937 if (prev.waitingVisible) {
938 prev.waitingVisible = false;
939 mWaitingVisibleActivities.remove(prev);
940 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
941 TAG, "Complete pause, no longer waiting: " + prev);
942 }
943 if (prev.configDestroy) {
944 // The previous is being paused because the configuration
945 // is changing, which means it is actually stopping...
946 // To juggle the fact that we are also starting a new
947 // instance right now, we need to first completely stop
948 // the current instance before starting the new one.
949 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700950 destroyActivityLocked(prev, true, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700951 } else {
952 mStoppingActivities.add(prev);
953 if (mStoppingActivities.size() > 3) {
954 // If we already have a few activities waiting to stop,
955 // then give up on things going idle and start clearing
956 // them out.
957 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
958 Message msg = Message.obtain();
959 msg.what = IDLE_NOW_MSG;
960 mHandler.sendMessage(msg);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800961 } else {
962 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700963 }
964 }
965 } else {
966 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
967 prev = null;
968 }
969 mPausingActivity = null;
970 }
971
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800972 if (!mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700973 resumeTopActivityLocked(prev);
974 } else {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800975 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700976 }
977
978 if (prev != null) {
979 prev.resumeKeyDispatchingLocked();
980 }
981
982 if (prev.app != null && prev.cpuTimeAtResume > 0
983 && mService.mBatteryStatsService.isOnBattery()) {
984 long diff = 0;
985 synchronized (mService.mProcessStatsThread) {
986 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
987 - prev.cpuTimeAtResume;
988 }
989 if (diff > 0) {
990 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
991 synchronized (bsi) {
992 BatteryStatsImpl.Uid.Proc ps =
993 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
994 prev.info.packageName);
995 if (ps != null) {
996 ps.addForegroundTimeLocked(diff);
997 }
998 }
999 }
1000 }
1001 prev.cpuTimeAtResume = 0; // reset it
1002 }
1003
1004 /**
1005 * Once we know that we have asked an application to put an activity in
1006 * the resumed state (either by launching it or explicitly telling it),
1007 * this function updates the rest of our state to match that fact.
1008 */
1009 private final void completeResumeLocked(ActivityRecord next) {
1010 next.idle = false;
1011 next.results = null;
1012 next.newIntents = null;
1013
1014 // schedule an idle timeout in case the app doesn't do it for us.
1015 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1016 msg.obj = next;
1017 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
1018
1019 if (false) {
1020 // The activity was never told to pause, so just keep
1021 // things going as-is. To maintain our own state,
1022 // we need to emulate it coming back and saying it is
1023 // idle.
1024 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
1025 msg.obj = next;
1026 mHandler.sendMessage(msg);
1027 }
1028
1029 if (mMainStack) {
1030 mService.reportResumedActivityLocked(next);
1031 }
1032
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001033 next.clearThumbnail();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001034 if (mMainStack) {
1035 mService.setFocusedActivityLocked(next);
1036 }
1037 next.resumeKeyDispatchingLocked();
1038 ensureActivitiesVisibleLocked(null, 0);
1039 mService.mWindowManager.executeAppTransition();
1040 mNoAnimActivities.clear();
1041
1042 // Mark the point when the activity is resuming
1043 // TODO: To be more accurate, the mark should be before the onCreate,
1044 // not after the onResume. But for subsequent starts, onResume is fine.
1045 if (next.app != null) {
1046 synchronized (mService.mProcessStatsThread) {
1047 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1048 }
1049 } else {
1050 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1051 }
1052 }
1053
1054 /**
1055 * Make sure that all activities that need to be visible (that is, they
1056 * currently can be seen by the user) actually are.
1057 */
1058 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1059 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1060 if (DEBUG_VISBILITY) Slog.v(
1061 TAG, "ensureActivitiesVisible behind " + top
1062 + " configChanges=0x" + Integer.toHexString(configChanges));
1063
1064 // If the top activity is not fullscreen, then we need to
1065 // make sure any activities under it are now visible.
1066 final int count = mHistory.size();
1067 int i = count-1;
1068 while (mHistory.get(i) != top) {
1069 i--;
1070 }
1071 ActivityRecord r;
1072 boolean behindFullscreen = false;
1073 for (; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001074 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001075 if (DEBUG_VISBILITY) Slog.v(
1076 TAG, "Make visible? " + r + " finishing=" + r.finishing
1077 + " state=" + r.state);
1078 if (r.finishing) {
1079 continue;
1080 }
1081
1082 final boolean doThisProcess = onlyThisProcess == null
1083 || onlyThisProcess.equals(r.processName);
1084
1085 // First: if this is not the current activity being started, make
1086 // sure it matches the current configuration.
1087 if (r != starting && doThisProcess) {
1088 ensureActivityConfigurationLocked(r, 0);
1089 }
1090
1091 if (r.app == null || r.app.thread == null) {
1092 if (onlyThisProcess == null
1093 || onlyThisProcess.equals(r.processName)) {
1094 // This activity needs to be visible, but isn't even
1095 // running... get it started, but don't resume it
1096 // at this point.
1097 if (DEBUG_VISBILITY) Slog.v(
1098 TAG, "Start and freeze screen for " + r);
1099 if (r != starting) {
1100 r.startFreezingScreenLocked(r.app, configChanges);
1101 }
1102 if (!r.visible) {
1103 if (DEBUG_VISBILITY) Slog.v(
1104 TAG, "Starting and making visible: " + r);
1105 mService.mWindowManager.setAppVisibility(r, true);
1106 }
1107 if (r != starting) {
1108 startSpecificActivityLocked(r, false, false);
1109 }
1110 }
1111
1112 } else if (r.visible) {
1113 // If this activity is already visible, then there is nothing
1114 // else to do here.
1115 if (DEBUG_VISBILITY) Slog.v(
1116 TAG, "Skipping: already visible at " + r);
1117 r.stopFreezingScreenLocked(false);
1118
1119 } else if (onlyThisProcess == null) {
1120 // This activity is not currently visible, but is running.
1121 // Tell it to become visible.
1122 r.visible = true;
1123 if (r.state != ActivityState.RESUMED && r != starting) {
1124 // If this activity is paused, tell it
1125 // to now show its window.
1126 if (DEBUG_VISBILITY) Slog.v(
1127 TAG, "Making visible and scheduling visibility: " + r);
1128 try {
1129 mService.mWindowManager.setAppVisibility(r, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001130 r.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001131 r.app.thread.scheduleWindowVisibility(r, true);
1132 r.stopFreezingScreenLocked(false);
1133 } catch (Exception e) {
1134 // Just skip on any failure; we'll make it
1135 // visible when it next restarts.
1136 Slog.w(TAG, "Exception thrown making visibile: "
1137 + r.intent.getComponent(), e);
1138 }
1139 }
1140 }
1141
1142 // Aggregate current change flags.
1143 configChanges |= r.configChangeFlags;
1144
1145 if (r.fullscreen) {
1146 // At this point, nothing else needs to be shown
1147 if (DEBUG_VISBILITY) Slog.v(
1148 TAG, "Stopping: fullscreen at " + r);
1149 behindFullscreen = true;
1150 i--;
1151 break;
1152 }
1153 }
1154
1155 // Now for any activities that aren't visible to the user, make
1156 // sure they no longer are keeping the screen frozen.
1157 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001158 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001159 if (DEBUG_VISBILITY) Slog.v(
1160 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1161 + " state=" + r.state
1162 + " behindFullscreen=" + behindFullscreen);
1163 if (!r.finishing) {
1164 if (behindFullscreen) {
1165 if (r.visible) {
1166 if (DEBUG_VISBILITY) Slog.v(
1167 TAG, "Making invisible: " + r);
1168 r.visible = false;
1169 try {
1170 mService.mWindowManager.setAppVisibility(r, false);
1171 if ((r.state == ActivityState.STOPPING
1172 || r.state == ActivityState.STOPPED)
1173 && r.app != null && r.app.thread != null) {
1174 if (DEBUG_VISBILITY) Slog.v(
1175 TAG, "Scheduling invisibility: " + r);
1176 r.app.thread.scheduleWindowVisibility(r, false);
1177 }
1178 } catch (Exception e) {
1179 // Just skip on any failure; we'll make it
1180 // visible when it next restarts.
1181 Slog.w(TAG, "Exception thrown making hidden: "
1182 + r.intent.getComponent(), e);
1183 }
1184 } else {
1185 if (DEBUG_VISBILITY) Slog.v(
1186 TAG, "Already invisible: " + r);
1187 }
1188 } else if (r.fullscreen) {
1189 if (DEBUG_VISBILITY) Slog.v(
1190 TAG, "Now behindFullscreen: " + r);
1191 behindFullscreen = true;
1192 }
1193 }
1194 i--;
1195 }
1196 }
1197
1198 /**
1199 * Version of ensureActivitiesVisible that can easily be called anywhere.
1200 */
1201 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1202 int configChanges) {
1203 ActivityRecord r = topRunningActivityLocked(null);
1204 if (r != null) {
1205 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1206 }
1207 }
1208
1209 /**
1210 * Ensure that the top activity in the stack is resumed.
1211 *
1212 * @param prev The previously resumed activity, for when in the process
1213 * of pausing; can be null to call from elsewhere.
1214 *
1215 * @return Returns true if something is being resumed, or false if
1216 * nothing happened.
1217 */
1218 final boolean resumeTopActivityLocked(ActivityRecord prev) {
1219 // Find the first activity that is not finishing.
1220 ActivityRecord next = topRunningActivityLocked(null);
1221
1222 // Remember how we'll process this pause/resume situation, and ensure
1223 // that the state is reset however we wind up proceeding.
1224 final boolean userLeaving = mUserLeaving;
1225 mUserLeaving = false;
1226
1227 if (next == null) {
1228 // There are no more activities! Let's just start up the
1229 // Launcher...
1230 if (mMainStack) {
1231 return mService.startHomeActivityLocked();
1232 }
1233 }
1234
1235 next.delayedResume = false;
1236
1237 // If the top activity is the resumed one, nothing to do.
1238 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1239 // Make sure we have executed any pending transitions, since there
1240 // should be nothing left to do at this point.
1241 mService.mWindowManager.executeAppTransition();
1242 mNoAnimActivities.clear();
1243 return false;
1244 }
1245
1246 // If we are sleeping, and there is no resumed activity, and the top
1247 // activity is paused, well that is the state we want.
1248 if ((mService.mSleeping || mService.mShuttingDown)
1249 && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
1250 // Make sure we have executed any pending transitions, since there
1251 // should be nothing left to do at this point.
1252 mService.mWindowManager.executeAppTransition();
1253 mNoAnimActivities.clear();
1254 return false;
1255 }
1256
1257 // The activity may be waiting for stop, but that is no longer
1258 // appropriate for it.
1259 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001260 mGoingToSleepActivities.remove(next);
1261 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001262 mWaitingVisibleActivities.remove(next);
1263
1264 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1265
1266 // If we are currently pausing an activity, then don't do anything
1267 // until that is done.
1268 if (mPausingActivity != null) {
1269 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
1270 return false;
1271 }
1272
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001273 // Okay we are now going to start a switch, to 'next'. We may first
1274 // have to pause the current activity, but this is an important point
1275 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001276 // XXX "App Redirected" dialog is getting too many false positives
1277 // at this point, so turn off for now.
1278 if (false) {
1279 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1280 long now = SystemClock.uptimeMillis();
1281 final boolean inTime = mLastStartedActivity.startTime != 0
1282 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1283 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1284 final int nextUid = next.info.applicationInfo.uid;
1285 if (inTime && lastUid != nextUid
1286 && lastUid != next.launchedFromUid
1287 && mService.checkPermission(
1288 android.Manifest.permission.STOP_APP_SWITCHES,
1289 -1, next.launchedFromUid)
1290 != PackageManager.PERMISSION_GRANTED) {
1291 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1292 } else {
1293 next.startTime = now;
1294 mLastStartedActivity = next;
1295 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001296 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001297 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001298 mLastStartedActivity = next;
1299 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001300 }
1301
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001302 // We need to start pausing the current activity so the top one
1303 // can be resumed...
1304 if (mResumedActivity != null) {
1305 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
1306 startPausingLocked(userLeaving, false);
1307 return true;
1308 }
1309
1310 if (prev != null && prev != next) {
1311 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1312 prev.waitingVisible = true;
1313 mWaitingVisibleActivities.add(prev);
1314 if (DEBUG_SWITCH) Slog.v(
1315 TAG, "Resuming top, waiting visible to hide: " + prev);
1316 } else {
1317 // The next activity is already visible, so hide the previous
1318 // activity's windows right now so we can show the new one ASAP.
1319 // We only do this if the previous is finishing, which should mean
1320 // it is on top of the one being resumed so hiding it quickly
1321 // is good. Otherwise, we want to do the normal route of allowing
1322 // the resumed activity to be shown so we can decide if the
1323 // previous should actually be hidden depending on whether the
1324 // new one is found to be full-screen or not.
1325 if (prev.finishing) {
1326 mService.mWindowManager.setAppVisibility(prev, false);
1327 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1328 + prev + ", waitingVisible="
1329 + (prev != null ? prev.waitingVisible : null)
1330 + ", nowVisible=" + next.nowVisible);
1331 } else {
1332 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1333 + prev + ", waitingVisible="
1334 + (prev != null ? prev.waitingVisible : null)
1335 + ", nowVisible=" + next.nowVisible);
1336 }
1337 }
1338 }
1339
Dianne Hackborne7f97212011-02-24 14:40:20 -08001340 // Launching this app's activity, make sure the app is no longer
1341 // considered stopped.
1342 try {
1343 AppGlobals.getPackageManager().setPackageStoppedState(
1344 next.packageName, false);
1345 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001346 } catch (IllegalArgumentException e) {
1347 Slog.w(TAG, "Failed trying to unstop package "
1348 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001349 }
1350
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001351 // We are starting up the next activity, so tell the window manager
1352 // that the previous one will be hidden soon. This way it can know
1353 // to ignore it when computing the desired screen orientation.
1354 if (prev != null) {
1355 if (prev.finishing) {
1356 if (DEBUG_TRANSITION) Slog.v(TAG,
1357 "Prepare close transition: prev=" + prev);
1358 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001359 mService.mWindowManager.prepareAppTransition(
1360 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001361 } else {
1362 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1363 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001364 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001365 }
1366 mService.mWindowManager.setAppWillBeHidden(prev);
1367 mService.mWindowManager.setAppVisibility(prev, false);
1368 } else {
1369 if (DEBUG_TRANSITION) Slog.v(TAG,
1370 "Prepare open transition: prev=" + prev);
1371 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001372 mService.mWindowManager.prepareAppTransition(
1373 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001374 } else {
1375 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1376 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001377 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001378 }
1379 }
1380 if (false) {
1381 mService.mWindowManager.setAppWillBeHidden(prev);
1382 mService.mWindowManager.setAppVisibility(prev, false);
1383 }
1384 } else if (mHistory.size() > 1) {
1385 if (DEBUG_TRANSITION) Slog.v(TAG,
1386 "Prepare open transition: no previous");
1387 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001388 mService.mWindowManager.prepareAppTransition(
1389 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001390 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001391 mService.mWindowManager.prepareAppTransition(
1392 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001393 }
1394 }
1395
1396 if (next.app != null && next.app.thread != null) {
1397 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1398
1399 // This activity is now becoming visible.
1400 mService.mWindowManager.setAppVisibility(next, true);
1401
1402 ActivityRecord lastResumedActivity = mResumedActivity;
1403 ActivityState lastState = next.state;
1404
1405 mService.updateCpuStats();
1406
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001407 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001408 next.state = ActivityState.RESUMED;
1409 mResumedActivity = next;
1410 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001411 if (mMainStack) {
1412 mService.addRecentTaskLocked(next.task);
1413 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001414 mService.updateLruProcessLocked(next.app, true, true);
1415 updateLRUListLocked(next);
1416
1417 // Have the window manager re-evaluate the orientation of
1418 // the screen based on the new activity order.
1419 boolean updated = false;
1420 if (mMainStack) {
1421 synchronized (mService) {
1422 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1423 mService.mConfiguration,
1424 next.mayFreezeScreenLocked(next.app) ? next : null);
1425 if (config != null) {
1426 next.frozenBeforeDestroy = true;
1427 }
Dianne Hackborn31ca8542011-07-19 14:58:28 -07001428 updated = mService.updateConfigurationLocked(config, next, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001429 }
1430 }
1431 if (!updated) {
1432 // The configuration update wasn't able to keep the existing
1433 // instance of the activity, and instead started a new one.
1434 // We should be all done, but let's just make sure our activity
1435 // is still at the top and schedule another run if something
1436 // weird happened.
1437 ActivityRecord nextNext = topRunningActivityLocked(null);
1438 if (DEBUG_SWITCH) Slog.i(TAG,
1439 "Activity config changed during resume: " + next
1440 + ", new next: " + nextNext);
1441 if (nextNext != next) {
1442 // Do over!
1443 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1444 }
1445 if (mMainStack) {
1446 mService.setFocusedActivityLocked(next);
1447 }
1448 ensureActivitiesVisibleLocked(null, 0);
1449 mService.mWindowManager.executeAppTransition();
1450 mNoAnimActivities.clear();
1451 return true;
1452 }
1453
1454 try {
1455 // Deliver all pending results.
1456 ArrayList a = next.results;
1457 if (a != null) {
1458 final int N = a.size();
1459 if (!next.finishing && N > 0) {
1460 if (DEBUG_RESULTS) Slog.v(
1461 TAG, "Delivering results to " + next
1462 + ": " + a);
1463 next.app.thread.scheduleSendResult(next, a);
1464 }
1465 }
1466
1467 if (next.newIntents != null) {
1468 next.app.thread.scheduleNewIntent(next.newIntents, next);
1469 }
1470
1471 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
1472 System.identityHashCode(next),
1473 next.task.taskId, next.shortComponentName);
1474
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001475 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001476 showAskCompatModeDialogLocked(next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001477 next.app.thread.scheduleResumeActivity(next,
1478 mService.isNextTransitionForward());
1479
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001480 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001481
1482 } catch (Exception e) {
1483 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001484 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1485 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001486 next.state = lastState;
1487 mResumedActivity = lastResumedActivity;
1488 Slog.i(TAG, "Restarting because process died: " + next);
1489 if (!next.hasBeenLaunched) {
1490 next.hasBeenLaunched = true;
1491 } else {
1492 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1493 mService.mWindowManager.setAppStartingWindow(
1494 next, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001495 mService.compatibilityInfoForPackageLocked(
1496 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001497 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001498 next.labelRes, next.icon, next.windowFlags,
1499 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001500 }
1501 }
1502 startSpecificActivityLocked(next, true, false);
1503 return true;
1504 }
1505
1506 // From this point on, if something goes wrong there is no way
1507 // to recover the activity.
1508 try {
1509 next.visible = true;
1510 completeResumeLocked(next);
1511 } catch (Exception e) {
1512 // If any exception gets thrown, toss away this
1513 // activity and try the next one.
1514 Slog.w(TAG, "Exception thrown during resume of " + next, e);
1515 requestFinishActivityLocked(next, Activity.RESULT_CANCELED, null,
1516 "resume-exception");
1517 return true;
1518 }
1519
1520 // Didn't need to use the icicle, and it is now out of date.
1521 next.icicle = null;
1522 next.haveState = false;
1523 next.stopped = false;
1524
1525 } else {
1526 // Whoops, need to restart this activity!
1527 if (!next.hasBeenLaunched) {
1528 next.hasBeenLaunched = true;
1529 } else {
1530 if (SHOW_APP_STARTING_PREVIEW) {
1531 mService.mWindowManager.setAppStartingWindow(
1532 next, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001533 mService.compatibilityInfoForPackageLocked(
1534 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001535 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001536 next.labelRes, next.icon, next.windowFlags,
1537 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001538 }
1539 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1540 }
1541 startSpecificActivityLocked(next, true, true);
1542 }
1543
1544 return true;
1545 }
1546
1547 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001548 boolean doResume, boolean keepCurTransition) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001549 final int NH = mHistory.size();
1550
1551 int addPos = -1;
1552
1553 if (!newTask) {
1554 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001555 boolean startIt = true;
1556 for (int i = NH-1; i >= 0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001557 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001558 if (p.finishing) {
1559 continue;
1560 }
1561 if (p.task == r.task) {
1562 // Here it is! Now, if this is not yet visible to the
1563 // user, then just add it without starting; it will
1564 // get started when the user navigates back to it.
1565 addPos = i+1;
1566 if (!startIt) {
1567 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001568 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001569 mService.mWindowManager.addAppToken(addPos, r, r.task.taskId,
1570 r.info.screenOrientation, r.fullscreen);
1571 if (VALIDATE_TOKENS) {
1572 mService.mWindowManager.validateAppTokens(mHistory);
1573 }
1574 return;
1575 }
1576 break;
1577 }
1578 if (p.fullscreen) {
1579 startIt = false;
1580 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001581 }
1582 }
1583
1584 // Place a new activity at top of stack, so it is next to interact
1585 // with the user.
1586 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001587 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001588 }
1589
1590 // If we are not placing the new activity frontmost, we do not want
1591 // to deliver the onUserLeaving callback to the actual frontmost
1592 // activity
1593 if (addPos < NH) {
1594 mUserLeaving = false;
1595 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1596 }
1597
1598 // Slot the activity into the history stack and proceed
1599 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001600 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001601 r.frontOfTask = newTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001602 if (NH > 0) {
1603 // We want to show the starting preview window if we are
1604 // switching to a new task, or the next activity's process is
1605 // not currently running.
1606 boolean showStartingIcon = newTask;
1607 ProcessRecord proc = r.app;
1608 if (proc == null) {
1609 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1610 }
1611 if (proc == null || proc.thread == null) {
1612 showStartingIcon = true;
1613 }
1614 if (DEBUG_TRANSITION) Slog.v(TAG,
1615 "Prepare open transition: starting " + r);
1616 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001617 mService.mWindowManager.prepareAppTransition(
1618 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001619 mNoAnimActivities.add(r);
1620 } else if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
1621 mService.mWindowManager.prepareAppTransition(
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001622 WindowManagerPolicy.TRANSIT_TASK_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001623 mNoAnimActivities.remove(r);
1624 } else {
1625 mService.mWindowManager.prepareAppTransition(newTask
1626 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001627 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001628 mNoAnimActivities.remove(r);
1629 }
1630 mService.mWindowManager.addAppToken(
1631 addPos, r, r.task.taskId, r.info.screenOrientation, r.fullscreen);
1632 boolean doShow = true;
1633 if (newTask) {
1634 // Even though this activity is starting fresh, we still need
1635 // to reset it to make sure we apply affinities to move any
1636 // existing activities from other tasks in to it.
1637 // If the caller has requested that the target task be
1638 // reset, then do so.
1639 if ((r.intent.getFlags()
1640 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1641 resetTaskIfNeededLocked(r, r);
1642 doShow = topRunningNonDelayedActivityLocked(null) == r;
1643 }
1644 }
1645 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1646 // Figure out if we are transitioning from another activity that is
1647 // "has the same starting icon" as the next one. This allows the
1648 // window manager to keep the previous window it had previously
1649 // created, if it still had one.
1650 ActivityRecord prev = mResumedActivity;
1651 if (prev != null) {
1652 // We don't want to reuse the previous starting preview if:
1653 // (1) The current activity is in a different task.
1654 if (prev.task != r.task) prev = null;
1655 // (2) The current activity is already displayed.
1656 else if (prev.nowVisible) prev = null;
1657 }
1658 mService.mWindowManager.setAppStartingWindow(
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001659 r, r.packageName, r.theme,
1660 mService.compatibilityInfoForPackageLocked(
1661 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001662 r.labelRes, r.icon, r.windowFlags, prev, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001663 }
1664 } else {
1665 // If this is the first activity, don't do any fancy animations,
1666 // because there is nothing for it to animate on top of.
1667 mService.mWindowManager.addAppToken(addPos, r, r.task.taskId,
1668 r.info.screenOrientation, r.fullscreen);
1669 }
1670 if (VALIDATE_TOKENS) {
1671 mService.mWindowManager.validateAppTokens(mHistory);
1672 }
1673
1674 if (doResume) {
1675 resumeTopActivityLocked(null);
1676 }
1677 }
1678
1679 /**
1680 * Perform a reset of the given task, if needed as part of launching it.
1681 * Returns the new HistoryRecord at the top of the task.
1682 */
1683 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1684 ActivityRecord newActivity) {
1685 boolean forceReset = (newActivity.info.flags
1686 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001687 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1688 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001689 if ((newActivity.info.flags
1690 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1691 forceReset = true;
1692 }
1693 }
1694
1695 final TaskRecord task = taskTop.task;
1696
1697 // We are going to move through the history list so that we can look
1698 // at each activity 'target' with 'below' either the interesting
1699 // activity immediately below it in the stack or null.
1700 ActivityRecord target = null;
1701 int targetI = 0;
1702 int taskTopI = -1;
1703 int replyChainEnd = -1;
1704 int lastReparentPos = -1;
1705 for (int i=mHistory.size()-1; i>=-1; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001706 ActivityRecord below = i >= 0 ? mHistory.get(i) : null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001707
1708 if (below != null && below.finishing) {
1709 continue;
1710 }
1711 if (target == null) {
1712 target = below;
1713 targetI = i;
1714 // If we were in the middle of a reply chain before this
1715 // task, it doesn't appear like the root of the chain wants
1716 // anything interesting, so drop it.
1717 replyChainEnd = -1;
1718 continue;
1719 }
1720
1721 final int flags = target.info.flags;
1722
1723 final boolean finishOnTaskLaunch =
1724 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1725 final boolean allowTaskReparenting =
1726 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1727
1728 if (target.task == task) {
1729 // We are inside of the task being reset... we'll either
1730 // finish this activity, push it out for another task,
1731 // or leave it as-is. We only do this
1732 // for activities that are not the root of the task (since
1733 // if we finish the root, we may no longer have the task!).
1734 if (taskTopI < 0) {
1735 taskTopI = targetI;
1736 }
1737 if (below != null && below.task == task) {
1738 final boolean clearWhenTaskReset =
1739 (target.intent.getFlags()
1740 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
1741 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
1742 // If this activity is sending a reply to a previous
1743 // activity, we can't do anything with it now until
1744 // we reach the start of the reply chain.
1745 // XXX note that we are assuming the result is always
1746 // to the previous activity, which is almost always
1747 // the case but we really shouldn't count on.
1748 if (replyChainEnd < 0) {
1749 replyChainEnd = targetI;
1750 }
1751 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
1752 && target.taskAffinity != null
1753 && !target.taskAffinity.equals(task.affinity)) {
1754 // If this activity has an affinity for another
1755 // task, then we need to move it out of here. We will
1756 // move it as far out of the way as possible, to the
1757 // bottom of the activity stack. This also keeps it
1758 // correctly ordered with any activities we previously
1759 // moved.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001760 ActivityRecord p = mHistory.get(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001761 if (target.taskAffinity != null
1762 && target.taskAffinity.equals(p.task.affinity)) {
1763 // If the activity currently at the bottom has the
1764 // same task affinity as the one we are moving,
1765 // then merge it into the same task.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001766 target.setTask(p.task, p.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001767 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1768 + " out to bottom task " + p.task);
1769 } else {
1770 mService.mCurTask++;
1771 if (mService.mCurTask <= 0) {
1772 mService.mCurTask = 1;
1773 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001774 target.setTask(new TaskRecord(mService.mCurTask, target.info, null),
1775 null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001776 target.task.affinityIntent = target.intent;
1777 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1778 + " out to new task " + target.task);
1779 }
1780 mService.mWindowManager.setAppGroupId(target, task.taskId);
1781 if (replyChainEnd < 0) {
1782 replyChainEnd = targetI;
1783 }
1784 int dstPos = 0;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001785 ThumbnailHolder curThumbHolder = target.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001786 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001787 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001788 if (p.finishing) {
1789 continue;
1790 }
1791 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
1792 + " out to target's task " + target.task);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001793 p.setTask(target.task, curThumbHolder, false);
1794 curThumbHolder = p.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001795 mHistory.remove(srcPos);
1796 mHistory.add(dstPos, p);
1797 mService.mWindowManager.moveAppToken(dstPos, p);
1798 mService.mWindowManager.setAppGroupId(p, p.task.taskId);
1799 dstPos++;
1800 if (VALIDATE_TOKENS) {
1801 mService.mWindowManager.validateAppTokens(mHistory);
1802 }
1803 i++;
1804 }
1805 if (taskTop == p) {
1806 taskTop = below;
1807 }
1808 if (taskTopI == replyChainEnd) {
1809 taskTopI = -1;
1810 }
1811 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001812 } else if (forceReset || finishOnTaskLaunch
1813 || clearWhenTaskReset) {
1814 // If the activity should just be removed -- either
1815 // because it asks for it, or the task should be
1816 // cleared -- then finish it and anything that is
1817 // part of its reply chain.
1818 if (clearWhenTaskReset) {
1819 // In this case, we want to finish this activity
1820 // and everything above it, so be sneaky and pretend
1821 // like these are all in the reply chain.
1822 replyChainEnd = targetI+1;
1823 while (replyChainEnd < mHistory.size() &&
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001824 (mHistory.get(
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001825 replyChainEnd)).task == task) {
1826 replyChainEnd++;
1827 }
1828 replyChainEnd--;
1829 } else if (replyChainEnd < 0) {
1830 replyChainEnd = targetI;
1831 }
1832 ActivityRecord p = null;
1833 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001834 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001835 if (p.finishing) {
1836 continue;
1837 }
1838 if (finishActivityLocked(p, srcPos,
1839 Activity.RESULT_CANCELED, null, "reset")) {
1840 replyChainEnd--;
1841 srcPos--;
1842 }
1843 }
1844 if (taskTop == p) {
1845 taskTop = below;
1846 }
1847 if (taskTopI == replyChainEnd) {
1848 taskTopI = -1;
1849 }
1850 replyChainEnd = -1;
1851 } else {
1852 // If we were in the middle of a chain, well the
1853 // activity that started it all doesn't want anything
1854 // special, so leave it all as-is.
1855 replyChainEnd = -1;
1856 }
1857 } else {
1858 // Reached the bottom of the task -- any reply chain
1859 // should be left as-is.
1860 replyChainEnd = -1;
1861 }
1862
1863 } else if (target.resultTo != null) {
1864 // If this activity is sending a reply to a previous
1865 // activity, we can't do anything with it now until
1866 // we reach the start of the reply chain.
1867 // XXX note that we are assuming the result is always
1868 // to the previous activity, which is almost always
1869 // the case but we really shouldn't count on.
1870 if (replyChainEnd < 0) {
1871 replyChainEnd = targetI;
1872 }
1873
1874 } else if (taskTopI >= 0 && allowTaskReparenting
1875 && task.affinity != null
1876 && task.affinity.equals(target.taskAffinity)) {
1877 // We are inside of another task... if this activity has
1878 // an affinity for our task, then either remove it if we are
1879 // clearing or move it over to our task. Note that
1880 // we currently punt on the case where we are resetting a
1881 // task that is not at the top but who has activities above
1882 // with an affinity to it... this is really not a normal
1883 // case, and we will need to later pull that task to the front
1884 // and usually at that point we will do the reset and pick
1885 // up those remaining activities. (This only happens if
1886 // someone starts an activity in a new task from an activity
1887 // in a task that is not currently on top.)
1888 if (forceReset || finishOnTaskLaunch) {
1889 if (replyChainEnd < 0) {
1890 replyChainEnd = targetI;
1891 }
1892 ActivityRecord p = null;
1893 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001894 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001895 if (p.finishing) {
1896 continue;
1897 }
1898 if (finishActivityLocked(p, srcPos,
1899 Activity.RESULT_CANCELED, null, "reset")) {
1900 taskTopI--;
1901 lastReparentPos--;
1902 replyChainEnd--;
1903 srcPos--;
1904 }
1905 }
1906 replyChainEnd = -1;
1907 } else {
1908 if (replyChainEnd < 0) {
1909 replyChainEnd = targetI;
1910 }
1911 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001912 ActivityRecord p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001913 if (p.finishing) {
1914 continue;
1915 }
1916 if (lastReparentPos < 0) {
1917 lastReparentPos = taskTopI;
1918 taskTop = p;
1919 } else {
1920 lastReparentPos--;
1921 }
1922 mHistory.remove(srcPos);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001923 p.setTask(task, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001924 mHistory.add(lastReparentPos, p);
1925 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
1926 + " in to resetting task " + task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001927 mService.mWindowManager.moveAppToken(lastReparentPos, p);
1928 mService.mWindowManager.setAppGroupId(p, p.task.taskId);
1929 if (VALIDATE_TOKENS) {
1930 mService.mWindowManager.validateAppTokens(mHistory);
1931 }
1932 }
1933 replyChainEnd = -1;
1934
1935 // Now we've moved it in to place... but what if this is
1936 // a singleTop activity and we have put it on top of another
1937 // instance of the same activity? Then we drop the instance
1938 // below so it remains singleTop.
1939 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
1940 for (int j=lastReparentPos-1; j>=0; j--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001941 ActivityRecord p = mHistory.get(j);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001942 if (p.finishing) {
1943 continue;
1944 }
1945 if (p.intent.getComponent().equals(target.intent.getComponent())) {
1946 if (finishActivityLocked(p, j,
1947 Activity.RESULT_CANCELED, null, "replace")) {
1948 taskTopI--;
1949 lastReparentPos--;
1950 }
1951 }
1952 }
1953 }
1954 }
1955 }
1956
1957 target = below;
1958 targetI = i;
1959 }
1960
1961 return taskTop;
1962 }
1963
1964 /**
1965 * Perform clear operation as requested by
1966 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
1967 * stack to the given task, then look for
1968 * an instance of that activity in the stack and, if found, finish all
1969 * activities on top of it and return the instance.
1970 *
1971 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001972 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001973 * or null if none was found.
1974 */
1975 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001976 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001977 int i = mHistory.size();
1978
1979 // First find the requested task.
1980 while (i > 0) {
1981 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001982 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001983 if (r.task.taskId == taskId) {
1984 i++;
1985 break;
1986 }
1987 }
1988
1989 // Now clear it.
1990 while (i > 0) {
1991 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001992 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001993 if (r.finishing) {
1994 continue;
1995 }
1996 if (r.task.taskId != taskId) {
1997 return null;
1998 }
1999 if (r.realActivity.equals(newR.realActivity)) {
2000 // Here it is! Now finish everything in front...
2001 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002002 while (i < (mHistory.size()-1)) {
2003 i++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002004 r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002005 if (r.task.taskId != taskId) {
2006 break;
2007 }
2008 if (r.finishing) {
2009 continue;
2010 }
2011 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2012 null, "clear")) {
2013 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002014 }
2015 }
2016
2017 // Finally, if this is a normal launch mode (that is, not
2018 // expecting onNewIntent()), then we will finish the current
2019 // instance of the activity so a new fresh one can be started.
2020 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2021 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
2022 if (!ret.finishing) {
2023 int index = indexOfTokenLocked(ret);
2024 if (index >= 0) {
2025 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
2026 null, "clear");
2027 }
2028 return null;
2029 }
2030 }
2031
2032 return ret;
2033 }
2034 }
2035
2036 return null;
2037 }
2038
2039 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002040 * Completely remove all activities associated with an existing
2041 * task starting at a specified index.
2042 */
2043 private final void performClearTaskAtIndexLocked(int taskId, int i) {
2044 while (i < (mHistory.size()-1)) {
2045 ActivityRecord r = mHistory.get(i);
2046 if (r.task.taskId != taskId) {
2047 // Whoops hit the end.
2048 return;
2049 }
2050 if (r.finishing) {
2051 i++;
2052 continue;
2053 }
2054 if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2055 null, "clear")) {
2056 i++;
2057 }
2058 }
2059 }
2060
2061 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002062 * Completely remove all activities associated with an existing task.
2063 */
2064 private final void performClearTaskLocked(int taskId) {
2065 int i = mHistory.size();
2066
2067 // First find the requested task.
2068 while (i > 0) {
2069 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002070 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002071 if (r.task.taskId == taskId) {
2072 i++;
2073 break;
2074 }
2075 }
2076
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002077 // Now find the start and clear it.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002078 while (i > 0) {
2079 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002080 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002081 if (r.finishing) {
2082 continue;
2083 }
2084 if (r.task.taskId != taskId) {
2085 // We hit the bottom. Now finish it all...
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002086 performClearTaskAtIndexLocked(taskId, i+1);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002087 return;
2088 }
2089 }
2090 }
2091
2092 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002093 * Find the activity in the history stack within the given task. Returns
2094 * the index within the history at which it's found, or < 0 if not found.
2095 */
2096 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2097 int i = mHistory.size();
2098 while (i > 0) {
2099 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002100 ActivityRecord candidate = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002101 if (candidate.task.taskId != task) {
2102 break;
2103 }
2104 if (candidate.realActivity.equals(r.realActivity)) {
2105 return i;
2106 }
2107 }
2108
2109 return -1;
2110 }
2111
2112 /**
2113 * Reorder the history stack so that the activity at the given index is
2114 * brought to the front.
2115 */
2116 private final ActivityRecord moveActivityToFrontLocked(int where) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002117 ActivityRecord newTop = mHistory.remove(where);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002118 int top = mHistory.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002119 ActivityRecord oldTop = mHistory.get(top-1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002120 mHistory.add(top, newTop);
2121 oldTop.frontOfTask = false;
2122 newTop.frontOfTask = true;
2123 return newTop;
2124 }
2125
2126 final int startActivityLocked(IApplicationThread caller,
2127 Intent intent, String resolvedType,
2128 Uri[] grantedUriPermissions,
2129 int grantedMode, ActivityInfo aInfo, IBinder resultTo,
2130 String resultWho, int requestCode,
2131 int callingPid, int callingUid, boolean onlyIfNeeded,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002132 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002133
2134 int err = START_SUCCESS;
2135
2136 ProcessRecord callerApp = null;
2137 if (caller != null) {
2138 callerApp = mService.getRecordForAppLocked(caller);
2139 if (callerApp != null) {
2140 callingPid = callerApp.pid;
2141 callingUid = callerApp.info.uid;
2142 } else {
2143 Slog.w(TAG, "Unable to find app for caller " + caller
2144 + " (pid=" + callingPid + ") when starting: "
2145 + intent.toString());
2146 err = START_PERMISSION_DENIED;
2147 }
2148 }
2149
2150 if (err == START_SUCCESS) {
2151 Slog.i(TAG, "Starting: " + intent + " from pid "
2152 + (callerApp != null ? callerApp.pid : callingPid));
2153 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002154
2155 ActivityRecord sourceRecord = null;
2156 ActivityRecord resultRecord = null;
2157 if (resultTo != null) {
2158 int index = indexOfTokenLocked(resultTo);
2159 if (DEBUG_RESULTS) Slog.v(
2160 TAG, "Sending result to " + resultTo + " (index " + index + ")");
2161 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002162 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002163 if (requestCode >= 0 && !sourceRecord.finishing) {
2164 resultRecord = sourceRecord;
2165 }
2166 }
2167 }
2168
2169 int launchFlags = intent.getFlags();
2170
2171 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2172 && sourceRecord != null) {
2173 // Transfer the result target from the source activity to the new
2174 // one being started, including any failures.
2175 if (requestCode >= 0) {
2176 return START_FORWARD_AND_REQUEST_CONFLICT;
2177 }
2178 resultRecord = sourceRecord.resultTo;
2179 resultWho = sourceRecord.resultWho;
2180 requestCode = sourceRecord.requestCode;
2181 sourceRecord.resultTo = null;
2182 if (resultRecord != null) {
2183 resultRecord.removeResultsLocked(
2184 sourceRecord, resultWho, requestCode);
2185 }
2186 }
2187
Dianne Hackbornefb58102010-10-14 16:47:34 -07002188 if (err == START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002189 // We couldn't find a class that can handle the given Intent.
2190 // That's the end of that!
2191 err = START_INTENT_NOT_RESOLVED;
2192 }
2193
2194 if (err == START_SUCCESS && aInfo == null) {
2195 // We couldn't find the specific class specified in the Intent.
2196 // Also the end of the line.
2197 err = START_CLASS_NOT_FOUND;
2198 }
2199
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002200 if (err != START_SUCCESS) {
2201 if (resultRecord != null) {
2202 sendActivityResultLocked(-1,
2203 resultRecord, resultWho, requestCode,
2204 Activity.RESULT_CANCELED, null);
2205 }
2206 return err;
2207 }
2208
2209 final int perm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002210 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002211 if (perm != PackageManager.PERMISSION_GRANTED) {
2212 if (resultRecord != null) {
2213 sendActivityResultLocked(-1,
2214 resultRecord, resultWho, requestCode,
2215 Activity.RESULT_CANCELED, null);
2216 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002217 String msg;
2218 if (!aInfo.exported) {
2219 msg = "Permission Denial: starting " + intent.toString()
2220 + " from " + callerApp + " (pid=" + callingPid
2221 + ", uid=" + callingUid + ")"
2222 + " not exported from uid " + aInfo.applicationInfo.uid;
2223 } else {
2224 msg = "Permission Denial: starting " + intent.toString()
2225 + " from " + callerApp + " (pid=" + callingPid
2226 + ", uid=" + callingUid + ")"
2227 + " requires " + aInfo.permission;
2228 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002229 Slog.w(TAG, msg);
2230 throw new SecurityException(msg);
2231 }
2232
2233 if (mMainStack) {
2234 if (mService.mController != null) {
2235 boolean abort = false;
2236 try {
2237 // The Intent we give to the watcher has the extra data
2238 // stripped off, since it can contain private information.
2239 Intent watchIntent = intent.cloneFilter();
2240 abort = !mService.mController.activityStarting(watchIntent,
2241 aInfo.applicationInfo.packageName);
2242 } catch (RemoteException e) {
2243 mService.mController = null;
2244 }
2245
2246 if (abort) {
2247 if (resultRecord != null) {
2248 sendActivityResultLocked(-1,
2249 resultRecord, resultWho, requestCode,
2250 Activity.RESULT_CANCELED, null);
2251 }
2252 // We pretend to the caller that it was really started, but
2253 // they will just get a cancel result.
2254 return START_SUCCESS;
2255 }
2256 }
2257 }
2258
2259 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2260 intent, resolvedType, aInfo, mService.mConfiguration,
2261 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002262 if (outActivity != null) {
2263 outActivity[0] = r;
2264 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002265
2266 if (mMainStack) {
2267 if (mResumedActivity == null
2268 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2269 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2270 PendingActivityLaunch pal = new PendingActivityLaunch();
2271 pal.r = r;
2272 pal.sourceRecord = sourceRecord;
2273 pal.grantedUriPermissions = grantedUriPermissions;
2274 pal.grantedMode = grantedMode;
2275 pal.onlyIfNeeded = onlyIfNeeded;
2276 mService.mPendingActivityLaunches.add(pal);
2277 return START_SWITCHES_CANCELED;
2278 }
2279 }
2280
2281 if (mService.mDidAppSwitch) {
2282 // This is the second allowed switch since we stopped switches,
2283 // so now just generally allow switches. Use case: user presses
2284 // home (switches disabled, switch to home, mDidAppSwitch now true);
2285 // user taps a home icon (coming from home so allowed, we hit here
2286 // and now allow anyone to switch again).
2287 mService.mAppSwitchesAllowedTime = 0;
2288 } else {
2289 mService.mDidAppSwitch = true;
2290 }
2291
2292 mService.doPendingActivityLaunchesLocked(false);
2293 }
2294
2295 return startActivityUncheckedLocked(r, sourceRecord,
2296 grantedUriPermissions, grantedMode, onlyIfNeeded, true);
2297 }
2298
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002299 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2300 if ((launchFlags &
2301 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2302 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2303 // Caller wants to appear on home activity, so before starting
2304 // their own activity we will bring home to the front.
2305 moveHomeToFrontLocked();
2306 }
2307 }
2308
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002309 final int startActivityUncheckedLocked(ActivityRecord r,
2310 ActivityRecord sourceRecord, Uri[] grantedUriPermissions,
2311 int grantedMode, boolean onlyIfNeeded, boolean doResume) {
2312 final Intent intent = r.intent;
2313 final int callingUid = r.launchedFromUid;
2314
2315 int launchFlags = intent.getFlags();
2316
2317 // We'll invoke onUserLeaving before onPause only if the launching
2318 // activity did not explicitly state that this is an automated launch.
2319 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2320 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2321 "startActivity() => mUserLeaving=" + mUserLeaving);
2322
2323 // If the caller has asked not to resume at this point, we make note
2324 // of this in the record so that we can skip it when trying to find
2325 // the top running activity.
2326 if (!doResume) {
2327 r.delayedResume = true;
2328 }
2329
2330 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2331 != 0 ? r : null;
2332
2333 // If the onlyIfNeeded flag is set, then we can do this if the activity
2334 // being launched is the same as the one making the call... or, as
2335 // a special case, if we do not know the caller then we count the
2336 // current top activity as the caller.
2337 if (onlyIfNeeded) {
2338 ActivityRecord checkedCaller = sourceRecord;
2339 if (checkedCaller == null) {
2340 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2341 }
2342 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2343 // Caller is not the same as launcher, so always needed.
2344 onlyIfNeeded = false;
2345 }
2346 }
2347
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002348 if (sourceRecord == null) {
2349 // This activity is not being started from another... in this
2350 // case we -always- start a new task.
2351 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2352 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2353 + intent);
2354 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2355 }
2356 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2357 // The original activity who is starting us is running as a single
2358 // instance... this new activity it is starting must go on its
2359 // own task.
2360 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2361 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2362 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2363 // The activity being started is a single instance... it always
2364 // gets launched into its own task.
2365 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2366 }
2367
2368 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2369 // For whatever reason this activity is being launched into a new
2370 // task... yet the caller has requested a result back. Well, that
2371 // is pretty messed up, so instead immediately send back a cancel
2372 // and let the new task continue launched as normal without a
2373 // dependency on its originator.
2374 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2375 sendActivityResultLocked(-1,
2376 r.resultTo, r.resultWho, r.requestCode,
2377 Activity.RESULT_CANCELED, null);
2378 r.resultTo = null;
2379 }
2380
2381 boolean addingToTask = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002382 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002383 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2384 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2385 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2386 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2387 // If bring to front is requested, and no result is requested, and
2388 // we can find a task that was started with this same
2389 // component, then instead of launching bring that one to the front.
2390 if (r.resultTo == null) {
2391 // See if there is a task to bring to the front. If this is
2392 // a SINGLE_INSTANCE activity, there can be one and only one
2393 // instance of it in the history, and it is always in its own
2394 // unique task, so we do a special search.
2395 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2396 ? findTaskLocked(intent, r.info)
2397 : findActivityLocked(intent, r.info);
2398 if (taskTop != null) {
2399 if (taskTop.task.intent == null) {
2400 // This task was started because of movement of
2401 // the activity based on affinity... now that we
2402 // are actually launching it, we can assign the
2403 // base intent.
2404 taskTop.task.setIntent(intent, r.info);
2405 }
2406 // If the target task is not in the front, then we need
2407 // to bring it to the front... except... well, with
2408 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2409 // to have the same behavior as if a new instance was
2410 // being started, which means not bringing it to the front
2411 // if the caller is not itself in the front.
2412 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002413 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002414 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2415 boolean callerAtFront = sourceRecord == null
2416 || curTop.task == sourceRecord.task;
2417 if (callerAtFront) {
2418 // We really do want to push this one into the
2419 // user's face, right now.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002420 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002421 moveTaskToFrontLocked(taskTop.task, r);
2422 }
2423 }
2424 // If the caller has requested that the target task be
2425 // reset, then do so.
2426 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2427 taskTop = resetTaskIfNeededLocked(taskTop, r);
2428 }
2429 if (onlyIfNeeded) {
2430 // We don't need to start a new activity, and
2431 // the client said not to do anything if that
2432 // is the case, so this is it! And for paranoia, make
2433 // sure we have correctly resumed the top activity.
2434 if (doResume) {
2435 resumeTopActivityLocked(null);
2436 }
2437 return START_RETURN_INTENT_TO_CALLER;
2438 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002439 if ((launchFlags &
2440 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2441 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2442 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002443 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002444 // not be too hard...
2445 reuseTask = taskTop.task;
2446 performClearTaskLocked(taskTop.task.taskId);
2447 reuseTask.setIntent(r.intent, r.info);
2448 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002449 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2450 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2451 // In this situation we want to remove all activities
2452 // from the task up to the one being started. In most
2453 // cases this means we are resetting the task to its
2454 // initial state.
2455 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002456 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002457 if (top != null) {
2458 if (top.frontOfTask) {
2459 // Activity aliases may mean we use different
2460 // intents for the top activity, so make sure
2461 // the task now has the identity of the new
2462 // intent.
2463 top.task.setIntent(r.intent, r.info);
2464 }
2465 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002466 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002467 } else {
2468 // A special case: we need to
2469 // start the activity because it is not currently
2470 // running, and the caller has asked to clear the
2471 // current task to have this activity at the top.
2472 addingToTask = true;
2473 // Now pretend like this activity is being started
2474 // by the top of its task, so it is put in the
2475 // right place.
2476 sourceRecord = taskTop;
2477 }
2478 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2479 // In this case the top activity on the task is the
2480 // same as the one being launched, so we take that
2481 // as a request to bring the task to the foreground.
2482 // If the top activity in the task is the root
2483 // activity, deliver this new intent to it if it
2484 // desires.
2485 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2486 && taskTop.realActivity.equals(r.realActivity)) {
2487 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2488 if (taskTop.frontOfTask) {
2489 taskTop.task.setIntent(r.intent, r.info);
2490 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002491 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002492 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2493 // In this case we are launching the root activity
2494 // of the task, but with a different intent. We
2495 // should start a new instance on top.
2496 addingToTask = true;
2497 sourceRecord = taskTop;
2498 }
2499 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2500 // In this case an activity is being launched in to an
2501 // existing task, without resetting that task. This
2502 // is typically the situation of launching an activity
2503 // from a notification or shortcut. We want to place
2504 // the new activity on top of the current task.
2505 addingToTask = true;
2506 sourceRecord = taskTop;
2507 } else if (!taskTop.task.rootWasReset) {
2508 // In this case we are launching in to an existing task
2509 // that has not yet been started from its front door.
2510 // The current task has been brought to the front.
2511 // Ideally, we'd probably like to place this new task
2512 // at the bottom of its stack, but that's a little hard
2513 // to do with the current organization of the code so
2514 // for now we'll just drop it.
2515 taskTop.task.setIntent(r.intent, r.info);
2516 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002517 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002518 // We didn't do anything... but it was needed (a.k.a., client
2519 // don't use that intent!) And for paranoia, make
2520 // sure we have correctly resumed the top activity.
2521 if (doResume) {
2522 resumeTopActivityLocked(null);
2523 }
2524 return START_TASK_TO_FRONT;
2525 }
2526 }
2527 }
2528 }
2529
2530 //String uri = r.intent.toURI();
2531 //Intent intent2 = new Intent(uri);
2532 //Slog.i(TAG, "Given intent: " + r.intent);
2533 //Slog.i(TAG, "URI is: " + uri);
2534 //Slog.i(TAG, "To intent: " + intent2);
2535
2536 if (r.packageName != null) {
2537 // If the activity being launched is the same as the one currently
2538 // at the top, then we need to check if it should only be launched
2539 // once.
2540 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2541 if (top != null && r.resultTo == null) {
2542 if (top.realActivity.equals(r.realActivity)) {
2543 if (top.app != null && top.app.thread != null) {
2544 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2545 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2546 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2547 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2548 // For paranoia, make sure we have correctly
2549 // resumed the top activity.
2550 if (doResume) {
2551 resumeTopActivityLocked(null);
2552 }
2553 if (onlyIfNeeded) {
2554 // We don't need to start a new activity, and
2555 // the client said not to do anything if that
2556 // is the case, so this is it!
2557 return START_RETURN_INTENT_TO_CALLER;
2558 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002559 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002560 return START_DELIVERED_TO_TOP;
2561 }
2562 }
2563 }
2564 }
2565
2566 } else {
2567 if (r.resultTo != null) {
2568 sendActivityResultLocked(-1,
2569 r.resultTo, r.resultWho, r.requestCode,
2570 Activity.RESULT_CANCELED, null);
2571 }
2572 return START_CLASS_NOT_FOUND;
2573 }
2574
2575 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002576 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002577
2578 // Should this be considered a new task?
2579 if (r.resultTo == null && !addingToTask
2580 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002581 if (reuseTask == null) {
2582 // todo: should do better management of integers.
2583 mService.mCurTask++;
2584 if (mService.mCurTask <= 0) {
2585 mService.mCurTask = 1;
2586 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002587 r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002588 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2589 + " in new task " + r.task);
2590 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002591 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002592 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002593 newTask = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002594 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002595
2596 } else if (sourceRecord != null) {
2597 if (!addingToTask &&
2598 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2599 // In this case, we are adding the activity to an existing
2600 // task, but the caller has asked to clear that task if the
2601 // activity is already running.
2602 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002603 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002604 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002605 if (top != null) {
2606 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002607 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002608 // For paranoia, make sure we have correctly
2609 // resumed the top activity.
2610 if (doResume) {
2611 resumeTopActivityLocked(null);
2612 }
2613 return START_DELIVERED_TO_TOP;
2614 }
2615 } else if (!addingToTask &&
2616 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2617 // In this case, we are launching an activity in our own task
2618 // that may already be running somewhere in the history, and
2619 // we want to shuffle it to the front of the stack if so.
2620 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2621 if (where >= 0) {
2622 ActivityRecord top = moveActivityToFrontLocked(where);
2623 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002624 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002625 if (doResume) {
2626 resumeTopActivityLocked(null);
2627 }
2628 return START_DELIVERED_TO_TOP;
2629 }
2630 }
2631 // An existing activity is starting this new activity, so we want
2632 // to keep the new one in the same task as the one that is starting
2633 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002634 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002635 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2636 + " in existing task " + r.task);
2637
2638 } else {
2639 // This not being started from an existing activity, and not part
2640 // of a new task... just put it in the top task, though these days
2641 // this case should never happen.
2642 final int N = mHistory.size();
2643 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002644 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002645 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002646 ? prev.task
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002647 : new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002648 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2649 + " in new guessed " + r.task);
2650 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002651
2652 if (grantedUriPermissions != null && callingUid > 0) {
2653 for (int i=0; i<grantedUriPermissions.length; i++) {
2654 mService.grantUriPermissionLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002655 grantedUriPermissions[i], grantedMode, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002656 }
2657 }
2658
2659 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002660 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002661
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002662 if (newTask) {
2663 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
2664 }
2665 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002666 startActivityLocked(r, newTask, doResume, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002667 return START_SUCCESS;
2668 }
2669
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002670 ActivityInfo resolveActivity(Intent intent, String resolvedType, boolean debug) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002671 // Collect information about the target of the Intent.
2672 ActivityInfo aInfo;
2673 try {
2674 ResolveInfo rInfo =
2675 AppGlobals.getPackageManager().resolveIntent(
2676 intent, resolvedType,
2677 PackageManager.MATCH_DEFAULT_ONLY
2678 | ActivityManagerService.STOCK_PM_FLAGS);
2679 aInfo = rInfo != null ? rInfo.activityInfo : null;
2680 } catch (RemoteException e) {
2681 aInfo = null;
2682 }
2683
2684 if (aInfo != null) {
2685 // Store the found target back into the intent, because now that
2686 // we have it we never want to do this again. For example, if the
2687 // user navigates back to this point in the history, we should
2688 // always restart the exact same activity.
2689 intent.setComponent(new ComponentName(
2690 aInfo.applicationInfo.packageName, aInfo.name));
2691
2692 // Don't debug things in the system process
2693 if (debug) {
2694 if (!aInfo.processName.equals("system")) {
2695 mService.setDebugApp(aInfo.processName, true, false);
2696 }
2697 }
2698 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002699 return aInfo;
2700 }
2701
2702 final int startActivityMayWait(IApplicationThread caller, int callingUid,
2703 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2704 int grantedMode, IBinder resultTo,
2705 String resultWho, int requestCode, boolean onlyIfNeeded,
2706 boolean debug, WaitResult outResult, Configuration config) {
2707 // Refuse possible leaked file descriptors
2708 if (intent != null && intent.hasFileDescriptors()) {
2709 throw new IllegalArgumentException("File descriptors passed in Intent");
2710 }
2711
2712 boolean componentSpecified = intent.getComponent() != null;
2713
2714 // Don't modify the client's object!
2715 intent = new Intent(intent);
2716
2717 // Collect information about the target of the Intent.
2718 ActivityInfo aInfo = resolveActivity(intent, resolvedType, debug);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002719
2720 synchronized (mService) {
2721 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002722 if (callingUid >= 0) {
2723 callingPid = -1;
2724 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002725 callingPid = Binder.getCallingPid();
2726 callingUid = Binder.getCallingUid();
2727 } else {
2728 callingPid = callingUid = -1;
2729 }
2730
2731 mConfigWillChange = config != null
2732 && mService.mConfiguration.diff(config) != 0;
2733 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2734 "Starting activity when config will change = " + mConfigWillChange);
2735
2736 final long origId = Binder.clearCallingIdentity();
2737
2738 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07002739 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002740 // This may be a heavy-weight process! Check to see if we already
2741 // have another, different heavy-weight process running.
2742 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
2743 if (mService.mHeavyWeightProcess != null &&
2744 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
2745 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
2746 int realCallingPid = callingPid;
2747 int realCallingUid = callingUid;
2748 if (caller != null) {
2749 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
2750 if (callerApp != null) {
2751 realCallingPid = callerApp.pid;
2752 realCallingUid = callerApp.info.uid;
2753 } else {
2754 Slog.w(TAG, "Unable to find app for caller " + caller
2755 + " (pid=" + realCallingPid + ") when starting: "
2756 + intent.toString());
2757 return START_PERMISSION_DENIED;
2758 }
2759 }
2760
2761 IIntentSender target = mService.getIntentSenderLocked(
2762 IActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002763 realCallingUid, null, null, 0, new Intent[] { intent },
2764 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002765 | PendingIntent.FLAG_ONE_SHOT);
2766
2767 Intent newIntent = new Intent();
2768 if (requestCode >= 0) {
2769 // Caller is requesting a result.
2770 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
2771 }
2772 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
2773 new IntentSender(target));
2774 if (mService.mHeavyWeightProcess.activities.size() > 0) {
2775 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
2776 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
2777 hist.packageName);
2778 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
2779 hist.task.taskId);
2780 }
2781 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
2782 aInfo.packageName);
2783 newIntent.setFlags(intent.getFlags());
2784 newIntent.setClassName("android",
2785 HeavyWeightSwitcherActivity.class.getName());
2786 intent = newIntent;
2787 resolvedType = null;
2788 caller = null;
2789 callingUid = Binder.getCallingUid();
2790 callingPid = Binder.getCallingPid();
2791 componentSpecified = true;
2792 try {
2793 ResolveInfo rInfo =
2794 AppGlobals.getPackageManager().resolveIntent(
2795 intent, null,
2796 PackageManager.MATCH_DEFAULT_ONLY
2797 | ActivityManagerService.STOCK_PM_FLAGS);
2798 aInfo = rInfo != null ? rInfo.activityInfo : null;
2799 } catch (RemoteException e) {
2800 aInfo = null;
2801 }
2802 }
2803 }
2804 }
2805
2806 int res = startActivityLocked(caller, intent, resolvedType,
2807 grantedUriPermissions, grantedMode, aInfo,
2808 resultTo, resultWho, requestCode, callingPid, callingUid,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002809 onlyIfNeeded, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002810
2811 if (mConfigWillChange && mMainStack) {
2812 // If the caller also wants to switch to a new configuration,
2813 // do so now. This allows a clean switch, as we are waiting
2814 // for the current activity to pause (so we will not destroy
2815 // it), and have not yet started the next activity.
2816 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
2817 "updateConfiguration()");
2818 mConfigWillChange = false;
2819 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2820 "Updating to new configuration after starting activity.");
Dianne Hackborn31ca8542011-07-19 14:58:28 -07002821 mService.updateConfigurationLocked(config, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002822 }
2823
2824 Binder.restoreCallingIdentity(origId);
2825
2826 if (outResult != null) {
2827 outResult.result = res;
2828 if (res == IActivityManager.START_SUCCESS) {
2829 mWaitingActivityLaunched.add(outResult);
2830 do {
2831 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07002832 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002833 } catch (InterruptedException e) {
2834 }
2835 } while (!outResult.timeout && outResult.who == null);
2836 } else if (res == IActivityManager.START_TASK_TO_FRONT) {
2837 ActivityRecord r = this.topRunningActivityLocked(null);
2838 if (r.nowVisible) {
2839 outResult.timeout = false;
2840 outResult.who = new ComponentName(r.info.packageName, r.info.name);
2841 outResult.totalTime = 0;
2842 outResult.thisTime = 0;
2843 } else {
2844 outResult.thisTime = SystemClock.uptimeMillis();
2845 mWaitingActivityVisible.add(outResult);
2846 do {
2847 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07002848 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002849 } catch (InterruptedException e) {
2850 }
2851 } while (!outResult.timeout && outResult.who == null);
2852 }
2853 }
2854 }
2855
2856 return res;
2857 }
2858 }
2859
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002860 final int startActivities(IApplicationThread caller, int callingUid,
2861 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
2862 if (intents == null) {
2863 throw new NullPointerException("intents is null");
2864 }
2865 if (resolvedTypes == null) {
2866 throw new NullPointerException("resolvedTypes is null");
2867 }
2868 if (intents.length != resolvedTypes.length) {
2869 throw new IllegalArgumentException("intents are length different than resolvedTypes");
2870 }
2871
2872 ActivityRecord[] outActivity = new ActivityRecord[1];
2873
2874 int callingPid;
2875 if (callingUid >= 0) {
2876 callingPid = -1;
2877 } else if (caller == null) {
2878 callingPid = Binder.getCallingPid();
2879 callingUid = Binder.getCallingUid();
2880 } else {
2881 callingPid = callingUid = -1;
2882 }
2883 final long origId = Binder.clearCallingIdentity();
2884 try {
2885 synchronized (mService) {
2886
2887 for (int i=0; i<intents.length; i++) {
2888 Intent intent = intents[i];
2889 if (intent == null) {
2890 continue;
2891 }
2892
2893 // Refuse possible leaked file descriptors
2894 if (intent != null && intent.hasFileDescriptors()) {
2895 throw new IllegalArgumentException("File descriptors passed in Intent");
2896 }
2897
2898 boolean componentSpecified = intent.getComponent() != null;
2899
2900 // Don't modify the client's object!
2901 intent = new Intent(intent);
2902
2903 // Collect information about the target of the Intent.
2904 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i], false);
2905
2906 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
2907 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
2908 throw new IllegalArgumentException(
2909 "FLAG_CANT_SAVE_STATE not supported here");
2910 }
2911
2912 int res = startActivityLocked(caller, intent, resolvedTypes[i],
2913 null, 0, aInfo, resultTo, null, -1, callingPid, callingUid,
2914 false, componentSpecified, outActivity);
2915 if (res < 0) {
2916 return res;
2917 }
2918
2919 resultTo = outActivity[0];
2920 }
2921 }
2922 } finally {
2923 Binder.restoreCallingIdentity(origId);
2924 }
2925
2926 return IActivityManager.START_SUCCESS;
2927 }
2928
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002929 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
2930 long thisTime, long totalTime) {
2931 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
2932 WaitResult w = mWaitingActivityLaunched.get(i);
2933 w.timeout = timeout;
2934 if (r != null) {
2935 w.who = new ComponentName(r.info.packageName, r.info.name);
2936 }
2937 w.thisTime = thisTime;
2938 w.totalTime = totalTime;
2939 }
2940 mService.notifyAll();
2941 }
2942
2943 void reportActivityVisibleLocked(ActivityRecord r) {
2944 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
2945 WaitResult w = mWaitingActivityVisible.get(i);
2946 w.timeout = false;
2947 if (r != null) {
2948 w.who = new ComponentName(r.info.packageName, r.info.name);
2949 }
2950 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
2951 w.thisTime = w.totalTime;
2952 }
2953 mService.notifyAll();
2954 }
2955
2956 void sendActivityResultLocked(int callingUid, ActivityRecord r,
2957 String resultWho, int requestCode, int resultCode, Intent data) {
2958
2959 if (callingUid > 0) {
2960 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002961 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002962 }
2963
2964 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
2965 + " : who=" + resultWho + " req=" + requestCode
2966 + " res=" + resultCode + " data=" + data);
2967 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
2968 try {
2969 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
2970 list.add(new ResultInfo(resultWho, requestCode,
2971 resultCode, data));
2972 r.app.thread.scheduleSendResult(r, list);
2973 return;
2974 } catch (Exception e) {
2975 Slog.w(TAG, "Exception thrown sending result to " + r, e);
2976 }
2977 }
2978
2979 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
2980 }
2981
2982 private final void stopActivityLocked(ActivityRecord r) {
2983 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
2984 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
2985 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
2986 if (!r.finishing) {
2987 requestFinishActivityLocked(r, Activity.RESULT_CANCELED, null,
2988 "no-history");
2989 }
2990 } else if (r.app != null && r.app.thread != null) {
2991 if (mMainStack) {
2992 if (mService.mFocusedActivity == r) {
2993 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
2994 }
2995 }
2996 r.resumeKeyDispatchingLocked();
2997 try {
2998 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002999 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3000 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003001 r.state = ActivityState.STOPPING;
3002 if (DEBUG_VISBILITY) Slog.v(
3003 TAG, "Stopping visible=" + r.visible + " for " + r);
3004 if (!r.visible) {
3005 mService.mWindowManager.setAppVisibility(r, false);
3006 }
3007 r.app.thread.scheduleStopActivity(r, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003008 if (mService.isSleeping()) {
3009 r.setSleeping(true);
3010 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003011 } catch (Exception e) {
3012 // Maybe just ignore exceptions here... if the process
3013 // has crashed, our death notification will clean things
3014 // up.
3015 Slog.w(TAG, "Exception thrown during pause", e);
3016 // Just in case, assume it to be stopped.
3017 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003018 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003019 r.state = ActivityState.STOPPED;
3020 if (r.configDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003021 destroyActivityLocked(r, true, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003022 }
3023 }
3024 }
3025 }
3026
3027 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3028 boolean remove) {
3029 int N = mStoppingActivities.size();
3030 if (N <= 0) return null;
3031
3032 ArrayList<ActivityRecord> stops = null;
3033
3034 final boolean nowVisible = mResumedActivity != null
3035 && mResumedActivity.nowVisible
3036 && !mResumedActivity.waitingVisible;
3037 for (int i=0; i<N; i++) {
3038 ActivityRecord s = mStoppingActivities.get(i);
3039 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3040 + nowVisible + " waitingVisible=" + s.waitingVisible
3041 + " finishing=" + s.finishing);
3042 if (s.waitingVisible && nowVisible) {
3043 mWaitingVisibleActivities.remove(s);
3044 s.waitingVisible = false;
3045 if (s.finishing) {
3046 // If this activity is finishing, it is sitting on top of
3047 // everyone else but we now know it is no longer needed...
3048 // so get rid of it. Otherwise, we need to go through the
3049 // normal flow and hide it once we determine that it is
3050 // hidden by the activities in front of it.
3051 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
3052 mService.mWindowManager.setAppVisibility(s, false);
3053 }
3054 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003055 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003056 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3057 if (stops == null) {
3058 stops = new ArrayList<ActivityRecord>();
3059 }
3060 stops.add(s);
3061 mStoppingActivities.remove(i);
3062 N--;
3063 i--;
3064 }
3065 }
3066
3067 return stops;
3068 }
3069
3070 final void activityIdleInternal(IBinder token, boolean fromTimeout,
3071 Configuration config) {
3072 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3073
3074 ArrayList<ActivityRecord> stops = null;
3075 ArrayList<ActivityRecord> finishes = null;
3076 ArrayList<ActivityRecord> thumbnails = null;
3077 int NS = 0;
3078 int NF = 0;
3079 int NT = 0;
3080 IApplicationThread sendThumbnail = null;
3081 boolean booting = false;
3082 boolean enableScreen = false;
3083
3084 synchronized (mService) {
3085 if (token != null) {
3086 mHandler.removeMessages(IDLE_TIMEOUT_MSG, token);
3087 }
3088
3089 // Get the activity record.
3090 int index = indexOfTokenLocked(token);
3091 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003092 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003093
3094 if (fromTimeout) {
3095 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3096 }
3097
3098 // This is a hack to semi-deal with a race condition
3099 // in the client where it can be constructed with a
3100 // newer configuration from when we asked it to launch.
3101 // We'll update with whatever configuration it now says
3102 // it used to launch.
3103 if (config != null) {
3104 r.configuration = config;
3105 }
3106
3107 // No longer need to keep the device awake.
3108 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3109 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3110 mLaunchingActivity.release();
3111 }
3112
3113 // We are now idle. If someone is waiting for a thumbnail from
3114 // us, we can now deliver.
3115 r.idle = true;
3116 mService.scheduleAppGcsLocked();
3117 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3118 sendThumbnail = r.app.thread;
3119 r.thumbnailNeeded = false;
3120 }
3121
3122 // If this activity is fullscreen, set up to hide those under it.
3123
3124 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3125 ensureActivitiesVisibleLocked(null, 0);
3126
3127 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3128 if (mMainStack) {
3129 if (!mService.mBooted && !fromTimeout) {
3130 mService.mBooted = true;
3131 enableScreen = true;
3132 }
3133 }
3134
3135 } else if (fromTimeout) {
3136 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3137 }
3138
3139 // Atomically retrieve all of the other things to do.
3140 stops = processStoppingActivitiesLocked(true);
3141 NS = stops != null ? stops.size() : 0;
3142 if ((NF=mFinishingActivities.size()) > 0) {
3143 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3144 mFinishingActivities.clear();
3145 }
3146 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3147 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3148 mService.mCancelledThumbnails.clear();
3149 }
3150
3151 if (mMainStack) {
3152 booting = mService.mBooting;
3153 mService.mBooting = false;
3154 }
3155 }
3156
3157 int i;
3158
3159 // Send thumbnail if requested.
3160 if (sendThumbnail != null) {
3161 try {
3162 sendThumbnail.requestThumbnail(token);
3163 } catch (Exception e) {
3164 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3165 mService.sendPendingThumbnail(null, token, null, null, true);
3166 }
3167 }
3168
3169 // Stop any activities that are scheduled to do so but have been
3170 // waiting for the next one to start.
3171 for (i=0; i<NS; i++) {
3172 ActivityRecord r = (ActivityRecord)stops.get(i);
3173 synchronized (mService) {
3174 if (r.finishing) {
3175 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY);
3176 } else {
3177 stopActivityLocked(r);
3178 }
3179 }
3180 }
3181
3182 // Finish any activities that are scheduled to do so but have been
3183 // waiting for the next one to start.
3184 for (i=0; i<NF; i++) {
3185 ActivityRecord r = (ActivityRecord)finishes.get(i);
3186 synchronized (mService) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003187 destroyActivityLocked(r, true, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003188 }
3189 }
3190
3191 // Report back to any thumbnail receivers.
3192 for (i=0; i<NT; i++) {
3193 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3194 mService.sendPendingThumbnail(r, null, null, null, true);
3195 }
3196
3197 if (booting) {
3198 mService.finishBooting();
3199 }
3200
3201 mService.trimApplications();
3202 //dump();
3203 //mWindowManager.dump();
3204
3205 if (enableScreen) {
3206 mService.enableScreenAfterBoot();
3207 }
3208 }
3209
3210 /**
3211 * @return Returns true if the activity is being finished, false if for
3212 * some reason it is being left as-is.
3213 */
3214 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
3215 Intent resultData, String reason) {
3216 if (DEBUG_RESULTS) Slog.v(
3217 TAG, "Finishing activity: token=" + token
3218 + ", result=" + resultCode + ", data=" + resultData);
3219
3220 int index = indexOfTokenLocked(token);
3221 if (index < 0) {
3222 return false;
3223 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003224 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003225
3226 // Is this the last activity left?
3227 boolean lastActivity = true;
3228 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003229 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003230 if (!p.finishing && p != r) {
3231 lastActivity = false;
3232 break;
3233 }
3234 }
3235
3236 // If this is the last activity, but it is the home activity, then
3237 // just don't finish it.
3238 if (lastActivity) {
3239 if (r.intent.hasCategory(Intent.CATEGORY_HOME)) {
3240 return false;
3241 }
3242 }
3243
3244 finishActivityLocked(r, index, resultCode, resultData, reason);
3245 return true;
3246 }
3247
3248 /**
3249 * @return Returns true if this activity has been removed from the history
3250 * list, or false if it is still in the list and will be removed later.
3251 */
3252 final boolean finishActivityLocked(ActivityRecord r, int index,
3253 int resultCode, Intent resultData, String reason) {
3254 if (r.finishing) {
3255 Slog.w(TAG, "Duplicate finish request for " + r);
3256 return false;
3257 }
3258
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003259 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003260 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3261 System.identityHashCode(r),
3262 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003263 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003264 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003265 if (next.task == r.task) {
3266 if (r.frontOfTask) {
3267 // The next activity is now the front of the task.
3268 next.frontOfTask = true;
3269 }
3270 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3271 // If the caller asked that this activity (and all above it)
3272 // be cleared when the task is reset, don't lose that information,
3273 // but propagate it up to the next activity.
3274 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3275 }
3276 }
3277 }
3278
3279 r.pauseKeyDispatchingLocked();
3280 if (mMainStack) {
3281 if (mService.mFocusedActivity == r) {
3282 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3283 }
3284 }
3285
3286 // send the result
3287 ActivityRecord resultTo = r.resultTo;
3288 if (resultTo != null) {
3289 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3290 + " who=" + r.resultWho + " req=" + r.requestCode
3291 + " res=" + resultCode + " data=" + resultData);
3292 if (r.info.applicationInfo.uid > 0) {
3293 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
Dianne Hackborna1c69e02010-09-01 22:55:02 -07003294 resultTo.packageName, resultData,
3295 resultTo.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003296 }
3297 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3298 resultData);
3299 r.resultTo = null;
3300 }
3301 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3302
3303 // Make sure this HistoryRecord is not holding on to other resources,
3304 // because clients have remote IPC references to this object so we
3305 // can't assume that will go away and want to avoid circular IPC refs.
3306 r.results = null;
3307 r.pendingResults = null;
3308 r.newIntents = null;
3309 r.icicle = null;
3310
3311 if (mService.mPendingThumbnails.size() > 0) {
3312 // There are clients waiting to receive thumbnails so, in case
3313 // this is an activity that someone is waiting for, add it
3314 // to the pending list so we can correctly update the clients.
3315 mService.mCancelledThumbnails.add(r);
3316 }
3317
3318 if (mResumedActivity == r) {
3319 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003320 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003321 if (DEBUG_TRANSITION) Slog.v(TAG,
3322 "Prepare close transition: finishing " + r);
3323 mService.mWindowManager.prepareAppTransition(endTask
3324 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003325 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003326
3327 // Tell window manager to prepare for this one to be removed.
3328 mService.mWindowManager.setAppVisibility(r, false);
3329
3330 if (mPausingActivity == null) {
3331 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3332 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3333 startPausingLocked(false, false);
3334 }
3335
3336 } else if (r.state != ActivityState.PAUSING) {
3337 // If the activity is PAUSING, we will complete the finish once
3338 // it is done pausing; else we can just directly finish it here.
3339 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3340 return finishCurrentActivityLocked(r, index,
3341 FINISH_AFTER_PAUSE) == null;
3342 } else {
3343 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3344 }
3345
3346 return false;
3347 }
3348
3349 private static final int FINISH_IMMEDIATELY = 0;
3350 private static final int FINISH_AFTER_PAUSE = 1;
3351 private static final int FINISH_AFTER_VISIBLE = 2;
3352
3353 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3354 int mode) {
3355 final int index = indexOfTokenLocked(r);
3356 if (index < 0) {
3357 return null;
3358 }
3359
3360 return finishCurrentActivityLocked(r, index, mode);
3361 }
3362
3363 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3364 int index, int mode) {
3365 // First things first: if this activity is currently visible,
3366 // and the resumed activity is not yet visible, then hold off on
3367 // finishing until the resumed one becomes visible.
3368 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3369 if (!mStoppingActivities.contains(r)) {
3370 mStoppingActivities.add(r);
3371 if (mStoppingActivities.size() > 3) {
3372 // If we already have a few activities waiting to stop,
3373 // then give up on things going idle and start clearing
3374 // them out.
3375 Message msg = Message.obtain();
3376 msg.what = IDLE_NOW_MSG;
3377 mHandler.sendMessage(msg);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003378 } else {
3379 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003380 }
3381 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003382 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3383 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003384 r.state = ActivityState.STOPPING;
3385 mService.updateOomAdjLocked();
3386 return r;
3387 }
3388
3389 // make sure the record is cleaned out of other places.
3390 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003391 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003392 mWaitingVisibleActivities.remove(r);
3393 if (mResumedActivity == r) {
3394 mResumedActivity = null;
3395 }
3396 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003397 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003398 r.state = ActivityState.FINISHING;
3399
3400 if (mode == FINISH_IMMEDIATELY
3401 || prevState == ActivityState.STOPPED
3402 || prevState == ActivityState.INITIALIZING) {
3403 // If this activity is already stopped, we can just finish
3404 // it right now.
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003405 return destroyActivityLocked(r, true, true) ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003406 } else {
3407 // Need to go through the full pause cycle to get this
3408 // activity into the stopped state and then finish it.
3409 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3410 mFinishingActivities.add(r);
3411 resumeTopActivityLocked(null);
3412 }
3413 return r;
3414 }
3415
3416 /**
3417 * Perform the common clean-up of an activity record. This is called both
3418 * as part of destroyActivityLocked() (when destroying the client-side
3419 * representation) and cleaning things up as a result of its hosting
3420 * processing going away, in which case there is no remaining client-side
3421 * state to destroy so only the cleanup here is needed.
3422 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003423 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3424 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003425 if (mResumedActivity == r) {
3426 mResumedActivity = null;
3427 }
3428 if (mService.mFocusedActivity == r) {
3429 mService.mFocusedActivity = null;
3430 }
3431
3432 r.configDestroy = false;
3433 r.frozenBeforeDestroy = false;
3434
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003435 if (setState) {
3436 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3437 r.state = ActivityState.DESTROYED;
3438 }
3439
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003440 // Make sure this record is no longer in the pending finishes list.
3441 // This could happen, for example, if we are trimming activities
3442 // down to the max limit while they are still waiting to finish.
3443 mFinishingActivities.remove(r);
3444 mWaitingVisibleActivities.remove(r);
3445
3446 // Remove any pending results.
3447 if (r.finishing && r.pendingResults != null) {
3448 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3449 PendingIntentRecord rec = apr.get();
3450 if (rec != null) {
3451 mService.cancelIntentSenderLocked(rec, false);
3452 }
3453 }
3454 r.pendingResults = null;
3455 }
3456
3457 if (cleanServices) {
3458 cleanUpActivityServicesLocked(r);
3459 }
3460
3461 if (mService.mPendingThumbnails.size() > 0) {
3462 // There are clients waiting to receive thumbnails so, in case
3463 // this is an activity that someone is waiting for, add it
3464 // to the pending list so we can correctly update the clients.
3465 mService.mCancelledThumbnails.add(r);
3466 }
3467
3468 // Get rid of any pending idle timeouts.
3469 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
3470 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003471 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003472 }
3473
3474 private final void removeActivityFromHistoryLocked(ActivityRecord r) {
3475 if (r.state != ActivityState.DESTROYED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003476 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003477 mHistory.remove(r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003478 r.takeFromHistory();
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003479 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3480 + " (removed from history)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003481 r.state = ActivityState.DESTROYED;
3482 mService.mWindowManager.removeAppToken(r);
3483 if (VALIDATE_TOKENS) {
3484 mService.mWindowManager.validateAppTokens(mHistory);
3485 }
3486 cleanUpActivityServicesLocked(r);
3487 r.removeUriPermissionsLocked();
3488 }
3489 }
3490
3491 /**
3492 * Perform clean-up of service connections in an activity record.
3493 */
3494 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3495 // Throw away any services that have been bound by this activity.
3496 if (r.connections != null) {
3497 Iterator<ConnectionRecord> it = r.connections.iterator();
3498 while (it.hasNext()) {
3499 ConnectionRecord c = it.next();
3500 mService.removeConnectionLocked(c, null, r);
3501 }
3502 r.connections = null;
3503 }
3504 }
3505
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003506 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj) {
3507 for (int i=mHistory.size()-1; i>=0; i--) {
3508 ActivityRecord r = mHistory.get(i);
3509 if (owner != null && r.app != owner) {
3510 continue;
3511 }
3512 // We can destroy this one if we have its icicle saved and
3513 // it is not in the process of pausing/stopping/finishing.
3514 if (r.app != null && r.haveState && !r.visible && r.stopped && !r.finishing
3515 && r.state != ActivityState.DESTROYING
3516 && r.state != ActivityState.DESTROYED) {
3517 destroyActivityLocked(r, true, oomAdj);
3518 }
3519 }
3520 }
3521
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003522 /**
3523 * Destroy the current CLIENT SIDE instance of an activity. This may be
3524 * called both when actually finishing an activity, or when performing
3525 * a configuration switch where we destroy the current client-side object
3526 * but then create a new client-side object for this same HistoryRecord.
3527 */
3528 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003529 boolean removeFromApp, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003530 if (DEBUG_SWITCH) Slog.v(
3531 TAG, "Removing activity: token=" + r
3532 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3533 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3534 System.identityHashCode(r),
3535 r.task.taskId, r.shortComponentName);
3536
3537 boolean removedFromHistory = false;
3538
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003539 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003540
3541 final boolean hadApp = r.app != null;
3542
3543 if (hadApp) {
3544 if (removeFromApp) {
3545 int idx = r.app.activities.indexOf(r);
3546 if (idx >= 0) {
3547 r.app.activities.remove(idx);
3548 }
3549 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
3550 mService.mHeavyWeightProcess = null;
3551 mService.mHandler.sendEmptyMessage(
3552 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
3553 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003554 if (r.app.activities.size() == 0) {
3555 // No longer have activities, so update location in
3556 // LRU list.
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003557 mService.updateLruProcessLocked(r.app, oomAdj, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003558 }
3559 }
3560
3561 boolean skipDestroy = false;
3562
3563 try {
3564 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
3565 r.app.thread.scheduleDestroyActivity(r, r.finishing,
3566 r.configChangeFlags);
3567 } catch (Exception e) {
3568 // We can just ignore exceptions here... if the process
3569 // has crashed, our death notification will clean things
3570 // up.
3571 //Slog.w(TAG, "Exception thrown during finish", e);
3572 if (r.finishing) {
3573 removeActivityFromHistoryLocked(r);
3574 removedFromHistory = true;
3575 skipDestroy = true;
3576 }
3577 }
3578
3579 r.app = null;
3580 r.nowVisible = false;
3581
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003582 // If the activity is finishing, we need to wait on removing it
3583 // from the list to give it a chance to do its cleanup. During
3584 // that time it may make calls back with its token so we need to
3585 // be able to find it on the list and so we don't want to remove
3586 // it from the list yet. Otherwise, we can just immediately put
3587 // it in the destroyed state since we are not removing it from the
3588 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003589 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003590 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
3591 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003592 r.state = ActivityState.DESTROYING;
3593 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
3594 msg.obj = r;
3595 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
3596 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003597 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3598 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003599 r.state = ActivityState.DESTROYED;
3600 }
3601 } else {
3602 // remove this record from the history.
3603 if (r.finishing) {
3604 removeActivityFromHistoryLocked(r);
3605 removedFromHistory = true;
3606 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003607 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3608 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003609 r.state = ActivityState.DESTROYED;
3610 }
3611 }
3612
3613 r.configChangeFlags = 0;
3614
3615 if (!mLRUActivities.remove(r) && hadApp) {
3616 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
3617 }
3618
3619 return removedFromHistory;
3620 }
3621
3622 final void activityDestroyed(IBinder token) {
3623 synchronized (mService) {
3624 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, token);
3625
3626 int index = indexOfTokenLocked(token);
3627 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003628 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003629 if (r.state == ActivityState.DESTROYING) {
3630 final long origId = Binder.clearCallingIdentity();
3631 removeActivityFromHistoryLocked(r);
3632 Binder.restoreCallingIdentity(origId);
3633 }
3634 }
3635 }
3636 }
3637
3638 private static void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
3639 int i = list.size();
3640 if (localLOGV) Slog.v(
3641 TAG, "Removing app " + app + " from list " + list
3642 + " with " + i + " entries");
3643 while (i > 0) {
3644 i--;
3645 ActivityRecord r = (ActivityRecord)list.get(i);
3646 if (localLOGV) Slog.v(
3647 TAG, "Record #" + i + " " + r + ": app=" + r.app);
3648 if (r.app == app) {
3649 if (localLOGV) Slog.v(TAG, "Removing this entry!");
3650 list.remove(i);
3651 }
3652 }
3653 }
3654
3655 void removeHistoryRecordsForAppLocked(ProcessRecord app) {
3656 removeHistoryRecordsForAppLocked(mLRUActivities, app);
3657 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003658 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003659 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
3660 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
3661 }
3662
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003663 /**
3664 * Move the current home activity's task (if one exists) to the front
3665 * of the stack.
3666 */
3667 final void moveHomeToFrontLocked() {
3668 TaskRecord homeTask = null;
3669 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003670 ActivityRecord hr = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003671 if (hr.isHomeActivity) {
3672 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003673 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003674 }
3675 }
3676 if (homeTask != null) {
3677 moveTaskToFrontLocked(homeTask, null);
3678 }
3679 }
3680
3681
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003682 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason) {
3683 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
3684
3685 final int task = tr.taskId;
3686 int top = mHistory.size()-1;
3687
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003688 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003689 // nothing to do!
3690 return;
3691 }
3692
3693 ArrayList moved = new ArrayList();
3694
3695 // Applying the affinities may have removed entries from the history,
3696 // so get the size again.
3697 top = mHistory.size()-1;
3698 int pos = top;
3699
3700 // Shift all activities with this task up to the top
3701 // of the stack, keeping them in the same internal order.
3702 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003703 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003704 if (localLOGV) Slog.v(
3705 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003706 if (r.task.taskId == task) {
3707 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
3708 mHistory.remove(pos);
3709 mHistory.add(top, r);
3710 moved.add(0, r);
3711 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003712 }
3713 pos--;
3714 }
3715
3716 if (DEBUG_TRANSITION) Slog.v(TAG,
3717 "Prepare to front transition: task=" + tr);
3718 if (reason != null &&
3719 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003720 mService.mWindowManager.prepareAppTransition(
3721 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003722 ActivityRecord r = topRunningActivityLocked(null);
3723 if (r != null) {
3724 mNoAnimActivities.add(r);
3725 }
3726 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003727 mService.mWindowManager.prepareAppTransition(
3728 WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003729 }
3730
3731 mService.mWindowManager.moveAppTokensToTop(moved);
3732 if (VALIDATE_TOKENS) {
3733 mService.mWindowManager.validateAppTokens(mHistory);
3734 }
3735
3736 finishTaskMoveLocked(task);
3737 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
3738 }
3739
3740 private final void finishTaskMoveLocked(int task) {
3741 resumeTopActivityLocked(null);
3742 }
3743
3744 /**
3745 * Worker method for rearranging history stack. Implements the function of moving all
3746 * activities for a specific task (gathering them if disjoint) into a single group at the
3747 * bottom of the stack.
3748 *
3749 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
3750 * to premeptively cancel the move.
3751 *
3752 * @param task The taskId to collect and move to the bottom.
3753 * @return Returns true if the move completed, false if not.
3754 */
3755 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
3756 Slog.i(TAG, "moveTaskToBack: " + task);
3757
3758 // If we have a watcher, preflight the move before committing to it. First check
3759 // for *other* available tasks, but if none are available, then try again allowing the
3760 // current task to be selected.
3761 if (mMainStack && mService.mController != null) {
3762 ActivityRecord next = topRunningActivityLocked(null, task);
3763 if (next == null) {
3764 next = topRunningActivityLocked(null, 0);
3765 }
3766 if (next != null) {
3767 // ask watcher if this is allowed
3768 boolean moveOK = true;
3769 try {
3770 moveOK = mService.mController.activityResuming(next.packageName);
3771 } catch (RemoteException e) {
3772 mService.mController = null;
3773 }
3774 if (!moveOK) {
3775 return false;
3776 }
3777 }
3778 }
3779
3780 ArrayList moved = new ArrayList();
3781
3782 if (DEBUG_TRANSITION) Slog.v(TAG,
3783 "Prepare to back transition: task=" + task);
3784
3785 final int N = mHistory.size();
3786 int bottom = 0;
3787 int pos = 0;
3788
3789 // Shift all activities with this task down to the bottom
3790 // of the stack, keeping them in the same internal order.
3791 while (pos < N) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003792 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003793 if (localLOGV) Slog.v(
3794 TAG, "At " + pos + " ckp " + r.task + ": " + r);
3795 if (r.task.taskId == task) {
3796 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
3797 mHistory.remove(pos);
3798 mHistory.add(bottom, r);
3799 moved.add(r);
3800 bottom++;
3801 }
3802 pos++;
3803 }
3804
3805 if (reason != null &&
3806 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003807 mService.mWindowManager.prepareAppTransition(
3808 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003809 ActivityRecord r = topRunningActivityLocked(null);
3810 if (r != null) {
3811 mNoAnimActivities.add(r);
3812 }
3813 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003814 mService.mWindowManager.prepareAppTransition(
3815 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003816 }
3817 mService.mWindowManager.moveAppTokensToBottom(moved);
3818 if (VALIDATE_TOKENS) {
3819 mService.mWindowManager.validateAppTokens(mHistory);
3820 }
3821
3822 finishTaskMoveLocked(task);
3823 return true;
3824 }
3825
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003826 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
3827 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
3828 ActivityRecord resumed = mResumedActivity;
3829 if (resumed != null && resumed.thumbHolder == tr) {
3830 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
3831 } else {
3832 info.mainThumbnail = tr.lastThumbnail;
3833 }
3834 return info;
3835 }
3836
3837 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex) {
3838 TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
3839 if (info.root == null) {
3840 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
3841 return null;
3842 }
3843
3844 if (subTaskIndex < 0) {
3845 // Just remove the entire task.
3846 performClearTaskAtIndexLocked(taskId, info.rootIndex);
3847 return info.root;
3848 }
3849
3850 if (subTaskIndex >= info.subtasks.size()) {
3851 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
3852 return null;
3853 }
3854
3855 // Remove all of this task's activies starting at the sub task.
3856 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
3857 performClearTaskAtIndexLocked(taskId, subtask.index);
3858 return subtask.activity;
3859 }
3860
3861 public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
3862 ActivityRecord resumed = mResumedActivity;
3863 final TaskAccessInfo thumbs = new TaskAccessInfo();
3864 // How many different sub-thumbnails?
3865 final int NA = mHistory.size();
3866 int j = 0;
3867 ThumbnailHolder holder = null;
3868 while (j < NA) {
3869 ActivityRecord ar = mHistory.get(j);
3870 if (!ar.finishing && ar.task.taskId == taskId) {
3871 holder = ar.thumbHolder;
3872 break;
3873 }
3874 j++;
3875 }
3876
3877 if (j >= NA) {
3878 return thumbs;
3879 }
3880
3881 thumbs.root = mHistory.get(j);
3882 thumbs.rootIndex = j;
3883
3884 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
3885 thumbs.subtasks = subtasks;
3886 ActivityRecord lastActivity = null;
3887 while (j < NA) {
3888 ActivityRecord ar = mHistory.get(j);
3889 j++;
3890 if (ar.finishing) {
3891 continue;
3892 }
3893 if (ar.task.taskId != taskId) {
3894 break;
3895 }
3896 lastActivity = ar;
3897 if (ar.thumbHolder != holder && holder != null) {
3898 thumbs.numSubThumbbails++;
3899 holder = ar.thumbHolder;
3900 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
3901 sub.thumbnail = holder.lastThumbnail;
3902 sub.activity = ar;
3903 sub.index = j-1;
3904 subtasks.add(sub);
3905 }
3906 }
3907 if (lastActivity != null && subtasks.size() > 0) {
3908 if (resumed == lastActivity) {
3909 TaskAccessInfo.SubTask sub = subtasks.get(subtasks.size()-1);
3910 sub.thumbnail = lastActivity.stack.screenshotActivities(lastActivity);
3911 }
3912 }
3913 if (thumbs.numSubThumbbails > 0) {
3914 thumbs.retriever = new IThumbnailRetriever.Stub() {
3915 public Bitmap getThumbnail(int index) {
3916 if (index < 0 || index >= thumbs.subtasks.size()) {
3917 return null;
3918 }
3919 return thumbs.subtasks.get(index).thumbnail;
3920 }
3921 };
3922 }
3923 return thumbs;
3924 }
3925
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003926 private final void logStartActivity(int tag, ActivityRecord r,
3927 TaskRecord task) {
3928 EventLog.writeEvent(tag,
3929 System.identityHashCode(r), task.taskId,
3930 r.shortComponentName, r.intent.getAction(),
3931 r.intent.getType(), r.intent.getDataString(),
3932 r.intent.getFlags());
3933 }
3934
3935 /**
3936 * Make sure the given activity matches the current configuration. Returns
3937 * false if the activity had to be destroyed. Returns true if the
3938 * configuration is the same, or the activity will remain running as-is
3939 * for whatever reason. Ensures the HistoryRecord is updated with the
3940 * correct configuration and all other bookkeeping is handled.
3941 */
3942 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
3943 int globalChanges) {
3944 if (mConfigWillChange) {
3945 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3946 "Skipping config check (will change): " + r);
3947 return true;
3948 }
3949
3950 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3951 "Ensuring correct configuration: " + r);
3952
3953 // Short circuit: if the two configurations are the exact same
3954 // object (the common case), then there is nothing to do.
3955 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003956 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003957 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3958 "Configuration unchanged in " + r);
3959 return true;
3960 }
3961
3962 // We don't worry about activities that are finishing.
3963 if (r.finishing) {
3964 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3965 "Configuration doesn't matter in finishing " + r);
3966 r.stopFreezingScreenLocked(false);
3967 return true;
3968 }
3969
3970 // Okay we now are going to make this activity have the new config.
3971 // But then we need to figure out how it needs to deal with that.
3972 Configuration oldConfig = r.configuration;
3973 r.configuration = newConfig;
3974
3975 // If the activity isn't currently running, just leave the new
3976 // configuration and it will pick that up next time it starts.
3977 if (r.app == null || r.app.thread == null) {
3978 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3979 "Configuration doesn't matter not running " + r);
3980 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003981 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003982 return true;
3983 }
3984
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07003985 // Figure out what has changed between the two configurations.
3986 int changes = oldConfig.diff(newConfig);
3987 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
3988 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
3989 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07003990 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07003991 + ", newConfig=" + newConfig);
3992 }
Dianne Hackborne6676352011-06-01 16:51:20 -07003993 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07003994 // Aha, the activity isn't handling the change, so DIE DIE DIE.
3995 r.configChangeFlags |= changes;
3996 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003997 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07003998 if (r.app == null || r.app.thread == null) {
3999 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4000 "Switch is destroying non-running " + r);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004001 destroyActivityLocked(r, true, false);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004002 } else if (r.state == ActivityState.PAUSING) {
4003 // A little annoying: we are waiting for this activity to
4004 // finish pausing. Let's not do anything now, but just
4005 // flag that it needs to be restarted when done pausing.
4006 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4007 "Switch is skipping already pausing " + r);
4008 r.configDestroy = true;
4009 return true;
4010 } else if (r.state == ActivityState.RESUMED) {
4011 // Try to optimize this case: the configuration is changing
4012 // and we need to restart the top, resumed activity.
4013 // Instead of doing the normal handshaking, just say
4014 // "restart!".
4015 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4016 "Switch is restarting resumed " + r);
4017 relaunchActivityLocked(r, r.configChangeFlags, true);
4018 r.configChangeFlags = 0;
4019 } else {
4020 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4021 "Switch is restarting non-resumed " + r);
4022 relaunchActivityLocked(r, r.configChangeFlags, false);
4023 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004024 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004025
4026 // All done... tell the caller we weren't able to keep this
4027 // activity around.
4028 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004029 }
4030
4031 // Default case: the activity can handle this new configuration, so
4032 // hand it over. Note that we don't need to give it the new
4033 // configuration, since we always send configuration changes to all
4034 // process when they happen so it can just use whatever configuration
4035 // it last got.
4036 if (r.app != null && r.app.thread != null) {
4037 try {
4038 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
4039 r.app.thread.scheduleActivityConfigurationChanged(r);
4040 } catch (RemoteException e) {
4041 // If process died, whatever.
4042 }
4043 }
4044 r.stopFreezingScreenLocked(false);
4045
4046 return true;
4047 }
4048
4049 private final boolean relaunchActivityLocked(ActivityRecord r,
4050 int changes, boolean andResume) {
4051 List<ResultInfo> results = null;
4052 List<Intent> newIntents = null;
4053 if (andResume) {
4054 results = r.results;
4055 newIntents = r.newIntents;
4056 }
4057 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4058 + " with results=" + results + " newIntents=" + newIntents
4059 + " andResume=" + andResume);
4060 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
4061 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
4062 r.task.taskId, r.shortComponentName);
4063
4064 r.startFreezingScreenLocked(r.app, 0);
4065
4066 try {
4067 if (DEBUG_SWITCH) Slog.i(TAG, "Switch is restarting resumed " + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004068 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004069 r.app.thread.scheduleRelaunchActivity(r, results, newIntents,
4070 changes, !andResume, mService.mConfiguration);
4071 // Note: don't need to call pauseIfSleepingLocked() here, because
4072 // the caller will only pass in 'andResume' if this activity is
4073 // currently resumed, which implies we aren't sleeping.
4074 } catch (RemoteException e) {
4075 return false;
4076 }
4077
4078 if (andResume) {
4079 r.results = null;
4080 r.newIntents = null;
4081 if (mMainStack) {
4082 mService.reportResumedActivityLocked(r);
4083 }
4084 }
4085
4086 return true;
4087 }
4088}