blob: 35dee3cb96a112b81375e94621ade73977a73c2d [file] [log] [blame]
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
19import com.android.internal.app.HeavyWeightSwitcherActivity;
20import com.android.internal.os.BatteryStatsImpl;
21import com.android.server.am.ActivityManagerService.PendingActivityLaunch;
22
23import android.app.Activity;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070024import android.app.ActivityManager;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070025import android.app.AppGlobals;
26import android.app.IActivityManager;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070027import android.app.IThumbnailRetriever;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070028import static android.app.IActivityManager.START_CLASS_NOT_FOUND;
29import static android.app.IActivityManager.START_DELIVERED_TO_TOP;
30import static android.app.IActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
31import static android.app.IActivityManager.START_INTENT_NOT_RESOLVED;
32import static android.app.IActivityManager.START_PERMISSION_DENIED;
33import static android.app.IActivityManager.START_RETURN_INTENT_TO_CALLER;
34import static android.app.IActivityManager.START_SUCCESS;
35import static android.app.IActivityManager.START_SWITCHES_CANCELED;
36import static android.app.IActivityManager.START_TASK_TO_FRONT;
37import android.app.IApplicationThread;
38import android.app.PendingIntent;
39import android.app.ResultInfo;
40import android.app.IActivityManager.WaitResult;
41import android.content.ComponentName;
42import android.content.Context;
43import android.content.IIntentSender;
44import android.content.Intent;
45import android.content.IntentSender;
46import android.content.pm.ActivityInfo;
47import android.content.pm.ApplicationInfo;
48import android.content.pm.PackageManager;
49import android.content.pm.ResolveInfo;
50import android.content.res.Configuration;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -080051import android.content.res.Resources;
52import android.graphics.Bitmap;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070053import android.net.Uri;
54import android.os.Binder;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070055import android.os.Bundle;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070056import android.os.Handler;
57import android.os.IBinder;
58import android.os.Message;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070059import android.os.ParcelFileDescriptor;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070060import android.os.PowerManager;
61import android.os.RemoteException;
62import android.os.SystemClock;
63import android.util.EventLog;
64import android.util.Log;
65import android.util.Slog;
66import android.view.WindowManagerPolicy;
67
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070068import java.io.IOException;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070069import java.lang.ref.WeakReference;
70import java.util.ArrayList;
71import java.util.Iterator;
72import java.util.List;
73
74/**
75 * State and management of a single stack of activities.
76 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070077final class ActivityStack {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070078 static final String TAG = ActivityManagerService.TAG;
Dianne Hackbornb961cd22011-06-21 12:13:37 -070079 static final boolean localLOGV = ActivityManagerService.localLOGV;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070080 static final boolean DEBUG_SWITCH = ActivityManagerService.DEBUG_SWITCH;
81 static final boolean DEBUG_PAUSE = ActivityManagerService.DEBUG_PAUSE;
82 static final boolean DEBUG_VISBILITY = ActivityManagerService.DEBUG_VISBILITY;
83 static final boolean DEBUG_USER_LEAVING = ActivityManagerService.DEBUG_USER_LEAVING;
84 static final boolean DEBUG_TRANSITION = ActivityManagerService.DEBUG_TRANSITION;
85 static final boolean DEBUG_RESULTS = ActivityManagerService.DEBUG_RESULTS;
86 static final boolean DEBUG_CONFIGURATION = ActivityManagerService.DEBUG_CONFIGURATION;
87 static final boolean DEBUG_TASKS = ActivityManagerService.DEBUG_TASKS;
88
Dianne Hackbornce86ba82011-07-13 19:33:41 -070089 static final boolean DEBUG_STATES = false;
90
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070091 static final boolean VALIDATE_TOKENS = ActivityManagerService.VALIDATE_TOKENS;
92
93 // How long we wait until giving up on the last activity telling us it
94 // is idle.
95 static final int IDLE_TIMEOUT = 10*1000;
96
97 // How long we wait until giving up on the last activity to pause. This
98 // is short because it directly impacts the responsiveness of starting the
99 // next activity.
100 static final int PAUSE_TIMEOUT = 500;
101
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800102 // How long we can hold the sleep wake lock before giving up.
103 static final int SLEEP_TIMEOUT = 5*1000;
104
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700105 // How long we can hold the launch wake lock before giving up.
106 static final int LAUNCH_TIMEOUT = 10*1000;
107
108 // How long we wait until giving up on an activity telling us it has
109 // finished destroying itself.
110 static final int DESTROY_TIMEOUT = 10*1000;
111
112 // How long until we reset a task when the user returns to it. Currently
Dianne Hackborn621e17d2010-11-22 15:59:56 -0800113 // disabled.
114 static final long ACTIVITY_INACTIVE_RESET_TIME = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700115
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700116 // How long between activity launches that we consider safe to not warn
117 // the user about an unexpected activity being launched on top.
118 static final long START_WARN_TIME = 5*1000;
119
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700120 // Set to false to disable the preview that is shown while a new activity
121 // is being started.
122 static final boolean SHOW_APP_STARTING_PREVIEW = true;
123
124 enum ActivityState {
125 INITIALIZING,
126 RESUMED,
127 PAUSING,
128 PAUSED,
129 STOPPING,
130 STOPPED,
131 FINISHING,
132 DESTROYING,
133 DESTROYED
134 }
135
136 final ActivityManagerService mService;
137 final boolean mMainStack;
138
139 final Context mContext;
140
141 /**
142 * The back history of all previous (and possibly still
143 * running) activities. It contains HistoryRecord objects.
144 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700145 final ArrayList<ActivityRecord> mHistory = new ArrayList<ActivityRecord>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700146
147 /**
148 * List of running activities, sorted by recent usage.
149 * The first entry in the list is the least recently used.
150 * It contains HistoryRecord objects.
151 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700152 final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700153
154 /**
155 * List of activities that are waiting for a new activity
156 * to become visible before completing whatever operation they are
157 * supposed to do.
158 */
159 final ArrayList<ActivityRecord> mWaitingVisibleActivities
160 = new ArrayList<ActivityRecord>();
161
162 /**
163 * List of activities that are ready to be stopped, but waiting
164 * for the next activity to settle down before doing so. It contains
165 * HistoryRecord objects.
166 */
167 final ArrayList<ActivityRecord> mStoppingActivities
168 = new ArrayList<ActivityRecord>();
169
170 /**
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800171 * List of activities that are in the process of going to sleep.
172 */
173 final ArrayList<ActivityRecord> mGoingToSleepActivities
174 = new ArrayList<ActivityRecord>();
175
176 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700177 * Animations that for the current transition have requested not to
178 * be considered for the transition animation.
179 */
180 final ArrayList<ActivityRecord> mNoAnimActivities
181 = new ArrayList<ActivityRecord>();
182
183 /**
184 * List of activities that are ready to be finished, but waiting
185 * for the previous activity to settle down before doing so. It contains
186 * HistoryRecord objects.
187 */
188 final ArrayList<ActivityRecord> mFinishingActivities
189 = new ArrayList<ActivityRecord>();
190
191 /**
192 * List of people waiting to find out about the next launched activity.
193 */
194 final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched
195 = new ArrayList<IActivityManager.WaitResult>();
196
197 /**
198 * List of people waiting to find out about the next visible activity.
199 */
200 final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible
201 = new ArrayList<IActivityManager.WaitResult>();
202
203 /**
204 * Set when the system is going to sleep, until we have
205 * successfully paused the current activity and released our wake lock.
206 * At that point the system is allowed to actually sleep.
207 */
208 final PowerManager.WakeLock mGoingToSleep;
209
210 /**
211 * We don't want to allow the device to go to sleep while in the process
212 * of launching an activity. This is primarily to allow alarm intent
213 * receivers to launch an activity and get that to run before the device
214 * goes back to sleep.
215 */
216 final PowerManager.WakeLock mLaunchingActivity;
217
218 /**
219 * When we are in the process of pausing an activity, before starting the
220 * next one, this variable holds the activity that is currently being paused.
221 */
222 ActivityRecord mPausingActivity = null;
223
224 /**
225 * This is the last activity that we put into the paused state. This is
226 * used to determine if we need to do an activity transition while sleeping,
227 * when we normally hold the top activity paused.
228 */
229 ActivityRecord mLastPausedActivity = null;
230
231 /**
232 * Current activity that is resumed, or null if there is none.
233 */
234 ActivityRecord mResumedActivity = null;
235
236 /**
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700237 * This is the last activity that has been started. It is only used to
238 * identify when multiple activities are started at once so that the user
239 * can be warned they may not be in the activity they think they are.
240 */
241 ActivityRecord mLastStartedActivity = null;
242
243 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700244 * Set when we know we are going to be calling updateConfiguration()
245 * soon, so want to skip intermediate config checks.
246 */
247 boolean mConfigWillChange;
248
249 /**
250 * Set to indicate whether to issue an onUserLeaving callback when a
251 * newly launched activity is being brought in front of us.
252 */
253 boolean mUserLeaving = false;
254
255 long mInitialStartTime = 0;
256
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800257 /**
258 * Set when we have taken too long waiting to go to sleep.
259 */
260 boolean mSleepTimeout = false;
261
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800262 int mThumbnailWidth = -1;
263 int mThumbnailHeight = -1;
264
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800265 static final int SLEEP_TIMEOUT_MSG = 8;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700266 static final int PAUSE_TIMEOUT_MSG = 9;
267 static final int IDLE_TIMEOUT_MSG = 10;
268 static final int IDLE_NOW_MSG = 11;
269 static final int LAUNCH_TIMEOUT_MSG = 16;
270 static final int DESTROY_TIMEOUT_MSG = 17;
271 static final int RESUME_TOP_ACTIVITY_MSG = 19;
272
273 final Handler mHandler = new Handler() {
274 //public Handler() {
275 // if (localLOGV) Slog.v(TAG, "Handler started!");
276 //}
277
278 public void handleMessage(Message msg) {
279 switch (msg.what) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800280 case SLEEP_TIMEOUT_MSG: {
Dianne Hackborn8e8d65f2011-08-11 19:36:18 -0700281 synchronized (mService) {
282 if (mService.isSleeping()) {
283 Slog.w(TAG, "Sleep timeout! Sleeping now.");
284 mSleepTimeout = true;
285 checkReadyForSleepLocked();
286 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800287 }
288 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700289 case PAUSE_TIMEOUT_MSG: {
290 IBinder token = (IBinder)msg.obj;
291 // We don't at this point know if the activity is fullscreen,
292 // so we need to be conservative and assume it isn't.
293 Slog.w(TAG, "Activity pause timeout for " + token);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800294 activityPaused(token, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700295 } break;
296 case IDLE_TIMEOUT_MSG: {
297 if (mService.mDidDexOpt) {
298 mService.mDidDexOpt = false;
299 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
300 nmsg.obj = msg.obj;
301 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
302 return;
303 }
304 // We don't at this point know if the activity is fullscreen,
305 // so we need to be conservative and assume it isn't.
306 IBinder token = (IBinder)msg.obj;
307 Slog.w(TAG, "Activity idle timeout for " + token);
308 activityIdleInternal(token, true, null);
309 } break;
310 case DESTROY_TIMEOUT_MSG: {
311 IBinder token = (IBinder)msg.obj;
312 // We don't at this point know if the activity is fullscreen,
313 // so we need to be conservative and assume it isn't.
314 Slog.w(TAG, "Activity destroy timeout for " + token);
315 activityDestroyed(token);
316 } break;
317 case IDLE_NOW_MSG: {
318 IBinder token = (IBinder)msg.obj;
319 activityIdleInternal(token, false, null);
320 } break;
321 case LAUNCH_TIMEOUT_MSG: {
322 if (mService.mDidDexOpt) {
323 mService.mDidDexOpt = false;
324 Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
325 mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
326 return;
327 }
328 synchronized (mService) {
329 if (mLaunchingActivity.isHeld()) {
330 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
331 mLaunchingActivity.release();
332 }
333 }
334 } break;
335 case RESUME_TOP_ACTIVITY_MSG: {
336 synchronized (mService) {
337 resumeTopActivityLocked(null);
338 }
339 } break;
340 }
341 }
342 };
343
344 ActivityStack(ActivityManagerService service, Context context, boolean mainStack) {
345 mService = service;
346 mContext = context;
347 mMainStack = mainStack;
348 PowerManager pm =
349 (PowerManager)context.getSystemService(Context.POWER_SERVICE);
350 mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
351 mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
352 mLaunchingActivity.setReferenceCounted(false);
353 }
354
355 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
356 int i = mHistory.size()-1;
357 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700358 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700359 if (!r.finishing && r != notTop) {
360 return r;
361 }
362 i--;
363 }
364 return null;
365 }
366
367 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
368 int i = mHistory.size()-1;
369 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700370 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700371 if (!r.finishing && !r.delayedResume && r != notTop) {
372 return r;
373 }
374 i--;
375 }
376 return null;
377 }
378
379 /**
380 * This is a simplified version of topRunningActivityLocked that provides a number of
381 * optional skip-over modes. It is intended for use with the ActivityController hook only.
382 *
383 * @param token If non-null, any history records matching this token will be skipped.
384 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
385 *
386 * @return Returns the HistoryRecord of the next activity on the stack.
387 */
388 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
389 int i = mHistory.size()-1;
390 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700391 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700392 // Note: the taskId check depends on real taskId fields being non-zero
393 if (!r.finishing && (token != r) && (taskId != r.task.taskId)) {
394 return r;
395 }
396 i--;
397 }
398 return null;
399 }
400
401 final int indexOfTokenLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700402 try {
403 ActivityRecord r = (ActivityRecord)token;
404 return mHistory.indexOf(r);
405 } catch (ClassCastException e) {
406 Slog.w(TAG, "Bad activity token: " + token, e);
407 return -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700408 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700409 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700410
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700411 final ActivityRecord isInStackLocked(IBinder token) {
412 try {
413 ActivityRecord r = (ActivityRecord)token;
414 if (mHistory.contains(r)) {
415 return r;
416 }
417 } catch (ClassCastException e) {
418 Slog.w(TAG, "Bad activity token: " + token, e);
419 }
420 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700421 }
422
423 private final boolean updateLRUListLocked(ActivityRecord r) {
424 final boolean hadit = mLRUActivities.remove(r);
425 mLRUActivities.add(r);
426 return hadit;
427 }
428
429 /**
430 * Returns the top activity in any existing task matching the given
431 * Intent. Returns null if no such task is found.
432 */
433 private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
434 ComponentName cls = intent.getComponent();
435 if (info.targetActivity != null) {
436 cls = new ComponentName(info.packageName, info.targetActivity);
437 }
438
439 TaskRecord cp = null;
440
441 final int N = mHistory.size();
442 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700443 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700444 if (!r.finishing && r.task != cp
445 && r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
446 cp = r.task;
447 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
448 // + "/aff=" + r.task.affinity + " to new cls="
449 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
450 if (r.task.affinity != null) {
451 if (r.task.affinity.equals(info.taskAffinity)) {
452 //Slog.i(TAG, "Found matching affinity!");
453 return r;
454 }
455 } else if (r.task.intent != null
456 && r.task.intent.getComponent().equals(cls)) {
457 //Slog.i(TAG, "Found matching class!");
458 //dump();
459 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
460 return r;
461 } else if (r.task.affinityIntent != null
462 && r.task.affinityIntent.getComponent().equals(cls)) {
463 //Slog.i(TAG, "Found matching class!");
464 //dump();
465 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
466 return r;
467 }
468 }
469 }
470
471 return null;
472 }
473
474 /**
475 * Returns the first activity (starting from the top of the stack) that
476 * is the same as the given activity. Returns null if no such activity
477 * is found.
478 */
479 private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
480 ComponentName cls = intent.getComponent();
481 if (info.targetActivity != null) {
482 cls = new ComponentName(info.packageName, info.targetActivity);
483 }
484
485 final int N = mHistory.size();
486 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700487 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700488 if (!r.finishing) {
489 if (r.intent.getComponent().equals(cls)) {
490 //Slog.i(TAG, "Found matching class!");
491 //dump();
492 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
493 return r;
494 }
495 }
496 }
497
498 return null;
499 }
500
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700501 final void showAskCompatModeDialogLocked(ActivityRecord r) {
502 Message msg = Message.obtain();
503 msg.what = ActivityManagerService.SHOW_COMPAT_MODE_DIALOG_MSG;
504 msg.obj = r.task.askedCompatMode ? null : r;
505 mService.mHandler.sendMessage(msg);
506 }
507
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700508 final boolean realStartActivityLocked(ActivityRecord r,
509 ProcessRecord app, boolean andResume, boolean checkConfig)
510 throws RemoteException {
511
512 r.startFreezingScreenLocked(app, 0);
513 mService.mWindowManager.setAppVisibility(r, true);
514
515 // Have the window manager re-evaluate the orientation of
516 // the screen based on the new activity order. Note that
517 // as a result of this, it can call back into the activity
518 // manager with a new orientation. We don't care about that,
519 // because the activity is not currently running so we are
520 // just restarting it anyway.
521 if (checkConfig) {
522 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
523 mService.mConfiguration,
524 r.mayFreezeScreenLocked(app) ? r : null);
Dianne Hackborn31ca8542011-07-19 14:58:28 -0700525 mService.updateConfigurationLocked(config, r, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700526 }
527
528 r.app = app;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700529 app.waitingToKill = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700530
531 if (localLOGV) Slog.v(TAG, "Launching: " + r);
532
533 int idx = app.activities.indexOf(r);
534 if (idx < 0) {
535 app.activities.add(r);
536 }
537 mService.updateLruProcessLocked(app, true, true);
538
539 try {
540 if (app.thread == null) {
541 throw new RemoteException();
542 }
543 List<ResultInfo> results = null;
544 List<Intent> newIntents = null;
545 if (andResume) {
546 results = r.results;
547 newIntents = r.newIntents;
548 }
549 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
550 + " icicle=" + r.icicle
551 + " with results=" + results + " newIntents=" + newIntents
552 + " andResume=" + andResume);
553 if (andResume) {
554 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
555 System.identityHashCode(r),
556 r.task.taskId, r.shortComponentName);
557 }
558 if (r.isHomeActivity) {
559 mService.mHomeProcess = app;
560 }
561 mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800562 r.sleeping = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400563 r.forceNewConfig = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700564 showAskCompatModeDialogLocked(r);
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700565 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700566 String profileFile = null;
567 ParcelFileDescriptor profileFd = null;
568 boolean profileAutoStop = false;
569 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
570 if (mService.mProfileProc == null || mService.mProfileProc == app) {
571 mService.mProfileProc = app;
572 profileFile = mService.mProfileFile;
573 profileFd = mService.mProfileFd;
574 profileAutoStop = mService.mAutoStopProfiler;
575 }
576 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -0700577 app.hasShownUi = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700578 app.pendingUiClean = true;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700579 if (profileFd != null) {
580 try {
581 profileFd = profileFd.dup();
582 } catch (IOException e) {
583 profileFd = null;
584 }
585 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700586 app.thread.scheduleLaunchActivity(new Intent(r.intent), r,
587 System.identityHashCode(r),
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700588 r.info, r.compat, r.icicle, results, newIntents, !andResume,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700589 mService.isNextTransitionForward(), profileFile, profileFd,
590 profileAutoStop);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700591
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700592 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700593 // This may be a heavy-weight process! Note that the package
594 // manager will ensure that only activity can run in the main
595 // process of the .apk, which is the only thing that will be
596 // considered heavy-weight.
597 if (app.processName.equals(app.info.packageName)) {
598 if (mService.mHeavyWeightProcess != null
599 && mService.mHeavyWeightProcess != app) {
600 Log.w(TAG, "Starting new heavy weight process " + app
601 + " when already running "
602 + mService.mHeavyWeightProcess);
603 }
604 mService.mHeavyWeightProcess = app;
605 Message msg = mService.mHandler.obtainMessage(
606 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
607 msg.obj = r;
608 mService.mHandler.sendMessage(msg);
609 }
610 }
611
612 } catch (RemoteException e) {
613 if (r.launchFailed) {
614 // This is the second time we failed -- finish activity
615 // and give up.
616 Slog.e(TAG, "Second failure launching "
617 + r.intent.getComponent().flattenToShortString()
618 + ", giving up", e);
619 mService.appDiedLocked(app, app.pid, app.thread);
620 requestFinishActivityLocked(r, Activity.RESULT_CANCELED, null,
621 "2nd-crash");
622 return false;
623 }
624
625 // This is the first time we failed -- restart process and
626 // retry.
627 app.activities.remove(r);
628 throw e;
629 }
630
631 r.launchFailed = false;
632 if (updateLRUListLocked(r)) {
633 Slog.w(TAG, "Activity " + r
634 + " being launched, but already in LRU list");
635 }
636
637 if (andResume) {
638 // As part of the process of launching, ActivityThread also performs
639 // a resume.
640 r.state = ActivityState.RESUMED;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700641 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
642 + " (starting new instance)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700643 r.stopped = false;
644 mResumedActivity = r;
645 r.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -0800646 if (mMainStack) {
647 mService.addRecentTaskLocked(r.task);
648 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700649 completeResumeLocked(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800650 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700651 } else {
652 // This activity is not starting in the resumed state... which
653 // should look like we asked it to pause+stop (but remain visible),
654 // and it has done so and reported back the current icicle and
655 // other state.
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700656 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
657 + " (starting in stopped state)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700658 r.state = ActivityState.STOPPED;
659 r.stopped = true;
660 }
661
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800662 r.icicle = null;
663 r.haveState = false;
664
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700665 // Launch the new version setup screen if needed. We do this -after-
666 // launching the initial activity (that is, home), so that it can have
667 // a chance to initialize itself while in the background, making the
668 // switch back to it faster and look better.
669 if (mMainStack) {
670 mService.startSetupActivityLocked();
671 }
672
673 return true;
674 }
675
676 private final void startSpecificActivityLocked(ActivityRecord r,
677 boolean andResume, boolean checkConfig) {
678 // Is this activity's application already running?
679 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
680 r.info.applicationInfo.uid);
681
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700682 if (r.launchTime == 0) {
683 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700684 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700685 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700686 }
687 } else if (mInitialStartTime == 0) {
688 mInitialStartTime = SystemClock.uptimeMillis();
689 }
690
691 if (app != null && app.thread != null) {
692 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700693 app.addPackage(r.info.packageName);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700694 realStartActivityLocked(r, app, andResume, checkConfig);
695 return;
696 } catch (RemoteException e) {
697 Slog.w(TAG, "Exception when starting activity "
698 + r.intent.getComponent().flattenToShortString(), e);
699 }
700
701 // If a dead object exception was thrown -- fall through to
702 // restart the application.
703 }
704
705 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
706 "activity", r.intent.getComponent(), false);
707 }
708
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800709 void stopIfSleepingLocked() {
710 if (mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700711 if (!mGoingToSleep.isHeld()) {
712 mGoingToSleep.acquire();
713 if (mLaunchingActivity.isHeld()) {
714 mLaunchingActivity.release();
715 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
716 }
717 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800718 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
719 Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
720 mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
721 checkReadyForSleepLocked();
722 }
723 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700724
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800725 void awakeFromSleepingLocked() {
726 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
727 mSleepTimeout = false;
728 if (mGoingToSleep.isHeld()) {
729 mGoingToSleep.release();
730 }
731 // Ensure activities are no longer sleeping.
732 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700733 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800734 r.setSleeping(false);
735 }
736 mGoingToSleepActivities.clear();
737 }
738
739 void activitySleptLocked(ActivityRecord r) {
740 mGoingToSleepActivities.remove(r);
741 checkReadyForSleepLocked();
742 }
743
744 void checkReadyForSleepLocked() {
745 if (!mService.isSleeping()) {
746 // Do not care.
747 return;
748 }
749
750 if (!mSleepTimeout) {
751 if (mResumedActivity != null) {
752 // Still have something resumed; can't sleep until it is paused.
753 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700754 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
755 startPausingLocked(false, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800756 return;
757 }
758 if (mPausingActivity != null) {
759 // Still waiting for something to pause; can't sleep yet.
760 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
761 return;
762 }
763
764 if (mStoppingActivities.size() > 0) {
765 // Still need to tell some activities to stop; can't sleep yet.
766 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
767 + mStoppingActivities.size() + " activities");
Dianne Hackborn80a7ac12011-09-22 18:32:52 -0700768 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800769 return;
770 }
771
772 ensureActivitiesVisibleLocked(null, 0);
773
774 // Make sure any stopped but visible activities are now sleeping.
775 // This ensures that the activity's onStop() is called.
776 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700777 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800778 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
779 r.setSleeping(true);
780 }
781 }
782
783 if (mGoingToSleepActivities.size() > 0) {
784 // Still need to tell some activities to sleep; can't sleep yet.
785 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
786 + mGoingToSleepActivities.size() + " activities");
787 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700788 }
789 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800790
791 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
792
793 if (mGoingToSleep.isHeld()) {
794 mGoingToSleep.release();
795 }
796 if (mService.mShuttingDown) {
797 mService.notifyAll();
798 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700799 }
800
Dianne Hackbornd2835932010-12-13 16:28:46 -0800801 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -0800802 if (who.noDisplay) {
803 return null;
804 }
805
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800806 Resources res = mService.mContext.getResources();
807 int w = mThumbnailWidth;
808 int h = mThumbnailHeight;
809 if (w < 0) {
810 mThumbnailWidth = w =
811 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
812 mThumbnailHeight = h =
813 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
814 }
815
816 if (w > 0) {
Dianne Hackborn7c8a4b32010-12-15 14:58:00 -0800817 return mService.mWindowManager.screenshotApplications(who, w, h);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800818 }
819 return null;
820 }
821
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700822 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
823 if (mPausingActivity != null) {
824 RuntimeException e = new RuntimeException();
825 Slog.e(TAG, "Trying to pause when pause is already pending for "
826 + mPausingActivity, e);
827 }
828 ActivityRecord prev = mResumedActivity;
829 if (prev == null) {
830 RuntimeException e = new RuntimeException();
831 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
832 resumeTopActivityLocked(null);
833 return;
834 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700835 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
836 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700837 mResumedActivity = null;
838 mPausingActivity = prev;
839 mLastPausedActivity = prev;
840 prev.state = ActivityState.PAUSING;
841 prev.task.touchActiveTime();
Dianne Hackbornf26fd992011-04-08 18:14:09 -0700842 prev.updateThumbnail(screenshotActivities(prev), null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700843
844 mService.updateCpuStats();
845
846 if (prev.app != null && prev.app.thread != null) {
847 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
848 try {
849 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
850 System.identityHashCode(prev),
851 prev.shortComponentName);
852 prev.app.thread.schedulePauseActivity(prev, prev.finishing, userLeaving,
853 prev.configChangeFlags);
854 if (mMainStack) {
855 mService.updateUsageStats(prev, false);
856 }
857 } catch (Exception e) {
858 // Ignore exception, if process died other code will cleanup.
859 Slog.w(TAG, "Exception thrown during pause", e);
860 mPausingActivity = null;
861 mLastPausedActivity = null;
862 }
863 } else {
864 mPausingActivity = null;
865 mLastPausedActivity = null;
866 }
867
868 // If we are not going to sleep, we want to ensure the device is
869 // awake until the next activity is started.
870 if (!mService.mSleeping && !mService.mShuttingDown) {
871 mLaunchingActivity.acquire();
872 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
873 // To be safe, don't allow the wake lock to be held for too long.
874 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
875 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
876 }
877 }
878
879
880 if (mPausingActivity != null) {
881 // Have the window manager pause its key dispatching until the new
882 // activity has started. If we're pausing the activity just because
883 // the screen is being turned off and the UI is sleeping, don't interrupt
884 // key dispatch; the same activity will pick it up again on wakeup.
885 if (!uiSleeping) {
886 prev.pauseKeyDispatchingLocked();
887 } else {
888 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
889 }
890
891 // Schedule a pause timeout in case the app doesn't respond.
892 // We don't give it much time because this directly impacts the
893 // responsiveness seen by the user.
894 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
895 msg.obj = prev;
896 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
897 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
898 } else {
899 // This activity failed to schedule the
900 // pause, so just treat it as being paused now.
901 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
902 resumeTopActivityLocked(null);
903 }
904 }
905
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800906 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700907 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800908 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700909
910 ActivityRecord r = null;
911
912 synchronized (mService) {
913 int index = indexOfTokenLocked(token);
914 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700915 r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700916 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
917 if (mPausingActivity == r) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700918 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
919 + (timeout ? " (due to timeout)" : " (pause complete)"));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700920 r.state = ActivityState.PAUSED;
921 completePauseLocked();
922 } else {
923 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
924 System.identityHashCode(r), r.shortComponentName,
925 mPausingActivity != null
926 ? mPausingActivity.shortComponentName : "(none)");
927 }
928 }
929 }
930 }
931
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700932 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
933 CharSequence description) {
934 r.icicle = icicle;
935 r.haveState = true;
936 r.updateThumbnail(thumbnail, description);
937 r.stopped = true;
938 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
939 r.state = ActivityState.STOPPED;
940 if (!r.finishing) {
941 if (r.configDestroy) {
942 destroyActivityLocked(r, true, false);
943 resumeTopActivityLocked(null);
944 }
945 }
946 }
947
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700948 private final void completePauseLocked() {
949 ActivityRecord prev = mPausingActivity;
950 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
951
952 if (prev != null) {
953 if (prev.finishing) {
954 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
955 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE);
956 } else if (prev.app != null) {
957 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
958 if (prev.waitingVisible) {
959 prev.waitingVisible = false;
960 mWaitingVisibleActivities.remove(prev);
961 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
962 TAG, "Complete pause, no longer waiting: " + prev);
963 }
964 if (prev.configDestroy) {
965 // The previous is being paused because the configuration
966 // is changing, which means it is actually stopping...
967 // To juggle the fact that we are also starting a new
968 // instance right now, we need to first completely stop
969 // the current instance before starting the new one.
970 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700971 destroyActivityLocked(prev, true, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700972 } else {
973 mStoppingActivities.add(prev);
974 if (mStoppingActivities.size() > 3) {
975 // If we already have a few activities waiting to stop,
976 // then give up on things going idle and start clearing
977 // them out.
978 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
Dianne Hackborn80a7ac12011-09-22 18:32:52 -0700979 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800980 } else {
981 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700982 }
983 }
984 } else {
985 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
986 prev = null;
987 }
988 mPausingActivity = null;
989 }
990
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800991 if (!mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700992 resumeTopActivityLocked(prev);
993 } else {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800994 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700995 }
996
997 if (prev != null) {
998 prev.resumeKeyDispatchingLocked();
999 }
1000
1001 if (prev.app != null && prev.cpuTimeAtResume > 0
1002 && mService.mBatteryStatsService.isOnBattery()) {
1003 long diff = 0;
1004 synchronized (mService.mProcessStatsThread) {
1005 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
1006 - prev.cpuTimeAtResume;
1007 }
1008 if (diff > 0) {
1009 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
1010 synchronized (bsi) {
1011 BatteryStatsImpl.Uid.Proc ps =
1012 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
1013 prev.info.packageName);
1014 if (ps != null) {
1015 ps.addForegroundTimeLocked(diff);
1016 }
1017 }
1018 }
1019 }
1020 prev.cpuTimeAtResume = 0; // reset it
1021 }
1022
1023 /**
1024 * Once we know that we have asked an application to put an activity in
1025 * the resumed state (either by launching it or explicitly telling it),
1026 * this function updates the rest of our state to match that fact.
1027 */
1028 private final void completeResumeLocked(ActivityRecord next) {
1029 next.idle = false;
1030 next.results = null;
1031 next.newIntents = null;
1032
1033 // schedule an idle timeout in case the app doesn't do it for us.
1034 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1035 msg.obj = next;
1036 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
1037
1038 if (false) {
1039 // The activity was never told to pause, so just keep
1040 // things going as-is. To maintain our own state,
1041 // we need to emulate it coming back and saying it is
1042 // idle.
1043 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
1044 msg.obj = next;
1045 mHandler.sendMessage(msg);
1046 }
1047
1048 if (mMainStack) {
1049 mService.reportResumedActivityLocked(next);
1050 }
1051
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001052 next.clearThumbnail();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001053 if (mMainStack) {
1054 mService.setFocusedActivityLocked(next);
1055 }
1056 next.resumeKeyDispatchingLocked();
1057 ensureActivitiesVisibleLocked(null, 0);
1058 mService.mWindowManager.executeAppTransition();
1059 mNoAnimActivities.clear();
1060
1061 // Mark the point when the activity is resuming
1062 // TODO: To be more accurate, the mark should be before the onCreate,
1063 // not after the onResume. But for subsequent starts, onResume is fine.
1064 if (next.app != null) {
1065 synchronized (mService.mProcessStatsThread) {
1066 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1067 }
1068 } else {
1069 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1070 }
1071 }
1072
1073 /**
1074 * Make sure that all activities that need to be visible (that is, they
1075 * currently can be seen by the user) actually are.
1076 */
1077 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1078 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1079 if (DEBUG_VISBILITY) Slog.v(
1080 TAG, "ensureActivitiesVisible behind " + top
1081 + " configChanges=0x" + Integer.toHexString(configChanges));
1082
1083 // If the top activity is not fullscreen, then we need to
1084 // make sure any activities under it are now visible.
1085 final int count = mHistory.size();
1086 int i = count-1;
1087 while (mHistory.get(i) != top) {
1088 i--;
1089 }
1090 ActivityRecord r;
1091 boolean behindFullscreen = false;
1092 for (; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001093 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001094 if (DEBUG_VISBILITY) Slog.v(
1095 TAG, "Make visible? " + r + " finishing=" + r.finishing
1096 + " state=" + r.state);
1097 if (r.finishing) {
1098 continue;
1099 }
1100
1101 final boolean doThisProcess = onlyThisProcess == null
1102 || onlyThisProcess.equals(r.processName);
1103
1104 // First: if this is not the current activity being started, make
1105 // sure it matches the current configuration.
1106 if (r != starting && doThisProcess) {
1107 ensureActivityConfigurationLocked(r, 0);
1108 }
1109
1110 if (r.app == null || r.app.thread == null) {
1111 if (onlyThisProcess == null
1112 || onlyThisProcess.equals(r.processName)) {
1113 // This activity needs to be visible, but isn't even
1114 // running... get it started, but don't resume it
1115 // at this point.
1116 if (DEBUG_VISBILITY) Slog.v(
1117 TAG, "Start and freeze screen for " + r);
1118 if (r != starting) {
1119 r.startFreezingScreenLocked(r.app, configChanges);
1120 }
1121 if (!r.visible) {
1122 if (DEBUG_VISBILITY) Slog.v(
1123 TAG, "Starting and making visible: " + r);
1124 mService.mWindowManager.setAppVisibility(r, true);
1125 }
1126 if (r != starting) {
1127 startSpecificActivityLocked(r, false, false);
1128 }
1129 }
1130
1131 } else if (r.visible) {
1132 // If this activity is already visible, then there is nothing
1133 // else to do here.
1134 if (DEBUG_VISBILITY) Slog.v(
1135 TAG, "Skipping: already visible at " + r);
1136 r.stopFreezingScreenLocked(false);
1137
1138 } else if (onlyThisProcess == null) {
1139 // This activity is not currently visible, but is running.
1140 // Tell it to become visible.
1141 r.visible = true;
1142 if (r.state != ActivityState.RESUMED && r != starting) {
1143 // If this activity is paused, tell it
1144 // to now show its window.
1145 if (DEBUG_VISBILITY) Slog.v(
1146 TAG, "Making visible and scheduling visibility: " + r);
1147 try {
1148 mService.mWindowManager.setAppVisibility(r, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001149 r.sleeping = false;
Dianne Hackborn905577f2011-09-07 18:31:28 -07001150 r.app.pendingUiClean = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001151 r.app.thread.scheduleWindowVisibility(r, true);
1152 r.stopFreezingScreenLocked(false);
1153 } catch (Exception e) {
1154 // Just skip on any failure; we'll make it
1155 // visible when it next restarts.
1156 Slog.w(TAG, "Exception thrown making visibile: "
1157 + r.intent.getComponent(), e);
1158 }
1159 }
1160 }
1161
1162 // Aggregate current change flags.
1163 configChanges |= r.configChangeFlags;
1164
1165 if (r.fullscreen) {
1166 // At this point, nothing else needs to be shown
1167 if (DEBUG_VISBILITY) Slog.v(
1168 TAG, "Stopping: fullscreen at " + r);
1169 behindFullscreen = true;
1170 i--;
1171 break;
1172 }
1173 }
1174
1175 // Now for any activities that aren't visible to the user, make
1176 // sure they no longer are keeping the screen frozen.
1177 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001178 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001179 if (DEBUG_VISBILITY) Slog.v(
1180 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1181 + " state=" + r.state
1182 + " behindFullscreen=" + behindFullscreen);
1183 if (!r.finishing) {
1184 if (behindFullscreen) {
1185 if (r.visible) {
1186 if (DEBUG_VISBILITY) Slog.v(
1187 TAG, "Making invisible: " + r);
1188 r.visible = false;
1189 try {
1190 mService.mWindowManager.setAppVisibility(r, false);
1191 if ((r.state == ActivityState.STOPPING
1192 || r.state == ActivityState.STOPPED)
1193 && r.app != null && r.app.thread != null) {
1194 if (DEBUG_VISBILITY) Slog.v(
1195 TAG, "Scheduling invisibility: " + r);
1196 r.app.thread.scheduleWindowVisibility(r, false);
1197 }
1198 } catch (Exception e) {
1199 // Just skip on any failure; we'll make it
1200 // visible when it next restarts.
1201 Slog.w(TAG, "Exception thrown making hidden: "
1202 + r.intent.getComponent(), e);
1203 }
1204 } else {
1205 if (DEBUG_VISBILITY) Slog.v(
1206 TAG, "Already invisible: " + r);
1207 }
1208 } else if (r.fullscreen) {
1209 if (DEBUG_VISBILITY) Slog.v(
1210 TAG, "Now behindFullscreen: " + r);
1211 behindFullscreen = true;
1212 }
1213 }
1214 i--;
1215 }
1216 }
1217
1218 /**
1219 * Version of ensureActivitiesVisible that can easily be called anywhere.
1220 */
1221 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1222 int configChanges) {
1223 ActivityRecord r = topRunningActivityLocked(null);
1224 if (r != null) {
1225 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1226 }
1227 }
1228
1229 /**
1230 * Ensure that the top activity in the stack is resumed.
1231 *
1232 * @param prev The previously resumed activity, for when in the process
1233 * of pausing; can be null to call from elsewhere.
1234 *
1235 * @return Returns true if something is being resumed, or false if
1236 * nothing happened.
1237 */
1238 final boolean resumeTopActivityLocked(ActivityRecord prev) {
1239 // Find the first activity that is not finishing.
1240 ActivityRecord next = topRunningActivityLocked(null);
1241
1242 // Remember how we'll process this pause/resume situation, and ensure
1243 // that the state is reset however we wind up proceeding.
1244 final boolean userLeaving = mUserLeaving;
1245 mUserLeaving = false;
1246
1247 if (next == null) {
1248 // There are no more activities! Let's just start up the
1249 // Launcher...
1250 if (mMainStack) {
1251 return mService.startHomeActivityLocked();
1252 }
1253 }
1254
1255 next.delayedResume = false;
1256
1257 // If the top activity is the resumed one, nothing to do.
1258 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1259 // Make sure we have executed any pending transitions, since there
1260 // should be nothing left to do at this point.
1261 mService.mWindowManager.executeAppTransition();
1262 mNoAnimActivities.clear();
1263 return false;
1264 }
1265
1266 // If we are sleeping, and there is no resumed activity, and the top
1267 // activity is paused, well that is the state we want.
1268 if ((mService.mSleeping || mService.mShuttingDown)
1269 && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
1270 // Make sure we have executed any pending transitions, since there
1271 // should be nothing left to do at this point.
1272 mService.mWindowManager.executeAppTransition();
1273 mNoAnimActivities.clear();
1274 return false;
1275 }
1276
1277 // The activity may be waiting for stop, but that is no longer
1278 // appropriate for it.
1279 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001280 mGoingToSleepActivities.remove(next);
1281 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001282 mWaitingVisibleActivities.remove(next);
1283
1284 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1285
1286 // If we are currently pausing an activity, then don't do anything
1287 // until that is done.
1288 if (mPausingActivity != null) {
1289 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
1290 return false;
1291 }
1292
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001293 // Okay we are now going to start a switch, to 'next'. We may first
1294 // have to pause the current activity, but this is an important point
1295 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001296 // XXX "App Redirected" dialog is getting too many false positives
1297 // at this point, so turn off for now.
1298 if (false) {
1299 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1300 long now = SystemClock.uptimeMillis();
1301 final boolean inTime = mLastStartedActivity.startTime != 0
1302 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1303 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1304 final int nextUid = next.info.applicationInfo.uid;
1305 if (inTime && lastUid != nextUid
1306 && lastUid != next.launchedFromUid
1307 && mService.checkPermission(
1308 android.Manifest.permission.STOP_APP_SWITCHES,
1309 -1, next.launchedFromUid)
1310 != PackageManager.PERMISSION_GRANTED) {
1311 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1312 } else {
1313 next.startTime = now;
1314 mLastStartedActivity = next;
1315 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001316 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001317 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001318 mLastStartedActivity = next;
1319 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001320 }
1321
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001322 // We need to start pausing the current activity so the top one
1323 // can be resumed...
1324 if (mResumedActivity != null) {
1325 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
1326 startPausingLocked(userLeaving, false);
1327 return true;
1328 }
1329
1330 if (prev != null && prev != next) {
1331 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1332 prev.waitingVisible = true;
1333 mWaitingVisibleActivities.add(prev);
1334 if (DEBUG_SWITCH) Slog.v(
1335 TAG, "Resuming top, waiting visible to hide: " + prev);
1336 } else {
1337 // The next activity is already visible, so hide the previous
1338 // activity's windows right now so we can show the new one ASAP.
1339 // We only do this if the previous is finishing, which should mean
1340 // it is on top of the one being resumed so hiding it quickly
1341 // is good. Otherwise, we want to do the normal route of allowing
1342 // the resumed activity to be shown so we can decide if the
1343 // previous should actually be hidden depending on whether the
1344 // new one is found to be full-screen or not.
1345 if (prev.finishing) {
1346 mService.mWindowManager.setAppVisibility(prev, false);
1347 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1348 + prev + ", waitingVisible="
1349 + (prev != null ? prev.waitingVisible : null)
1350 + ", nowVisible=" + next.nowVisible);
1351 } else {
1352 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1353 + prev + ", waitingVisible="
1354 + (prev != null ? prev.waitingVisible : null)
1355 + ", nowVisible=" + next.nowVisible);
1356 }
1357 }
1358 }
1359
Dianne Hackborne7f97212011-02-24 14:40:20 -08001360 // Launching this app's activity, make sure the app is no longer
1361 // considered stopped.
1362 try {
1363 AppGlobals.getPackageManager().setPackageStoppedState(
1364 next.packageName, false);
1365 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001366 } catch (IllegalArgumentException e) {
1367 Slog.w(TAG, "Failed trying to unstop package "
1368 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001369 }
1370
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001371 // We are starting up the next activity, so tell the window manager
1372 // that the previous one will be hidden soon. This way it can know
1373 // to ignore it when computing the desired screen orientation.
1374 if (prev != null) {
1375 if (prev.finishing) {
1376 if (DEBUG_TRANSITION) Slog.v(TAG,
1377 "Prepare close transition: prev=" + prev);
1378 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001379 mService.mWindowManager.prepareAppTransition(
1380 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001381 } else {
1382 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1383 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001384 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001385 }
1386 mService.mWindowManager.setAppWillBeHidden(prev);
1387 mService.mWindowManager.setAppVisibility(prev, false);
1388 } else {
1389 if (DEBUG_TRANSITION) Slog.v(TAG,
1390 "Prepare open transition: prev=" + prev);
1391 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001392 mService.mWindowManager.prepareAppTransition(
1393 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001394 } else {
1395 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1396 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001397 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001398 }
1399 }
1400 if (false) {
1401 mService.mWindowManager.setAppWillBeHidden(prev);
1402 mService.mWindowManager.setAppVisibility(prev, false);
1403 }
1404 } else if (mHistory.size() > 1) {
1405 if (DEBUG_TRANSITION) Slog.v(TAG,
1406 "Prepare open transition: no previous");
1407 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001408 mService.mWindowManager.prepareAppTransition(
1409 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001410 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001411 mService.mWindowManager.prepareAppTransition(
1412 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001413 }
1414 }
1415
1416 if (next.app != null && next.app.thread != null) {
1417 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1418
1419 // This activity is now becoming visible.
1420 mService.mWindowManager.setAppVisibility(next, true);
1421
1422 ActivityRecord lastResumedActivity = mResumedActivity;
1423 ActivityState lastState = next.state;
1424
1425 mService.updateCpuStats();
1426
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001427 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001428 next.state = ActivityState.RESUMED;
1429 mResumedActivity = next;
1430 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001431 if (mMainStack) {
1432 mService.addRecentTaskLocked(next.task);
1433 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001434 mService.updateLruProcessLocked(next.app, true, true);
1435 updateLRUListLocked(next);
1436
1437 // Have the window manager re-evaluate the orientation of
1438 // the screen based on the new activity order.
1439 boolean updated = false;
1440 if (mMainStack) {
1441 synchronized (mService) {
1442 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1443 mService.mConfiguration,
1444 next.mayFreezeScreenLocked(next.app) ? next : null);
1445 if (config != null) {
1446 next.frozenBeforeDestroy = true;
1447 }
Dianne Hackborn31ca8542011-07-19 14:58:28 -07001448 updated = mService.updateConfigurationLocked(config, next, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001449 }
1450 }
1451 if (!updated) {
1452 // The configuration update wasn't able to keep the existing
1453 // instance of the activity, and instead started a new one.
1454 // We should be all done, but let's just make sure our activity
1455 // is still at the top and schedule another run if something
1456 // weird happened.
1457 ActivityRecord nextNext = topRunningActivityLocked(null);
1458 if (DEBUG_SWITCH) Slog.i(TAG,
1459 "Activity config changed during resume: " + next
1460 + ", new next: " + nextNext);
1461 if (nextNext != next) {
1462 // Do over!
1463 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1464 }
1465 if (mMainStack) {
1466 mService.setFocusedActivityLocked(next);
1467 }
1468 ensureActivitiesVisibleLocked(null, 0);
1469 mService.mWindowManager.executeAppTransition();
1470 mNoAnimActivities.clear();
1471 return true;
1472 }
1473
1474 try {
1475 // Deliver all pending results.
1476 ArrayList a = next.results;
1477 if (a != null) {
1478 final int N = a.size();
1479 if (!next.finishing && N > 0) {
1480 if (DEBUG_RESULTS) Slog.v(
1481 TAG, "Delivering results to " + next
1482 + ": " + a);
1483 next.app.thread.scheduleSendResult(next, a);
1484 }
1485 }
1486
1487 if (next.newIntents != null) {
1488 next.app.thread.scheduleNewIntent(next.newIntents, next);
1489 }
1490
1491 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
1492 System.identityHashCode(next),
1493 next.task.taskId, next.shortComponentName);
1494
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001495 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001496 showAskCompatModeDialogLocked(next);
Dianne Hackborn905577f2011-09-07 18:31:28 -07001497 next.app.pendingUiClean = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001498 next.app.thread.scheduleResumeActivity(next,
1499 mService.isNextTransitionForward());
1500
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001501 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001502
1503 } catch (Exception e) {
1504 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001505 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1506 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001507 next.state = lastState;
1508 mResumedActivity = lastResumedActivity;
1509 Slog.i(TAG, "Restarting because process died: " + next);
1510 if (!next.hasBeenLaunched) {
1511 next.hasBeenLaunched = true;
1512 } else {
1513 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1514 mService.mWindowManager.setAppStartingWindow(
1515 next, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001516 mService.compatibilityInfoForPackageLocked(
1517 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001518 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001519 next.labelRes, next.icon, next.windowFlags,
1520 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001521 }
1522 }
1523 startSpecificActivityLocked(next, true, false);
1524 return true;
1525 }
1526
1527 // From this point on, if something goes wrong there is no way
1528 // to recover the activity.
1529 try {
1530 next.visible = true;
1531 completeResumeLocked(next);
1532 } catch (Exception e) {
1533 // If any exception gets thrown, toss away this
1534 // activity and try the next one.
1535 Slog.w(TAG, "Exception thrown during resume of " + next, e);
1536 requestFinishActivityLocked(next, Activity.RESULT_CANCELED, null,
1537 "resume-exception");
1538 return true;
1539 }
1540
1541 // Didn't need to use the icicle, and it is now out of date.
1542 next.icicle = null;
1543 next.haveState = false;
1544 next.stopped = false;
1545
1546 } else {
1547 // Whoops, need to restart this activity!
1548 if (!next.hasBeenLaunched) {
1549 next.hasBeenLaunched = true;
1550 } else {
1551 if (SHOW_APP_STARTING_PREVIEW) {
1552 mService.mWindowManager.setAppStartingWindow(
1553 next, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001554 mService.compatibilityInfoForPackageLocked(
1555 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001556 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001557 next.labelRes, next.icon, next.windowFlags,
1558 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001559 }
1560 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1561 }
1562 startSpecificActivityLocked(next, true, true);
1563 }
1564
1565 return true;
1566 }
1567
1568 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001569 boolean doResume, boolean keepCurTransition) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001570 final int NH = mHistory.size();
1571
1572 int addPos = -1;
1573
1574 if (!newTask) {
1575 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001576 boolean startIt = true;
1577 for (int i = NH-1; i >= 0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001578 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001579 if (p.finishing) {
1580 continue;
1581 }
1582 if (p.task == r.task) {
1583 // Here it is! Now, if this is not yet visible to the
1584 // user, then just add it without starting; it will
1585 // get started when the user navigates back to it.
1586 addPos = i+1;
1587 if (!startIt) {
1588 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001589 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001590 mService.mWindowManager.addAppToken(addPos, r, r.task.taskId,
1591 r.info.screenOrientation, r.fullscreen);
1592 if (VALIDATE_TOKENS) {
1593 mService.mWindowManager.validateAppTokens(mHistory);
1594 }
1595 return;
1596 }
1597 break;
1598 }
1599 if (p.fullscreen) {
1600 startIt = false;
1601 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001602 }
1603 }
1604
1605 // Place a new activity at top of stack, so it is next to interact
1606 // with the user.
1607 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001608 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001609 }
1610
1611 // If we are not placing the new activity frontmost, we do not want
1612 // to deliver the onUserLeaving callback to the actual frontmost
1613 // activity
1614 if (addPos < NH) {
1615 mUserLeaving = false;
1616 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1617 }
1618
1619 // Slot the activity into the history stack and proceed
1620 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001621 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001622 r.frontOfTask = newTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001623 if (NH > 0) {
1624 // We want to show the starting preview window if we are
1625 // switching to a new task, or the next activity's process is
1626 // not currently running.
1627 boolean showStartingIcon = newTask;
1628 ProcessRecord proc = r.app;
1629 if (proc == null) {
1630 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1631 }
1632 if (proc == null || proc.thread == null) {
1633 showStartingIcon = true;
1634 }
1635 if (DEBUG_TRANSITION) Slog.v(TAG,
1636 "Prepare open transition: starting " + r);
1637 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001638 mService.mWindowManager.prepareAppTransition(
1639 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001640 mNoAnimActivities.add(r);
1641 } else if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
1642 mService.mWindowManager.prepareAppTransition(
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001643 WindowManagerPolicy.TRANSIT_TASK_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001644 mNoAnimActivities.remove(r);
1645 } else {
1646 mService.mWindowManager.prepareAppTransition(newTask
1647 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001648 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001649 mNoAnimActivities.remove(r);
1650 }
1651 mService.mWindowManager.addAppToken(
1652 addPos, r, r.task.taskId, r.info.screenOrientation, r.fullscreen);
1653 boolean doShow = true;
1654 if (newTask) {
1655 // Even though this activity is starting fresh, we still need
1656 // to reset it to make sure we apply affinities to move any
1657 // existing activities from other tasks in to it.
1658 // If the caller has requested that the target task be
1659 // reset, then do so.
1660 if ((r.intent.getFlags()
1661 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1662 resetTaskIfNeededLocked(r, r);
1663 doShow = topRunningNonDelayedActivityLocked(null) == r;
1664 }
1665 }
1666 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1667 // Figure out if we are transitioning from another activity that is
1668 // "has the same starting icon" as the next one. This allows the
1669 // window manager to keep the previous window it had previously
1670 // created, if it still had one.
1671 ActivityRecord prev = mResumedActivity;
1672 if (prev != null) {
1673 // We don't want to reuse the previous starting preview if:
1674 // (1) The current activity is in a different task.
1675 if (prev.task != r.task) prev = null;
1676 // (2) The current activity is already displayed.
1677 else if (prev.nowVisible) prev = null;
1678 }
1679 mService.mWindowManager.setAppStartingWindow(
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001680 r, r.packageName, r.theme,
1681 mService.compatibilityInfoForPackageLocked(
1682 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001683 r.labelRes, r.icon, r.windowFlags, prev, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001684 }
1685 } else {
1686 // If this is the first activity, don't do any fancy animations,
1687 // because there is nothing for it to animate on top of.
1688 mService.mWindowManager.addAppToken(addPos, r, r.task.taskId,
1689 r.info.screenOrientation, r.fullscreen);
1690 }
1691 if (VALIDATE_TOKENS) {
1692 mService.mWindowManager.validateAppTokens(mHistory);
1693 }
1694
1695 if (doResume) {
1696 resumeTopActivityLocked(null);
1697 }
1698 }
1699
1700 /**
1701 * Perform a reset of the given task, if needed as part of launching it.
1702 * Returns the new HistoryRecord at the top of the task.
1703 */
1704 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1705 ActivityRecord newActivity) {
1706 boolean forceReset = (newActivity.info.flags
1707 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001708 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1709 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001710 if ((newActivity.info.flags
1711 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1712 forceReset = true;
1713 }
1714 }
1715
1716 final TaskRecord task = taskTop.task;
1717
1718 // We are going to move through the history list so that we can look
1719 // at each activity 'target' with 'below' either the interesting
1720 // activity immediately below it in the stack or null.
1721 ActivityRecord target = null;
1722 int targetI = 0;
1723 int taskTopI = -1;
1724 int replyChainEnd = -1;
1725 int lastReparentPos = -1;
1726 for (int i=mHistory.size()-1; i>=-1; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001727 ActivityRecord below = i >= 0 ? mHistory.get(i) : null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001728
1729 if (below != null && below.finishing) {
1730 continue;
1731 }
1732 if (target == null) {
1733 target = below;
1734 targetI = i;
1735 // If we were in the middle of a reply chain before this
1736 // task, it doesn't appear like the root of the chain wants
1737 // anything interesting, so drop it.
1738 replyChainEnd = -1;
1739 continue;
1740 }
1741
1742 final int flags = target.info.flags;
1743
1744 final boolean finishOnTaskLaunch =
1745 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1746 final boolean allowTaskReparenting =
1747 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1748
1749 if (target.task == task) {
1750 // We are inside of the task being reset... we'll either
1751 // finish this activity, push it out for another task,
1752 // or leave it as-is. We only do this
1753 // for activities that are not the root of the task (since
1754 // if we finish the root, we may no longer have the task!).
1755 if (taskTopI < 0) {
1756 taskTopI = targetI;
1757 }
1758 if (below != null && below.task == task) {
1759 final boolean clearWhenTaskReset =
1760 (target.intent.getFlags()
1761 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
1762 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
1763 // If this activity is sending a reply to a previous
1764 // activity, we can't do anything with it now until
1765 // we reach the start of the reply chain.
1766 // XXX note that we are assuming the result is always
1767 // to the previous activity, which is almost always
1768 // the case but we really shouldn't count on.
1769 if (replyChainEnd < 0) {
1770 replyChainEnd = targetI;
1771 }
1772 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
1773 && target.taskAffinity != null
1774 && !target.taskAffinity.equals(task.affinity)) {
1775 // If this activity has an affinity for another
1776 // task, then we need to move it out of here. We will
1777 // move it as far out of the way as possible, to the
1778 // bottom of the activity stack. This also keeps it
1779 // correctly ordered with any activities we previously
1780 // moved.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001781 ActivityRecord p = mHistory.get(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001782 if (target.taskAffinity != null
1783 && target.taskAffinity.equals(p.task.affinity)) {
1784 // If the activity currently at the bottom has the
1785 // same task affinity as the one we are moving,
1786 // then merge it into the same task.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001787 target.setTask(p.task, p.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001788 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1789 + " out to bottom task " + p.task);
1790 } else {
1791 mService.mCurTask++;
1792 if (mService.mCurTask <= 0) {
1793 mService.mCurTask = 1;
1794 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001795 target.setTask(new TaskRecord(mService.mCurTask, target.info, null),
1796 null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001797 target.task.affinityIntent = target.intent;
1798 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1799 + " out to new task " + target.task);
1800 }
1801 mService.mWindowManager.setAppGroupId(target, task.taskId);
1802 if (replyChainEnd < 0) {
1803 replyChainEnd = targetI;
1804 }
1805 int dstPos = 0;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001806 ThumbnailHolder curThumbHolder = target.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001807 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001808 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001809 if (p.finishing) {
1810 continue;
1811 }
1812 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
1813 + " out to target's task " + target.task);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001814 p.setTask(target.task, curThumbHolder, false);
1815 curThumbHolder = p.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001816 mHistory.remove(srcPos);
1817 mHistory.add(dstPos, p);
1818 mService.mWindowManager.moveAppToken(dstPos, p);
1819 mService.mWindowManager.setAppGroupId(p, p.task.taskId);
1820 dstPos++;
1821 if (VALIDATE_TOKENS) {
1822 mService.mWindowManager.validateAppTokens(mHistory);
1823 }
1824 i++;
1825 }
1826 if (taskTop == p) {
1827 taskTop = below;
1828 }
1829 if (taskTopI == replyChainEnd) {
1830 taskTopI = -1;
1831 }
1832 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001833 } else if (forceReset || finishOnTaskLaunch
1834 || clearWhenTaskReset) {
1835 // If the activity should just be removed -- either
1836 // because it asks for it, or the task should be
1837 // cleared -- then finish it and anything that is
1838 // part of its reply chain.
1839 if (clearWhenTaskReset) {
1840 // In this case, we want to finish this activity
1841 // and everything above it, so be sneaky and pretend
1842 // like these are all in the reply chain.
1843 replyChainEnd = targetI+1;
1844 while (replyChainEnd < mHistory.size() &&
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001845 (mHistory.get(
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001846 replyChainEnd)).task == task) {
1847 replyChainEnd++;
1848 }
1849 replyChainEnd--;
1850 } else if (replyChainEnd < 0) {
1851 replyChainEnd = targetI;
1852 }
1853 ActivityRecord p = null;
1854 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001855 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001856 if (p.finishing) {
1857 continue;
1858 }
1859 if (finishActivityLocked(p, srcPos,
1860 Activity.RESULT_CANCELED, null, "reset")) {
1861 replyChainEnd--;
1862 srcPos--;
1863 }
1864 }
1865 if (taskTop == p) {
1866 taskTop = below;
1867 }
1868 if (taskTopI == replyChainEnd) {
1869 taskTopI = -1;
1870 }
1871 replyChainEnd = -1;
1872 } else {
1873 // If we were in the middle of a chain, well the
1874 // activity that started it all doesn't want anything
1875 // special, so leave it all as-is.
1876 replyChainEnd = -1;
1877 }
1878 } else {
1879 // Reached the bottom of the task -- any reply chain
1880 // should be left as-is.
1881 replyChainEnd = -1;
1882 }
1883
1884 } else if (target.resultTo != null) {
1885 // If this activity is sending a reply to a previous
1886 // activity, we can't do anything with it now until
1887 // we reach the start of the reply chain.
1888 // XXX note that we are assuming the result is always
1889 // to the previous activity, which is almost always
1890 // the case but we really shouldn't count on.
1891 if (replyChainEnd < 0) {
1892 replyChainEnd = targetI;
1893 }
1894
1895 } else if (taskTopI >= 0 && allowTaskReparenting
1896 && task.affinity != null
1897 && task.affinity.equals(target.taskAffinity)) {
1898 // We are inside of another task... if this activity has
1899 // an affinity for our task, then either remove it if we are
1900 // clearing or move it over to our task. Note that
1901 // we currently punt on the case where we are resetting a
1902 // task that is not at the top but who has activities above
1903 // with an affinity to it... this is really not a normal
1904 // case, and we will need to later pull that task to the front
1905 // and usually at that point we will do the reset and pick
1906 // up those remaining activities. (This only happens if
1907 // someone starts an activity in a new task from an activity
1908 // in a task that is not currently on top.)
1909 if (forceReset || finishOnTaskLaunch) {
1910 if (replyChainEnd < 0) {
1911 replyChainEnd = targetI;
1912 }
1913 ActivityRecord p = null;
1914 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001915 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001916 if (p.finishing) {
1917 continue;
1918 }
1919 if (finishActivityLocked(p, srcPos,
1920 Activity.RESULT_CANCELED, null, "reset")) {
1921 taskTopI--;
1922 lastReparentPos--;
1923 replyChainEnd--;
1924 srcPos--;
1925 }
1926 }
1927 replyChainEnd = -1;
1928 } else {
1929 if (replyChainEnd < 0) {
1930 replyChainEnd = targetI;
1931 }
1932 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001933 ActivityRecord p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001934 if (p.finishing) {
1935 continue;
1936 }
1937 if (lastReparentPos < 0) {
1938 lastReparentPos = taskTopI;
1939 taskTop = p;
1940 } else {
1941 lastReparentPos--;
1942 }
1943 mHistory.remove(srcPos);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001944 p.setTask(task, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001945 mHistory.add(lastReparentPos, p);
1946 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
1947 + " in to resetting task " + task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001948 mService.mWindowManager.moveAppToken(lastReparentPos, p);
1949 mService.mWindowManager.setAppGroupId(p, p.task.taskId);
1950 if (VALIDATE_TOKENS) {
1951 mService.mWindowManager.validateAppTokens(mHistory);
1952 }
1953 }
1954 replyChainEnd = -1;
1955
1956 // Now we've moved it in to place... but what if this is
1957 // a singleTop activity and we have put it on top of another
1958 // instance of the same activity? Then we drop the instance
1959 // below so it remains singleTop.
1960 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
1961 for (int j=lastReparentPos-1; j>=0; j--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001962 ActivityRecord p = mHistory.get(j);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001963 if (p.finishing) {
1964 continue;
1965 }
1966 if (p.intent.getComponent().equals(target.intent.getComponent())) {
1967 if (finishActivityLocked(p, j,
1968 Activity.RESULT_CANCELED, null, "replace")) {
1969 taskTopI--;
1970 lastReparentPos--;
1971 }
1972 }
1973 }
1974 }
1975 }
1976 }
1977
1978 target = below;
1979 targetI = i;
1980 }
1981
1982 return taskTop;
1983 }
1984
1985 /**
1986 * Perform clear operation as requested by
1987 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
1988 * stack to the given task, then look for
1989 * an instance of that activity in the stack and, if found, finish all
1990 * activities on top of it and return the instance.
1991 *
1992 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001993 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001994 * or null if none was found.
1995 */
1996 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001997 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001998 int i = mHistory.size();
1999
2000 // First find the requested task.
2001 while (i > 0) {
2002 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002003 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002004 if (r.task.taskId == taskId) {
2005 i++;
2006 break;
2007 }
2008 }
2009
2010 // Now clear it.
2011 while (i > 0) {
2012 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002013 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002014 if (r.finishing) {
2015 continue;
2016 }
2017 if (r.task.taskId != taskId) {
2018 return null;
2019 }
2020 if (r.realActivity.equals(newR.realActivity)) {
2021 // Here it is! Now finish everything in front...
2022 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002023 while (i < (mHistory.size()-1)) {
2024 i++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002025 r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002026 if (r.task.taskId != taskId) {
2027 break;
2028 }
2029 if (r.finishing) {
2030 continue;
2031 }
2032 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2033 null, "clear")) {
2034 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002035 }
2036 }
2037
2038 // Finally, if this is a normal launch mode (that is, not
2039 // expecting onNewIntent()), then we will finish the current
2040 // instance of the activity so a new fresh one can be started.
2041 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2042 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
2043 if (!ret.finishing) {
2044 int index = indexOfTokenLocked(ret);
2045 if (index >= 0) {
2046 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
2047 null, "clear");
2048 }
2049 return null;
2050 }
2051 }
2052
2053 return ret;
2054 }
2055 }
2056
2057 return null;
2058 }
2059
2060 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002061 * Completely remove all activities associated with an existing
2062 * task starting at a specified index.
2063 */
2064 private final void performClearTaskAtIndexLocked(int taskId, int i) {
2065 while (i < (mHistory.size()-1)) {
2066 ActivityRecord r = mHistory.get(i);
2067 if (r.task.taskId != taskId) {
2068 // Whoops hit the end.
2069 return;
2070 }
2071 if (r.finishing) {
2072 i++;
2073 continue;
2074 }
2075 if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2076 null, "clear")) {
2077 i++;
2078 }
2079 }
2080 }
2081
2082 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002083 * Completely remove all activities associated with an existing task.
2084 */
2085 private final void performClearTaskLocked(int taskId) {
2086 int i = mHistory.size();
2087
2088 // First find the requested task.
2089 while (i > 0) {
2090 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002091 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002092 if (r.task.taskId == taskId) {
2093 i++;
2094 break;
2095 }
2096 }
2097
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002098 // Now find the start and clear it.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002099 while (i > 0) {
2100 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002101 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002102 if (r.finishing) {
2103 continue;
2104 }
2105 if (r.task.taskId != taskId) {
2106 // We hit the bottom. Now finish it all...
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002107 performClearTaskAtIndexLocked(taskId, i+1);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002108 return;
2109 }
2110 }
2111 }
2112
2113 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002114 * Find the activity in the history stack within the given task. Returns
2115 * the index within the history at which it's found, or < 0 if not found.
2116 */
2117 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2118 int i = mHistory.size();
2119 while (i > 0) {
2120 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002121 ActivityRecord candidate = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002122 if (candidate.task.taskId != task) {
2123 break;
2124 }
2125 if (candidate.realActivity.equals(r.realActivity)) {
2126 return i;
2127 }
2128 }
2129
2130 return -1;
2131 }
2132
2133 /**
2134 * Reorder the history stack so that the activity at the given index is
2135 * brought to the front.
2136 */
2137 private final ActivityRecord moveActivityToFrontLocked(int where) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002138 ActivityRecord newTop = mHistory.remove(where);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002139 int top = mHistory.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002140 ActivityRecord oldTop = mHistory.get(top-1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002141 mHistory.add(top, newTop);
2142 oldTop.frontOfTask = false;
2143 newTop.frontOfTask = true;
2144 return newTop;
2145 }
2146
2147 final int startActivityLocked(IApplicationThread caller,
2148 Intent intent, String resolvedType,
2149 Uri[] grantedUriPermissions,
2150 int grantedMode, ActivityInfo aInfo, IBinder resultTo,
2151 String resultWho, int requestCode,
2152 int callingPid, int callingUid, boolean onlyIfNeeded,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002153 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002154
2155 int err = START_SUCCESS;
2156
2157 ProcessRecord callerApp = null;
2158 if (caller != null) {
2159 callerApp = mService.getRecordForAppLocked(caller);
2160 if (callerApp != null) {
2161 callingPid = callerApp.pid;
2162 callingUid = callerApp.info.uid;
2163 } else {
2164 Slog.w(TAG, "Unable to find app for caller " + caller
2165 + " (pid=" + callingPid + ") when starting: "
2166 + intent.toString());
2167 err = START_PERMISSION_DENIED;
2168 }
2169 }
2170
2171 if (err == START_SUCCESS) {
2172 Slog.i(TAG, "Starting: " + intent + " from pid "
2173 + (callerApp != null ? callerApp.pid : callingPid));
2174 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002175
2176 ActivityRecord sourceRecord = null;
2177 ActivityRecord resultRecord = null;
2178 if (resultTo != null) {
2179 int index = indexOfTokenLocked(resultTo);
2180 if (DEBUG_RESULTS) Slog.v(
2181 TAG, "Sending result to " + resultTo + " (index " + index + ")");
2182 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002183 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002184 if (requestCode >= 0 && !sourceRecord.finishing) {
2185 resultRecord = sourceRecord;
2186 }
2187 }
2188 }
2189
2190 int launchFlags = intent.getFlags();
2191
2192 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2193 && sourceRecord != null) {
2194 // Transfer the result target from the source activity to the new
2195 // one being started, including any failures.
2196 if (requestCode >= 0) {
2197 return START_FORWARD_AND_REQUEST_CONFLICT;
2198 }
2199 resultRecord = sourceRecord.resultTo;
2200 resultWho = sourceRecord.resultWho;
2201 requestCode = sourceRecord.requestCode;
2202 sourceRecord.resultTo = null;
2203 if (resultRecord != null) {
2204 resultRecord.removeResultsLocked(
2205 sourceRecord, resultWho, requestCode);
2206 }
2207 }
2208
Dianne Hackbornefb58102010-10-14 16:47:34 -07002209 if (err == START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002210 // We couldn't find a class that can handle the given Intent.
2211 // That's the end of that!
2212 err = START_INTENT_NOT_RESOLVED;
2213 }
2214
2215 if (err == START_SUCCESS && aInfo == null) {
2216 // We couldn't find the specific class specified in the Intent.
2217 // Also the end of the line.
2218 err = START_CLASS_NOT_FOUND;
2219 }
2220
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002221 if (err != START_SUCCESS) {
2222 if (resultRecord != null) {
2223 sendActivityResultLocked(-1,
2224 resultRecord, resultWho, requestCode,
2225 Activity.RESULT_CANCELED, null);
2226 }
2227 return err;
2228 }
2229
2230 final int perm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002231 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002232 if (perm != PackageManager.PERMISSION_GRANTED) {
2233 if (resultRecord != null) {
2234 sendActivityResultLocked(-1,
2235 resultRecord, resultWho, requestCode,
2236 Activity.RESULT_CANCELED, null);
2237 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002238 String msg;
2239 if (!aInfo.exported) {
2240 msg = "Permission Denial: starting " + intent.toString()
2241 + " from " + callerApp + " (pid=" + callingPid
2242 + ", uid=" + callingUid + ")"
2243 + " not exported from uid " + aInfo.applicationInfo.uid;
2244 } else {
2245 msg = "Permission Denial: starting " + intent.toString()
2246 + " from " + callerApp + " (pid=" + callingPid
2247 + ", uid=" + callingUid + ")"
2248 + " requires " + aInfo.permission;
2249 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002250 Slog.w(TAG, msg);
2251 throw new SecurityException(msg);
2252 }
2253
2254 if (mMainStack) {
2255 if (mService.mController != null) {
2256 boolean abort = false;
2257 try {
2258 // The Intent we give to the watcher has the extra data
2259 // stripped off, since it can contain private information.
2260 Intent watchIntent = intent.cloneFilter();
2261 abort = !mService.mController.activityStarting(watchIntent,
2262 aInfo.applicationInfo.packageName);
2263 } catch (RemoteException e) {
2264 mService.mController = null;
2265 }
2266
2267 if (abort) {
2268 if (resultRecord != null) {
2269 sendActivityResultLocked(-1,
2270 resultRecord, resultWho, requestCode,
2271 Activity.RESULT_CANCELED, null);
2272 }
2273 // We pretend to the caller that it was really started, but
2274 // they will just get a cancel result.
2275 return START_SUCCESS;
2276 }
2277 }
2278 }
2279
2280 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2281 intent, resolvedType, aInfo, mService.mConfiguration,
2282 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002283 if (outActivity != null) {
2284 outActivity[0] = r;
2285 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002286
2287 if (mMainStack) {
2288 if (mResumedActivity == null
2289 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2290 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2291 PendingActivityLaunch pal = new PendingActivityLaunch();
2292 pal.r = r;
2293 pal.sourceRecord = sourceRecord;
2294 pal.grantedUriPermissions = grantedUriPermissions;
2295 pal.grantedMode = grantedMode;
2296 pal.onlyIfNeeded = onlyIfNeeded;
2297 mService.mPendingActivityLaunches.add(pal);
2298 return START_SWITCHES_CANCELED;
2299 }
2300 }
2301
2302 if (mService.mDidAppSwitch) {
2303 // This is the second allowed switch since we stopped switches,
2304 // so now just generally allow switches. Use case: user presses
2305 // home (switches disabled, switch to home, mDidAppSwitch now true);
2306 // user taps a home icon (coming from home so allowed, we hit here
2307 // and now allow anyone to switch again).
2308 mService.mAppSwitchesAllowedTime = 0;
2309 } else {
2310 mService.mDidAppSwitch = true;
2311 }
2312
2313 mService.doPendingActivityLaunchesLocked(false);
2314 }
2315
2316 return startActivityUncheckedLocked(r, sourceRecord,
2317 grantedUriPermissions, grantedMode, onlyIfNeeded, true);
2318 }
2319
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002320 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2321 if ((launchFlags &
2322 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2323 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2324 // Caller wants to appear on home activity, so before starting
2325 // their own activity we will bring home to the front.
2326 moveHomeToFrontLocked();
2327 }
2328 }
2329
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002330 final int startActivityUncheckedLocked(ActivityRecord r,
2331 ActivityRecord sourceRecord, Uri[] grantedUriPermissions,
2332 int grantedMode, boolean onlyIfNeeded, boolean doResume) {
2333 final Intent intent = r.intent;
2334 final int callingUid = r.launchedFromUid;
2335
2336 int launchFlags = intent.getFlags();
2337
2338 // We'll invoke onUserLeaving before onPause only if the launching
2339 // activity did not explicitly state that this is an automated launch.
2340 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2341 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2342 "startActivity() => mUserLeaving=" + mUserLeaving);
2343
2344 // If the caller has asked not to resume at this point, we make note
2345 // of this in the record so that we can skip it when trying to find
2346 // the top running activity.
2347 if (!doResume) {
2348 r.delayedResume = true;
2349 }
2350
2351 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2352 != 0 ? r : null;
2353
2354 // If the onlyIfNeeded flag is set, then we can do this if the activity
2355 // being launched is the same as the one making the call... or, as
2356 // a special case, if we do not know the caller then we count the
2357 // current top activity as the caller.
2358 if (onlyIfNeeded) {
2359 ActivityRecord checkedCaller = sourceRecord;
2360 if (checkedCaller == null) {
2361 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2362 }
2363 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2364 // Caller is not the same as launcher, so always needed.
2365 onlyIfNeeded = false;
2366 }
2367 }
2368
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002369 if (sourceRecord == null) {
2370 // This activity is not being started from another... in this
2371 // case we -always- start a new task.
2372 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2373 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2374 + intent);
2375 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2376 }
2377 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2378 // The original activity who is starting us is running as a single
2379 // instance... this new activity it is starting must go on its
2380 // own task.
2381 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2382 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2383 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2384 // The activity being started is a single instance... it always
2385 // gets launched into its own task.
2386 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2387 }
2388
2389 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2390 // For whatever reason this activity is being launched into a new
2391 // task... yet the caller has requested a result back. Well, that
2392 // is pretty messed up, so instead immediately send back a cancel
2393 // and let the new task continue launched as normal without a
2394 // dependency on its originator.
2395 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2396 sendActivityResultLocked(-1,
2397 r.resultTo, r.resultWho, r.requestCode,
2398 Activity.RESULT_CANCELED, null);
2399 r.resultTo = null;
2400 }
2401
2402 boolean addingToTask = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002403 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002404 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2405 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2406 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2407 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2408 // If bring to front is requested, and no result is requested, and
2409 // we can find a task that was started with this same
2410 // component, then instead of launching bring that one to the front.
2411 if (r.resultTo == null) {
2412 // See if there is a task to bring to the front. If this is
2413 // a SINGLE_INSTANCE activity, there can be one and only one
2414 // instance of it in the history, and it is always in its own
2415 // unique task, so we do a special search.
2416 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2417 ? findTaskLocked(intent, r.info)
2418 : findActivityLocked(intent, r.info);
2419 if (taskTop != null) {
2420 if (taskTop.task.intent == null) {
2421 // This task was started because of movement of
2422 // the activity based on affinity... now that we
2423 // are actually launching it, we can assign the
2424 // base intent.
2425 taskTop.task.setIntent(intent, r.info);
2426 }
2427 // If the target task is not in the front, then we need
2428 // to bring it to the front... except... well, with
2429 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2430 // to have the same behavior as if a new instance was
2431 // being started, which means not bringing it to the front
2432 // if the caller is not itself in the front.
2433 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002434 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002435 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2436 boolean callerAtFront = sourceRecord == null
2437 || curTop.task == sourceRecord.task;
2438 if (callerAtFront) {
2439 // We really do want to push this one into the
2440 // user's face, right now.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002441 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002442 moveTaskToFrontLocked(taskTop.task, r);
2443 }
2444 }
2445 // If the caller has requested that the target task be
2446 // reset, then do so.
2447 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2448 taskTop = resetTaskIfNeededLocked(taskTop, r);
2449 }
2450 if (onlyIfNeeded) {
2451 // We don't need to start a new activity, and
2452 // the client said not to do anything if that
2453 // is the case, so this is it! And for paranoia, make
2454 // sure we have correctly resumed the top activity.
2455 if (doResume) {
2456 resumeTopActivityLocked(null);
2457 }
2458 return START_RETURN_INTENT_TO_CALLER;
2459 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002460 if ((launchFlags &
2461 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2462 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2463 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002464 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002465 // not be too hard...
2466 reuseTask = taskTop.task;
2467 performClearTaskLocked(taskTop.task.taskId);
2468 reuseTask.setIntent(r.intent, r.info);
2469 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002470 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2471 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2472 // In this situation we want to remove all activities
2473 // from the task up to the one being started. In most
2474 // cases this means we are resetting the task to its
2475 // initial state.
2476 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002477 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002478 if (top != null) {
2479 if (top.frontOfTask) {
2480 // Activity aliases may mean we use different
2481 // intents for the top activity, so make sure
2482 // the task now has the identity of the new
2483 // intent.
2484 top.task.setIntent(r.intent, r.info);
2485 }
2486 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002487 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002488 } else {
2489 // A special case: we need to
2490 // start the activity because it is not currently
2491 // running, and the caller has asked to clear the
2492 // current task to have this activity at the top.
2493 addingToTask = true;
2494 // Now pretend like this activity is being started
2495 // by the top of its task, so it is put in the
2496 // right place.
2497 sourceRecord = taskTop;
2498 }
2499 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2500 // In this case the top activity on the task is the
2501 // same as the one being launched, so we take that
2502 // as a request to bring the task to the foreground.
2503 // If the top activity in the task is the root
2504 // activity, deliver this new intent to it if it
2505 // desires.
2506 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2507 && taskTop.realActivity.equals(r.realActivity)) {
2508 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2509 if (taskTop.frontOfTask) {
2510 taskTop.task.setIntent(r.intent, r.info);
2511 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002512 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002513 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2514 // In this case we are launching the root activity
2515 // of the task, but with a different intent. We
2516 // should start a new instance on top.
2517 addingToTask = true;
2518 sourceRecord = taskTop;
2519 }
2520 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2521 // In this case an activity is being launched in to an
2522 // existing task, without resetting that task. This
2523 // is typically the situation of launching an activity
2524 // from a notification or shortcut. We want to place
2525 // the new activity on top of the current task.
2526 addingToTask = true;
2527 sourceRecord = taskTop;
2528 } else if (!taskTop.task.rootWasReset) {
2529 // In this case we are launching in to an existing task
2530 // that has not yet been started from its front door.
2531 // The current task has been brought to the front.
2532 // Ideally, we'd probably like to place this new task
2533 // at the bottom of its stack, but that's a little hard
2534 // to do with the current organization of the code so
2535 // for now we'll just drop it.
2536 taskTop.task.setIntent(r.intent, r.info);
2537 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002538 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002539 // We didn't do anything... but it was needed (a.k.a., client
2540 // don't use that intent!) And for paranoia, make
2541 // sure we have correctly resumed the top activity.
2542 if (doResume) {
2543 resumeTopActivityLocked(null);
2544 }
2545 return START_TASK_TO_FRONT;
2546 }
2547 }
2548 }
2549 }
2550
2551 //String uri = r.intent.toURI();
2552 //Intent intent2 = new Intent(uri);
2553 //Slog.i(TAG, "Given intent: " + r.intent);
2554 //Slog.i(TAG, "URI is: " + uri);
2555 //Slog.i(TAG, "To intent: " + intent2);
2556
2557 if (r.packageName != null) {
2558 // If the activity being launched is the same as the one currently
2559 // at the top, then we need to check if it should only be launched
2560 // once.
2561 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2562 if (top != null && r.resultTo == null) {
2563 if (top.realActivity.equals(r.realActivity)) {
2564 if (top.app != null && top.app.thread != null) {
2565 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2566 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2567 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2568 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2569 // For paranoia, make sure we have correctly
2570 // resumed the top activity.
2571 if (doResume) {
2572 resumeTopActivityLocked(null);
2573 }
2574 if (onlyIfNeeded) {
2575 // We don't need to start a new activity, and
2576 // the client said not to do anything if that
2577 // is the case, so this is it!
2578 return START_RETURN_INTENT_TO_CALLER;
2579 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002580 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002581 return START_DELIVERED_TO_TOP;
2582 }
2583 }
2584 }
2585 }
2586
2587 } else {
2588 if (r.resultTo != null) {
2589 sendActivityResultLocked(-1,
2590 r.resultTo, r.resultWho, r.requestCode,
2591 Activity.RESULT_CANCELED, null);
2592 }
2593 return START_CLASS_NOT_FOUND;
2594 }
2595
2596 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002597 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002598
2599 // Should this be considered a new task?
2600 if (r.resultTo == null && !addingToTask
2601 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002602 if (reuseTask == null) {
2603 // todo: should do better management of integers.
2604 mService.mCurTask++;
2605 if (mService.mCurTask <= 0) {
2606 mService.mCurTask = 1;
2607 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002608 r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002609 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2610 + " in new task " + r.task);
2611 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002612 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002613 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002614 newTask = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002615 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002616
2617 } else if (sourceRecord != null) {
2618 if (!addingToTask &&
2619 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2620 // In this case, we are adding the activity to an existing
2621 // task, but the caller has asked to clear that task if the
2622 // activity is already running.
2623 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002624 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002625 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002626 if (top != null) {
2627 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002628 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002629 // For paranoia, make sure we have correctly
2630 // resumed the top activity.
2631 if (doResume) {
2632 resumeTopActivityLocked(null);
2633 }
2634 return START_DELIVERED_TO_TOP;
2635 }
2636 } else if (!addingToTask &&
2637 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2638 // In this case, we are launching an activity in our own task
2639 // that may already be running somewhere in the history, and
2640 // we want to shuffle it to the front of the stack if so.
2641 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2642 if (where >= 0) {
2643 ActivityRecord top = moveActivityToFrontLocked(where);
2644 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002645 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002646 if (doResume) {
2647 resumeTopActivityLocked(null);
2648 }
2649 return START_DELIVERED_TO_TOP;
2650 }
2651 }
2652 // An existing activity is starting this new activity, so we want
2653 // to keep the new one in the same task as the one that is starting
2654 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002655 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002656 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2657 + " in existing task " + r.task);
2658
2659 } else {
2660 // This not being started from an existing activity, and not part
2661 // of a new task... just put it in the top task, though these days
2662 // this case should never happen.
2663 final int N = mHistory.size();
2664 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002665 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002666 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002667 ? prev.task
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002668 : new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002669 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2670 + " in new guessed " + r.task);
2671 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002672
2673 if (grantedUriPermissions != null && callingUid > 0) {
2674 for (int i=0; i<grantedUriPermissions.length; i++) {
2675 mService.grantUriPermissionLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002676 grantedUriPermissions[i], grantedMode, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002677 }
2678 }
2679
2680 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002681 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002682
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002683 if (newTask) {
2684 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
2685 }
2686 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002687 startActivityLocked(r, newTask, doResume, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002688 return START_SUCCESS;
2689 }
2690
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002691 ActivityInfo resolveActivity(Intent intent, String resolvedType, boolean debug,
2692 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002693 // Collect information about the target of the Intent.
2694 ActivityInfo aInfo;
2695 try {
2696 ResolveInfo rInfo =
2697 AppGlobals.getPackageManager().resolveIntent(
2698 intent, resolvedType,
2699 PackageManager.MATCH_DEFAULT_ONLY
2700 | ActivityManagerService.STOCK_PM_FLAGS);
2701 aInfo = rInfo != null ? rInfo.activityInfo : null;
2702 } catch (RemoteException e) {
2703 aInfo = null;
2704 }
2705
2706 if (aInfo != null) {
2707 // Store the found target back into the intent, because now that
2708 // we have it we never want to do this again. For example, if the
2709 // user navigates back to this point in the history, we should
2710 // always restart the exact same activity.
2711 intent.setComponent(new ComponentName(
2712 aInfo.applicationInfo.packageName, aInfo.name));
2713
2714 // Don't debug things in the system process
2715 if (debug) {
2716 if (!aInfo.processName.equals("system")) {
2717 mService.setDebugApp(aInfo.processName, true, false);
2718 }
2719 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002720
2721 if (profileFile != null) {
2722 if (!aInfo.processName.equals("system")) {
2723 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
2724 profileFile, profileFd, autoStopProfiler);
2725 }
2726 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002727 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002728 return aInfo;
2729 }
2730
2731 final int startActivityMayWait(IApplicationThread caller, int callingUid,
2732 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2733 int grantedMode, IBinder resultTo,
2734 String resultWho, int requestCode, boolean onlyIfNeeded,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002735 boolean debug, String profileFile, ParcelFileDescriptor profileFd,
2736 boolean autoStopProfiler, WaitResult outResult, Configuration config) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002737 // Refuse possible leaked file descriptors
2738 if (intent != null && intent.hasFileDescriptors()) {
2739 throw new IllegalArgumentException("File descriptors passed in Intent");
2740 }
2741
2742 boolean componentSpecified = intent.getComponent() != null;
2743
2744 // Don't modify the client's object!
2745 intent = new Intent(intent);
2746
2747 // Collect information about the target of the Intent.
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002748 ActivityInfo aInfo = resolveActivity(intent, resolvedType, debug,
2749 profileFile, profileFd, autoStopProfiler);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002750
2751 synchronized (mService) {
2752 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002753 if (callingUid >= 0) {
2754 callingPid = -1;
2755 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002756 callingPid = Binder.getCallingPid();
2757 callingUid = Binder.getCallingUid();
2758 } else {
2759 callingPid = callingUid = -1;
2760 }
2761
2762 mConfigWillChange = config != null
2763 && mService.mConfiguration.diff(config) != 0;
2764 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2765 "Starting activity when config will change = " + mConfigWillChange);
2766
2767 final long origId = Binder.clearCallingIdentity();
2768
2769 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07002770 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002771 // This may be a heavy-weight process! Check to see if we already
2772 // have another, different heavy-weight process running.
2773 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
2774 if (mService.mHeavyWeightProcess != null &&
2775 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
2776 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
2777 int realCallingPid = callingPid;
2778 int realCallingUid = callingUid;
2779 if (caller != null) {
2780 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
2781 if (callerApp != null) {
2782 realCallingPid = callerApp.pid;
2783 realCallingUid = callerApp.info.uid;
2784 } else {
2785 Slog.w(TAG, "Unable to find app for caller " + caller
2786 + " (pid=" + realCallingPid + ") when starting: "
2787 + intent.toString());
2788 return START_PERMISSION_DENIED;
2789 }
2790 }
2791
2792 IIntentSender target = mService.getIntentSenderLocked(
2793 IActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002794 realCallingUid, null, null, 0, new Intent[] { intent },
2795 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002796 | PendingIntent.FLAG_ONE_SHOT);
2797
2798 Intent newIntent = new Intent();
2799 if (requestCode >= 0) {
2800 // Caller is requesting a result.
2801 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
2802 }
2803 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
2804 new IntentSender(target));
2805 if (mService.mHeavyWeightProcess.activities.size() > 0) {
2806 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
2807 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
2808 hist.packageName);
2809 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
2810 hist.task.taskId);
2811 }
2812 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
2813 aInfo.packageName);
2814 newIntent.setFlags(intent.getFlags());
2815 newIntent.setClassName("android",
2816 HeavyWeightSwitcherActivity.class.getName());
2817 intent = newIntent;
2818 resolvedType = null;
2819 caller = null;
2820 callingUid = Binder.getCallingUid();
2821 callingPid = Binder.getCallingPid();
2822 componentSpecified = true;
2823 try {
2824 ResolveInfo rInfo =
2825 AppGlobals.getPackageManager().resolveIntent(
2826 intent, null,
2827 PackageManager.MATCH_DEFAULT_ONLY
2828 | ActivityManagerService.STOCK_PM_FLAGS);
2829 aInfo = rInfo != null ? rInfo.activityInfo : null;
2830 } catch (RemoteException e) {
2831 aInfo = null;
2832 }
2833 }
2834 }
2835 }
2836
2837 int res = startActivityLocked(caller, intent, resolvedType,
2838 grantedUriPermissions, grantedMode, aInfo,
2839 resultTo, resultWho, requestCode, callingPid, callingUid,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002840 onlyIfNeeded, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002841
2842 if (mConfigWillChange && mMainStack) {
2843 // If the caller also wants to switch to a new configuration,
2844 // do so now. This allows a clean switch, as we are waiting
2845 // for the current activity to pause (so we will not destroy
2846 // it), and have not yet started the next activity.
2847 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
2848 "updateConfiguration()");
2849 mConfigWillChange = false;
2850 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2851 "Updating to new configuration after starting activity.");
Dianne Hackborn31ca8542011-07-19 14:58:28 -07002852 mService.updateConfigurationLocked(config, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002853 }
2854
2855 Binder.restoreCallingIdentity(origId);
2856
2857 if (outResult != null) {
2858 outResult.result = res;
2859 if (res == IActivityManager.START_SUCCESS) {
2860 mWaitingActivityLaunched.add(outResult);
2861 do {
2862 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07002863 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002864 } catch (InterruptedException e) {
2865 }
2866 } while (!outResult.timeout && outResult.who == null);
2867 } else if (res == IActivityManager.START_TASK_TO_FRONT) {
2868 ActivityRecord r = this.topRunningActivityLocked(null);
2869 if (r.nowVisible) {
2870 outResult.timeout = false;
2871 outResult.who = new ComponentName(r.info.packageName, r.info.name);
2872 outResult.totalTime = 0;
2873 outResult.thisTime = 0;
2874 } else {
2875 outResult.thisTime = SystemClock.uptimeMillis();
2876 mWaitingActivityVisible.add(outResult);
2877 do {
2878 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07002879 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002880 } catch (InterruptedException e) {
2881 }
2882 } while (!outResult.timeout && outResult.who == null);
2883 }
2884 }
2885 }
2886
2887 return res;
2888 }
2889 }
2890
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002891 final int startActivities(IApplicationThread caller, int callingUid,
2892 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
2893 if (intents == null) {
2894 throw new NullPointerException("intents is null");
2895 }
2896 if (resolvedTypes == null) {
2897 throw new NullPointerException("resolvedTypes is null");
2898 }
2899 if (intents.length != resolvedTypes.length) {
2900 throw new IllegalArgumentException("intents are length different than resolvedTypes");
2901 }
2902
2903 ActivityRecord[] outActivity = new ActivityRecord[1];
2904
2905 int callingPid;
2906 if (callingUid >= 0) {
2907 callingPid = -1;
2908 } else if (caller == null) {
2909 callingPid = Binder.getCallingPid();
2910 callingUid = Binder.getCallingUid();
2911 } else {
2912 callingPid = callingUid = -1;
2913 }
2914 final long origId = Binder.clearCallingIdentity();
2915 try {
2916 synchronized (mService) {
2917
2918 for (int i=0; i<intents.length; i++) {
2919 Intent intent = intents[i];
2920 if (intent == null) {
2921 continue;
2922 }
2923
2924 // Refuse possible leaked file descriptors
2925 if (intent != null && intent.hasFileDescriptors()) {
2926 throw new IllegalArgumentException("File descriptors passed in Intent");
2927 }
2928
2929 boolean componentSpecified = intent.getComponent() != null;
2930
2931 // Don't modify the client's object!
2932 intent = new Intent(intent);
2933
2934 // Collect information about the target of the Intent.
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002935 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i], false,
2936 null, null, false);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002937
2938 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
2939 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
2940 throw new IllegalArgumentException(
2941 "FLAG_CANT_SAVE_STATE not supported here");
2942 }
2943
2944 int res = startActivityLocked(caller, intent, resolvedTypes[i],
2945 null, 0, aInfo, resultTo, null, -1, callingPid, callingUid,
2946 false, componentSpecified, outActivity);
2947 if (res < 0) {
2948 return res;
2949 }
2950
2951 resultTo = outActivity[0];
2952 }
2953 }
2954 } finally {
2955 Binder.restoreCallingIdentity(origId);
2956 }
2957
2958 return IActivityManager.START_SUCCESS;
2959 }
2960
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002961 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
2962 long thisTime, long totalTime) {
2963 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
2964 WaitResult w = mWaitingActivityLaunched.get(i);
2965 w.timeout = timeout;
2966 if (r != null) {
2967 w.who = new ComponentName(r.info.packageName, r.info.name);
2968 }
2969 w.thisTime = thisTime;
2970 w.totalTime = totalTime;
2971 }
2972 mService.notifyAll();
2973 }
2974
2975 void reportActivityVisibleLocked(ActivityRecord r) {
2976 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
2977 WaitResult w = mWaitingActivityVisible.get(i);
2978 w.timeout = false;
2979 if (r != null) {
2980 w.who = new ComponentName(r.info.packageName, r.info.name);
2981 }
2982 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
2983 w.thisTime = w.totalTime;
2984 }
2985 mService.notifyAll();
2986 }
2987
2988 void sendActivityResultLocked(int callingUid, ActivityRecord r,
2989 String resultWho, int requestCode, int resultCode, Intent data) {
2990
2991 if (callingUid > 0) {
2992 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002993 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002994 }
2995
2996 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
2997 + " : who=" + resultWho + " req=" + requestCode
2998 + " res=" + resultCode + " data=" + data);
2999 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3000 try {
3001 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3002 list.add(new ResultInfo(resultWho, requestCode,
3003 resultCode, data));
3004 r.app.thread.scheduleSendResult(r, list);
3005 return;
3006 } catch (Exception e) {
3007 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3008 }
3009 }
3010
3011 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3012 }
3013
3014 private final void stopActivityLocked(ActivityRecord r) {
3015 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3016 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3017 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3018 if (!r.finishing) {
3019 requestFinishActivityLocked(r, Activity.RESULT_CANCELED, null,
3020 "no-history");
3021 }
3022 } else if (r.app != null && r.app.thread != null) {
3023 if (mMainStack) {
3024 if (mService.mFocusedActivity == r) {
3025 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3026 }
3027 }
3028 r.resumeKeyDispatchingLocked();
3029 try {
3030 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003031 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3032 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003033 r.state = ActivityState.STOPPING;
3034 if (DEBUG_VISBILITY) Slog.v(
3035 TAG, "Stopping visible=" + r.visible + " for " + r);
3036 if (!r.visible) {
3037 mService.mWindowManager.setAppVisibility(r, false);
3038 }
3039 r.app.thread.scheduleStopActivity(r, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003040 if (mService.isSleeping()) {
3041 r.setSleeping(true);
3042 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003043 } catch (Exception e) {
3044 // Maybe just ignore exceptions here... if the process
3045 // has crashed, our death notification will clean things
3046 // up.
3047 Slog.w(TAG, "Exception thrown during pause", e);
3048 // Just in case, assume it to be stopped.
3049 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003050 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003051 r.state = ActivityState.STOPPED;
3052 if (r.configDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003053 destroyActivityLocked(r, true, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003054 }
3055 }
3056 }
3057 }
3058
3059 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3060 boolean remove) {
3061 int N = mStoppingActivities.size();
3062 if (N <= 0) return null;
3063
3064 ArrayList<ActivityRecord> stops = null;
3065
3066 final boolean nowVisible = mResumedActivity != null
3067 && mResumedActivity.nowVisible
3068 && !mResumedActivity.waitingVisible;
3069 for (int i=0; i<N; i++) {
3070 ActivityRecord s = mStoppingActivities.get(i);
3071 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3072 + nowVisible + " waitingVisible=" + s.waitingVisible
3073 + " finishing=" + s.finishing);
3074 if (s.waitingVisible && nowVisible) {
3075 mWaitingVisibleActivities.remove(s);
3076 s.waitingVisible = false;
3077 if (s.finishing) {
3078 // If this activity is finishing, it is sitting on top of
3079 // everyone else but we now know it is no longer needed...
3080 // so get rid of it. Otherwise, we need to go through the
3081 // normal flow and hide it once we determine that it is
3082 // hidden by the activities in front of it.
3083 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
3084 mService.mWindowManager.setAppVisibility(s, false);
3085 }
3086 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003087 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003088 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3089 if (stops == null) {
3090 stops = new ArrayList<ActivityRecord>();
3091 }
3092 stops.add(s);
3093 mStoppingActivities.remove(i);
3094 N--;
3095 i--;
3096 }
3097 }
3098
3099 return stops;
3100 }
3101
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003102 final void scheduleIdleLocked() {
3103 Message msg = Message.obtain();
3104 msg.what = IDLE_NOW_MSG;
3105 mHandler.sendMessage(msg);
3106 }
3107
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003108 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003109 Configuration config) {
3110 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3111
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003112 ActivityRecord res = null;
3113
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003114 ArrayList<ActivityRecord> stops = null;
3115 ArrayList<ActivityRecord> finishes = null;
3116 ArrayList<ActivityRecord> thumbnails = null;
3117 int NS = 0;
3118 int NF = 0;
3119 int NT = 0;
3120 IApplicationThread sendThumbnail = null;
3121 boolean booting = false;
3122 boolean enableScreen = false;
3123
3124 synchronized (mService) {
3125 if (token != null) {
3126 mHandler.removeMessages(IDLE_TIMEOUT_MSG, token);
3127 }
3128
3129 // Get the activity record.
3130 int index = indexOfTokenLocked(token);
3131 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003132 ActivityRecord r = mHistory.get(index);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003133 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003134
3135 if (fromTimeout) {
3136 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3137 }
3138
3139 // This is a hack to semi-deal with a race condition
3140 // in the client where it can be constructed with a
3141 // newer configuration from when we asked it to launch.
3142 // We'll update with whatever configuration it now says
3143 // it used to launch.
3144 if (config != null) {
3145 r.configuration = config;
3146 }
3147
3148 // No longer need to keep the device awake.
3149 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3150 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3151 mLaunchingActivity.release();
3152 }
3153
3154 // We are now idle. If someone is waiting for a thumbnail from
3155 // us, we can now deliver.
3156 r.idle = true;
3157 mService.scheduleAppGcsLocked();
3158 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3159 sendThumbnail = r.app.thread;
3160 r.thumbnailNeeded = false;
3161 }
3162
3163 // If this activity is fullscreen, set up to hide those under it.
3164
3165 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3166 ensureActivitiesVisibleLocked(null, 0);
3167
3168 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3169 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003170 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003171 mService.mBooted = true;
3172 enableScreen = true;
3173 }
3174 }
3175
3176 } else if (fromTimeout) {
3177 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3178 }
3179
3180 // Atomically retrieve all of the other things to do.
3181 stops = processStoppingActivitiesLocked(true);
3182 NS = stops != null ? stops.size() : 0;
3183 if ((NF=mFinishingActivities.size()) > 0) {
3184 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3185 mFinishingActivities.clear();
3186 }
3187 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3188 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3189 mService.mCancelledThumbnails.clear();
3190 }
3191
3192 if (mMainStack) {
3193 booting = mService.mBooting;
3194 mService.mBooting = false;
3195 }
3196 }
3197
3198 int i;
3199
3200 // Send thumbnail if requested.
3201 if (sendThumbnail != null) {
3202 try {
3203 sendThumbnail.requestThumbnail(token);
3204 } catch (Exception e) {
3205 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3206 mService.sendPendingThumbnail(null, token, null, null, true);
3207 }
3208 }
3209
3210 // Stop any activities that are scheduled to do so but have been
3211 // waiting for the next one to start.
3212 for (i=0; i<NS; i++) {
3213 ActivityRecord r = (ActivityRecord)stops.get(i);
3214 synchronized (mService) {
3215 if (r.finishing) {
3216 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY);
3217 } else {
3218 stopActivityLocked(r);
3219 }
3220 }
3221 }
3222
3223 // Finish any activities that are scheduled to do so but have been
3224 // waiting for the next one to start.
3225 for (i=0; i<NF; i++) {
3226 ActivityRecord r = (ActivityRecord)finishes.get(i);
3227 synchronized (mService) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003228 destroyActivityLocked(r, true, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003229 }
3230 }
3231
3232 // Report back to any thumbnail receivers.
3233 for (i=0; i<NT; i++) {
3234 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3235 mService.sendPendingThumbnail(r, null, null, null, true);
3236 }
3237
3238 if (booting) {
3239 mService.finishBooting();
3240 }
3241
3242 mService.trimApplications();
3243 //dump();
3244 //mWindowManager.dump();
3245
3246 if (enableScreen) {
3247 mService.enableScreenAfterBoot();
3248 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003249
3250 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003251 }
3252
3253 /**
3254 * @return Returns true if the activity is being finished, false if for
3255 * some reason it is being left as-is.
3256 */
3257 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
3258 Intent resultData, String reason) {
3259 if (DEBUG_RESULTS) Slog.v(
3260 TAG, "Finishing activity: token=" + token
3261 + ", result=" + resultCode + ", data=" + resultData);
3262
3263 int index = indexOfTokenLocked(token);
3264 if (index < 0) {
3265 return false;
3266 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003267 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003268
3269 // Is this the last activity left?
3270 boolean lastActivity = true;
3271 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003272 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003273 if (!p.finishing && p != r) {
3274 lastActivity = false;
3275 break;
3276 }
3277 }
3278
3279 // If this is the last activity, but it is the home activity, then
3280 // just don't finish it.
3281 if (lastActivity) {
3282 if (r.intent.hasCategory(Intent.CATEGORY_HOME)) {
3283 return false;
3284 }
3285 }
3286
3287 finishActivityLocked(r, index, resultCode, resultData, reason);
3288 return true;
3289 }
3290
3291 /**
3292 * @return Returns true if this activity has been removed from the history
3293 * list, or false if it is still in the list and will be removed later.
3294 */
3295 final boolean finishActivityLocked(ActivityRecord r, int index,
3296 int resultCode, Intent resultData, String reason) {
3297 if (r.finishing) {
3298 Slog.w(TAG, "Duplicate finish request for " + r);
3299 return false;
3300 }
3301
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003302 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003303 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3304 System.identityHashCode(r),
3305 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003306 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003307 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003308 if (next.task == r.task) {
3309 if (r.frontOfTask) {
3310 // The next activity is now the front of the task.
3311 next.frontOfTask = true;
3312 }
3313 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3314 // If the caller asked that this activity (and all above it)
3315 // be cleared when the task is reset, don't lose that information,
3316 // but propagate it up to the next activity.
3317 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3318 }
3319 }
3320 }
3321
3322 r.pauseKeyDispatchingLocked();
3323 if (mMainStack) {
3324 if (mService.mFocusedActivity == r) {
3325 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3326 }
3327 }
3328
3329 // send the result
3330 ActivityRecord resultTo = r.resultTo;
3331 if (resultTo != null) {
3332 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3333 + " who=" + r.resultWho + " req=" + r.requestCode
3334 + " res=" + resultCode + " data=" + resultData);
3335 if (r.info.applicationInfo.uid > 0) {
3336 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
Dianne Hackborna1c69e02010-09-01 22:55:02 -07003337 resultTo.packageName, resultData,
3338 resultTo.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003339 }
3340 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3341 resultData);
3342 r.resultTo = null;
3343 }
3344 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3345
3346 // Make sure this HistoryRecord is not holding on to other resources,
3347 // because clients have remote IPC references to this object so we
3348 // can't assume that will go away and want to avoid circular IPC refs.
3349 r.results = null;
3350 r.pendingResults = null;
3351 r.newIntents = null;
3352 r.icicle = null;
3353
3354 if (mService.mPendingThumbnails.size() > 0) {
3355 // There are clients waiting to receive thumbnails so, in case
3356 // this is an activity that someone is waiting for, add it
3357 // to the pending list so we can correctly update the clients.
3358 mService.mCancelledThumbnails.add(r);
3359 }
3360
3361 if (mResumedActivity == r) {
3362 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003363 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003364 if (DEBUG_TRANSITION) Slog.v(TAG,
3365 "Prepare close transition: finishing " + r);
3366 mService.mWindowManager.prepareAppTransition(endTask
3367 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003368 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003369
3370 // Tell window manager to prepare for this one to be removed.
3371 mService.mWindowManager.setAppVisibility(r, false);
3372
3373 if (mPausingActivity == null) {
3374 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3375 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3376 startPausingLocked(false, false);
3377 }
3378
3379 } else if (r.state != ActivityState.PAUSING) {
3380 // If the activity is PAUSING, we will complete the finish once
3381 // it is done pausing; else we can just directly finish it here.
3382 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3383 return finishCurrentActivityLocked(r, index,
3384 FINISH_AFTER_PAUSE) == null;
3385 } else {
3386 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3387 }
3388
3389 return false;
3390 }
3391
3392 private static final int FINISH_IMMEDIATELY = 0;
3393 private static final int FINISH_AFTER_PAUSE = 1;
3394 private static final int FINISH_AFTER_VISIBLE = 2;
3395
3396 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3397 int mode) {
3398 final int index = indexOfTokenLocked(r);
3399 if (index < 0) {
3400 return null;
3401 }
3402
3403 return finishCurrentActivityLocked(r, index, mode);
3404 }
3405
3406 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3407 int index, int mode) {
3408 // First things first: if this activity is currently visible,
3409 // and the resumed activity is not yet visible, then hold off on
3410 // finishing until the resumed one becomes visible.
3411 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3412 if (!mStoppingActivities.contains(r)) {
3413 mStoppingActivities.add(r);
3414 if (mStoppingActivities.size() > 3) {
3415 // If we already have a few activities waiting to stop,
3416 // then give up on things going idle and start clearing
3417 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003418 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003419 } else {
3420 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003421 }
3422 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003423 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3424 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003425 r.state = ActivityState.STOPPING;
3426 mService.updateOomAdjLocked();
3427 return r;
3428 }
3429
3430 // make sure the record is cleaned out of other places.
3431 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003432 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003433 mWaitingVisibleActivities.remove(r);
3434 if (mResumedActivity == r) {
3435 mResumedActivity = null;
3436 }
3437 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003438 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003439 r.state = ActivityState.FINISHING;
3440
3441 if (mode == FINISH_IMMEDIATELY
3442 || prevState == ActivityState.STOPPED
3443 || prevState == ActivityState.INITIALIZING) {
3444 // If this activity is already stopped, we can just finish
3445 // it right now.
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003446 return destroyActivityLocked(r, true, true) ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003447 } else {
3448 // Need to go through the full pause cycle to get this
3449 // activity into the stopped state and then finish it.
3450 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3451 mFinishingActivities.add(r);
3452 resumeTopActivityLocked(null);
3453 }
3454 return r;
3455 }
3456
3457 /**
3458 * Perform the common clean-up of an activity record. This is called both
3459 * as part of destroyActivityLocked() (when destroying the client-side
3460 * representation) and cleaning things up as a result of its hosting
3461 * processing going away, in which case there is no remaining client-side
3462 * state to destroy so only the cleanup here is needed.
3463 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003464 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3465 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003466 if (mResumedActivity == r) {
3467 mResumedActivity = null;
3468 }
3469 if (mService.mFocusedActivity == r) {
3470 mService.mFocusedActivity = null;
3471 }
3472
3473 r.configDestroy = false;
3474 r.frozenBeforeDestroy = false;
3475
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003476 if (setState) {
3477 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3478 r.state = ActivityState.DESTROYED;
3479 }
3480
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003481 // Make sure this record is no longer in the pending finishes list.
3482 // This could happen, for example, if we are trimming activities
3483 // down to the max limit while they are still waiting to finish.
3484 mFinishingActivities.remove(r);
3485 mWaitingVisibleActivities.remove(r);
3486
3487 // Remove any pending results.
3488 if (r.finishing && r.pendingResults != null) {
3489 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3490 PendingIntentRecord rec = apr.get();
3491 if (rec != null) {
3492 mService.cancelIntentSenderLocked(rec, false);
3493 }
3494 }
3495 r.pendingResults = null;
3496 }
3497
3498 if (cleanServices) {
3499 cleanUpActivityServicesLocked(r);
3500 }
3501
3502 if (mService.mPendingThumbnails.size() > 0) {
3503 // There are clients waiting to receive thumbnails so, in case
3504 // this is an activity that someone is waiting for, add it
3505 // to the pending list so we can correctly update the clients.
3506 mService.mCancelledThumbnails.add(r);
3507 }
3508
3509 // Get rid of any pending idle timeouts.
3510 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
3511 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003512 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003513 }
3514
3515 private final void removeActivityFromHistoryLocked(ActivityRecord r) {
3516 if (r.state != ActivityState.DESTROYED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003517 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003518 mHistory.remove(r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003519 r.takeFromHistory();
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003520 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3521 + " (removed from history)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003522 r.state = ActivityState.DESTROYED;
3523 mService.mWindowManager.removeAppToken(r);
3524 if (VALIDATE_TOKENS) {
3525 mService.mWindowManager.validateAppTokens(mHistory);
3526 }
3527 cleanUpActivityServicesLocked(r);
3528 r.removeUriPermissionsLocked();
3529 }
3530 }
3531
3532 /**
3533 * Perform clean-up of service connections in an activity record.
3534 */
3535 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3536 // Throw away any services that have been bound by this activity.
3537 if (r.connections != null) {
3538 Iterator<ConnectionRecord> it = r.connections.iterator();
3539 while (it.hasNext()) {
3540 ConnectionRecord c = it.next();
3541 mService.removeConnectionLocked(c, null, r);
3542 }
3543 r.connections = null;
3544 }
3545 }
3546
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003547 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj) {
3548 for (int i=mHistory.size()-1; i>=0; i--) {
3549 ActivityRecord r = mHistory.get(i);
3550 if (owner != null && r.app != owner) {
3551 continue;
3552 }
3553 // We can destroy this one if we have its icicle saved and
3554 // it is not in the process of pausing/stopping/finishing.
3555 if (r.app != null && r.haveState && !r.visible && r.stopped && !r.finishing
3556 && r.state != ActivityState.DESTROYING
3557 && r.state != ActivityState.DESTROYED) {
3558 destroyActivityLocked(r, true, oomAdj);
3559 }
3560 }
3561 }
3562
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003563 /**
3564 * Destroy the current CLIENT SIDE instance of an activity. This may be
3565 * called both when actually finishing an activity, or when performing
3566 * a configuration switch where we destroy the current client-side object
3567 * but then create a new client-side object for this same HistoryRecord.
3568 */
3569 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003570 boolean removeFromApp, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003571 if (DEBUG_SWITCH) Slog.v(
3572 TAG, "Removing activity: token=" + r
3573 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3574 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3575 System.identityHashCode(r),
3576 r.task.taskId, r.shortComponentName);
3577
3578 boolean removedFromHistory = false;
3579
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003580 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003581
3582 final boolean hadApp = r.app != null;
3583
3584 if (hadApp) {
3585 if (removeFromApp) {
3586 int idx = r.app.activities.indexOf(r);
3587 if (idx >= 0) {
3588 r.app.activities.remove(idx);
3589 }
3590 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
3591 mService.mHeavyWeightProcess = null;
3592 mService.mHandler.sendEmptyMessage(
3593 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
3594 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003595 if (r.app.activities.size() == 0) {
3596 // No longer have activities, so update location in
3597 // LRU list.
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003598 mService.updateLruProcessLocked(r.app, oomAdj, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003599 }
3600 }
3601
3602 boolean skipDestroy = false;
3603
3604 try {
3605 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
3606 r.app.thread.scheduleDestroyActivity(r, r.finishing,
3607 r.configChangeFlags);
3608 } catch (Exception e) {
3609 // We can just ignore exceptions here... if the process
3610 // has crashed, our death notification will clean things
3611 // up.
3612 //Slog.w(TAG, "Exception thrown during finish", e);
3613 if (r.finishing) {
3614 removeActivityFromHistoryLocked(r);
3615 removedFromHistory = true;
3616 skipDestroy = true;
3617 }
3618 }
3619
3620 r.app = null;
3621 r.nowVisible = false;
3622
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003623 // If the activity is finishing, we need to wait on removing it
3624 // from the list to give it a chance to do its cleanup. During
3625 // that time it may make calls back with its token so we need to
3626 // be able to find it on the list and so we don't want to remove
3627 // it from the list yet. Otherwise, we can just immediately put
3628 // it in the destroyed state since we are not removing it from the
3629 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003630 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003631 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
3632 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003633 r.state = ActivityState.DESTROYING;
3634 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
3635 msg.obj = r;
3636 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
3637 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003638 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3639 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003640 r.state = ActivityState.DESTROYED;
3641 }
3642 } else {
3643 // remove this record from the history.
3644 if (r.finishing) {
3645 removeActivityFromHistoryLocked(r);
3646 removedFromHistory = true;
3647 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003648 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3649 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003650 r.state = ActivityState.DESTROYED;
3651 }
3652 }
3653
3654 r.configChangeFlags = 0;
3655
3656 if (!mLRUActivities.remove(r) && hadApp) {
3657 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
3658 }
3659
3660 return removedFromHistory;
3661 }
3662
3663 final void activityDestroyed(IBinder token) {
3664 synchronized (mService) {
3665 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, token);
3666
3667 int index = indexOfTokenLocked(token);
3668 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003669 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003670 if (r.state == ActivityState.DESTROYING) {
3671 final long origId = Binder.clearCallingIdentity();
3672 removeActivityFromHistoryLocked(r);
3673 Binder.restoreCallingIdentity(origId);
3674 }
3675 }
3676 }
3677 }
3678
3679 private static void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
3680 int i = list.size();
3681 if (localLOGV) Slog.v(
3682 TAG, "Removing app " + app + " from list " + list
3683 + " with " + i + " entries");
3684 while (i > 0) {
3685 i--;
3686 ActivityRecord r = (ActivityRecord)list.get(i);
3687 if (localLOGV) Slog.v(
3688 TAG, "Record #" + i + " " + r + ": app=" + r.app);
3689 if (r.app == app) {
3690 if (localLOGV) Slog.v(TAG, "Removing this entry!");
3691 list.remove(i);
3692 }
3693 }
3694 }
3695
3696 void removeHistoryRecordsForAppLocked(ProcessRecord app) {
3697 removeHistoryRecordsForAppLocked(mLRUActivities, app);
3698 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003699 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003700 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
3701 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
3702 }
3703
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003704 /**
3705 * Move the current home activity's task (if one exists) to the front
3706 * of the stack.
3707 */
3708 final void moveHomeToFrontLocked() {
3709 TaskRecord homeTask = null;
3710 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003711 ActivityRecord hr = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003712 if (hr.isHomeActivity) {
3713 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003714 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003715 }
3716 }
3717 if (homeTask != null) {
3718 moveTaskToFrontLocked(homeTask, null);
3719 }
3720 }
3721
3722
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003723 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason) {
3724 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
3725
3726 final int task = tr.taskId;
3727 int top = mHistory.size()-1;
3728
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003729 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003730 // nothing to do!
3731 return;
3732 }
3733
3734 ArrayList moved = new ArrayList();
3735
3736 // Applying the affinities may have removed entries from the history,
3737 // so get the size again.
3738 top = mHistory.size()-1;
3739 int pos = top;
3740
3741 // Shift all activities with this task up to the top
3742 // of the stack, keeping them in the same internal order.
3743 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003744 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003745 if (localLOGV) Slog.v(
3746 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003747 if (r.task.taskId == task) {
3748 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
3749 mHistory.remove(pos);
3750 mHistory.add(top, r);
3751 moved.add(0, r);
3752 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003753 }
3754 pos--;
3755 }
3756
3757 if (DEBUG_TRANSITION) Slog.v(TAG,
3758 "Prepare to front transition: task=" + tr);
3759 if (reason != null &&
3760 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003761 mService.mWindowManager.prepareAppTransition(
3762 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003763 ActivityRecord r = topRunningActivityLocked(null);
3764 if (r != null) {
3765 mNoAnimActivities.add(r);
3766 }
3767 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003768 mService.mWindowManager.prepareAppTransition(
3769 WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003770 }
3771
3772 mService.mWindowManager.moveAppTokensToTop(moved);
3773 if (VALIDATE_TOKENS) {
3774 mService.mWindowManager.validateAppTokens(mHistory);
3775 }
3776
3777 finishTaskMoveLocked(task);
3778 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
3779 }
3780
3781 private final void finishTaskMoveLocked(int task) {
3782 resumeTopActivityLocked(null);
3783 }
3784
3785 /**
3786 * Worker method for rearranging history stack. Implements the function of moving all
3787 * activities for a specific task (gathering them if disjoint) into a single group at the
3788 * bottom of the stack.
3789 *
3790 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
3791 * to premeptively cancel the move.
3792 *
3793 * @param task The taskId to collect and move to the bottom.
3794 * @return Returns true if the move completed, false if not.
3795 */
3796 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
3797 Slog.i(TAG, "moveTaskToBack: " + task);
3798
3799 // If we have a watcher, preflight the move before committing to it. First check
3800 // for *other* available tasks, but if none are available, then try again allowing the
3801 // current task to be selected.
3802 if (mMainStack && mService.mController != null) {
3803 ActivityRecord next = topRunningActivityLocked(null, task);
3804 if (next == null) {
3805 next = topRunningActivityLocked(null, 0);
3806 }
3807 if (next != null) {
3808 // ask watcher if this is allowed
3809 boolean moveOK = true;
3810 try {
3811 moveOK = mService.mController.activityResuming(next.packageName);
3812 } catch (RemoteException e) {
3813 mService.mController = null;
3814 }
3815 if (!moveOK) {
3816 return false;
3817 }
3818 }
3819 }
3820
3821 ArrayList moved = new ArrayList();
3822
3823 if (DEBUG_TRANSITION) Slog.v(TAG,
3824 "Prepare to back transition: task=" + task);
3825
3826 final int N = mHistory.size();
3827 int bottom = 0;
3828 int pos = 0;
3829
3830 // Shift all activities with this task down to the bottom
3831 // of the stack, keeping them in the same internal order.
3832 while (pos < N) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003833 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003834 if (localLOGV) Slog.v(
3835 TAG, "At " + pos + " ckp " + r.task + ": " + r);
3836 if (r.task.taskId == task) {
3837 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
3838 mHistory.remove(pos);
3839 mHistory.add(bottom, r);
3840 moved.add(r);
3841 bottom++;
3842 }
3843 pos++;
3844 }
3845
3846 if (reason != null &&
3847 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003848 mService.mWindowManager.prepareAppTransition(
3849 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003850 ActivityRecord r = topRunningActivityLocked(null);
3851 if (r != null) {
3852 mNoAnimActivities.add(r);
3853 }
3854 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003855 mService.mWindowManager.prepareAppTransition(
3856 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003857 }
3858 mService.mWindowManager.moveAppTokensToBottom(moved);
3859 if (VALIDATE_TOKENS) {
3860 mService.mWindowManager.validateAppTokens(mHistory);
3861 }
3862
3863 finishTaskMoveLocked(task);
3864 return true;
3865 }
3866
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003867 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
3868 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
3869 ActivityRecord resumed = mResumedActivity;
3870 if (resumed != null && resumed.thumbHolder == tr) {
3871 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
3872 } else {
3873 info.mainThumbnail = tr.lastThumbnail;
3874 }
3875 return info;
3876 }
3877
3878 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex) {
3879 TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
3880 if (info.root == null) {
3881 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
3882 return null;
3883 }
3884
3885 if (subTaskIndex < 0) {
3886 // Just remove the entire task.
3887 performClearTaskAtIndexLocked(taskId, info.rootIndex);
3888 return info.root;
3889 }
3890
3891 if (subTaskIndex >= info.subtasks.size()) {
3892 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
3893 return null;
3894 }
3895
3896 // Remove all of this task's activies starting at the sub task.
3897 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
3898 performClearTaskAtIndexLocked(taskId, subtask.index);
3899 return subtask.activity;
3900 }
3901
3902 public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
3903 ActivityRecord resumed = mResumedActivity;
3904 final TaskAccessInfo thumbs = new TaskAccessInfo();
3905 // How many different sub-thumbnails?
3906 final int NA = mHistory.size();
3907 int j = 0;
3908 ThumbnailHolder holder = null;
3909 while (j < NA) {
3910 ActivityRecord ar = mHistory.get(j);
3911 if (!ar.finishing && ar.task.taskId == taskId) {
3912 holder = ar.thumbHolder;
3913 break;
3914 }
3915 j++;
3916 }
3917
3918 if (j >= NA) {
3919 return thumbs;
3920 }
3921
3922 thumbs.root = mHistory.get(j);
3923 thumbs.rootIndex = j;
3924
3925 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
3926 thumbs.subtasks = subtasks;
3927 ActivityRecord lastActivity = null;
3928 while (j < NA) {
3929 ActivityRecord ar = mHistory.get(j);
3930 j++;
3931 if (ar.finishing) {
3932 continue;
3933 }
3934 if (ar.task.taskId != taskId) {
3935 break;
3936 }
3937 lastActivity = ar;
3938 if (ar.thumbHolder != holder && holder != null) {
3939 thumbs.numSubThumbbails++;
3940 holder = ar.thumbHolder;
3941 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
3942 sub.thumbnail = holder.lastThumbnail;
3943 sub.activity = ar;
3944 sub.index = j-1;
3945 subtasks.add(sub);
3946 }
3947 }
3948 if (lastActivity != null && subtasks.size() > 0) {
3949 if (resumed == lastActivity) {
3950 TaskAccessInfo.SubTask sub = subtasks.get(subtasks.size()-1);
3951 sub.thumbnail = lastActivity.stack.screenshotActivities(lastActivity);
3952 }
3953 }
3954 if (thumbs.numSubThumbbails > 0) {
3955 thumbs.retriever = new IThumbnailRetriever.Stub() {
3956 public Bitmap getThumbnail(int index) {
3957 if (index < 0 || index >= thumbs.subtasks.size()) {
3958 return null;
3959 }
3960 return thumbs.subtasks.get(index).thumbnail;
3961 }
3962 };
3963 }
3964 return thumbs;
3965 }
3966
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003967 private final void logStartActivity(int tag, ActivityRecord r,
3968 TaskRecord task) {
3969 EventLog.writeEvent(tag,
3970 System.identityHashCode(r), task.taskId,
3971 r.shortComponentName, r.intent.getAction(),
3972 r.intent.getType(), r.intent.getDataString(),
3973 r.intent.getFlags());
3974 }
3975
3976 /**
3977 * Make sure the given activity matches the current configuration. Returns
3978 * false if the activity had to be destroyed. Returns true if the
3979 * configuration is the same, or the activity will remain running as-is
3980 * for whatever reason. Ensures the HistoryRecord is updated with the
3981 * correct configuration and all other bookkeeping is handled.
3982 */
3983 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
3984 int globalChanges) {
3985 if (mConfigWillChange) {
3986 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3987 "Skipping config check (will change): " + r);
3988 return true;
3989 }
3990
3991 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3992 "Ensuring correct configuration: " + r);
3993
3994 // Short circuit: if the two configurations are the exact same
3995 // object (the common case), then there is nothing to do.
3996 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003997 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003998 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3999 "Configuration unchanged in " + r);
4000 return true;
4001 }
4002
4003 // We don't worry about activities that are finishing.
4004 if (r.finishing) {
4005 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4006 "Configuration doesn't matter in finishing " + r);
4007 r.stopFreezingScreenLocked(false);
4008 return true;
4009 }
4010
4011 // Okay we now are going to make this activity have the new config.
4012 // But then we need to figure out how it needs to deal with that.
4013 Configuration oldConfig = r.configuration;
4014 r.configuration = newConfig;
4015
4016 // If the activity isn't currently running, just leave the new
4017 // configuration and it will pick that up next time it starts.
4018 if (r.app == null || r.app.thread == null) {
4019 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4020 "Configuration doesn't matter not running " + r);
4021 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004022 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004023 return true;
4024 }
4025
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004026 // Figure out what has changed between the two configurations.
4027 int changes = oldConfig.diff(newConfig);
4028 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4029 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
4030 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07004031 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004032 + ", newConfig=" + newConfig);
4033 }
Dianne Hackborne6676352011-06-01 16:51:20 -07004034 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004035 // Aha, the activity isn't handling the change, so DIE DIE DIE.
4036 r.configChangeFlags |= changes;
4037 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004038 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004039 if (r.app == null || r.app.thread == null) {
4040 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4041 "Switch is destroying non-running " + r);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004042 destroyActivityLocked(r, true, false);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004043 } else if (r.state == ActivityState.PAUSING) {
4044 // A little annoying: we are waiting for this activity to
4045 // finish pausing. Let's not do anything now, but just
4046 // flag that it needs to be restarted when done pausing.
4047 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4048 "Switch is skipping already pausing " + r);
4049 r.configDestroy = true;
4050 return true;
4051 } else if (r.state == ActivityState.RESUMED) {
4052 // Try to optimize this case: the configuration is changing
4053 // and we need to restart the top, resumed activity.
4054 // Instead of doing the normal handshaking, just say
4055 // "restart!".
4056 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4057 "Switch is restarting resumed " + r);
4058 relaunchActivityLocked(r, r.configChangeFlags, true);
4059 r.configChangeFlags = 0;
4060 } else {
4061 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4062 "Switch is restarting non-resumed " + r);
4063 relaunchActivityLocked(r, r.configChangeFlags, false);
4064 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004065 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004066
4067 // All done... tell the caller we weren't able to keep this
4068 // activity around.
4069 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004070 }
4071
4072 // Default case: the activity can handle this new configuration, so
4073 // hand it over. Note that we don't need to give it the new
4074 // configuration, since we always send configuration changes to all
4075 // process when they happen so it can just use whatever configuration
4076 // it last got.
4077 if (r.app != null && r.app.thread != null) {
4078 try {
4079 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
4080 r.app.thread.scheduleActivityConfigurationChanged(r);
4081 } catch (RemoteException e) {
4082 // If process died, whatever.
4083 }
4084 }
4085 r.stopFreezingScreenLocked(false);
4086
4087 return true;
4088 }
4089
4090 private final boolean relaunchActivityLocked(ActivityRecord r,
4091 int changes, boolean andResume) {
4092 List<ResultInfo> results = null;
4093 List<Intent> newIntents = null;
4094 if (andResume) {
4095 results = r.results;
4096 newIntents = r.newIntents;
4097 }
4098 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4099 + " with results=" + results + " newIntents=" + newIntents
4100 + " andResume=" + andResume);
4101 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
4102 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
4103 r.task.taskId, r.shortComponentName);
4104
4105 r.startFreezingScreenLocked(r.app, 0);
4106
4107 try {
4108 if (DEBUG_SWITCH) Slog.i(TAG, "Switch is restarting resumed " + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004109 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004110 r.app.thread.scheduleRelaunchActivity(r, results, newIntents,
4111 changes, !andResume, mService.mConfiguration);
4112 // Note: don't need to call pauseIfSleepingLocked() here, because
4113 // the caller will only pass in 'andResume' if this activity is
4114 // currently resumed, which implies we aren't sleeping.
4115 } catch (RemoteException e) {
4116 return false;
4117 }
4118
4119 if (andResume) {
4120 r.results = null;
4121 r.newIntents = null;
4122 if (mMainStack) {
4123 mService.reportResumedActivityLocked(r);
4124 }
4125 }
4126
4127 return true;
4128 }
4129}