blob: 33b21ab3824aef13609ee04077395e8ba9e3af3c [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 Hackbornc68c9132011-07-29 01:25:18 -0700563 app.pendingUiClean = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700564 app.thread.scheduleLaunchActivity(new Intent(r.intent), r,
565 System.identityHashCode(r),
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700566 r.info, r.compat, r.icicle, results, newIntents, !andResume,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700567 mService.isNextTransitionForward());
568
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700569 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700570 // This may be a heavy-weight process! Note that the package
571 // manager will ensure that only activity can run in the main
572 // process of the .apk, which is the only thing that will be
573 // considered heavy-weight.
574 if (app.processName.equals(app.info.packageName)) {
575 if (mService.mHeavyWeightProcess != null
576 && mService.mHeavyWeightProcess != app) {
577 Log.w(TAG, "Starting new heavy weight process " + app
578 + " when already running "
579 + mService.mHeavyWeightProcess);
580 }
581 mService.mHeavyWeightProcess = app;
582 Message msg = mService.mHandler.obtainMessage(
583 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
584 msg.obj = r;
585 mService.mHandler.sendMessage(msg);
586 }
587 }
588
589 } catch (RemoteException e) {
590 if (r.launchFailed) {
591 // This is the second time we failed -- finish activity
592 // and give up.
593 Slog.e(TAG, "Second failure launching "
594 + r.intent.getComponent().flattenToShortString()
595 + ", giving up", e);
596 mService.appDiedLocked(app, app.pid, app.thread);
597 requestFinishActivityLocked(r, Activity.RESULT_CANCELED, null,
598 "2nd-crash");
599 return false;
600 }
601
602 // This is the first time we failed -- restart process and
603 // retry.
604 app.activities.remove(r);
605 throw e;
606 }
607
608 r.launchFailed = false;
609 if (updateLRUListLocked(r)) {
610 Slog.w(TAG, "Activity " + r
611 + " being launched, but already in LRU list");
612 }
613
614 if (andResume) {
615 // As part of the process of launching, ActivityThread also performs
616 // a resume.
617 r.state = ActivityState.RESUMED;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700618 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
619 + " (starting new instance)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700620 r.stopped = false;
621 mResumedActivity = r;
622 r.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -0800623 if (mMainStack) {
624 mService.addRecentTaskLocked(r.task);
625 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700626 completeResumeLocked(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800627 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700628 } else {
629 // This activity is not starting in the resumed state... which
630 // should look like we asked it to pause+stop (but remain visible),
631 // and it has done so and reported back the current icicle and
632 // other state.
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700633 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
634 + " (starting in stopped state)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700635 r.state = ActivityState.STOPPED;
636 r.stopped = true;
637 }
638
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800639 r.icicle = null;
640 r.haveState = false;
641
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700642 // Launch the new version setup screen if needed. We do this -after-
643 // launching the initial activity (that is, home), so that it can have
644 // a chance to initialize itself while in the background, making the
645 // switch back to it faster and look better.
646 if (mMainStack) {
647 mService.startSetupActivityLocked();
648 }
649
650 return true;
651 }
652
653 private final void startSpecificActivityLocked(ActivityRecord r,
654 boolean andResume, boolean checkConfig) {
655 // Is this activity's application already running?
656 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
657 r.info.applicationInfo.uid);
658
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700659 if (r.launchTime == 0) {
660 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700661 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700662 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700663 }
664 } else if (mInitialStartTime == 0) {
665 mInitialStartTime = SystemClock.uptimeMillis();
666 }
667
668 if (app != null && app.thread != null) {
669 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700670 app.addPackage(r.info.packageName);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700671 realStartActivityLocked(r, app, andResume, checkConfig);
672 return;
673 } catch (RemoteException e) {
674 Slog.w(TAG, "Exception when starting activity "
675 + r.intent.getComponent().flattenToShortString(), e);
676 }
677
678 // If a dead object exception was thrown -- fall through to
679 // restart the application.
680 }
681
682 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
683 "activity", r.intent.getComponent(), false);
684 }
685
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800686 void stopIfSleepingLocked() {
687 if (mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700688 if (!mGoingToSleep.isHeld()) {
689 mGoingToSleep.acquire();
690 if (mLaunchingActivity.isHeld()) {
691 mLaunchingActivity.release();
692 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
693 }
694 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800695 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
696 Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
697 mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
698 checkReadyForSleepLocked();
699 }
700 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700701
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800702 void awakeFromSleepingLocked() {
703 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
704 mSleepTimeout = false;
705 if (mGoingToSleep.isHeld()) {
706 mGoingToSleep.release();
707 }
708 // Ensure activities are no longer sleeping.
709 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700710 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800711 r.setSleeping(false);
712 }
713 mGoingToSleepActivities.clear();
714 }
715
716 void activitySleptLocked(ActivityRecord r) {
717 mGoingToSleepActivities.remove(r);
718 checkReadyForSleepLocked();
719 }
720
721 void checkReadyForSleepLocked() {
722 if (!mService.isSleeping()) {
723 // Do not care.
724 return;
725 }
726
727 if (!mSleepTimeout) {
728 if (mResumedActivity != null) {
729 // Still have something resumed; can't sleep until it is paused.
730 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700731 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
732 startPausingLocked(false, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800733 return;
734 }
735 if (mPausingActivity != null) {
736 // Still waiting for something to pause; can't sleep yet.
737 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
738 return;
739 }
740
741 if (mStoppingActivities.size() > 0) {
742 // Still need to tell some activities to stop; can't sleep yet.
743 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
744 + mStoppingActivities.size() + " activities");
745 Message msg = Message.obtain();
746 msg.what = IDLE_NOW_MSG;
747 mHandler.sendMessage(msg);
748 return;
749 }
750
751 ensureActivitiesVisibleLocked(null, 0);
752
753 // Make sure any stopped but visible activities are now sleeping.
754 // This ensures that the activity's onStop() is called.
755 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700756 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800757 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
758 r.setSleeping(true);
759 }
760 }
761
762 if (mGoingToSleepActivities.size() > 0) {
763 // Still need to tell some activities to sleep; can't sleep yet.
764 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
765 + mGoingToSleepActivities.size() + " activities");
766 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700767 }
768 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800769
770 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
771
772 if (mGoingToSleep.isHeld()) {
773 mGoingToSleep.release();
774 }
775 if (mService.mShuttingDown) {
776 mService.notifyAll();
777 }
778
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700779 }
780
Dianne Hackbornd2835932010-12-13 16:28:46 -0800781 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -0800782 if (who.noDisplay) {
783 return null;
784 }
785
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800786 Resources res = mService.mContext.getResources();
787 int w = mThumbnailWidth;
788 int h = mThumbnailHeight;
789 if (w < 0) {
790 mThumbnailWidth = w =
791 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
792 mThumbnailHeight = h =
793 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
794 }
795
796 if (w > 0) {
Dianne Hackborn7c8a4b32010-12-15 14:58:00 -0800797 return mService.mWindowManager.screenshotApplications(who, w, h);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800798 }
799 return null;
800 }
801
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700802 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
803 if (mPausingActivity != null) {
804 RuntimeException e = new RuntimeException();
805 Slog.e(TAG, "Trying to pause when pause is already pending for "
806 + mPausingActivity, e);
807 }
808 ActivityRecord prev = mResumedActivity;
809 if (prev == null) {
810 RuntimeException e = new RuntimeException();
811 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
812 resumeTopActivityLocked(null);
813 return;
814 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700815 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
816 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700817 mResumedActivity = null;
818 mPausingActivity = prev;
819 mLastPausedActivity = prev;
820 prev.state = ActivityState.PAUSING;
821 prev.task.touchActiveTime();
Dianne Hackbornf26fd992011-04-08 18:14:09 -0700822 prev.updateThumbnail(screenshotActivities(prev), null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700823
824 mService.updateCpuStats();
825
826 if (prev.app != null && prev.app.thread != null) {
827 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
828 try {
829 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
830 System.identityHashCode(prev),
831 prev.shortComponentName);
832 prev.app.thread.schedulePauseActivity(prev, prev.finishing, userLeaving,
833 prev.configChangeFlags);
834 if (mMainStack) {
835 mService.updateUsageStats(prev, false);
836 }
837 } catch (Exception e) {
838 // Ignore exception, if process died other code will cleanup.
839 Slog.w(TAG, "Exception thrown during pause", e);
840 mPausingActivity = null;
841 mLastPausedActivity = null;
842 }
843 } else {
844 mPausingActivity = null;
845 mLastPausedActivity = null;
846 }
847
848 // If we are not going to sleep, we want to ensure the device is
849 // awake until the next activity is started.
850 if (!mService.mSleeping && !mService.mShuttingDown) {
851 mLaunchingActivity.acquire();
852 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
853 // To be safe, don't allow the wake lock to be held for too long.
854 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
855 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
856 }
857 }
858
859
860 if (mPausingActivity != null) {
861 // Have the window manager pause its key dispatching until the new
862 // activity has started. If we're pausing the activity just because
863 // the screen is being turned off and the UI is sleeping, don't interrupt
864 // key dispatch; the same activity will pick it up again on wakeup.
865 if (!uiSleeping) {
866 prev.pauseKeyDispatchingLocked();
867 } else {
868 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
869 }
870
871 // Schedule a pause timeout in case the app doesn't respond.
872 // We don't give it much time because this directly impacts the
873 // responsiveness seen by the user.
874 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
875 msg.obj = prev;
876 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
877 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
878 } else {
879 // This activity failed to schedule the
880 // pause, so just treat it as being paused now.
881 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
882 resumeTopActivityLocked(null);
883 }
884 }
885
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800886 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700887 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800888 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700889
890 ActivityRecord r = null;
891
892 synchronized (mService) {
893 int index = indexOfTokenLocked(token);
894 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700895 r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700896 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
897 if (mPausingActivity == r) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700898 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
899 + (timeout ? " (due to timeout)" : " (pause complete)"));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700900 r.state = ActivityState.PAUSED;
901 completePauseLocked();
902 } else {
903 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
904 System.identityHashCode(r), r.shortComponentName,
905 mPausingActivity != null
906 ? mPausingActivity.shortComponentName : "(none)");
907 }
908 }
909 }
910 }
911
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700912 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
913 CharSequence description) {
914 r.icicle = icicle;
915 r.haveState = true;
916 r.updateThumbnail(thumbnail, description);
917 r.stopped = true;
918 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
919 r.state = ActivityState.STOPPED;
920 if (!r.finishing) {
921 if (r.configDestroy) {
922 destroyActivityLocked(r, true, false);
923 resumeTopActivityLocked(null);
924 }
925 }
926 }
927
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700928 private final void completePauseLocked() {
929 ActivityRecord prev = mPausingActivity;
930 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
931
932 if (prev != null) {
933 if (prev.finishing) {
934 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
935 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE);
936 } else if (prev.app != null) {
937 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
938 if (prev.waitingVisible) {
939 prev.waitingVisible = false;
940 mWaitingVisibleActivities.remove(prev);
941 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
942 TAG, "Complete pause, no longer waiting: " + prev);
943 }
944 if (prev.configDestroy) {
945 // The previous is being paused because the configuration
946 // is changing, which means it is actually stopping...
947 // To juggle the fact that we are also starting a new
948 // instance right now, we need to first completely stop
949 // the current instance before starting the new one.
950 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700951 destroyActivityLocked(prev, true, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700952 } else {
953 mStoppingActivities.add(prev);
954 if (mStoppingActivities.size() > 3) {
955 // If we already have a few activities waiting to stop,
956 // then give up on things going idle and start clearing
957 // them out.
958 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
959 Message msg = Message.obtain();
960 msg.what = IDLE_NOW_MSG;
961 mHandler.sendMessage(msg);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800962 } else {
963 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700964 }
965 }
966 } else {
967 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
968 prev = null;
969 }
970 mPausingActivity = null;
971 }
972
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800973 if (!mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700974 resumeTopActivityLocked(prev);
975 } else {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800976 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700977 }
978
979 if (prev != null) {
980 prev.resumeKeyDispatchingLocked();
981 }
982
983 if (prev.app != null && prev.cpuTimeAtResume > 0
984 && mService.mBatteryStatsService.isOnBattery()) {
985 long diff = 0;
986 synchronized (mService.mProcessStatsThread) {
987 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
988 - prev.cpuTimeAtResume;
989 }
990 if (diff > 0) {
991 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
992 synchronized (bsi) {
993 BatteryStatsImpl.Uid.Proc ps =
994 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
995 prev.info.packageName);
996 if (ps != null) {
997 ps.addForegroundTimeLocked(diff);
998 }
999 }
1000 }
1001 }
1002 prev.cpuTimeAtResume = 0; // reset it
1003 }
1004
1005 /**
1006 * Once we know that we have asked an application to put an activity in
1007 * the resumed state (either by launching it or explicitly telling it),
1008 * this function updates the rest of our state to match that fact.
1009 */
1010 private final void completeResumeLocked(ActivityRecord next) {
1011 next.idle = false;
1012 next.results = null;
1013 next.newIntents = null;
1014
1015 // schedule an idle timeout in case the app doesn't do it for us.
1016 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1017 msg.obj = next;
1018 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
1019
1020 if (false) {
1021 // The activity was never told to pause, so just keep
1022 // things going as-is. To maintain our own state,
1023 // we need to emulate it coming back and saying it is
1024 // idle.
1025 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
1026 msg.obj = next;
1027 mHandler.sendMessage(msg);
1028 }
1029
1030 if (mMainStack) {
1031 mService.reportResumedActivityLocked(next);
1032 }
1033
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001034 next.clearThumbnail();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001035 if (mMainStack) {
1036 mService.setFocusedActivityLocked(next);
1037 }
1038 next.resumeKeyDispatchingLocked();
1039 ensureActivitiesVisibleLocked(null, 0);
1040 mService.mWindowManager.executeAppTransition();
1041 mNoAnimActivities.clear();
1042
1043 // Mark the point when the activity is resuming
1044 // TODO: To be more accurate, the mark should be before the onCreate,
1045 // not after the onResume. But for subsequent starts, onResume is fine.
1046 if (next.app != null) {
1047 synchronized (mService.mProcessStatsThread) {
1048 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1049 }
1050 } else {
1051 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1052 }
1053 }
1054
1055 /**
1056 * Make sure that all activities that need to be visible (that is, they
1057 * currently can be seen by the user) actually are.
1058 */
1059 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1060 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1061 if (DEBUG_VISBILITY) Slog.v(
1062 TAG, "ensureActivitiesVisible behind " + top
1063 + " configChanges=0x" + Integer.toHexString(configChanges));
1064
1065 // If the top activity is not fullscreen, then we need to
1066 // make sure any activities under it are now visible.
1067 final int count = mHistory.size();
1068 int i = count-1;
1069 while (mHistory.get(i) != top) {
1070 i--;
1071 }
1072 ActivityRecord r;
1073 boolean behindFullscreen = false;
1074 for (; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001075 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001076 if (DEBUG_VISBILITY) Slog.v(
1077 TAG, "Make visible? " + r + " finishing=" + r.finishing
1078 + " state=" + r.state);
1079 if (r.finishing) {
1080 continue;
1081 }
1082
1083 final boolean doThisProcess = onlyThisProcess == null
1084 || onlyThisProcess.equals(r.processName);
1085
1086 // First: if this is not the current activity being started, make
1087 // sure it matches the current configuration.
1088 if (r != starting && doThisProcess) {
1089 ensureActivityConfigurationLocked(r, 0);
1090 }
1091
1092 if (r.app == null || r.app.thread == null) {
1093 if (onlyThisProcess == null
1094 || onlyThisProcess.equals(r.processName)) {
1095 // This activity needs to be visible, but isn't even
1096 // running... get it started, but don't resume it
1097 // at this point.
1098 if (DEBUG_VISBILITY) Slog.v(
1099 TAG, "Start and freeze screen for " + r);
1100 if (r != starting) {
1101 r.startFreezingScreenLocked(r.app, configChanges);
1102 }
1103 if (!r.visible) {
1104 if (DEBUG_VISBILITY) Slog.v(
1105 TAG, "Starting and making visible: " + r);
1106 mService.mWindowManager.setAppVisibility(r, true);
1107 }
1108 if (r != starting) {
1109 startSpecificActivityLocked(r, false, false);
1110 }
1111 }
1112
1113 } else if (r.visible) {
1114 // If this activity is already visible, then there is nothing
1115 // else to do here.
1116 if (DEBUG_VISBILITY) Slog.v(
1117 TAG, "Skipping: already visible at " + r);
1118 r.stopFreezingScreenLocked(false);
1119
1120 } else if (onlyThisProcess == null) {
1121 // This activity is not currently visible, but is running.
1122 // Tell it to become visible.
1123 r.visible = true;
1124 if (r.state != ActivityState.RESUMED && r != starting) {
1125 // If this activity is paused, tell it
1126 // to now show its window.
1127 if (DEBUG_VISBILITY) Slog.v(
1128 TAG, "Making visible and scheduling visibility: " + r);
1129 try {
1130 mService.mWindowManager.setAppVisibility(r, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001131 r.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001132 r.app.thread.scheduleWindowVisibility(r, true);
1133 r.stopFreezingScreenLocked(false);
1134 } catch (Exception e) {
1135 // Just skip on any failure; we'll make it
1136 // visible when it next restarts.
1137 Slog.w(TAG, "Exception thrown making visibile: "
1138 + r.intent.getComponent(), e);
1139 }
1140 }
1141 }
1142
1143 // Aggregate current change flags.
1144 configChanges |= r.configChangeFlags;
1145
1146 if (r.fullscreen) {
1147 // At this point, nothing else needs to be shown
1148 if (DEBUG_VISBILITY) Slog.v(
1149 TAG, "Stopping: fullscreen at " + r);
1150 behindFullscreen = true;
1151 i--;
1152 break;
1153 }
1154 }
1155
1156 // Now for any activities that aren't visible to the user, make
1157 // sure they no longer are keeping the screen frozen.
1158 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001159 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001160 if (DEBUG_VISBILITY) Slog.v(
1161 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1162 + " state=" + r.state
1163 + " behindFullscreen=" + behindFullscreen);
1164 if (!r.finishing) {
1165 if (behindFullscreen) {
1166 if (r.visible) {
1167 if (DEBUG_VISBILITY) Slog.v(
1168 TAG, "Making invisible: " + r);
1169 r.visible = false;
1170 try {
1171 mService.mWindowManager.setAppVisibility(r, false);
1172 if ((r.state == ActivityState.STOPPING
1173 || r.state == ActivityState.STOPPED)
1174 && r.app != null && r.app.thread != null) {
1175 if (DEBUG_VISBILITY) Slog.v(
1176 TAG, "Scheduling invisibility: " + r);
1177 r.app.thread.scheduleWindowVisibility(r, false);
1178 }
1179 } catch (Exception e) {
1180 // Just skip on any failure; we'll make it
1181 // visible when it next restarts.
1182 Slog.w(TAG, "Exception thrown making hidden: "
1183 + r.intent.getComponent(), e);
1184 }
1185 } else {
1186 if (DEBUG_VISBILITY) Slog.v(
1187 TAG, "Already invisible: " + r);
1188 }
1189 } else if (r.fullscreen) {
1190 if (DEBUG_VISBILITY) Slog.v(
1191 TAG, "Now behindFullscreen: " + r);
1192 behindFullscreen = true;
1193 }
1194 }
1195 i--;
1196 }
1197 }
1198
1199 /**
1200 * Version of ensureActivitiesVisible that can easily be called anywhere.
1201 */
1202 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1203 int configChanges) {
1204 ActivityRecord r = topRunningActivityLocked(null);
1205 if (r != null) {
1206 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1207 }
1208 }
1209
1210 /**
1211 * Ensure that the top activity in the stack is resumed.
1212 *
1213 * @param prev The previously resumed activity, for when in the process
1214 * of pausing; can be null to call from elsewhere.
1215 *
1216 * @return Returns true if something is being resumed, or false if
1217 * nothing happened.
1218 */
1219 final boolean resumeTopActivityLocked(ActivityRecord prev) {
1220 // Find the first activity that is not finishing.
1221 ActivityRecord next = topRunningActivityLocked(null);
1222
1223 // Remember how we'll process this pause/resume situation, and ensure
1224 // that the state is reset however we wind up proceeding.
1225 final boolean userLeaving = mUserLeaving;
1226 mUserLeaving = false;
1227
1228 if (next == null) {
1229 // There are no more activities! Let's just start up the
1230 // Launcher...
1231 if (mMainStack) {
1232 return mService.startHomeActivityLocked();
1233 }
1234 }
1235
1236 next.delayedResume = false;
1237
1238 // If the top activity is the resumed one, nothing to do.
1239 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1240 // Make sure we have executed any pending transitions, since there
1241 // should be nothing left to do at this point.
1242 mService.mWindowManager.executeAppTransition();
1243 mNoAnimActivities.clear();
1244 return false;
1245 }
1246
1247 // If we are sleeping, and there is no resumed activity, and the top
1248 // activity is paused, well that is the state we want.
1249 if ((mService.mSleeping || mService.mShuttingDown)
1250 && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
1251 // Make sure we have executed any pending transitions, since there
1252 // should be nothing left to do at this point.
1253 mService.mWindowManager.executeAppTransition();
1254 mNoAnimActivities.clear();
1255 return false;
1256 }
1257
1258 // The activity may be waiting for stop, but that is no longer
1259 // appropriate for it.
1260 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001261 mGoingToSleepActivities.remove(next);
1262 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001263 mWaitingVisibleActivities.remove(next);
1264
1265 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1266
1267 // If we are currently pausing an activity, then don't do anything
1268 // until that is done.
1269 if (mPausingActivity != null) {
1270 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
1271 return false;
1272 }
1273
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001274 // Okay we are now going to start a switch, to 'next'. We may first
1275 // have to pause the current activity, but this is an important point
1276 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001277 // XXX "App Redirected" dialog is getting too many false positives
1278 // at this point, so turn off for now.
1279 if (false) {
1280 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1281 long now = SystemClock.uptimeMillis();
1282 final boolean inTime = mLastStartedActivity.startTime != 0
1283 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1284 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1285 final int nextUid = next.info.applicationInfo.uid;
1286 if (inTime && lastUid != nextUid
1287 && lastUid != next.launchedFromUid
1288 && mService.checkPermission(
1289 android.Manifest.permission.STOP_APP_SWITCHES,
1290 -1, next.launchedFromUid)
1291 != PackageManager.PERMISSION_GRANTED) {
1292 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1293 } else {
1294 next.startTime = now;
1295 mLastStartedActivity = next;
1296 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001297 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001298 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001299 mLastStartedActivity = next;
1300 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001301 }
1302
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001303 // We need to start pausing the current activity so the top one
1304 // can be resumed...
1305 if (mResumedActivity != null) {
1306 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
1307 startPausingLocked(userLeaving, false);
1308 return true;
1309 }
1310
1311 if (prev != null && prev != next) {
1312 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1313 prev.waitingVisible = true;
1314 mWaitingVisibleActivities.add(prev);
1315 if (DEBUG_SWITCH) Slog.v(
1316 TAG, "Resuming top, waiting visible to hide: " + prev);
1317 } else {
1318 // The next activity is already visible, so hide the previous
1319 // activity's windows right now so we can show the new one ASAP.
1320 // We only do this if the previous is finishing, which should mean
1321 // it is on top of the one being resumed so hiding it quickly
1322 // is good. Otherwise, we want to do the normal route of allowing
1323 // the resumed activity to be shown so we can decide if the
1324 // previous should actually be hidden depending on whether the
1325 // new one is found to be full-screen or not.
1326 if (prev.finishing) {
1327 mService.mWindowManager.setAppVisibility(prev, false);
1328 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1329 + prev + ", waitingVisible="
1330 + (prev != null ? prev.waitingVisible : null)
1331 + ", nowVisible=" + next.nowVisible);
1332 } else {
1333 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1334 + prev + ", waitingVisible="
1335 + (prev != null ? prev.waitingVisible : null)
1336 + ", nowVisible=" + next.nowVisible);
1337 }
1338 }
1339 }
1340
Dianne Hackborne7f97212011-02-24 14:40:20 -08001341 // Launching this app's activity, make sure the app is no longer
1342 // considered stopped.
1343 try {
1344 AppGlobals.getPackageManager().setPackageStoppedState(
1345 next.packageName, false);
1346 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001347 } catch (IllegalArgumentException e) {
1348 Slog.w(TAG, "Failed trying to unstop package "
1349 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001350 }
1351
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001352 // We are starting up the next activity, so tell the window manager
1353 // that the previous one will be hidden soon. This way it can know
1354 // to ignore it when computing the desired screen orientation.
1355 if (prev != null) {
1356 if (prev.finishing) {
1357 if (DEBUG_TRANSITION) Slog.v(TAG,
1358 "Prepare close transition: prev=" + prev);
1359 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001360 mService.mWindowManager.prepareAppTransition(
1361 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001362 } else {
1363 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1364 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001365 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001366 }
1367 mService.mWindowManager.setAppWillBeHidden(prev);
1368 mService.mWindowManager.setAppVisibility(prev, false);
1369 } else {
1370 if (DEBUG_TRANSITION) Slog.v(TAG,
1371 "Prepare open transition: prev=" + prev);
1372 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001373 mService.mWindowManager.prepareAppTransition(
1374 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001375 } else {
1376 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1377 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001378 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001379 }
1380 }
1381 if (false) {
1382 mService.mWindowManager.setAppWillBeHidden(prev);
1383 mService.mWindowManager.setAppVisibility(prev, false);
1384 }
1385 } else if (mHistory.size() > 1) {
1386 if (DEBUG_TRANSITION) Slog.v(TAG,
1387 "Prepare open transition: no previous");
1388 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001389 mService.mWindowManager.prepareAppTransition(
1390 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001391 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001392 mService.mWindowManager.prepareAppTransition(
1393 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001394 }
1395 }
1396
1397 if (next.app != null && next.app.thread != null) {
1398 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1399
1400 // This activity is now becoming visible.
1401 mService.mWindowManager.setAppVisibility(next, true);
1402
1403 ActivityRecord lastResumedActivity = mResumedActivity;
1404 ActivityState lastState = next.state;
1405
1406 mService.updateCpuStats();
1407
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001408 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001409 next.state = ActivityState.RESUMED;
1410 mResumedActivity = next;
1411 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001412 if (mMainStack) {
1413 mService.addRecentTaskLocked(next.task);
1414 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001415 mService.updateLruProcessLocked(next.app, true, true);
1416 updateLRUListLocked(next);
1417
1418 // Have the window manager re-evaluate the orientation of
1419 // the screen based on the new activity order.
1420 boolean updated = false;
1421 if (mMainStack) {
1422 synchronized (mService) {
1423 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1424 mService.mConfiguration,
1425 next.mayFreezeScreenLocked(next.app) ? next : null);
1426 if (config != null) {
1427 next.frozenBeforeDestroy = true;
1428 }
Dianne Hackborn31ca8542011-07-19 14:58:28 -07001429 updated = mService.updateConfigurationLocked(config, next, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001430 }
1431 }
1432 if (!updated) {
1433 // The configuration update wasn't able to keep the existing
1434 // instance of the activity, and instead started a new one.
1435 // We should be all done, but let's just make sure our activity
1436 // is still at the top and schedule another run if something
1437 // weird happened.
1438 ActivityRecord nextNext = topRunningActivityLocked(null);
1439 if (DEBUG_SWITCH) Slog.i(TAG,
1440 "Activity config changed during resume: " + next
1441 + ", new next: " + nextNext);
1442 if (nextNext != next) {
1443 // Do over!
1444 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1445 }
1446 if (mMainStack) {
1447 mService.setFocusedActivityLocked(next);
1448 }
1449 ensureActivitiesVisibleLocked(null, 0);
1450 mService.mWindowManager.executeAppTransition();
1451 mNoAnimActivities.clear();
1452 return true;
1453 }
1454
1455 try {
1456 // Deliver all pending results.
1457 ArrayList a = next.results;
1458 if (a != null) {
1459 final int N = a.size();
1460 if (!next.finishing && N > 0) {
1461 if (DEBUG_RESULTS) Slog.v(
1462 TAG, "Delivering results to " + next
1463 + ": " + a);
1464 next.app.thread.scheduleSendResult(next, a);
1465 }
1466 }
1467
1468 if (next.newIntents != null) {
1469 next.app.thread.scheduleNewIntent(next.newIntents, next);
1470 }
1471
1472 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
1473 System.identityHashCode(next),
1474 next.task.taskId, next.shortComponentName);
1475
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001476 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001477 showAskCompatModeDialogLocked(next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001478 next.app.thread.scheduleResumeActivity(next,
1479 mService.isNextTransitionForward());
1480
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001481 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001482
1483 } catch (Exception e) {
1484 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001485 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1486 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001487 next.state = lastState;
1488 mResumedActivity = lastResumedActivity;
1489 Slog.i(TAG, "Restarting because process died: " + next);
1490 if (!next.hasBeenLaunched) {
1491 next.hasBeenLaunched = true;
1492 } else {
1493 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1494 mService.mWindowManager.setAppStartingWindow(
1495 next, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001496 mService.compatibilityInfoForPackageLocked(
1497 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001498 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001499 next.labelRes, next.icon, next.windowFlags,
1500 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001501 }
1502 }
1503 startSpecificActivityLocked(next, true, false);
1504 return true;
1505 }
1506
1507 // From this point on, if something goes wrong there is no way
1508 // to recover the activity.
1509 try {
1510 next.visible = true;
1511 completeResumeLocked(next);
1512 } catch (Exception e) {
1513 // If any exception gets thrown, toss away this
1514 // activity and try the next one.
1515 Slog.w(TAG, "Exception thrown during resume of " + next, e);
1516 requestFinishActivityLocked(next, Activity.RESULT_CANCELED, null,
1517 "resume-exception");
1518 return true;
1519 }
1520
1521 // Didn't need to use the icicle, and it is now out of date.
1522 next.icicle = null;
1523 next.haveState = false;
1524 next.stopped = false;
1525
1526 } else {
1527 // Whoops, need to restart this activity!
1528 if (!next.hasBeenLaunched) {
1529 next.hasBeenLaunched = true;
1530 } else {
1531 if (SHOW_APP_STARTING_PREVIEW) {
1532 mService.mWindowManager.setAppStartingWindow(
1533 next, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001534 mService.compatibilityInfoForPackageLocked(
1535 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001536 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001537 next.labelRes, next.icon, next.windowFlags,
1538 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001539 }
1540 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1541 }
1542 startSpecificActivityLocked(next, true, true);
1543 }
1544
1545 return true;
1546 }
1547
1548 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001549 boolean doResume, boolean keepCurTransition) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001550 final int NH = mHistory.size();
1551
1552 int addPos = -1;
1553
1554 if (!newTask) {
1555 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001556 boolean startIt = true;
1557 for (int i = NH-1; i >= 0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001558 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001559 if (p.finishing) {
1560 continue;
1561 }
1562 if (p.task == r.task) {
1563 // Here it is! Now, if this is not yet visible to the
1564 // user, then just add it without starting; it will
1565 // get started when the user navigates back to it.
1566 addPos = i+1;
1567 if (!startIt) {
1568 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001569 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001570 mService.mWindowManager.addAppToken(addPos, r, r.task.taskId,
1571 r.info.screenOrientation, r.fullscreen);
1572 if (VALIDATE_TOKENS) {
1573 mService.mWindowManager.validateAppTokens(mHistory);
1574 }
1575 return;
1576 }
1577 break;
1578 }
1579 if (p.fullscreen) {
1580 startIt = false;
1581 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001582 }
1583 }
1584
1585 // Place a new activity at top of stack, so it is next to interact
1586 // with the user.
1587 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001588 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001589 }
1590
1591 // If we are not placing the new activity frontmost, we do not want
1592 // to deliver the onUserLeaving callback to the actual frontmost
1593 // activity
1594 if (addPos < NH) {
1595 mUserLeaving = false;
1596 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1597 }
1598
1599 // Slot the activity into the history stack and proceed
1600 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001601 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001602 r.frontOfTask = newTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001603 if (NH > 0) {
1604 // We want to show the starting preview window if we are
1605 // switching to a new task, or the next activity's process is
1606 // not currently running.
1607 boolean showStartingIcon = newTask;
1608 ProcessRecord proc = r.app;
1609 if (proc == null) {
1610 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1611 }
1612 if (proc == null || proc.thread == null) {
1613 showStartingIcon = true;
1614 }
1615 if (DEBUG_TRANSITION) Slog.v(TAG,
1616 "Prepare open transition: starting " + r);
1617 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001618 mService.mWindowManager.prepareAppTransition(
1619 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001620 mNoAnimActivities.add(r);
1621 } else if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
1622 mService.mWindowManager.prepareAppTransition(
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001623 WindowManagerPolicy.TRANSIT_TASK_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001624 mNoAnimActivities.remove(r);
1625 } else {
1626 mService.mWindowManager.prepareAppTransition(newTask
1627 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001628 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001629 mNoAnimActivities.remove(r);
1630 }
1631 mService.mWindowManager.addAppToken(
1632 addPos, r, r.task.taskId, r.info.screenOrientation, r.fullscreen);
1633 boolean doShow = true;
1634 if (newTask) {
1635 // Even though this activity is starting fresh, we still need
1636 // to reset it to make sure we apply affinities to move any
1637 // existing activities from other tasks in to it.
1638 // If the caller has requested that the target task be
1639 // reset, then do so.
1640 if ((r.intent.getFlags()
1641 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1642 resetTaskIfNeededLocked(r, r);
1643 doShow = topRunningNonDelayedActivityLocked(null) == r;
1644 }
1645 }
1646 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1647 // Figure out if we are transitioning from another activity that is
1648 // "has the same starting icon" as the next one. This allows the
1649 // window manager to keep the previous window it had previously
1650 // created, if it still had one.
1651 ActivityRecord prev = mResumedActivity;
1652 if (prev != null) {
1653 // We don't want to reuse the previous starting preview if:
1654 // (1) The current activity is in a different task.
1655 if (prev.task != r.task) prev = null;
1656 // (2) The current activity is already displayed.
1657 else if (prev.nowVisible) prev = null;
1658 }
1659 mService.mWindowManager.setAppStartingWindow(
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001660 r, r.packageName, r.theme,
1661 mService.compatibilityInfoForPackageLocked(
1662 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001663 r.labelRes, r.icon, r.windowFlags, prev, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001664 }
1665 } else {
1666 // If this is the first activity, don't do any fancy animations,
1667 // because there is nothing for it to animate on top of.
1668 mService.mWindowManager.addAppToken(addPos, r, r.task.taskId,
1669 r.info.screenOrientation, r.fullscreen);
1670 }
1671 if (VALIDATE_TOKENS) {
1672 mService.mWindowManager.validateAppTokens(mHistory);
1673 }
1674
1675 if (doResume) {
1676 resumeTopActivityLocked(null);
1677 }
1678 }
1679
1680 /**
1681 * Perform a reset of the given task, if needed as part of launching it.
1682 * Returns the new HistoryRecord at the top of the task.
1683 */
1684 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1685 ActivityRecord newActivity) {
1686 boolean forceReset = (newActivity.info.flags
1687 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001688 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1689 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001690 if ((newActivity.info.flags
1691 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1692 forceReset = true;
1693 }
1694 }
1695
1696 final TaskRecord task = taskTop.task;
1697
1698 // We are going to move through the history list so that we can look
1699 // at each activity 'target' with 'below' either the interesting
1700 // activity immediately below it in the stack or null.
1701 ActivityRecord target = null;
1702 int targetI = 0;
1703 int taskTopI = -1;
1704 int replyChainEnd = -1;
1705 int lastReparentPos = -1;
1706 for (int i=mHistory.size()-1; i>=-1; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001707 ActivityRecord below = i >= 0 ? mHistory.get(i) : null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001708
1709 if (below != null && below.finishing) {
1710 continue;
1711 }
1712 if (target == null) {
1713 target = below;
1714 targetI = i;
1715 // If we were in the middle of a reply chain before this
1716 // task, it doesn't appear like the root of the chain wants
1717 // anything interesting, so drop it.
1718 replyChainEnd = -1;
1719 continue;
1720 }
1721
1722 final int flags = target.info.flags;
1723
1724 final boolean finishOnTaskLaunch =
1725 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1726 final boolean allowTaskReparenting =
1727 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1728
1729 if (target.task == task) {
1730 // We are inside of the task being reset... we'll either
1731 // finish this activity, push it out for another task,
1732 // or leave it as-is. We only do this
1733 // for activities that are not the root of the task (since
1734 // if we finish the root, we may no longer have the task!).
1735 if (taskTopI < 0) {
1736 taskTopI = targetI;
1737 }
1738 if (below != null && below.task == task) {
1739 final boolean clearWhenTaskReset =
1740 (target.intent.getFlags()
1741 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
1742 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
1743 // If this activity is sending a reply to a previous
1744 // activity, we can't do anything with it now until
1745 // we reach the start of the reply chain.
1746 // XXX note that we are assuming the result is always
1747 // to the previous activity, which is almost always
1748 // the case but we really shouldn't count on.
1749 if (replyChainEnd < 0) {
1750 replyChainEnd = targetI;
1751 }
1752 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
1753 && target.taskAffinity != null
1754 && !target.taskAffinity.equals(task.affinity)) {
1755 // If this activity has an affinity for another
1756 // task, then we need to move it out of here. We will
1757 // move it as far out of the way as possible, to the
1758 // bottom of the activity stack. This also keeps it
1759 // correctly ordered with any activities we previously
1760 // moved.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001761 ActivityRecord p = mHistory.get(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001762 if (target.taskAffinity != null
1763 && target.taskAffinity.equals(p.task.affinity)) {
1764 // If the activity currently at the bottom has the
1765 // same task affinity as the one we are moving,
1766 // then merge it into the same task.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001767 target.setTask(p.task, p.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001768 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1769 + " out to bottom task " + p.task);
1770 } else {
1771 mService.mCurTask++;
1772 if (mService.mCurTask <= 0) {
1773 mService.mCurTask = 1;
1774 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001775 target.setTask(new TaskRecord(mService.mCurTask, target.info, null),
1776 null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001777 target.task.affinityIntent = target.intent;
1778 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1779 + " out to new task " + target.task);
1780 }
1781 mService.mWindowManager.setAppGroupId(target, task.taskId);
1782 if (replyChainEnd < 0) {
1783 replyChainEnd = targetI;
1784 }
1785 int dstPos = 0;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001786 ThumbnailHolder curThumbHolder = target.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001787 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001788 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001789 if (p.finishing) {
1790 continue;
1791 }
1792 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
1793 + " out to target's task " + target.task);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001794 p.setTask(target.task, curThumbHolder, false);
1795 curThumbHolder = p.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001796 mHistory.remove(srcPos);
1797 mHistory.add(dstPos, p);
1798 mService.mWindowManager.moveAppToken(dstPos, p);
1799 mService.mWindowManager.setAppGroupId(p, p.task.taskId);
1800 dstPos++;
1801 if (VALIDATE_TOKENS) {
1802 mService.mWindowManager.validateAppTokens(mHistory);
1803 }
1804 i++;
1805 }
1806 if (taskTop == p) {
1807 taskTop = below;
1808 }
1809 if (taskTopI == replyChainEnd) {
1810 taskTopI = -1;
1811 }
1812 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001813 } else if (forceReset || finishOnTaskLaunch
1814 || clearWhenTaskReset) {
1815 // If the activity should just be removed -- either
1816 // because it asks for it, or the task should be
1817 // cleared -- then finish it and anything that is
1818 // part of its reply chain.
1819 if (clearWhenTaskReset) {
1820 // In this case, we want to finish this activity
1821 // and everything above it, so be sneaky and pretend
1822 // like these are all in the reply chain.
1823 replyChainEnd = targetI+1;
1824 while (replyChainEnd < mHistory.size() &&
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001825 (mHistory.get(
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001826 replyChainEnd)).task == task) {
1827 replyChainEnd++;
1828 }
1829 replyChainEnd--;
1830 } else if (replyChainEnd < 0) {
1831 replyChainEnd = targetI;
1832 }
1833 ActivityRecord p = null;
1834 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001835 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001836 if (p.finishing) {
1837 continue;
1838 }
1839 if (finishActivityLocked(p, srcPos,
1840 Activity.RESULT_CANCELED, null, "reset")) {
1841 replyChainEnd--;
1842 srcPos--;
1843 }
1844 }
1845 if (taskTop == p) {
1846 taskTop = below;
1847 }
1848 if (taskTopI == replyChainEnd) {
1849 taskTopI = -1;
1850 }
1851 replyChainEnd = -1;
1852 } else {
1853 // If we were in the middle of a chain, well the
1854 // activity that started it all doesn't want anything
1855 // special, so leave it all as-is.
1856 replyChainEnd = -1;
1857 }
1858 } else {
1859 // Reached the bottom of the task -- any reply chain
1860 // should be left as-is.
1861 replyChainEnd = -1;
1862 }
1863
1864 } else if (target.resultTo != null) {
1865 // If this activity is sending a reply to a previous
1866 // activity, we can't do anything with it now until
1867 // we reach the start of the reply chain.
1868 // XXX note that we are assuming the result is always
1869 // to the previous activity, which is almost always
1870 // the case but we really shouldn't count on.
1871 if (replyChainEnd < 0) {
1872 replyChainEnd = targetI;
1873 }
1874
1875 } else if (taskTopI >= 0 && allowTaskReparenting
1876 && task.affinity != null
1877 && task.affinity.equals(target.taskAffinity)) {
1878 // We are inside of another task... if this activity has
1879 // an affinity for our task, then either remove it if we are
1880 // clearing or move it over to our task. Note that
1881 // we currently punt on the case where we are resetting a
1882 // task that is not at the top but who has activities above
1883 // with an affinity to it... this is really not a normal
1884 // case, and we will need to later pull that task to the front
1885 // and usually at that point we will do the reset and pick
1886 // up those remaining activities. (This only happens if
1887 // someone starts an activity in a new task from an activity
1888 // in a task that is not currently on top.)
1889 if (forceReset || finishOnTaskLaunch) {
1890 if (replyChainEnd < 0) {
1891 replyChainEnd = targetI;
1892 }
1893 ActivityRecord p = null;
1894 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001895 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001896 if (p.finishing) {
1897 continue;
1898 }
1899 if (finishActivityLocked(p, srcPos,
1900 Activity.RESULT_CANCELED, null, "reset")) {
1901 taskTopI--;
1902 lastReparentPos--;
1903 replyChainEnd--;
1904 srcPos--;
1905 }
1906 }
1907 replyChainEnd = -1;
1908 } else {
1909 if (replyChainEnd < 0) {
1910 replyChainEnd = targetI;
1911 }
1912 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001913 ActivityRecord p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001914 if (p.finishing) {
1915 continue;
1916 }
1917 if (lastReparentPos < 0) {
1918 lastReparentPos = taskTopI;
1919 taskTop = p;
1920 } else {
1921 lastReparentPos--;
1922 }
1923 mHistory.remove(srcPos);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001924 p.setTask(task, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001925 mHistory.add(lastReparentPos, p);
1926 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
1927 + " in to resetting task " + task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001928 mService.mWindowManager.moveAppToken(lastReparentPos, p);
1929 mService.mWindowManager.setAppGroupId(p, p.task.taskId);
1930 if (VALIDATE_TOKENS) {
1931 mService.mWindowManager.validateAppTokens(mHistory);
1932 }
1933 }
1934 replyChainEnd = -1;
1935
1936 // Now we've moved it in to place... but what if this is
1937 // a singleTop activity and we have put it on top of another
1938 // instance of the same activity? Then we drop the instance
1939 // below so it remains singleTop.
1940 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
1941 for (int j=lastReparentPos-1; j>=0; j--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001942 ActivityRecord p = mHistory.get(j);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001943 if (p.finishing) {
1944 continue;
1945 }
1946 if (p.intent.getComponent().equals(target.intent.getComponent())) {
1947 if (finishActivityLocked(p, j,
1948 Activity.RESULT_CANCELED, null, "replace")) {
1949 taskTopI--;
1950 lastReparentPos--;
1951 }
1952 }
1953 }
1954 }
1955 }
1956 }
1957
1958 target = below;
1959 targetI = i;
1960 }
1961
1962 return taskTop;
1963 }
1964
1965 /**
1966 * Perform clear operation as requested by
1967 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
1968 * stack to the given task, then look for
1969 * an instance of that activity in the stack and, if found, finish all
1970 * activities on top of it and return the instance.
1971 *
1972 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001973 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001974 * or null if none was found.
1975 */
1976 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001977 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001978 int i = mHistory.size();
1979
1980 // First find the requested task.
1981 while (i > 0) {
1982 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001983 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001984 if (r.task.taskId == taskId) {
1985 i++;
1986 break;
1987 }
1988 }
1989
1990 // Now clear it.
1991 while (i > 0) {
1992 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001993 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001994 if (r.finishing) {
1995 continue;
1996 }
1997 if (r.task.taskId != taskId) {
1998 return null;
1999 }
2000 if (r.realActivity.equals(newR.realActivity)) {
2001 // Here it is! Now finish everything in front...
2002 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002003 while (i < (mHistory.size()-1)) {
2004 i++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002005 r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002006 if (r.task.taskId != taskId) {
2007 break;
2008 }
2009 if (r.finishing) {
2010 continue;
2011 }
2012 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2013 null, "clear")) {
2014 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002015 }
2016 }
2017
2018 // Finally, if this is a normal launch mode (that is, not
2019 // expecting onNewIntent()), then we will finish the current
2020 // instance of the activity so a new fresh one can be started.
2021 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2022 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
2023 if (!ret.finishing) {
2024 int index = indexOfTokenLocked(ret);
2025 if (index >= 0) {
2026 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
2027 null, "clear");
2028 }
2029 return null;
2030 }
2031 }
2032
2033 return ret;
2034 }
2035 }
2036
2037 return null;
2038 }
2039
2040 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002041 * Completely remove all activities associated with an existing
2042 * task starting at a specified index.
2043 */
2044 private final void performClearTaskAtIndexLocked(int taskId, int i) {
2045 while (i < (mHistory.size()-1)) {
2046 ActivityRecord r = mHistory.get(i);
2047 if (r.task.taskId != taskId) {
2048 // Whoops hit the end.
2049 return;
2050 }
2051 if (r.finishing) {
2052 i++;
2053 continue;
2054 }
2055 if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2056 null, "clear")) {
2057 i++;
2058 }
2059 }
2060 }
2061
2062 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002063 * Completely remove all activities associated with an existing task.
2064 */
2065 private final void performClearTaskLocked(int taskId) {
2066 int i = mHistory.size();
2067
2068 // First find the requested task.
2069 while (i > 0) {
2070 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002071 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002072 if (r.task.taskId == taskId) {
2073 i++;
2074 break;
2075 }
2076 }
2077
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002078 // Now find the start and clear it.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002079 while (i > 0) {
2080 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002081 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002082 if (r.finishing) {
2083 continue;
2084 }
2085 if (r.task.taskId != taskId) {
2086 // We hit the bottom. Now finish it all...
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002087 performClearTaskAtIndexLocked(taskId, i+1);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002088 return;
2089 }
2090 }
2091 }
2092
2093 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002094 * Find the activity in the history stack within the given task. Returns
2095 * the index within the history at which it's found, or < 0 if not found.
2096 */
2097 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2098 int i = mHistory.size();
2099 while (i > 0) {
2100 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002101 ActivityRecord candidate = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002102 if (candidate.task.taskId != task) {
2103 break;
2104 }
2105 if (candidate.realActivity.equals(r.realActivity)) {
2106 return i;
2107 }
2108 }
2109
2110 return -1;
2111 }
2112
2113 /**
2114 * Reorder the history stack so that the activity at the given index is
2115 * brought to the front.
2116 */
2117 private final ActivityRecord moveActivityToFrontLocked(int where) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002118 ActivityRecord newTop = mHistory.remove(where);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002119 int top = mHistory.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002120 ActivityRecord oldTop = mHistory.get(top-1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002121 mHistory.add(top, newTop);
2122 oldTop.frontOfTask = false;
2123 newTop.frontOfTask = true;
2124 return newTop;
2125 }
2126
2127 final int startActivityLocked(IApplicationThread caller,
2128 Intent intent, String resolvedType,
2129 Uri[] grantedUriPermissions,
2130 int grantedMode, ActivityInfo aInfo, IBinder resultTo,
2131 String resultWho, int requestCode,
2132 int callingPid, int callingUid, boolean onlyIfNeeded,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002133 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002134
2135 int err = START_SUCCESS;
2136
2137 ProcessRecord callerApp = null;
2138 if (caller != null) {
2139 callerApp = mService.getRecordForAppLocked(caller);
2140 if (callerApp != null) {
2141 callingPid = callerApp.pid;
2142 callingUid = callerApp.info.uid;
2143 } else {
2144 Slog.w(TAG, "Unable to find app for caller " + caller
2145 + " (pid=" + callingPid + ") when starting: "
2146 + intent.toString());
2147 err = START_PERMISSION_DENIED;
2148 }
2149 }
2150
2151 if (err == START_SUCCESS) {
2152 Slog.i(TAG, "Starting: " + intent + " from pid "
2153 + (callerApp != null ? callerApp.pid : callingPid));
2154 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002155
2156 ActivityRecord sourceRecord = null;
2157 ActivityRecord resultRecord = null;
2158 if (resultTo != null) {
2159 int index = indexOfTokenLocked(resultTo);
2160 if (DEBUG_RESULTS) Slog.v(
2161 TAG, "Sending result to " + resultTo + " (index " + index + ")");
2162 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002163 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002164 if (requestCode >= 0 && !sourceRecord.finishing) {
2165 resultRecord = sourceRecord;
2166 }
2167 }
2168 }
2169
2170 int launchFlags = intent.getFlags();
2171
2172 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2173 && sourceRecord != null) {
2174 // Transfer the result target from the source activity to the new
2175 // one being started, including any failures.
2176 if (requestCode >= 0) {
2177 return START_FORWARD_AND_REQUEST_CONFLICT;
2178 }
2179 resultRecord = sourceRecord.resultTo;
2180 resultWho = sourceRecord.resultWho;
2181 requestCode = sourceRecord.requestCode;
2182 sourceRecord.resultTo = null;
2183 if (resultRecord != null) {
2184 resultRecord.removeResultsLocked(
2185 sourceRecord, resultWho, requestCode);
2186 }
2187 }
2188
Dianne Hackbornefb58102010-10-14 16:47:34 -07002189 if (err == START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002190 // We couldn't find a class that can handle the given Intent.
2191 // That's the end of that!
2192 err = START_INTENT_NOT_RESOLVED;
2193 }
2194
2195 if (err == START_SUCCESS && aInfo == null) {
2196 // We couldn't find the specific class specified in the Intent.
2197 // Also the end of the line.
2198 err = START_CLASS_NOT_FOUND;
2199 }
2200
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002201 if (err != START_SUCCESS) {
2202 if (resultRecord != null) {
2203 sendActivityResultLocked(-1,
2204 resultRecord, resultWho, requestCode,
2205 Activity.RESULT_CANCELED, null);
2206 }
2207 return err;
2208 }
2209
2210 final int perm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002211 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002212 if (perm != PackageManager.PERMISSION_GRANTED) {
2213 if (resultRecord != null) {
2214 sendActivityResultLocked(-1,
2215 resultRecord, resultWho, requestCode,
2216 Activity.RESULT_CANCELED, null);
2217 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002218 String msg;
2219 if (!aInfo.exported) {
2220 msg = "Permission Denial: starting " + intent.toString()
2221 + " from " + callerApp + " (pid=" + callingPid
2222 + ", uid=" + callingUid + ")"
2223 + " not exported from uid " + aInfo.applicationInfo.uid;
2224 } else {
2225 msg = "Permission Denial: starting " + intent.toString()
2226 + " from " + callerApp + " (pid=" + callingPid
2227 + ", uid=" + callingUid + ")"
2228 + " requires " + aInfo.permission;
2229 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002230 Slog.w(TAG, msg);
2231 throw new SecurityException(msg);
2232 }
2233
2234 if (mMainStack) {
2235 if (mService.mController != null) {
2236 boolean abort = false;
2237 try {
2238 // The Intent we give to the watcher has the extra data
2239 // stripped off, since it can contain private information.
2240 Intent watchIntent = intent.cloneFilter();
2241 abort = !mService.mController.activityStarting(watchIntent,
2242 aInfo.applicationInfo.packageName);
2243 } catch (RemoteException e) {
2244 mService.mController = null;
2245 }
2246
2247 if (abort) {
2248 if (resultRecord != null) {
2249 sendActivityResultLocked(-1,
2250 resultRecord, resultWho, requestCode,
2251 Activity.RESULT_CANCELED, null);
2252 }
2253 // We pretend to the caller that it was really started, but
2254 // they will just get a cancel result.
2255 return START_SUCCESS;
2256 }
2257 }
2258 }
2259
2260 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2261 intent, resolvedType, aInfo, mService.mConfiguration,
2262 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002263 if (outActivity != null) {
2264 outActivity[0] = r;
2265 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002266
2267 if (mMainStack) {
2268 if (mResumedActivity == null
2269 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2270 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2271 PendingActivityLaunch pal = new PendingActivityLaunch();
2272 pal.r = r;
2273 pal.sourceRecord = sourceRecord;
2274 pal.grantedUriPermissions = grantedUriPermissions;
2275 pal.grantedMode = grantedMode;
2276 pal.onlyIfNeeded = onlyIfNeeded;
2277 mService.mPendingActivityLaunches.add(pal);
2278 return START_SWITCHES_CANCELED;
2279 }
2280 }
2281
2282 if (mService.mDidAppSwitch) {
2283 // This is the second allowed switch since we stopped switches,
2284 // so now just generally allow switches. Use case: user presses
2285 // home (switches disabled, switch to home, mDidAppSwitch now true);
2286 // user taps a home icon (coming from home so allowed, we hit here
2287 // and now allow anyone to switch again).
2288 mService.mAppSwitchesAllowedTime = 0;
2289 } else {
2290 mService.mDidAppSwitch = true;
2291 }
2292
2293 mService.doPendingActivityLaunchesLocked(false);
2294 }
2295
2296 return startActivityUncheckedLocked(r, sourceRecord,
2297 grantedUriPermissions, grantedMode, onlyIfNeeded, true);
2298 }
2299
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002300 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2301 if ((launchFlags &
2302 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2303 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2304 // Caller wants to appear on home activity, so before starting
2305 // their own activity we will bring home to the front.
2306 moveHomeToFrontLocked();
2307 }
2308 }
2309
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002310 final int startActivityUncheckedLocked(ActivityRecord r,
2311 ActivityRecord sourceRecord, Uri[] grantedUriPermissions,
2312 int grantedMode, boolean onlyIfNeeded, boolean doResume) {
2313 final Intent intent = r.intent;
2314 final int callingUid = r.launchedFromUid;
2315
2316 int launchFlags = intent.getFlags();
2317
2318 // We'll invoke onUserLeaving before onPause only if the launching
2319 // activity did not explicitly state that this is an automated launch.
2320 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2321 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2322 "startActivity() => mUserLeaving=" + mUserLeaving);
2323
2324 // If the caller has asked not to resume at this point, we make note
2325 // of this in the record so that we can skip it when trying to find
2326 // the top running activity.
2327 if (!doResume) {
2328 r.delayedResume = true;
2329 }
2330
2331 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2332 != 0 ? r : null;
2333
2334 // If the onlyIfNeeded flag is set, then we can do this if the activity
2335 // being launched is the same as the one making the call... or, as
2336 // a special case, if we do not know the caller then we count the
2337 // current top activity as the caller.
2338 if (onlyIfNeeded) {
2339 ActivityRecord checkedCaller = sourceRecord;
2340 if (checkedCaller == null) {
2341 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2342 }
2343 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2344 // Caller is not the same as launcher, so always needed.
2345 onlyIfNeeded = false;
2346 }
2347 }
2348
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002349 if (sourceRecord == null) {
2350 // This activity is not being started from another... in this
2351 // case we -always- start a new task.
2352 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2353 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2354 + intent);
2355 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2356 }
2357 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2358 // The original activity who is starting us is running as a single
2359 // instance... this new activity it is starting must go on its
2360 // own task.
2361 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2362 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2363 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2364 // The activity being started is a single instance... it always
2365 // gets launched into its own task.
2366 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2367 }
2368
2369 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2370 // For whatever reason this activity is being launched into a new
2371 // task... yet the caller has requested a result back. Well, that
2372 // is pretty messed up, so instead immediately send back a cancel
2373 // and let the new task continue launched as normal without a
2374 // dependency on its originator.
2375 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2376 sendActivityResultLocked(-1,
2377 r.resultTo, r.resultWho, r.requestCode,
2378 Activity.RESULT_CANCELED, null);
2379 r.resultTo = null;
2380 }
2381
2382 boolean addingToTask = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002383 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002384 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2385 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2386 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2387 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2388 // If bring to front is requested, and no result is requested, and
2389 // we can find a task that was started with this same
2390 // component, then instead of launching bring that one to the front.
2391 if (r.resultTo == null) {
2392 // See if there is a task to bring to the front. If this is
2393 // a SINGLE_INSTANCE activity, there can be one and only one
2394 // instance of it in the history, and it is always in its own
2395 // unique task, so we do a special search.
2396 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2397 ? findTaskLocked(intent, r.info)
2398 : findActivityLocked(intent, r.info);
2399 if (taskTop != null) {
2400 if (taskTop.task.intent == null) {
2401 // This task was started because of movement of
2402 // the activity based on affinity... now that we
2403 // are actually launching it, we can assign the
2404 // base intent.
2405 taskTop.task.setIntent(intent, r.info);
2406 }
2407 // If the target task is not in the front, then we need
2408 // to bring it to the front... except... well, with
2409 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2410 // to have the same behavior as if a new instance was
2411 // being started, which means not bringing it to the front
2412 // if the caller is not itself in the front.
2413 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002414 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002415 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2416 boolean callerAtFront = sourceRecord == null
2417 || curTop.task == sourceRecord.task;
2418 if (callerAtFront) {
2419 // We really do want to push this one into the
2420 // user's face, right now.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002421 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002422 moveTaskToFrontLocked(taskTop.task, r);
2423 }
2424 }
2425 // If the caller has requested that the target task be
2426 // reset, then do so.
2427 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2428 taskTop = resetTaskIfNeededLocked(taskTop, r);
2429 }
2430 if (onlyIfNeeded) {
2431 // We don't need to start a new activity, and
2432 // the client said not to do anything if that
2433 // is the case, so this is it! And for paranoia, make
2434 // sure we have correctly resumed the top activity.
2435 if (doResume) {
2436 resumeTopActivityLocked(null);
2437 }
2438 return START_RETURN_INTENT_TO_CALLER;
2439 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002440 if ((launchFlags &
2441 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2442 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2443 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002444 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002445 // not be too hard...
2446 reuseTask = taskTop.task;
2447 performClearTaskLocked(taskTop.task.taskId);
2448 reuseTask.setIntent(r.intent, r.info);
2449 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002450 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2451 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2452 // In this situation we want to remove all activities
2453 // from the task up to the one being started. In most
2454 // cases this means we are resetting the task to its
2455 // initial state.
2456 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002457 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002458 if (top != null) {
2459 if (top.frontOfTask) {
2460 // Activity aliases may mean we use different
2461 // intents for the top activity, so make sure
2462 // the task now has the identity of the new
2463 // intent.
2464 top.task.setIntent(r.intent, r.info);
2465 }
2466 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002467 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002468 } else {
2469 // A special case: we need to
2470 // start the activity because it is not currently
2471 // running, and the caller has asked to clear the
2472 // current task to have this activity at the top.
2473 addingToTask = true;
2474 // Now pretend like this activity is being started
2475 // by the top of its task, so it is put in the
2476 // right place.
2477 sourceRecord = taskTop;
2478 }
2479 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2480 // In this case the top activity on the task is the
2481 // same as the one being launched, so we take that
2482 // as a request to bring the task to the foreground.
2483 // If the top activity in the task is the root
2484 // activity, deliver this new intent to it if it
2485 // desires.
2486 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2487 && taskTop.realActivity.equals(r.realActivity)) {
2488 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2489 if (taskTop.frontOfTask) {
2490 taskTop.task.setIntent(r.intent, r.info);
2491 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002492 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002493 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2494 // In this case we are launching the root activity
2495 // of the task, but with a different intent. We
2496 // should start a new instance on top.
2497 addingToTask = true;
2498 sourceRecord = taskTop;
2499 }
2500 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2501 // In this case an activity is being launched in to an
2502 // existing task, without resetting that task. This
2503 // is typically the situation of launching an activity
2504 // from a notification or shortcut. We want to place
2505 // the new activity on top of the current task.
2506 addingToTask = true;
2507 sourceRecord = taskTop;
2508 } else if (!taskTop.task.rootWasReset) {
2509 // In this case we are launching in to an existing task
2510 // that has not yet been started from its front door.
2511 // The current task has been brought to the front.
2512 // Ideally, we'd probably like to place this new task
2513 // at the bottom of its stack, but that's a little hard
2514 // to do with the current organization of the code so
2515 // for now we'll just drop it.
2516 taskTop.task.setIntent(r.intent, r.info);
2517 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002518 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002519 // We didn't do anything... but it was needed (a.k.a., client
2520 // don't use that intent!) And for paranoia, make
2521 // sure we have correctly resumed the top activity.
2522 if (doResume) {
2523 resumeTopActivityLocked(null);
2524 }
2525 return START_TASK_TO_FRONT;
2526 }
2527 }
2528 }
2529 }
2530
2531 //String uri = r.intent.toURI();
2532 //Intent intent2 = new Intent(uri);
2533 //Slog.i(TAG, "Given intent: " + r.intent);
2534 //Slog.i(TAG, "URI is: " + uri);
2535 //Slog.i(TAG, "To intent: " + intent2);
2536
2537 if (r.packageName != null) {
2538 // If the activity being launched is the same as the one currently
2539 // at the top, then we need to check if it should only be launched
2540 // once.
2541 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2542 if (top != null && r.resultTo == null) {
2543 if (top.realActivity.equals(r.realActivity)) {
2544 if (top.app != null && top.app.thread != null) {
2545 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2546 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2547 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2548 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2549 // For paranoia, make sure we have correctly
2550 // resumed the top activity.
2551 if (doResume) {
2552 resumeTopActivityLocked(null);
2553 }
2554 if (onlyIfNeeded) {
2555 // We don't need to start a new activity, and
2556 // the client said not to do anything if that
2557 // is the case, so this is it!
2558 return START_RETURN_INTENT_TO_CALLER;
2559 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002560 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002561 return START_DELIVERED_TO_TOP;
2562 }
2563 }
2564 }
2565 }
2566
2567 } else {
2568 if (r.resultTo != null) {
2569 sendActivityResultLocked(-1,
2570 r.resultTo, r.resultWho, r.requestCode,
2571 Activity.RESULT_CANCELED, null);
2572 }
2573 return START_CLASS_NOT_FOUND;
2574 }
2575
2576 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002577 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002578
2579 // Should this be considered a new task?
2580 if (r.resultTo == null && !addingToTask
2581 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002582 if (reuseTask == null) {
2583 // todo: should do better management of integers.
2584 mService.mCurTask++;
2585 if (mService.mCurTask <= 0) {
2586 mService.mCurTask = 1;
2587 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002588 r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002589 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2590 + " in new task " + r.task);
2591 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002592 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002593 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002594 newTask = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002595 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002596
2597 } else if (sourceRecord != null) {
2598 if (!addingToTask &&
2599 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2600 // In this case, we are adding the activity to an existing
2601 // task, but the caller has asked to clear that task if the
2602 // activity is already running.
2603 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002604 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002605 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002606 if (top != null) {
2607 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002608 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002609 // For paranoia, make sure we have correctly
2610 // resumed the top activity.
2611 if (doResume) {
2612 resumeTopActivityLocked(null);
2613 }
2614 return START_DELIVERED_TO_TOP;
2615 }
2616 } else if (!addingToTask &&
2617 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2618 // In this case, we are launching an activity in our own task
2619 // that may already be running somewhere in the history, and
2620 // we want to shuffle it to the front of the stack if so.
2621 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2622 if (where >= 0) {
2623 ActivityRecord top = moveActivityToFrontLocked(where);
2624 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002625 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002626 if (doResume) {
2627 resumeTopActivityLocked(null);
2628 }
2629 return START_DELIVERED_TO_TOP;
2630 }
2631 }
2632 // An existing activity is starting this new activity, so we want
2633 // to keep the new one in the same task as the one that is starting
2634 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002635 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002636 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2637 + " in existing task " + r.task);
2638
2639 } else {
2640 // This not being started from an existing activity, and not part
2641 // of a new task... just put it in the top task, though these days
2642 // this case should never happen.
2643 final int N = mHistory.size();
2644 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002645 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002646 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002647 ? prev.task
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002648 : new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002649 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2650 + " in new guessed " + r.task);
2651 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002652
2653 if (grantedUriPermissions != null && callingUid > 0) {
2654 for (int i=0; i<grantedUriPermissions.length; i++) {
2655 mService.grantUriPermissionLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002656 grantedUriPermissions[i], grantedMode, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002657 }
2658 }
2659
2660 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002661 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002662
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002663 if (newTask) {
2664 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
2665 }
2666 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002667 startActivityLocked(r, newTask, doResume, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002668 return START_SUCCESS;
2669 }
2670
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002671 ActivityInfo resolveActivity(Intent intent, String resolvedType, boolean debug) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002672 // Collect information about the target of the Intent.
2673 ActivityInfo aInfo;
2674 try {
2675 ResolveInfo rInfo =
2676 AppGlobals.getPackageManager().resolveIntent(
2677 intent, resolvedType,
2678 PackageManager.MATCH_DEFAULT_ONLY
2679 | ActivityManagerService.STOCK_PM_FLAGS);
2680 aInfo = rInfo != null ? rInfo.activityInfo : null;
2681 } catch (RemoteException e) {
2682 aInfo = null;
2683 }
2684
2685 if (aInfo != null) {
2686 // Store the found target back into the intent, because now that
2687 // we have it we never want to do this again. For example, if the
2688 // user navigates back to this point in the history, we should
2689 // always restart the exact same activity.
2690 intent.setComponent(new ComponentName(
2691 aInfo.applicationInfo.packageName, aInfo.name));
2692
2693 // Don't debug things in the system process
2694 if (debug) {
2695 if (!aInfo.processName.equals("system")) {
2696 mService.setDebugApp(aInfo.processName, true, false);
2697 }
2698 }
2699 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002700 return aInfo;
2701 }
2702
2703 final int startActivityMayWait(IApplicationThread caller, int callingUid,
2704 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2705 int grantedMode, IBinder resultTo,
2706 String resultWho, int requestCode, boolean onlyIfNeeded,
2707 boolean debug, WaitResult outResult, Configuration config) {
2708 // Refuse possible leaked file descriptors
2709 if (intent != null && intent.hasFileDescriptors()) {
2710 throw new IllegalArgumentException("File descriptors passed in Intent");
2711 }
2712
2713 boolean componentSpecified = intent.getComponent() != null;
2714
2715 // Don't modify the client's object!
2716 intent = new Intent(intent);
2717
2718 // Collect information about the target of the Intent.
2719 ActivityInfo aInfo = resolveActivity(intent, resolvedType, debug);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002720
2721 synchronized (mService) {
2722 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002723 if (callingUid >= 0) {
2724 callingPid = -1;
2725 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002726 callingPid = Binder.getCallingPid();
2727 callingUid = Binder.getCallingUid();
2728 } else {
2729 callingPid = callingUid = -1;
2730 }
2731
2732 mConfigWillChange = config != null
2733 && mService.mConfiguration.diff(config) != 0;
2734 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2735 "Starting activity when config will change = " + mConfigWillChange);
2736
2737 final long origId = Binder.clearCallingIdentity();
2738
2739 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07002740 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002741 // This may be a heavy-weight process! Check to see if we already
2742 // have another, different heavy-weight process running.
2743 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
2744 if (mService.mHeavyWeightProcess != null &&
2745 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
2746 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
2747 int realCallingPid = callingPid;
2748 int realCallingUid = callingUid;
2749 if (caller != null) {
2750 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
2751 if (callerApp != null) {
2752 realCallingPid = callerApp.pid;
2753 realCallingUid = callerApp.info.uid;
2754 } else {
2755 Slog.w(TAG, "Unable to find app for caller " + caller
2756 + " (pid=" + realCallingPid + ") when starting: "
2757 + intent.toString());
2758 return START_PERMISSION_DENIED;
2759 }
2760 }
2761
2762 IIntentSender target = mService.getIntentSenderLocked(
2763 IActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002764 realCallingUid, null, null, 0, new Intent[] { intent },
2765 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002766 | PendingIntent.FLAG_ONE_SHOT);
2767
2768 Intent newIntent = new Intent();
2769 if (requestCode >= 0) {
2770 // Caller is requesting a result.
2771 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
2772 }
2773 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
2774 new IntentSender(target));
2775 if (mService.mHeavyWeightProcess.activities.size() > 0) {
2776 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
2777 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
2778 hist.packageName);
2779 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
2780 hist.task.taskId);
2781 }
2782 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
2783 aInfo.packageName);
2784 newIntent.setFlags(intent.getFlags());
2785 newIntent.setClassName("android",
2786 HeavyWeightSwitcherActivity.class.getName());
2787 intent = newIntent;
2788 resolvedType = null;
2789 caller = null;
2790 callingUid = Binder.getCallingUid();
2791 callingPid = Binder.getCallingPid();
2792 componentSpecified = true;
2793 try {
2794 ResolveInfo rInfo =
2795 AppGlobals.getPackageManager().resolveIntent(
2796 intent, null,
2797 PackageManager.MATCH_DEFAULT_ONLY
2798 | ActivityManagerService.STOCK_PM_FLAGS);
2799 aInfo = rInfo != null ? rInfo.activityInfo : null;
2800 } catch (RemoteException e) {
2801 aInfo = null;
2802 }
2803 }
2804 }
2805 }
2806
2807 int res = startActivityLocked(caller, intent, resolvedType,
2808 grantedUriPermissions, grantedMode, aInfo,
2809 resultTo, resultWho, requestCode, callingPid, callingUid,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002810 onlyIfNeeded, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002811
2812 if (mConfigWillChange && mMainStack) {
2813 // If the caller also wants to switch to a new configuration,
2814 // do so now. This allows a clean switch, as we are waiting
2815 // for the current activity to pause (so we will not destroy
2816 // it), and have not yet started the next activity.
2817 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
2818 "updateConfiguration()");
2819 mConfigWillChange = false;
2820 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2821 "Updating to new configuration after starting activity.");
Dianne Hackborn31ca8542011-07-19 14:58:28 -07002822 mService.updateConfigurationLocked(config, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002823 }
2824
2825 Binder.restoreCallingIdentity(origId);
2826
2827 if (outResult != null) {
2828 outResult.result = res;
2829 if (res == IActivityManager.START_SUCCESS) {
2830 mWaitingActivityLaunched.add(outResult);
2831 do {
2832 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07002833 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002834 } catch (InterruptedException e) {
2835 }
2836 } while (!outResult.timeout && outResult.who == null);
2837 } else if (res == IActivityManager.START_TASK_TO_FRONT) {
2838 ActivityRecord r = this.topRunningActivityLocked(null);
2839 if (r.nowVisible) {
2840 outResult.timeout = false;
2841 outResult.who = new ComponentName(r.info.packageName, r.info.name);
2842 outResult.totalTime = 0;
2843 outResult.thisTime = 0;
2844 } else {
2845 outResult.thisTime = SystemClock.uptimeMillis();
2846 mWaitingActivityVisible.add(outResult);
2847 do {
2848 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07002849 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002850 } catch (InterruptedException e) {
2851 }
2852 } while (!outResult.timeout && outResult.who == null);
2853 }
2854 }
2855 }
2856
2857 return res;
2858 }
2859 }
2860
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002861 final int startActivities(IApplicationThread caller, int callingUid,
2862 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
2863 if (intents == null) {
2864 throw new NullPointerException("intents is null");
2865 }
2866 if (resolvedTypes == null) {
2867 throw new NullPointerException("resolvedTypes is null");
2868 }
2869 if (intents.length != resolvedTypes.length) {
2870 throw new IllegalArgumentException("intents are length different than resolvedTypes");
2871 }
2872
2873 ActivityRecord[] outActivity = new ActivityRecord[1];
2874
2875 int callingPid;
2876 if (callingUid >= 0) {
2877 callingPid = -1;
2878 } else if (caller == null) {
2879 callingPid = Binder.getCallingPid();
2880 callingUid = Binder.getCallingUid();
2881 } else {
2882 callingPid = callingUid = -1;
2883 }
2884 final long origId = Binder.clearCallingIdentity();
2885 try {
2886 synchronized (mService) {
2887
2888 for (int i=0; i<intents.length; i++) {
2889 Intent intent = intents[i];
2890 if (intent == null) {
2891 continue;
2892 }
2893
2894 // Refuse possible leaked file descriptors
2895 if (intent != null && intent.hasFileDescriptors()) {
2896 throw new IllegalArgumentException("File descriptors passed in Intent");
2897 }
2898
2899 boolean componentSpecified = intent.getComponent() != null;
2900
2901 // Don't modify the client's object!
2902 intent = new Intent(intent);
2903
2904 // Collect information about the target of the Intent.
2905 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i], false);
2906
2907 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
2908 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
2909 throw new IllegalArgumentException(
2910 "FLAG_CANT_SAVE_STATE not supported here");
2911 }
2912
2913 int res = startActivityLocked(caller, intent, resolvedTypes[i],
2914 null, 0, aInfo, resultTo, null, -1, callingPid, callingUid,
2915 false, componentSpecified, outActivity);
2916 if (res < 0) {
2917 return res;
2918 }
2919
2920 resultTo = outActivity[0];
2921 }
2922 }
2923 } finally {
2924 Binder.restoreCallingIdentity(origId);
2925 }
2926
2927 return IActivityManager.START_SUCCESS;
2928 }
2929
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002930 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
2931 long thisTime, long totalTime) {
2932 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
2933 WaitResult w = mWaitingActivityLaunched.get(i);
2934 w.timeout = timeout;
2935 if (r != null) {
2936 w.who = new ComponentName(r.info.packageName, r.info.name);
2937 }
2938 w.thisTime = thisTime;
2939 w.totalTime = totalTime;
2940 }
2941 mService.notifyAll();
2942 }
2943
2944 void reportActivityVisibleLocked(ActivityRecord r) {
2945 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
2946 WaitResult w = mWaitingActivityVisible.get(i);
2947 w.timeout = false;
2948 if (r != null) {
2949 w.who = new ComponentName(r.info.packageName, r.info.name);
2950 }
2951 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
2952 w.thisTime = w.totalTime;
2953 }
2954 mService.notifyAll();
2955 }
2956
2957 void sendActivityResultLocked(int callingUid, ActivityRecord r,
2958 String resultWho, int requestCode, int resultCode, Intent data) {
2959
2960 if (callingUid > 0) {
2961 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002962 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002963 }
2964
2965 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
2966 + " : who=" + resultWho + " req=" + requestCode
2967 + " res=" + resultCode + " data=" + data);
2968 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
2969 try {
2970 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
2971 list.add(new ResultInfo(resultWho, requestCode,
2972 resultCode, data));
2973 r.app.thread.scheduleSendResult(r, list);
2974 return;
2975 } catch (Exception e) {
2976 Slog.w(TAG, "Exception thrown sending result to " + r, e);
2977 }
2978 }
2979
2980 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
2981 }
2982
2983 private final void stopActivityLocked(ActivityRecord r) {
2984 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
2985 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
2986 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
2987 if (!r.finishing) {
2988 requestFinishActivityLocked(r, Activity.RESULT_CANCELED, null,
2989 "no-history");
2990 }
2991 } else if (r.app != null && r.app.thread != null) {
2992 if (mMainStack) {
2993 if (mService.mFocusedActivity == r) {
2994 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
2995 }
2996 }
2997 r.resumeKeyDispatchingLocked();
2998 try {
2999 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003000 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3001 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003002 r.state = ActivityState.STOPPING;
3003 if (DEBUG_VISBILITY) Slog.v(
3004 TAG, "Stopping visible=" + r.visible + " for " + r);
3005 if (!r.visible) {
3006 mService.mWindowManager.setAppVisibility(r, false);
3007 }
3008 r.app.thread.scheduleStopActivity(r, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003009 if (mService.isSleeping()) {
3010 r.setSleeping(true);
3011 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003012 } catch (Exception e) {
3013 // Maybe just ignore exceptions here... if the process
3014 // has crashed, our death notification will clean things
3015 // up.
3016 Slog.w(TAG, "Exception thrown during pause", e);
3017 // Just in case, assume it to be stopped.
3018 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003019 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003020 r.state = ActivityState.STOPPED;
3021 if (r.configDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003022 destroyActivityLocked(r, true, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003023 }
3024 }
3025 }
3026 }
3027
3028 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3029 boolean remove) {
3030 int N = mStoppingActivities.size();
3031 if (N <= 0) return null;
3032
3033 ArrayList<ActivityRecord> stops = null;
3034
3035 final boolean nowVisible = mResumedActivity != null
3036 && mResumedActivity.nowVisible
3037 && !mResumedActivity.waitingVisible;
3038 for (int i=0; i<N; i++) {
3039 ActivityRecord s = mStoppingActivities.get(i);
3040 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3041 + nowVisible + " waitingVisible=" + s.waitingVisible
3042 + " finishing=" + s.finishing);
3043 if (s.waitingVisible && nowVisible) {
3044 mWaitingVisibleActivities.remove(s);
3045 s.waitingVisible = false;
3046 if (s.finishing) {
3047 // If this activity is finishing, it is sitting on top of
3048 // everyone else but we now know it is no longer needed...
3049 // so get rid of it. Otherwise, we need to go through the
3050 // normal flow and hide it once we determine that it is
3051 // hidden by the activities in front of it.
3052 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
3053 mService.mWindowManager.setAppVisibility(s, false);
3054 }
3055 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003056 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003057 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3058 if (stops == null) {
3059 stops = new ArrayList<ActivityRecord>();
3060 }
3061 stops.add(s);
3062 mStoppingActivities.remove(i);
3063 N--;
3064 i--;
3065 }
3066 }
3067
3068 return stops;
3069 }
3070
3071 final void activityIdleInternal(IBinder token, boolean fromTimeout,
3072 Configuration config) {
3073 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3074
3075 ArrayList<ActivityRecord> stops = null;
3076 ArrayList<ActivityRecord> finishes = null;
3077 ArrayList<ActivityRecord> thumbnails = null;
3078 int NS = 0;
3079 int NF = 0;
3080 int NT = 0;
3081 IApplicationThread sendThumbnail = null;
3082 boolean booting = false;
3083 boolean enableScreen = false;
3084
3085 synchronized (mService) {
3086 if (token != null) {
3087 mHandler.removeMessages(IDLE_TIMEOUT_MSG, token);
3088 }
3089
3090 // Get the activity record.
3091 int index = indexOfTokenLocked(token);
3092 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003093 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003094
3095 if (fromTimeout) {
3096 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3097 }
3098
3099 // This is a hack to semi-deal with a race condition
3100 // in the client where it can be constructed with a
3101 // newer configuration from when we asked it to launch.
3102 // We'll update with whatever configuration it now says
3103 // it used to launch.
3104 if (config != null) {
3105 r.configuration = config;
3106 }
3107
3108 // No longer need to keep the device awake.
3109 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3110 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3111 mLaunchingActivity.release();
3112 }
3113
3114 // We are now idle. If someone is waiting for a thumbnail from
3115 // us, we can now deliver.
3116 r.idle = true;
3117 mService.scheduleAppGcsLocked();
3118 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3119 sendThumbnail = r.app.thread;
3120 r.thumbnailNeeded = false;
3121 }
3122
3123 // If this activity is fullscreen, set up to hide those under it.
3124
3125 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3126 ensureActivitiesVisibleLocked(null, 0);
3127
3128 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3129 if (mMainStack) {
3130 if (!mService.mBooted && !fromTimeout) {
3131 mService.mBooted = true;
3132 enableScreen = true;
3133 }
3134 }
3135
3136 } else if (fromTimeout) {
3137 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3138 }
3139
3140 // Atomically retrieve all of the other things to do.
3141 stops = processStoppingActivitiesLocked(true);
3142 NS = stops != null ? stops.size() : 0;
3143 if ((NF=mFinishingActivities.size()) > 0) {
3144 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3145 mFinishingActivities.clear();
3146 }
3147 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3148 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3149 mService.mCancelledThumbnails.clear();
3150 }
3151
3152 if (mMainStack) {
3153 booting = mService.mBooting;
3154 mService.mBooting = false;
3155 }
3156 }
3157
3158 int i;
3159
3160 // Send thumbnail if requested.
3161 if (sendThumbnail != null) {
3162 try {
3163 sendThumbnail.requestThumbnail(token);
3164 } catch (Exception e) {
3165 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3166 mService.sendPendingThumbnail(null, token, null, null, true);
3167 }
3168 }
3169
3170 // Stop any activities that are scheduled to do so but have been
3171 // waiting for the next one to start.
3172 for (i=0; i<NS; i++) {
3173 ActivityRecord r = (ActivityRecord)stops.get(i);
3174 synchronized (mService) {
3175 if (r.finishing) {
3176 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY);
3177 } else {
3178 stopActivityLocked(r);
3179 }
3180 }
3181 }
3182
3183 // Finish any activities that are scheduled to do so but have been
3184 // waiting for the next one to start.
3185 for (i=0; i<NF; i++) {
3186 ActivityRecord r = (ActivityRecord)finishes.get(i);
3187 synchronized (mService) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003188 destroyActivityLocked(r, true, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003189 }
3190 }
3191
3192 // Report back to any thumbnail receivers.
3193 for (i=0; i<NT; i++) {
3194 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3195 mService.sendPendingThumbnail(r, null, null, null, true);
3196 }
3197
3198 if (booting) {
3199 mService.finishBooting();
3200 }
3201
3202 mService.trimApplications();
3203 //dump();
3204 //mWindowManager.dump();
3205
3206 if (enableScreen) {
3207 mService.enableScreenAfterBoot();
3208 }
3209 }
3210
3211 /**
3212 * @return Returns true if the activity is being finished, false if for
3213 * some reason it is being left as-is.
3214 */
3215 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
3216 Intent resultData, String reason) {
3217 if (DEBUG_RESULTS) Slog.v(
3218 TAG, "Finishing activity: token=" + token
3219 + ", result=" + resultCode + ", data=" + resultData);
3220
3221 int index = indexOfTokenLocked(token);
3222 if (index < 0) {
3223 return false;
3224 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003225 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003226
3227 // Is this the last activity left?
3228 boolean lastActivity = true;
3229 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003230 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003231 if (!p.finishing && p != r) {
3232 lastActivity = false;
3233 break;
3234 }
3235 }
3236
3237 // If this is the last activity, but it is the home activity, then
3238 // just don't finish it.
3239 if (lastActivity) {
3240 if (r.intent.hasCategory(Intent.CATEGORY_HOME)) {
3241 return false;
3242 }
3243 }
3244
3245 finishActivityLocked(r, index, resultCode, resultData, reason);
3246 return true;
3247 }
3248
3249 /**
3250 * @return Returns true if this activity has been removed from the history
3251 * list, or false if it is still in the list and will be removed later.
3252 */
3253 final boolean finishActivityLocked(ActivityRecord r, int index,
3254 int resultCode, Intent resultData, String reason) {
3255 if (r.finishing) {
3256 Slog.w(TAG, "Duplicate finish request for " + r);
3257 return false;
3258 }
3259
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003260 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003261 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3262 System.identityHashCode(r),
3263 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003264 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003265 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003266 if (next.task == r.task) {
3267 if (r.frontOfTask) {
3268 // The next activity is now the front of the task.
3269 next.frontOfTask = true;
3270 }
3271 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3272 // If the caller asked that this activity (and all above it)
3273 // be cleared when the task is reset, don't lose that information,
3274 // but propagate it up to the next activity.
3275 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3276 }
3277 }
3278 }
3279
3280 r.pauseKeyDispatchingLocked();
3281 if (mMainStack) {
3282 if (mService.mFocusedActivity == r) {
3283 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3284 }
3285 }
3286
3287 // send the result
3288 ActivityRecord resultTo = r.resultTo;
3289 if (resultTo != null) {
3290 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3291 + " who=" + r.resultWho + " req=" + r.requestCode
3292 + " res=" + resultCode + " data=" + resultData);
3293 if (r.info.applicationInfo.uid > 0) {
3294 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
Dianne Hackborna1c69e02010-09-01 22:55:02 -07003295 resultTo.packageName, resultData,
3296 resultTo.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003297 }
3298 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3299 resultData);
3300 r.resultTo = null;
3301 }
3302 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3303
3304 // Make sure this HistoryRecord is not holding on to other resources,
3305 // because clients have remote IPC references to this object so we
3306 // can't assume that will go away and want to avoid circular IPC refs.
3307 r.results = null;
3308 r.pendingResults = null;
3309 r.newIntents = null;
3310 r.icicle = null;
3311
3312 if (mService.mPendingThumbnails.size() > 0) {
3313 // There are clients waiting to receive thumbnails so, in case
3314 // this is an activity that someone is waiting for, add it
3315 // to the pending list so we can correctly update the clients.
3316 mService.mCancelledThumbnails.add(r);
3317 }
3318
3319 if (mResumedActivity == r) {
3320 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003321 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003322 if (DEBUG_TRANSITION) Slog.v(TAG,
3323 "Prepare close transition: finishing " + r);
3324 mService.mWindowManager.prepareAppTransition(endTask
3325 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003326 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003327
3328 // Tell window manager to prepare for this one to be removed.
3329 mService.mWindowManager.setAppVisibility(r, false);
3330
3331 if (mPausingActivity == null) {
3332 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3333 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3334 startPausingLocked(false, false);
3335 }
3336
3337 } else if (r.state != ActivityState.PAUSING) {
3338 // If the activity is PAUSING, we will complete the finish once
3339 // it is done pausing; else we can just directly finish it here.
3340 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3341 return finishCurrentActivityLocked(r, index,
3342 FINISH_AFTER_PAUSE) == null;
3343 } else {
3344 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3345 }
3346
3347 return false;
3348 }
3349
3350 private static final int FINISH_IMMEDIATELY = 0;
3351 private static final int FINISH_AFTER_PAUSE = 1;
3352 private static final int FINISH_AFTER_VISIBLE = 2;
3353
3354 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3355 int mode) {
3356 final int index = indexOfTokenLocked(r);
3357 if (index < 0) {
3358 return null;
3359 }
3360
3361 return finishCurrentActivityLocked(r, index, mode);
3362 }
3363
3364 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3365 int index, int mode) {
3366 // First things first: if this activity is currently visible,
3367 // and the resumed activity is not yet visible, then hold off on
3368 // finishing until the resumed one becomes visible.
3369 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3370 if (!mStoppingActivities.contains(r)) {
3371 mStoppingActivities.add(r);
3372 if (mStoppingActivities.size() > 3) {
3373 // If we already have a few activities waiting to stop,
3374 // then give up on things going idle and start clearing
3375 // them out.
3376 Message msg = Message.obtain();
3377 msg.what = IDLE_NOW_MSG;
3378 mHandler.sendMessage(msg);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003379 } else {
3380 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003381 }
3382 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003383 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3384 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003385 r.state = ActivityState.STOPPING;
3386 mService.updateOomAdjLocked();
3387 return r;
3388 }
3389
3390 // make sure the record is cleaned out of other places.
3391 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003392 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003393 mWaitingVisibleActivities.remove(r);
3394 if (mResumedActivity == r) {
3395 mResumedActivity = null;
3396 }
3397 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003398 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003399 r.state = ActivityState.FINISHING;
3400
3401 if (mode == FINISH_IMMEDIATELY
3402 || prevState == ActivityState.STOPPED
3403 || prevState == ActivityState.INITIALIZING) {
3404 // If this activity is already stopped, we can just finish
3405 // it right now.
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003406 return destroyActivityLocked(r, true, true) ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003407 } else {
3408 // Need to go through the full pause cycle to get this
3409 // activity into the stopped state and then finish it.
3410 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3411 mFinishingActivities.add(r);
3412 resumeTopActivityLocked(null);
3413 }
3414 return r;
3415 }
3416
3417 /**
3418 * Perform the common clean-up of an activity record. This is called both
3419 * as part of destroyActivityLocked() (when destroying the client-side
3420 * representation) and cleaning things up as a result of its hosting
3421 * processing going away, in which case there is no remaining client-side
3422 * state to destroy so only the cleanup here is needed.
3423 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003424 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3425 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003426 if (mResumedActivity == r) {
3427 mResumedActivity = null;
3428 }
3429 if (mService.mFocusedActivity == r) {
3430 mService.mFocusedActivity = null;
3431 }
3432
3433 r.configDestroy = false;
3434 r.frozenBeforeDestroy = false;
3435
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003436 if (setState) {
3437 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3438 r.state = ActivityState.DESTROYED;
3439 }
3440
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003441 // Make sure this record is no longer in the pending finishes list.
3442 // This could happen, for example, if we are trimming activities
3443 // down to the max limit while they are still waiting to finish.
3444 mFinishingActivities.remove(r);
3445 mWaitingVisibleActivities.remove(r);
3446
3447 // Remove any pending results.
3448 if (r.finishing && r.pendingResults != null) {
3449 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3450 PendingIntentRecord rec = apr.get();
3451 if (rec != null) {
3452 mService.cancelIntentSenderLocked(rec, false);
3453 }
3454 }
3455 r.pendingResults = null;
3456 }
3457
3458 if (cleanServices) {
3459 cleanUpActivityServicesLocked(r);
3460 }
3461
3462 if (mService.mPendingThumbnails.size() > 0) {
3463 // There are clients waiting to receive thumbnails so, in case
3464 // this is an activity that someone is waiting for, add it
3465 // to the pending list so we can correctly update the clients.
3466 mService.mCancelledThumbnails.add(r);
3467 }
3468
3469 // Get rid of any pending idle timeouts.
3470 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
3471 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003472 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003473 }
3474
3475 private final void removeActivityFromHistoryLocked(ActivityRecord r) {
3476 if (r.state != ActivityState.DESTROYED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003477 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003478 mHistory.remove(r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003479 r.takeFromHistory();
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003480 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3481 + " (removed from history)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003482 r.state = ActivityState.DESTROYED;
3483 mService.mWindowManager.removeAppToken(r);
3484 if (VALIDATE_TOKENS) {
3485 mService.mWindowManager.validateAppTokens(mHistory);
3486 }
3487 cleanUpActivityServicesLocked(r);
3488 r.removeUriPermissionsLocked();
3489 }
3490 }
3491
3492 /**
3493 * Perform clean-up of service connections in an activity record.
3494 */
3495 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3496 // Throw away any services that have been bound by this activity.
3497 if (r.connections != null) {
3498 Iterator<ConnectionRecord> it = r.connections.iterator();
3499 while (it.hasNext()) {
3500 ConnectionRecord c = it.next();
3501 mService.removeConnectionLocked(c, null, r);
3502 }
3503 r.connections = null;
3504 }
3505 }
3506
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003507 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj) {
3508 for (int i=mHistory.size()-1; i>=0; i--) {
3509 ActivityRecord r = mHistory.get(i);
3510 if (owner != null && r.app != owner) {
3511 continue;
3512 }
3513 // We can destroy this one if we have its icicle saved and
3514 // it is not in the process of pausing/stopping/finishing.
3515 if (r.app != null && r.haveState && !r.visible && r.stopped && !r.finishing
3516 && r.state != ActivityState.DESTROYING
3517 && r.state != ActivityState.DESTROYED) {
3518 destroyActivityLocked(r, true, oomAdj);
3519 }
3520 }
3521 }
3522
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003523 /**
3524 * Destroy the current CLIENT SIDE instance of an activity. This may be
3525 * called both when actually finishing an activity, or when performing
3526 * a configuration switch where we destroy the current client-side object
3527 * but then create a new client-side object for this same HistoryRecord.
3528 */
3529 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003530 boolean removeFromApp, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003531 if (DEBUG_SWITCH) Slog.v(
3532 TAG, "Removing activity: token=" + r
3533 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3534 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3535 System.identityHashCode(r),
3536 r.task.taskId, r.shortComponentName);
3537
3538 boolean removedFromHistory = false;
3539
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003540 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003541
3542 final boolean hadApp = r.app != null;
3543
3544 if (hadApp) {
3545 if (removeFromApp) {
3546 int idx = r.app.activities.indexOf(r);
3547 if (idx >= 0) {
3548 r.app.activities.remove(idx);
3549 }
3550 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
3551 mService.mHeavyWeightProcess = null;
3552 mService.mHandler.sendEmptyMessage(
3553 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
3554 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003555 if (r.app.activities.size() == 0) {
3556 // No longer have activities, so update location in
3557 // LRU list.
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003558 mService.updateLruProcessLocked(r.app, oomAdj, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003559 }
3560 }
3561
3562 boolean skipDestroy = false;
3563
3564 try {
3565 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
3566 r.app.thread.scheduleDestroyActivity(r, r.finishing,
3567 r.configChangeFlags);
3568 } catch (Exception e) {
3569 // We can just ignore exceptions here... if the process
3570 // has crashed, our death notification will clean things
3571 // up.
3572 //Slog.w(TAG, "Exception thrown during finish", e);
3573 if (r.finishing) {
3574 removeActivityFromHistoryLocked(r);
3575 removedFromHistory = true;
3576 skipDestroy = true;
3577 }
3578 }
3579
3580 r.app = null;
3581 r.nowVisible = false;
3582
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003583 // If the activity is finishing, we need to wait on removing it
3584 // from the list to give it a chance to do its cleanup. During
3585 // that time it may make calls back with its token so we need to
3586 // be able to find it on the list and so we don't want to remove
3587 // it from the list yet. Otherwise, we can just immediately put
3588 // it in the destroyed state since we are not removing it from the
3589 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003590 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003591 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
3592 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003593 r.state = ActivityState.DESTROYING;
3594 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
3595 msg.obj = r;
3596 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
3597 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003598 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3599 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003600 r.state = ActivityState.DESTROYED;
3601 }
3602 } else {
3603 // remove this record from the history.
3604 if (r.finishing) {
3605 removeActivityFromHistoryLocked(r);
3606 removedFromHistory = true;
3607 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003608 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3609 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003610 r.state = ActivityState.DESTROYED;
3611 }
3612 }
3613
3614 r.configChangeFlags = 0;
3615
3616 if (!mLRUActivities.remove(r) && hadApp) {
3617 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
3618 }
3619
3620 return removedFromHistory;
3621 }
3622
3623 final void activityDestroyed(IBinder token) {
3624 synchronized (mService) {
3625 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, token);
3626
3627 int index = indexOfTokenLocked(token);
3628 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003629 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003630 if (r.state == ActivityState.DESTROYING) {
3631 final long origId = Binder.clearCallingIdentity();
3632 removeActivityFromHistoryLocked(r);
3633 Binder.restoreCallingIdentity(origId);
3634 }
3635 }
3636 }
3637 }
3638
3639 private static void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
3640 int i = list.size();
3641 if (localLOGV) Slog.v(
3642 TAG, "Removing app " + app + " from list " + list
3643 + " with " + i + " entries");
3644 while (i > 0) {
3645 i--;
3646 ActivityRecord r = (ActivityRecord)list.get(i);
3647 if (localLOGV) Slog.v(
3648 TAG, "Record #" + i + " " + r + ": app=" + r.app);
3649 if (r.app == app) {
3650 if (localLOGV) Slog.v(TAG, "Removing this entry!");
3651 list.remove(i);
3652 }
3653 }
3654 }
3655
3656 void removeHistoryRecordsForAppLocked(ProcessRecord app) {
3657 removeHistoryRecordsForAppLocked(mLRUActivities, app);
3658 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003659 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003660 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
3661 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
3662 }
3663
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003664 /**
3665 * Move the current home activity's task (if one exists) to the front
3666 * of the stack.
3667 */
3668 final void moveHomeToFrontLocked() {
3669 TaskRecord homeTask = null;
3670 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003671 ActivityRecord hr = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003672 if (hr.isHomeActivity) {
3673 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003674 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003675 }
3676 }
3677 if (homeTask != null) {
3678 moveTaskToFrontLocked(homeTask, null);
3679 }
3680 }
3681
3682
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003683 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason) {
3684 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
3685
3686 final int task = tr.taskId;
3687 int top = mHistory.size()-1;
3688
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003689 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003690 // nothing to do!
3691 return;
3692 }
3693
3694 ArrayList moved = new ArrayList();
3695
3696 // Applying the affinities may have removed entries from the history,
3697 // so get the size again.
3698 top = mHistory.size()-1;
3699 int pos = top;
3700
3701 // Shift all activities with this task up to the top
3702 // of the stack, keeping them in the same internal order.
3703 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003704 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003705 if (localLOGV) Slog.v(
3706 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003707 if (r.task.taskId == task) {
3708 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
3709 mHistory.remove(pos);
3710 mHistory.add(top, r);
3711 moved.add(0, r);
3712 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003713 }
3714 pos--;
3715 }
3716
3717 if (DEBUG_TRANSITION) Slog.v(TAG,
3718 "Prepare to front transition: task=" + tr);
3719 if (reason != null &&
3720 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003721 mService.mWindowManager.prepareAppTransition(
3722 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003723 ActivityRecord r = topRunningActivityLocked(null);
3724 if (r != null) {
3725 mNoAnimActivities.add(r);
3726 }
3727 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003728 mService.mWindowManager.prepareAppTransition(
3729 WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003730 }
3731
3732 mService.mWindowManager.moveAppTokensToTop(moved);
3733 if (VALIDATE_TOKENS) {
3734 mService.mWindowManager.validateAppTokens(mHistory);
3735 }
3736
3737 finishTaskMoveLocked(task);
3738 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
3739 }
3740
3741 private final void finishTaskMoveLocked(int task) {
3742 resumeTopActivityLocked(null);
3743 }
3744
3745 /**
3746 * Worker method for rearranging history stack. Implements the function of moving all
3747 * activities for a specific task (gathering them if disjoint) into a single group at the
3748 * bottom of the stack.
3749 *
3750 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
3751 * to premeptively cancel the move.
3752 *
3753 * @param task The taskId to collect and move to the bottom.
3754 * @return Returns true if the move completed, false if not.
3755 */
3756 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
3757 Slog.i(TAG, "moveTaskToBack: " + task);
3758
3759 // If we have a watcher, preflight the move before committing to it. First check
3760 // for *other* available tasks, but if none are available, then try again allowing the
3761 // current task to be selected.
3762 if (mMainStack && mService.mController != null) {
3763 ActivityRecord next = topRunningActivityLocked(null, task);
3764 if (next == null) {
3765 next = topRunningActivityLocked(null, 0);
3766 }
3767 if (next != null) {
3768 // ask watcher if this is allowed
3769 boolean moveOK = true;
3770 try {
3771 moveOK = mService.mController.activityResuming(next.packageName);
3772 } catch (RemoteException e) {
3773 mService.mController = null;
3774 }
3775 if (!moveOK) {
3776 return false;
3777 }
3778 }
3779 }
3780
3781 ArrayList moved = new ArrayList();
3782
3783 if (DEBUG_TRANSITION) Slog.v(TAG,
3784 "Prepare to back transition: task=" + task);
3785
3786 final int N = mHistory.size();
3787 int bottom = 0;
3788 int pos = 0;
3789
3790 // Shift all activities with this task down to the bottom
3791 // of the stack, keeping them in the same internal order.
3792 while (pos < N) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003793 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003794 if (localLOGV) Slog.v(
3795 TAG, "At " + pos + " ckp " + r.task + ": " + r);
3796 if (r.task.taskId == task) {
3797 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
3798 mHistory.remove(pos);
3799 mHistory.add(bottom, r);
3800 moved.add(r);
3801 bottom++;
3802 }
3803 pos++;
3804 }
3805
3806 if (reason != null &&
3807 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003808 mService.mWindowManager.prepareAppTransition(
3809 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003810 ActivityRecord r = topRunningActivityLocked(null);
3811 if (r != null) {
3812 mNoAnimActivities.add(r);
3813 }
3814 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003815 mService.mWindowManager.prepareAppTransition(
3816 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003817 }
3818 mService.mWindowManager.moveAppTokensToBottom(moved);
3819 if (VALIDATE_TOKENS) {
3820 mService.mWindowManager.validateAppTokens(mHistory);
3821 }
3822
3823 finishTaskMoveLocked(task);
3824 return true;
3825 }
3826
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003827 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
3828 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
3829 ActivityRecord resumed = mResumedActivity;
3830 if (resumed != null && resumed.thumbHolder == tr) {
3831 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
3832 } else {
3833 info.mainThumbnail = tr.lastThumbnail;
3834 }
3835 return info;
3836 }
3837
3838 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex) {
3839 TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
3840 if (info.root == null) {
3841 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
3842 return null;
3843 }
3844
3845 if (subTaskIndex < 0) {
3846 // Just remove the entire task.
3847 performClearTaskAtIndexLocked(taskId, info.rootIndex);
3848 return info.root;
3849 }
3850
3851 if (subTaskIndex >= info.subtasks.size()) {
3852 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
3853 return null;
3854 }
3855
3856 // Remove all of this task's activies starting at the sub task.
3857 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
3858 performClearTaskAtIndexLocked(taskId, subtask.index);
3859 return subtask.activity;
3860 }
3861
3862 public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
3863 ActivityRecord resumed = mResumedActivity;
3864 final TaskAccessInfo thumbs = new TaskAccessInfo();
3865 // How many different sub-thumbnails?
3866 final int NA = mHistory.size();
3867 int j = 0;
3868 ThumbnailHolder holder = null;
3869 while (j < NA) {
3870 ActivityRecord ar = mHistory.get(j);
3871 if (!ar.finishing && ar.task.taskId == taskId) {
3872 holder = ar.thumbHolder;
3873 break;
3874 }
3875 j++;
3876 }
3877
3878 if (j >= NA) {
3879 return thumbs;
3880 }
3881
3882 thumbs.root = mHistory.get(j);
3883 thumbs.rootIndex = j;
3884
3885 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
3886 thumbs.subtasks = subtasks;
3887 ActivityRecord lastActivity = null;
3888 while (j < NA) {
3889 ActivityRecord ar = mHistory.get(j);
3890 j++;
3891 if (ar.finishing) {
3892 continue;
3893 }
3894 if (ar.task.taskId != taskId) {
3895 break;
3896 }
3897 lastActivity = ar;
3898 if (ar.thumbHolder != holder && holder != null) {
3899 thumbs.numSubThumbbails++;
3900 holder = ar.thumbHolder;
3901 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
3902 sub.thumbnail = holder.lastThumbnail;
3903 sub.activity = ar;
3904 sub.index = j-1;
3905 subtasks.add(sub);
3906 }
3907 }
3908 if (lastActivity != null && subtasks.size() > 0) {
3909 if (resumed == lastActivity) {
3910 TaskAccessInfo.SubTask sub = subtasks.get(subtasks.size()-1);
3911 sub.thumbnail = lastActivity.stack.screenshotActivities(lastActivity);
3912 }
3913 }
3914 if (thumbs.numSubThumbbails > 0) {
3915 thumbs.retriever = new IThumbnailRetriever.Stub() {
3916 public Bitmap getThumbnail(int index) {
3917 if (index < 0 || index >= thumbs.subtasks.size()) {
3918 return null;
3919 }
3920 return thumbs.subtasks.get(index).thumbnail;
3921 }
3922 };
3923 }
3924 return thumbs;
3925 }
3926
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003927 private final void logStartActivity(int tag, ActivityRecord r,
3928 TaskRecord task) {
3929 EventLog.writeEvent(tag,
3930 System.identityHashCode(r), task.taskId,
3931 r.shortComponentName, r.intent.getAction(),
3932 r.intent.getType(), r.intent.getDataString(),
3933 r.intent.getFlags());
3934 }
3935
3936 /**
3937 * Make sure the given activity matches the current configuration. Returns
3938 * false if the activity had to be destroyed. Returns true if the
3939 * configuration is the same, or the activity will remain running as-is
3940 * for whatever reason. Ensures the HistoryRecord is updated with the
3941 * correct configuration and all other bookkeeping is handled.
3942 */
3943 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
3944 int globalChanges) {
3945 if (mConfigWillChange) {
3946 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3947 "Skipping config check (will change): " + r);
3948 return true;
3949 }
3950
3951 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3952 "Ensuring correct configuration: " + r);
3953
3954 // Short circuit: if the two configurations are the exact same
3955 // object (the common case), then there is nothing to do.
3956 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003957 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003958 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3959 "Configuration unchanged in " + r);
3960 return true;
3961 }
3962
3963 // We don't worry about activities that are finishing.
3964 if (r.finishing) {
3965 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3966 "Configuration doesn't matter in finishing " + r);
3967 r.stopFreezingScreenLocked(false);
3968 return true;
3969 }
3970
3971 // Okay we now are going to make this activity have the new config.
3972 // But then we need to figure out how it needs to deal with that.
3973 Configuration oldConfig = r.configuration;
3974 r.configuration = newConfig;
3975
3976 // If the activity isn't currently running, just leave the new
3977 // configuration and it will pick that up next time it starts.
3978 if (r.app == null || r.app.thread == null) {
3979 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3980 "Configuration doesn't matter not running " + r);
3981 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003982 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003983 return true;
3984 }
3985
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07003986 // Figure out what has changed between the two configurations.
3987 int changes = oldConfig.diff(newConfig);
3988 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
3989 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
3990 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07003991 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07003992 + ", newConfig=" + newConfig);
3993 }
Dianne Hackborne6676352011-06-01 16:51:20 -07003994 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07003995 // Aha, the activity isn't handling the change, so DIE DIE DIE.
3996 r.configChangeFlags |= changes;
3997 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003998 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07003999 if (r.app == null || r.app.thread == null) {
4000 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4001 "Switch is destroying non-running " + r);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004002 destroyActivityLocked(r, true, false);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004003 } else if (r.state == ActivityState.PAUSING) {
4004 // A little annoying: we are waiting for this activity to
4005 // finish pausing. Let's not do anything now, but just
4006 // flag that it needs to be restarted when done pausing.
4007 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4008 "Switch is skipping already pausing " + r);
4009 r.configDestroy = true;
4010 return true;
4011 } else if (r.state == ActivityState.RESUMED) {
4012 // Try to optimize this case: the configuration is changing
4013 // and we need to restart the top, resumed activity.
4014 // Instead of doing the normal handshaking, just say
4015 // "restart!".
4016 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4017 "Switch is restarting resumed " + r);
4018 relaunchActivityLocked(r, r.configChangeFlags, true);
4019 r.configChangeFlags = 0;
4020 } else {
4021 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4022 "Switch is restarting non-resumed " + r);
4023 relaunchActivityLocked(r, r.configChangeFlags, false);
4024 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004025 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004026
4027 // All done... tell the caller we weren't able to keep this
4028 // activity around.
4029 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004030 }
4031
4032 // Default case: the activity can handle this new configuration, so
4033 // hand it over. Note that we don't need to give it the new
4034 // configuration, since we always send configuration changes to all
4035 // process when they happen so it can just use whatever configuration
4036 // it last got.
4037 if (r.app != null && r.app.thread != null) {
4038 try {
4039 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
4040 r.app.thread.scheduleActivityConfigurationChanged(r);
4041 } catch (RemoteException e) {
4042 // If process died, whatever.
4043 }
4044 }
4045 r.stopFreezingScreenLocked(false);
4046
4047 return true;
4048 }
4049
4050 private final boolean relaunchActivityLocked(ActivityRecord r,
4051 int changes, boolean andResume) {
4052 List<ResultInfo> results = null;
4053 List<Intent> newIntents = null;
4054 if (andResume) {
4055 results = r.results;
4056 newIntents = r.newIntents;
4057 }
4058 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4059 + " with results=" + results + " newIntents=" + newIntents
4060 + " andResume=" + andResume);
4061 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
4062 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
4063 r.task.taskId, r.shortComponentName);
4064
4065 r.startFreezingScreenLocked(r.app, 0);
4066
4067 try {
4068 if (DEBUG_SWITCH) Slog.i(TAG, "Switch is restarting resumed " + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004069 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004070 r.app.thread.scheduleRelaunchActivity(r, results, newIntents,
4071 changes, !andResume, mService.mConfiguration);
4072 // Note: don't need to call pauseIfSleepingLocked() here, because
4073 // the caller will only pass in 'andResume' if this activity is
4074 // currently resumed, which implies we aren't sleeping.
4075 } catch (RemoteException e) {
4076 return false;
4077 }
4078
4079 if (andResume) {
4080 r.results = null;
4081 r.newIntents = null;
4082 if (mMainStack) {
4083 mService.reportResumedActivityLocked(r);
4084 }
4085 }
4086
4087 return true;
4088 }
4089}