blob: a0aedf9844739fc2cef84f01a2d0b36b33ab2ab6 [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");
768 Message msg = Message.obtain();
769 msg.what = IDLE_NOW_MSG;
770 mHandler.sendMessage(msg);
771 return;
772 }
773
774 ensureActivitiesVisibleLocked(null, 0);
775
776 // Make sure any stopped but visible activities are now sleeping.
777 // This ensures that the activity's onStop() is called.
778 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700779 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800780 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
781 r.setSleeping(true);
782 }
783 }
784
785 if (mGoingToSleepActivities.size() > 0) {
786 // Still need to tell some activities to sleep; can't sleep yet.
787 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
788 + mGoingToSleepActivities.size() + " activities");
789 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700790 }
791 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800792
793 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
794
795 if (mGoingToSleep.isHeld()) {
796 mGoingToSleep.release();
797 }
798 if (mService.mShuttingDown) {
799 mService.notifyAll();
800 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700801 }
802
Dianne Hackbornd2835932010-12-13 16:28:46 -0800803 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -0800804 if (who.noDisplay) {
805 return null;
806 }
807
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800808 Resources res = mService.mContext.getResources();
809 int w = mThumbnailWidth;
810 int h = mThumbnailHeight;
811 if (w < 0) {
812 mThumbnailWidth = w =
813 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
814 mThumbnailHeight = h =
815 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
816 }
817
818 if (w > 0) {
Dianne Hackborn7c8a4b32010-12-15 14:58:00 -0800819 return mService.mWindowManager.screenshotApplications(who, w, h);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800820 }
821 return null;
822 }
823
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700824 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
825 if (mPausingActivity != null) {
826 RuntimeException e = new RuntimeException();
827 Slog.e(TAG, "Trying to pause when pause is already pending for "
828 + mPausingActivity, e);
829 }
830 ActivityRecord prev = mResumedActivity;
831 if (prev == null) {
832 RuntimeException e = new RuntimeException();
833 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
834 resumeTopActivityLocked(null);
835 return;
836 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700837 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
838 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700839 mResumedActivity = null;
840 mPausingActivity = prev;
841 mLastPausedActivity = prev;
842 prev.state = ActivityState.PAUSING;
843 prev.task.touchActiveTime();
Dianne Hackbornf26fd992011-04-08 18:14:09 -0700844 prev.updateThumbnail(screenshotActivities(prev), null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700845
846 mService.updateCpuStats();
847
848 if (prev.app != null && prev.app.thread != null) {
849 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
850 try {
851 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
852 System.identityHashCode(prev),
853 prev.shortComponentName);
854 prev.app.thread.schedulePauseActivity(prev, prev.finishing, userLeaving,
855 prev.configChangeFlags);
856 if (mMainStack) {
857 mService.updateUsageStats(prev, false);
858 }
859 } catch (Exception e) {
860 // Ignore exception, if process died other code will cleanup.
861 Slog.w(TAG, "Exception thrown during pause", e);
862 mPausingActivity = null;
863 mLastPausedActivity = null;
864 }
865 } else {
866 mPausingActivity = null;
867 mLastPausedActivity = null;
868 }
869
870 // If we are not going to sleep, we want to ensure the device is
871 // awake until the next activity is started.
872 if (!mService.mSleeping && !mService.mShuttingDown) {
873 mLaunchingActivity.acquire();
874 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
875 // To be safe, don't allow the wake lock to be held for too long.
876 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
877 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
878 }
879 }
880
881
882 if (mPausingActivity != null) {
883 // Have the window manager pause its key dispatching until the new
884 // activity has started. If we're pausing the activity just because
885 // the screen is being turned off and the UI is sleeping, don't interrupt
886 // key dispatch; the same activity will pick it up again on wakeup.
887 if (!uiSleeping) {
888 prev.pauseKeyDispatchingLocked();
889 } else {
890 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
891 }
892
893 // Schedule a pause timeout in case the app doesn't respond.
894 // We don't give it much time because this directly impacts the
895 // responsiveness seen by the user.
896 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
897 msg.obj = prev;
898 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
899 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
900 } else {
901 // This activity failed to schedule the
902 // pause, so just treat it as being paused now.
903 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
904 resumeTopActivityLocked(null);
905 }
906 }
907
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800908 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700909 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800910 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700911
912 ActivityRecord r = null;
913
914 synchronized (mService) {
915 int index = indexOfTokenLocked(token);
916 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700917 r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700918 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
919 if (mPausingActivity == r) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700920 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
921 + (timeout ? " (due to timeout)" : " (pause complete)"));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700922 r.state = ActivityState.PAUSED;
923 completePauseLocked();
924 } else {
925 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
926 System.identityHashCode(r), r.shortComponentName,
927 mPausingActivity != null
928 ? mPausingActivity.shortComponentName : "(none)");
929 }
930 }
931 }
932 }
933
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700934 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
935 CharSequence description) {
936 r.icicle = icicle;
937 r.haveState = true;
938 r.updateThumbnail(thumbnail, description);
939 r.stopped = true;
940 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
941 r.state = ActivityState.STOPPED;
942 if (!r.finishing) {
943 if (r.configDestroy) {
944 destroyActivityLocked(r, true, false);
945 resumeTopActivityLocked(null);
946 }
947 }
948 }
949
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700950 private final void completePauseLocked() {
951 ActivityRecord prev = mPausingActivity;
952 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
953
954 if (prev != null) {
955 if (prev.finishing) {
956 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
957 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE);
958 } else if (prev.app != null) {
959 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
960 if (prev.waitingVisible) {
961 prev.waitingVisible = false;
962 mWaitingVisibleActivities.remove(prev);
963 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
964 TAG, "Complete pause, no longer waiting: " + prev);
965 }
966 if (prev.configDestroy) {
967 // The previous is being paused because the configuration
968 // is changing, which means it is actually stopping...
969 // To juggle the fact that we are also starting a new
970 // instance right now, we need to first completely stop
971 // the current instance before starting the new one.
972 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700973 destroyActivityLocked(prev, true, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700974 } else {
975 mStoppingActivities.add(prev);
976 if (mStoppingActivities.size() > 3) {
977 // If we already have a few activities waiting to stop,
978 // then give up on things going idle and start clearing
979 // them out.
980 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
981 Message msg = Message.obtain();
982 msg.what = IDLE_NOW_MSG;
983 mHandler.sendMessage(msg);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800984 } else {
985 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700986 }
987 }
988 } else {
989 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
990 prev = null;
991 }
992 mPausingActivity = null;
993 }
994
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800995 if (!mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700996 resumeTopActivityLocked(prev);
997 } else {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800998 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700999 }
1000
1001 if (prev != null) {
1002 prev.resumeKeyDispatchingLocked();
1003 }
1004
1005 if (prev.app != null && prev.cpuTimeAtResume > 0
1006 && mService.mBatteryStatsService.isOnBattery()) {
1007 long diff = 0;
1008 synchronized (mService.mProcessStatsThread) {
1009 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
1010 - prev.cpuTimeAtResume;
1011 }
1012 if (diff > 0) {
1013 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
1014 synchronized (bsi) {
1015 BatteryStatsImpl.Uid.Proc ps =
1016 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
1017 prev.info.packageName);
1018 if (ps != null) {
1019 ps.addForegroundTimeLocked(diff);
1020 }
1021 }
1022 }
1023 }
1024 prev.cpuTimeAtResume = 0; // reset it
1025 }
1026
1027 /**
1028 * Once we know that we have asked an application to put an activity in
1029 * the resumed state (either by launching it or explicitly telling it),
1030 * this function updates the rest of our state to match that fact.
1031 */
1032 private final void completeResumeLocked(ActivityRecord next) {
1033 next.idle = false;
1034 next.results = null;
1035 next.newIntents = null;
1036
1037 // schedule an idle timeout in case the app doesn't do it for us.
1038 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1039 msg.obj = next;
1040 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
1041
1042 if (false) {
1043 // The activity was never told to pause, so just keep
1044 // things going as-is. To maintain our own state,
1045 // we need to emulate it coming back and saying it is
1046 // idle.
1047 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
1048 msg.obj = next;
1049 mHandler.sendMessage(msg);
1050 }
1051
1052 if (mMainStack) {
1053 mService.reportResumedActivityLocked(next);
1054 }
1055
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001056 next.clearThumbnail();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001057 if (mMainStack) {
1058 mService.setFocusedActivityLocked(next);
1059 }
1060 next.resumeKeyDispatchingLocked();
1061 ensureActivitiesVisibleLocked(null, 0);
1062 mService.mWindowManager.executeAppTransition();
1063 mNoAnimActivities.clear();
1064
1065 // Mark the point when the activity is resuming
1066 // TODO: To be more accurate, the mark should be before the onCreate,
1067 // not after the onResume. But for subsequent starts, onResume is fine.
1068 if (next.app != null) {
1069 synchronized (mService.mProcessStatsThread) {
1070 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1071 }
1072 } else {
1073 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1074 }
1075 }
1076
1077 /**
1078 * Make sure that all activities that need to be visible (that is, they
1079 * currently can be seen by the user) actually are.
1080 */
1081 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1082 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1083 if (DEBUG_VISBILITY) Slog.v(
1084 TAG, "ensureActivitiesVisible behind " + top
1085 + " configChanges=0x" + Integer.toHexString(configChanges));
1086
1087 // If the top activity is not fullscreen, then we need to
1088 // make sure any activities under it are now visible.
1089 final int count = mHistory.size();
1090 int i = count-1;
1091 while (mHistory.get(i) != top) {
1092 i--;
1093 }
1094 ActivityRecord r;
1095 boolean behindFullscreen = false;
1096 for (; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001097 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001098 if (DEBUG_VISBILITY) Slog.v(
1099 TAG, "Make visible? " + r + " finishing=" + r.finishing
1100 + " state=" + r.state);
1101 if (r.finishing) {
1102 continue;
1103 }
1104
1105 final boolean doThisProcess = onlyThisProcess == null
1106 || onlyThisProcess.equals(r.processName);
1107
1108 // First: if this is not the current activity being started, make
1109 // sure it matches the current configuration.
1110 if (r != starting && doThisProcess) {
1111 ensureActivityConfigurationLocked(r, 0);
1112 }
1113
1114 if (r.app == null || r.app.thread == null) {
1115 if (onlyThisProcess == null
1116 || onlyThisProcess.equals(r.processName)) {
1117 // This activity needs to be visible, but isn't even
1118 // running... get it started, but don't resume it
1119 // at this point.
1120 if (DEBUG_VISBILITY) Slog.v(
1121 TAG, "Start and freeze screen for " + r);
1122 if (r != starting) {
1123 r.startFreezingScreenLocked(r.app, configChanges);
1124 }
1125 if (!r.visible) {
1126 if (DEBUG_VISBILITY) Slog.v(
1127 TAG, "Starting and making visible: " + r);
1128 mService.mWindowManager.setAppVisibility(r, true);
1129 }
1130 if (r != starting) {
1131 startSpecificActivityLocked(r, false, false);
1132 }
1133 }
1134
1135 } else if (r.visible) {
1136 // If this activity is already visible, then there is nothing
1137 // else to do here.
1138 if (DEBUG_VISBILITY) Slog.v(
1139 TAG, "Skipping: already visible at " + r);
1140 r.stopFreezingScreenLocked(false);
1141
1142 } else if (onlyThisProcess == null) {
1143 // This activity is not currently visible, but is running.
1144 // Tell it to become visible.
1145 r.visible = true;
1146 if (r.state != ActivityState.RESUMED && r != starting) {
1147 // If this activity is paused, tell it
1148 // to now show its window.
1149 if (DEBUG_VISBILITY) Slog.v(
1150 TAG, "Making visible and scheduling visibility: " + r);
1151 try {
1152 mService.mWindowManager.setAppVisibility(r, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001153 r.sleeping = false;
Dianne Hackborn905577f2011-09-07 18:31:28 -07001154 r.app.pendingUiClean = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001155 r.app.thread.scheduleWindowVisibility(r, true);
1156 r.stopFreezingScreenLocked(false);
1157 } catch (Exception e) {
1158 // Just skip on any failure; we'll make it
1159 // visible when it next restarts.
1160 Slog.w(TAG, "Exception thrown making visibile: "
1161 + r.intent.getComponent(), e);
1162 }
1163 }
1164 }
1165
1166 // Aggregate current change flags.
1167 configChanges |= r.configChangeFlags;
1168
1169 if (r.fullscreen) {
1170 // At this point, nothing else needs to be shown
1171 if (DEBUG_VISBILITY) Slog.v(
1172 TAG, "Stopping: fullscreen at " + r);
1173 behindFullscreen = true;
1174 i--;
1175 break;
1176 }
1177 }
1178
1179 // Now for any activities that aren't visible to the user, make
1180 // sure they no longer are keeping the screen frozen.
1181 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001182 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001183 if (DEBUG_VISBILITY) Slog.v(
1184 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1185 + " state=" + r.state
1186 + " behindFullscreen=" + behindFullscreen);
1187 if (!r.finishing) {
1188 if (behindFullscreen) {
1189 if (r.visible) {
1190 if (DEBUG_VISBILITY) Slog.v(
1191 TAG, "Making invisible: " + r);
1192 r.visible = false;
1193 try {
1194 mService.mWindowManager.setAppVisibility(r, false);
1195 if ((r.state == ActivityState.STOPPING
1196 || r.state == ActivityState.STOPPED)
1197 && r.app != null && r.app.thread != null) {
1198 if (DEBUG_VISBILITY) Slog.v(
1199 TAG, "Scheduling invisibility: " + r);
1200 r.app.thread.scheduleWindowVisibility(r, false);
1201 }
1202 } catch (Exception e) {
1203 // Just skip on any failure; we'll make it
1204 // visible when it next restarts.
1205 Slog.w(TAG, "Exception thrown making hidden: "
1206 + r.intent.getComponent(), e);
1207 }
1208 } else {
1209 if (DEBUG_VISBILITY) Slog.v(
1210 TAG, "Already invisible: " + r);
1211 }
1212 } else if (r.fullscreen) {
1213 if (DEBUG_VISBILITY) Slog.v(
1214 TAG, "Now behindFullscreen: " + r);
1215 behindFullscreen = true;
1216 }
1217 }
1218 i--;
1219 }
1220 }
1221
1222 /**
1223 * Version of ensureActivitiesVisible that can easily be called anywhere.
1224 */
1225 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1226 int configChanges) {
1227 ActivityRecord r = topRunningActivityLocked(null);
1228 if (r != null) {
1229 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1230 }
1231 }
1232
1233 /**
1234 * Ensure that the top activity in the stack is resumed.
1235 *
1236 * @param prev The previously resumed activity, for when in the process
1237 * of pausing; can be null to call from elsewhere.
1238 *
1239 * @return Returns true if something is being resumed, or false if
1240 * nothing happened.
1241 */
1242 final boolean resumeTopActivityLocked(ActivityRecord prev) {
1243 // Find the first activity that is not finishing.
1244 ActivityRecord next = topRunningActivityLocked(null);
1245
1246 // Remember how we'll process this pause/resume situation, and ensure
1247 // that the state is reset however we wind up proceeding.
1248 final boolean userLeaving = mUserLeaving;
1249 mUserLeaving = false;
1250
1251 if (next == null) {
1252 // There are no more activities! Let's just start up the
1253 // Launcher...
1254 if (mMainStack) {
1255 return mService.startHomeActivityLocked();
1256 }
1257 }
1258
1259 next.delayedResume = false;
1260
1261 // If the top activity is the resumed one, nothing to do.
1262 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1263 // Make sure we have executed any pending transitions, since there
1264 // should be nothing left to do at this point.
1265 mService.mWindowManager.executeAppTransition();
1266 mNoAnimActivities.clear();
1267 return false;
1268 }
1269
1270 // If we are sleeping, and there is no resumed activity, and the top
1271 // activity is paused, well that is the state we want.
1272 if ((mService.mSleeping || mService.mShuttingDown)
1273 && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
1274 // Make sure we have executed any pending transitions, since there
1275 // should be nothing left to do at this point.
1276 mService.mWindowManager.executeAppTransition();
1277 mNoAnimActivities.clear();
1278 return false;
1279 }
1280
1281 // The activity may be waiting for stop, but that is no longer
1282 // appropriate for it.
1283 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001284 mGoingToSleepActivities.remove(next);
1285 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001286 mWaitingVisibleActivities.remove(next);
1287
1288 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1289
1290 // If we are currently pausing an activity, then don't do anything
1291 // until that is done.
1292 if (mPausingActivity != null) {
1293 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
1294 return false;
1295 }
1296
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001297 // Okay we are now going to start a switch, to 'next'. We may first
1298 // have to pause the current activity, but this is an important point
1299 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001300 // XXX "App Redirected" dialog is getting too many false positives
1301 // at this point, so turn off for now.
1302 if (false) {
1303 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1304 long now = SystemClock.uptimeMillis();
1305 final boolean inTime = mLastStartedActivity.startTime != 0
1306 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1307 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1308 final int nextUid = next.info.applicationInfo.uid;
1309 if (inTime && lastUid != nextUid
1310 && lastUid != next.launchedFromUid
1311 && mService.checkPermission(
1312 android.Manifest.permission.STOP_APP_SWITCHES,
1313 -1, next.launchedFromUid)
1314 != PackageManager.PERMISSION_GRANTED) {
1315 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1316 } else {
1317 next.startTime = now;
1318 mLastStartedActivity = next;
1319 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001320 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001321 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001322 mLastStartedActivity = next;
1323 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001324 }
1325
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001326 // We need to start pausing the current activity so the top one
1327 // can be resumed...
1328 if (mResumedActivity != null) {
1329 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
1330 startPausingLocked(userLeaving, false);
1331 return true;
1332 }
1333
1334 if (prev != null && prev != next) {
1335 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1336 prev.waitingVisible = true;
1337 mWaitingVisibleActivities.add(prev);
1338 if (DEBUG_SWITCH) Slog.v(
1339 TAG, "Resuming top, waiting visible to hide: " + prev);
1340 } else {
1341 // The next activity is already visible, so hide the previous
1342 // activity's windows right now so we can show the new one ASAP.
1343 // We only do this if the previous is finishing, which should mean
1344 // it is on top of the one being resumed so hiding it quickly
1345 // is good. Otherwise, we want to do the normal route of allowing
1346 // the resumed activity to be shown so we can decide if the
1347 // previous should actually be hidden depending on whether the
1348 // new one is found to be full-screen or not.
1349 if (prev.finishing) {
1350 mService.mWindowManager.setAppVisibility(prev, false);
1351 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1352 + prev + ", waitingVisible="
1353 + (prev != null ? prev.waitingVisible : null)
1354 + ", nowVisible=" + next.nowVisible);
1355 } else {
1356 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1357 + prev + ", waitingVisible="
1358 + (prev != null ? prev.waitingVisible : null)
1359 + ", nowVisible=" + next.nowVisible);
1360 }
1361 }
1362 }
1363
Dianne Hackborne7f97212011-02-24 14:40:20 -08001364 // Launching this app's activity, make sure the app is no longer
1365 // considered stopped.
1366 try {
1367 AppGlobals.getPackageManager().setPackageStoppedState(
1368 next.packageName, false);
1369 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001370 } catch (IllegalArgumentException e) {
1371 Slog.w(TAG, "Failed trying to unstop package "
1372 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001373 }
1374
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001375 // We are starting up the next activity, so tell the window manager
1376 // that the previous one will be hidden soon. This way it can know
1377 // to ignore it when computing the desired screen orientation.
1378 if (prev != null) {
1379 if (prev.finishing) {
1380 if (DEBUG_TRANSITION) Slog.v(TAG,
1381 "Prepare close transition: prev=" + prev);
1382 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001383 mService.mWindowManager.prepareAppTransition(
1384 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001385 } else {
1386 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1387 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001388 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001389 }
1390 mService.mWindowManager.setAppWillBeHidden(prev);
1391 mService.mWindowManager.setAppVisibility(prev, false);
1392 } else {
1393 if (DEBUG_TRANSITION) Slog.v(TAG,
1394 "Prepare open transition: prev=" + prev);
1395 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001396 mService.mWindowManager.prepareAppTransition(
1397 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001398 } else {
1399 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1400 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001401 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001402 }
1403 }
1404 if (false) {
1405 mService.mWindowManager.setAppWillBeHidden(prev);
1406 mService.mWindowManager.setAppVisibility(prev, false);
1407 }
1408 } else if (mHistory.size() > 1) {
1409 if (DEBUG_TRANSITION) Slog.v(TAG,
1410 "Prepare open transition: no previous");
1411 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001412 mService.mWindowManager.prepareAppTransition(
1413 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001414 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001415 mService.mWindowManager.prepareAppTransition(
1416 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001417 }
1418 }
1419
1420 if (next.app != null && next.app.thread != null) {
1421 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1422
1423 // This activity is now becoming visible.
1424 mService.mWindowManager.setAppVisibility(next, true);
1425
1426 ActivityRecord lastResumedActivity = mResumedActivity;
1427 ActivityState lastState = next.state;
1428
1429 mService.updateCpuStats();
1430
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001431 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001432 next.state = ActivityState.RESUMED;
1433 mResumedActivity = next;
1434 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001435 if (mMainStack) {
1436 mService.addRecentTaskLocked(next.task);
1437 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001438 mService.updateLruProcessLocked(next.app, true, true);
1439 updateLRUListLocked(next);
1440
1441 // Have the window manager re-evaluate the orientation of
1442 // the screen based on the new activity order.
1443 boolean updated = false;
1444 if (mMainStack) {
1445 synchronized (mService) {
1446 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1447 mService.mConfiguration,
1448 next.mayFreezeScreenLocked(next.app) ? next : null);
1449 if (config != null) {
1450 next.frozenBeforeDestroy = true;
1451 }
Dianne Hackborn31ca8542011-07-19 14:58:28 -07001452 updated = mService.updateConfigurationLocked(config, next, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001453 }
1454 }
1455 if (!updated) {
1456 // The configuration update wasn't able to keep the existing
1457 // instance of the activity, and instead started a new one.
1458 // We should be all done, but let's just make sure our activity
1459 // is still at the top and schedule another run if something
1460 // weird happened.
1461 ActivityRecord nextNext = topRunningActivityLocked(null);
1462 if (DEBUG_SWITCH) Slog.i(TAG,
1463 "Activity config changed during resume: " + next
1464 + ", new next: " + nextNext);
1465 if (nextNext != next) {
1466 // Do over!
1467 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1468 }
1469 if (mMainStack) {
1470 mService.setFocusedActivityLocked(next);
1471 }
1472 ensureActivitiesVisibleLocked(null, 0);
1473 mService.mWindowManager.executeAppTransition();
1474 mNoAnimActivities.clear();
1475 return true;
1476 }
1477
1478 try {
1479 // Deliver all pending results.
1480 ArrayList a = next.results;
1481 if (a != null) {
1482 final int N = a.size();
1483 if (!next.finishing && N > 0) {
1484 if (DEBUG_RESULTS) Slog.v(
1485 TAG, "Delivering results to " + next
1486 + ": " + a);
1487 next.app.thread.scheduleSendResult(next, a);
1488 }
1489 }
1490
1491 if (next.newIntents != null) {
1492 next.app.thread.scheduleNewIntent(next.newIntents, next);
1493 }
1494
1495 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
1496 System.identityHashCode(next),
1497 next.task.taskId, next.shortComponentName);
1498
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001499 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001500 showAskCompatModeDialogLocked(next);
Dianne Hackborn905577f2011-09-07 18:31:28 -07001501 next.app.pendingUiClean = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001502 next.app.thread.scheduleResumeActivity(next,
1503 mService.isNextTransitionForward());
1504
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001505 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001506
1507 } catch (Exception e) {
1508 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001509 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1510 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001511 next.state = lastState;
1512 mResumedActivity = lastResumedActivity;
1513 Slog.i(TAG, "Restarting because process died: " + next);
1514 if (!next.hasBeenLaunched) {
1515 next.hasBeenLaunched = true;
1516 } else {
1517 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1518 mService.mWindowManager.setAppStartingWindow(
1519 next, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001520 mService.compatibilityInfoForPackageLocked(
1521 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001522 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001523 next.labelRes, next.icon, next.windowFlags,
1524 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001525 }
1526 }
1527 startSpecificActivityLocked(next, true, false);
1528 return true;
1529 }
1530
1531 // From this point on, if something goes wrong there is no way
1532 // to recover the activity.
1533 try {
1534 next.visible = true;
1535 completeResumeLocked(next);
1536 } catch (Exception e) {
1537 // If any exception gets thrown, toss away this
1538 // activity and try the next one.
1539 Slog.w(TAG, "Exception thrown during resume of " + next, e);
1540 requestFinishActivityLocked(next, Activity.RESULT_CANCELED, null,
1541 "resume-exception");
1542 return true;
1543 }
1544
1545 // Didn't need to use the icicle, and it is now out of date.
1546 next.icicle = null;
1547 next.haveState = false;
1548 next.stopped = false;
1549
1550 } else {
1551 // Whoops, need to restart this activity!
1552 if (!next.hasBeenLaunched) {
1553 next.hasBeenLaunched = true;
1554 } else {
1555 if (SHOW_APP_STARTING_PREVIEW) {
1556 mService.mWindowManager.setAppStartingWindow(
1557 next, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001558 mService.compatibilityInfoForPackageLocked(
1559 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001560 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001561 next.labelRes, next.icon, next.windowFlags,
1562 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001563 }
1564 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1565 }
1566 startSpecificActivityLocked(next, true, true);
1567 }
1568
1569 return true;
1570 }
1571
1572 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001573 boolean doResume, boolean keepCurTransition) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001574 final int NH = mHistory.size();
1575
1576 int addPos = -1;
1577
1578 if (!newTask) {
1579 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001580 boolean startIt = true;
1581 for (int i = NH-1; i >= 0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001582 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001583 if (p.finishing) {
1584 continue;
1585 }
1586 if (p.task == r.task) {
1587 // Here it is! Now, if this is not yet visible to the
1588 // user, then just add it without starting; it will
1589 // get started when the user navigates back to it.
1590 addPos = i+1;
1591 if (!startIt) {
1592 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001593 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001594 mService.mWindowManager.addAppToken(addPos, r, r.task.taskId,
1595 r.info.screenOrientation, r.fullscreen);
1596 if (VALIDATE_TOKENS) {
1597 mService.mWindowManager.validateAppTokens(mHistory);
1598 }
1599 return;
1600 }
1601 break;
1602 }
1603 if (p.fullscreen) {
1604 startIt = false;
1605 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001606 }
1607 }
1608
1609 // Place a new activity at top of stack, so it is next to interact
1610 // with the user.
1611 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001612 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001613 }
1614
1615 // If we are not placing the new activity frontmost, we do not want
1616 // to deliver the onUserLeaving callback to the actual frontmost
1617 // activity
1618 if (addPos < NH) {
1619 mUserLeaving = false;
1620 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1621 }
1622
1623 // Slot the activity into the history stack and proceed
1624 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001625 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001626 r.frontOfTask = newTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001627 if (NH > 0) {
1628 // We want to show the starting preview window if we are
1629 // switching to a new task, or the next activity's process is
1630 // not currently running.
1631 boolean showStartingIcon = newTask;
1632 ProcessRecord proc = r.app;
1633 if (proc == null) {
1634 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1635 }
1636 if (proc == null || proc.thread == null) {
1637 showStartingIcon = true;
1638 }
1639 if (DEBUG_TRANSITION) Slog.v(TAG,
1640 "Prepare open transition: starting " + r);
1641 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001642 mService.mWindowManager.prepareAppTransition(
1643 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001644 mNoAnimActivities.add(r);
1645 } else if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
1646 mService.mWindowManager.prepareAppTransition(
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001647 WindowManagerPolicy.TRANSIT_TASK_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001648 mNoAnimActivities.remove(r);
1649 } else {
1650 mService.mWindowManager.prepareAppTransition(newTask
1651 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001652 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001653 mNoAnimActivities.remove(r);
1654 }
1655 mService.mWindowManager.addAppToken(
1656 addPos, r, r.task.taskId, r.info.screenOrientation, r.fullscreen);
1657 boolean doShow = true;
1658 if (newTask) {
1659 // Even though this activity is starting fresh, we still need
1660 // to reset it to make sure we apply affinities to move any
1661 // existing activities from other tasks in to it.
1662 // If the caller has requested that the target task be
1663 // reset, then do so.
1664 if ((r.intent.getFlags()
1665 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1666 resetTaskIfNeededLocked(r, r);
1667 doShow = topRunningNonDelayedActivityLocked(null) == r;
1668 }
1669 }
1670 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1671 // Figure out if we are transitioning from another activity that is
1672 // "has the same starting icon" as the next one. This allows the
1673 // window manager to keep the previous window it had previously
1674 // created, if it still had one.
1675 ActivityRecord prev = mResumedActivity;
1676 if (prev != null) {
1677 // We don't want to reuse the previous starting preview if:
1678 // (1) The current activity is in a different task.
1679 if (prev.task != r.task) prev = null;
1680 // (2) The current activity is already displayed.
1681 else if (prev.nowVisible) prev = null;
1682 }
1683 mService.mWindowManager.setAppStartingWindow(
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001684 r, r.packageName, r.theme,
1685 mService.compatibilityInfoForPackageLocked(
1686 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001687 r.labelRes, r.icon, r.windowFlags, prev, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001688 }
1689 } else {
1690 // If this is the first activity, don't do any fancy animations,
1691 // because there is nothing for it to animate on top of.
1692 mService.mWindowManager.addAppToken(addPos, r, r.task.taskId,
1693 r.info.screenOrientation, r.fullscreen);
1694 }
1695 if (VALIDATE_TOKENS) {
1696 mService.mWindowManager.validateAppTokens(mHistory);
1697 }
1698
1699 if (doResume) {
1700 resumeTopActivityLocked(null);
1701 }
1702 }
1703
1704 /**
1705 * Perform a reset of the given task, if needed as part of launching it.
1706 * Returns the new HistoryRecord at the top of the task.
1707 */
1708 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1709 ActivityRecord newActivity) {
1710 boolean forceReset = (newActivity.info.flags
1711 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001712 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1713 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001714 if ((newActivity.info.flags
1715 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1716 forceReset = true;
1717 }
1718 }
1719
1720 final TaskRecord task = taskTop.task;
1721
1722 // We are going to move through the history list so that we can look
1723 // at each activity 'target' with 'below' either the interesting
1724 // activity immediately below it in the stack or null.
1725 ActivityRecord target = null;
1726 int targetI = 0;
1727 int taskTopI = -1;
1728 int replyChainEnd = -1;
1729 int lastReparentPos = -1;
1730 for (int i=mHistory.size()-1; i>=-1; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001731 ActivityRecord below = i >= 0 ? mHistory.get(i) : null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001732
1733 if (below != null && below.finishing) {
1734 continue;
1735 }
1736 if (target == null) {
1737 target = below;
1738 targetI = i;
1739 // If we were in the middle of a reply chain before this
1740 // task, it doesn't appear like the root of the chain wants
1741 // anything interesting, so drop it.
1742 replyChainEnd = -1;
1743 continue;
1744 }
1745
1746 final int flags = target.info.flags;
1747
1748 final boolean finishOnTaskLaunch =
1749 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1750 final boolean allowTaskReparenting =
1751 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1752
1753 if (target.task == task) {
1754 // We are inside of the task being reset... we'll either
1755 // finish this activity, push it out for another task,
1756 // or leave it as-is. We only do this
1757 // for activities that are not the root of the task (since
1758 // if we finish the root, we may no longer have the task!).
1759 if (taskTopI < 0) {
1760 taskTopI = targetI;
1761 }
1762 if (below != null && below.task == task) {
1763 final boolean clearWhenTaskReset =
1764 (target.intent.getFlags()
1765 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
1766 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
1767 // If this activity is sending a reply to a previous
1768 // activity, we can't do anything with it now until
1769 // we reach the start of the reply chain.
1770 // XXX note that we are assuming the result is always
1771 // to the previous activity, which is almost always
1772 // the case but we really shouldn't count on.
1773 if (replyChainEnd < 0) {
1774 replyChainEnd = targetI;
1775 }
1776 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
1777 && target.taskAffinity != null
1778 && !target.taskAffinity.equals(task.affinity)) {
1779 // If this activity has an affinity for another
1780 // task, then we need to move it out of here. We will
1781 // move it as far out of the way as possible, to the
1782 // bottom of the activity stack. This also keeps it
1783 // correctly ordered with any activities we previously
1784 // moved.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001785 ActivityRecord p = mHistory.get(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001786 if (target.taskAffinity != null
1787 && target.taskAffinity.equals(p.task.affinity)) {
1788 // If the activity currently at the bottom has the
1789 // same task affinity as the one we are moving,
1790 // then merge it into the same task.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001791 target.setTask(p.task, p.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001792 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1793 + " out to bottom task " + p.task);
1794 } else {
1795 mService.mCurTask++;
1796 if (mService.mCurTask <= 0) {
1797 mService.mCurTask = 1;
1798 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001799 target.setTask(new TaskRecord(mService.mCurTask, target.info, null),
1800 null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001801 target.task.affinityIntent = target.intent;
1802 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1803 + " out to new task " + target.task);
1804 }
1805 mService.mWindowManager.setAppGroupId(target, task.taskId);
1806 if (replyChainEnd < 0) {
1807 replyChainEnd = targetI;
1808 }
1809 int dstPos = 0;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001810 ThumbnailHolder curThumbHolder = target.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001811 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001812 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001813 if (p.finishing) {
1814 continue;
1815 }
1816 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
1817 + " out to target's task " + target.task);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001818 p.setTask(target.task, curThumbHolder, false);
1819 curThumbHolder = p.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001820 mHistory.remove(srcPos);
1821 mHistory.add(dstPos, p);
1822 mService.mWindowManager.moveAppToken(dstPos, p);
1823 mService.mWindowManager.setAppGroupId(p, p.task.taskId);
1824 dstPos++;
1825 if (VALIDATE_TOKENS) {
1826 mService.mWindowManager.validateAppTokens(mHistory);
1827 }
1828 i++;
1829 }
1830 if (taskTop == p) {
1831 taskTop = below;
1832 }
1833 if (taskTopI == replyChainEnd) {
1834 taskTopI = -1;
1835 }
1836 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001837 } else if (forceReset || finishOnTaskLaunch
1838 || clearWhenTaskReset) {
1839 // If the activity should just be removed -- either
1840 // because it asks for it, or the task should be
1841 // cleared -- then finish it and anything that is
1842 // part of its reply chain.
1843 if (clearWhenTaskReset) {
1844 // In this case, we want to finish this activity
1845 // and everything above it, so be sneaky and pretend
1846 // like these are all in the reply chain.
1847 replyChainEnd = targetI+1;
1848 while (replyChainEnd < mHistory.size() &&
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001849 (mHistory.get(
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001850 replyChainEnd)).task == task) {
1851 replyChainEnd++;
1852 }
1853 replyChainEnd--;
1854 } else if (replyChainEnd < 0) {
1855 replyChainEnd = targetI;
1856 }
1857 ActivityRecord p = null;
1858 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001859 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001860 if (p.finishing) {
1861 continue;
1862 }
1863 if (finishActivityLocked(p, srcPos,
1864 Activity.RESULT_CANCELED, null, "reset")) {
1865 replyChainEnd--;
1866 srcPos--;
1867 }
1868 }
1869 if (taskTop == p) {
1870 taskTop = below;
1871 }
1872 if (taskTopI == replyChainEnd) {
1873 taskTopI = -1;
1874 }
1875 replyChainEnd = -1;
1876 } else {
1877 // If we were in the middle of a chain, well the
1878 // activity that started it all doesn't want anything
1879 // special, so leave it all as-is.
1880 replyChainEnd = -1;
1881 }
1882 } else {
1883 // Reached the bottom of the task -- any reply chain
1884 // should be left as-is.
1885 replyChainEnd = -1;
1886 }
1887
1888 } else if (target.resultTo != null) {
1889 // If this activity is sending a reply to a previous
1890 // activity, we can't do anything with it now until
1891 // we reach the start of the reply chain.
1892 // XXX note that we are assuming the result is always
1893 // to the previous activity, which is almost always
1894 // the case but we really shouldn't count on.
1895 if (replyChainEnd < 0) {
1896 replyChainEnd = targetI;
1897 }
1898
1899 } else if (taskTopI >= 0 && allowTaskReparenting
1900 && task.affinity != null
1901 && task.affinity.equals(target.taskAffinity)) {
1902 // We are inside of another task... if this activity has
1903 // an affinity for our task, then either remove it if we are
1904 // clearing or move it over to our task. Note that
1905 // we currently punt on the case where we are resetting a
1906 // task that is not at the top but who has activities above
1907 // with an affinity to it... this is really not a normal
1908 // case, and we will need to later pull that task to the front
1909 // and usually at that point we will do the reset and pick
1910 // up those remaining activities. (This only happens if
1911 // someone starts an activity in a new task from an activity
1912 // in a task that is not currently on top.)
1913 if (forceReset || finishOnTaskLaunch) {
1914 if (replyChainEnd < 0) {
1915 replyChainEnd = targetI;
1916 }
1917 ActivityRecord p = null;
1918 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001919 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001920 if (p.finishing) {
1921 continue;
1922 }
1923 if (finishActivityLocked(p, srcPos,
1924 Activity.RESULT_CANCELED, null, "reset")) {
1925 taskTopI--;
1926 lastReparentPos--;
1927 replyChainEnd--;
1928 srcPos--;
1929 }
1930 }
1931 replyChainEnd = -1;
1932 } else {
1933 if (replyChainEnd < 0) {
1934 replyChainEnd = targetI;
1935 }
1936 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001937 ActivityRecord p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001938 if (p.finishing) {
1939 continue;
1940 }
1941 if (lastReparentPos < 0) {
1942 lastReparentPos = taskTopI;
1943 taskTop = p;
1944 } else {
1945 lastReparentPos--;
1946 }
1947 mHistory.remove(srcPos);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001948 p.setTask(task, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001949 mHistory.add(lastReparentPos, p);
1950 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
1951 + " in to resetting task " + task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001952 mService.mWindowManager.moveAppToken(lastReparentPos, p);
1953 mService.mWindowManager.setAppGroupId(p, p.task.taskId);
1954 if (VALIDATE_TOKENS) {
1955 mService.mWindowManager.validateAppTokens(mHistory);
1956 }
1957 }
1958 replyChainEnd = -1;
1959
1960 // Now we've moved it in to place... but what if this is
1961 // a singleTop activity and we have put it on top of another
1962 // instance of the same activity? Then we drop the instance
1963 // below so it remains singleTop.
1964 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
1965 for (int j=lastReparentPos-1; j>=0; j--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001966 ActivityRecord p = mHistory.get(j);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001967 if (p.finishing) {
1968 continue;
1969 }
1970 if (p.intent.getComponent().equals(target.intent.getComponent())) {
1971 if (finishActivityLocked(p, j,
1972 Activity.RESULT_CANCELED, null, "replace")) {
1973 taskTopI--;
1974 lastReparentPos--;
1975 }
1976 }
1977 }
1978 }
1979 }
1980 }
1981
1982 target = below;
1983 targetI = i;
1984 }
1985
1986 return taskTop;
1987 }
1988
1989 /**
1990 * Perform clear operation as requested by
1991 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
1992 * stack to the given task, then look for
1993 * an instance of that activity in the stack and, if found, finish all
1994 * activities on top of it and return the instance.
1995 *
1996 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001997 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001998 * or null if none was found.
1999 */
2000 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002001 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002002 int i = mHistory.size();
2003
2004 // First find the requested task.
2005 while (i > 0) {
2006 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002007 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002008 if (r.task.taskId == taskId) {
2009 i++;
2010 break;
2011 }
2012 }
2013
2014 // Now clear it.
2015 while (i > 0) {
2016 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002017 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002018 if (r.finishing) {
2019 continue;
2020 }
2021 if (r.task.taskId != taskId) {
2022 return null;
2023 }
2024 if (r.realActivity.equals(newR.realActivity)) {
2025 // Here it is! Now finish everything in front...
2026 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002027 while (i < (mHistory.size()-1)) {
2028 i++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002029 r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002030 if (r.task.taskId != taskId) {
2031 break;
2032 }
2033 if (r.finishing) {
2034 continue;
2035 }
2036 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2037 null, "clear")) {
2038 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002039 }
2040 }
2041
2042 // Finally, if this is a normal launch mode (that is, not
2043 // expecting onNewIntent()), then we will finish the current
2044 // instance of the activity so a new fresh one can be started.
2045 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2046 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
2047 if (!ret.finishing) {
2048 int index = indexOfTokenLocked(ret);
2049 if (index >= 0) {
2050 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
2051 null, "clear");
2052 }
2053 return null;
2054 }
2055 }
2056
2057 return ret;
2058 }
2059 }
2060
2061 return null;
2062 }
2063
2064 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002065 * Completely remove all activities associated with an existing
2066 * task starting at a specified index.
2067 */
2068 private final void performClearTaskAtIndexLocked(int taskId, int i) {
2069 while (i < (mHistory.size()-1)) {
2070 ActivityRecord r = mHistory.get(i);
2071 if (r.task.taskId != taskId) {
2072 // Whoops hit the end.
2073 return;
2074 }
2075 if (r.finishing) {
2076 i++;
2077 continue;
2078 }
2079 if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2080 null, "clear")) {
2081 i++;
2082 }
2083 }
2084 }
2085
2086 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002087 * Completely remove all activities associated with an existing task.
2088 */
2089 private final void performClearTaskLocked(int taskId) {
2090 int i = mHistory.size();
2091
2092 // First find the requested task.
2093 while (i > 0) {
2094 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002095 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002096 if (r.task.taskId == taskId) {
2097 i++;
2098 break;
2099 }
2100 }
2101
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002102 // Now find the start and clear it.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002103 while (i > 0) {
2104 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002105 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002106 if (r.finishing) {
2107 continue;
2108 }
2109 if (r.task.taskId != taskId) {
2110 // We hit the bottom. Now finish it all...
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002111 performClearTaskAtIndexLocked(taskId, i+1);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002112 return;
2113 }
2114 }
2115 }
2116
2117 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002118 * Find the activity in the history stack within the given task. Returns
2119 * the index within the history at which it's found, or < 0 if not found.
2120 */
2121 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2122 int i = mHistory.size();
2123 while (i > 0) {
2124 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002125 ActivityRecord candidate = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002126 if (candidate.task.taskId != task) {
2127 break;
2128 }
2129 if (candidate.realActivity.equals(r.realActivity)) {
2130 return i;
2131 }
2132 }
2133
2134 return -1;
2135 }
2136
2137 /**
2138 * Reorder the history stack so that the activity at the given index is
2139 * brought to the front.
2140 */
2141 private final ActivityRecord moveActivityToFrontLocked(int where) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002142 ActivityRecord newTop = mHistory.remove(where);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002143 int top = mHistory.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002144 ActivityRecord oldTop = mHistory.get(top-1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002145 mHistory.add(top, newTop);
2146 oldTop.frontOfTask = false;
2147 newTop.frontOfTask = true;
2148 return newTop;
2149 }
2150
2151 final int startActivityLocked(IApplicationThread caller,
2152 Intent intent, String resolvedType,
2153 Uri[] grantedUriPermissions,
2154 int grantedMode, ActivityInfo aInfo, IBinder resultTo,
2155 String resultWho, int requestCode,
2156 int callingPid, int callingUid, boolean onlyIfNeeded,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002157 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002158
2159 int err = START_SUCCESS;
2160
2161 ProcessRecord callerApp = null;
2162 if (caller != null) {
2163 callerApp = mService.getRecordForAppLocked(caller);
2164 if (callerApp != null) {
2165 callingPid = callerApp.pid;
2166 callingUid = callerApp.info.uid;
2167 } else {
2168 Slog.w(TAG, "Unable to find app for caller " + caller
2169 + " (pid=" + callingPid + ") when starting: "
2170 + intent.toString());
2171 err = START_PERMISSION_DENIED;
2172 }
2173 }
2174
2175 if (err == START_SUCCESS) {
2176 Slog.i(TAG, "Starting: " + intent + " from pid "
2177 + (callerApp != null ? callerApp.pid : callingPid));
2178 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002179
2180 ActivityRecord sourceRecord = null;
2181 ActivityRecord resultRecord = null;
2182 if (resultTo != null) {
2183 int index = indexOfTokenLocked(resultTo);
2184 if (DEBUG_RESULTS) Slog.v(
2185 TAG, "Sending result to " + resultTo + " (index " + index + ")");
2186 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002187 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002188 if (requestCode >= 0 && !sourceRecord.finishing) {
2189 resultRecord = sourceRecord;
2190 }
2191 }
2192 }
2193
2194 int launchFlags = intent.getFlags();
2195
2196 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2197 && sourceRecord != null) {
2198 // Transfer the result target from the source activity to the new
2199 // one being started, including any failures.
2200 if (requestCode >= 0) {
2201 return START_FORWARD_AND_REQUEST_CONFLICT;
2202 }
2203 resultRecord = sourceRecord.resultTo;
2204 resultWho = sourceRecord.resultWho;
2205 requestCode = sourceRecord.requestCode;
2206 sourceRecord.resultTo = null;
2207 if (resultRecord != null) {
2208 resultRecord.removeResultsLocked(
2209 sourceRecord, resultWho, requestCode);
2210 }
2211 }
2212
Dianne Hackbornefb58102010-10-14 16:47:34 -07002213 if (err == START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002214 // We couldn't find a class that can handle the given Intent.
2215 // That's the end of that!
2216 err = START_INTENT_NOT_RESOLVED;
2217 }
2218
2219 if (err == START_SUCCESS && aInfo == null) {
2220 // We couldn't find the specific class specified in the Intent.
2221 // Also the end of the line.
2222 err = START_CLASS_NOT_FOUND;
2223 }
2224
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002225 if (err != START_SUCCESS) {
2226 if (resultRecord != null) {
2227 sendActivityResultLocked(-1,
2228 resultRecord, resultWho, requestCode,
2229 Activity.RESULT_CANCELED, null);
2230 }
2231 return err;
2232 }
2233
2234 final int perm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002235 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002236 if (perm != PackageManager.PERMISSION_GRANTED) {
2237 if (resultRecord != null) {
2238 sendActivityResultLocked(-1,
2239 resultRecord, resultWho, requestCode,
2240 Activity.RESULT_CANCELED, null);
2241 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002242 String msg;
2243 if (!aInfo.exported) {
2244 msg = "Permission Denial: starting " + intent.toString()
2245 + " from " + callerApp + " (pid=" + callingPid
2246 + ", uid=" + callingUid + ")"
2247 + " not exported from uid " + aInfo.applicationInfo.uid;
2248 } else {
2249 msg = "Permission Denial: starting " + intent.toString()
2250 + " from " + callerApp + " (pid=" + callingPid
2251 + ", uid=" + callingUid + ")"
2252 + " requires " + aInfo.permission;
2253 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002254 Slog.w(TAG, msg);
2255 throw new SecurityException(msg);
2256 }
2257
2258 if (mMainStack) {
2259 if (mService.mController != null) {
2260 boolean abort = false;
2261 try {
2262 // The Intent we give to the watcher has the extra data
2263 // stripped off, since it can contain private information.
2264 Intent watchIntent = intent.cloneFilter();
2265 abort = !mService.mController.activityStarting(watchIntent,
2266 aInfo.applicationInfo.packageName);
2267 } catch (RemoteException e) {
2268 mService.mController = null;
2269 }
2270
2271 if (abort) {
2272 if (resultRecord != null) {
2273 sendActivityResultLocked(-1,
2274 resultRecord, resultWho, requestCode,
2275 Activity.RESULT_CANCELED, null);
2276 }
2277 // We pretend to the caller that it was really started, but
2278 // they will just get a cancel result.
2279 return START_SUCCESS;
2280 }
2281 }
2282 }
2283
2284 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2285 intent, resolvedType, aInfo, mService.mConfiguration,
2286 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002287 if (outActivity != null) {
2288 outActivity[0] = r;
2289 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002290
2291 if (mMainStack) {
2292 if (mResumedActivity == null
2293 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2294 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2295 PendingActivityLaunch pal = new PendingActivityLaunch();
2296 pal.r = r;
2297 pal.sourceRecord = sourceRecord;
2298 pal.grantedUriPermissions = grantedUriPermissions;
2299 pal.grantedMode = grantedMode;
2300 pal.onlyIfNeeded = onlyIfNeeded;
2301 mService.mPendingActivityLaunches.add(pal);
2302 return START_SWITCHES_CANCELED;
2303 }
2304 }
2305
2306 if (mService.mDidAppSwitch) {
2307 // This is the second allowed switch since we stopped switches,
2308 // so now just generally allow switches. Use case: user presses
2309 // home (switches disabled, switch to home, mDidAppSwitch now true);
2310 // user taps a home icon (coming from home so allowed, we hit here
2311 // and now allow anyone to switch again).
2312 mService.mAppSwitchesAllowedTime = 0;
2313 } else {
2314 mService.mDidAppSwitch = true;
2315 }
2316
2317 mService.doPendingActivityLaunchesLocked(false);
2318 }
2319
2320 return startActivityUncheckedLocked(r, sourceRecord,
2321 grantedUriPermissions, grantedMode, onlyIfNeeded, true);
2322 }
2323
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002324 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2325 if ((launchFlags &
2326 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2327 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2328 // Caller wants to appear on home activity, so before starting
2329 // their own activity we will bring home to the front.
2330 moveHomeToFrontLocked();
2331 }
2332 }
2333
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002334 final int startActivityUncheckedLocked(ActivityRecord r,
2335 ActivityRecord sourceRecord, Uri[] grantedUriPermissions,
2336 int grantedMode, boolean onlyIfNeeded, boolean doResume) {
2337 final Intent intent = r.intent;
2338 final int callingUid = r.launchedFromUid;
2339
2340 int launchFlags = intent.getFlags();
2341
2342 // We'll invoke onUserLeaving before onPause only if the launching
2343 // activity did not explicitly state that this is an automated launch.
2344 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2345 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2346 "startActivity() => mUserLeaving=" + mUserLeaving);
2347
2348 // If the caller has asked not to resume at this point, we make note
2349 // of this in the record so that we can skip it when trying to find
2350 // the top running activity.
2351 if (!doResume) {
2352 r.delayedResume = true;
2353 }
2354
2355 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2356 != 0 ? r : null;
2357
2358 // If the onlyIfNeeded flag is set, then we can do this if the activity
2359 // being launched is the same as the one making the call... or, as
2360 // a special case, if we do not know the caller then we count the
2361 // current top activity as the caller.
2362 if (onlyIfNeeded) {
2363 ActivityRecord checkedCaller = sourceRecord;
2364 if (checkedCaller == null) {
2365 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2366 }
2367 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2368 // Caller is not the same as launcher, so always needed.
2369 onlyIfNeeded = false;
2370 }
2371 }
2372
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002373 if (sourceRecord == null) {
2374 // This activity is not being started from another... in this
2375 // case we -always- start a new task.
2376 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2377 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2378 + intent);
2379 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2380 }
2381 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2382 // The original activity who is starting us is running as a single
2383 // instance... this new activity it is starting must go on its
2384 // own task.
2385 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2386 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2387 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2388 // The activity being started is a single instance... it always
2389 // gets launched into its own task.
2390 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2391 }
2392
2393 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2394 // For whatever reason this activity is being launched into a new
2395 // task... yet the caller has requested a result back. Well, that
2396 // is pretty messed up, so instead immediately send back a cancel
2397 // and let the new task continue launched as normal without a
2398 // dependency on its originator.
2399 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2400 sendActivityResultLocked(-1,
2401 r.resultTo, r.resultWho, r.requestCode,
2402 Activity.RESULT_CANCELED, null);
2403 r.resultTo = null;
2404 }
2405
2406 boolean addingToTask = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002407 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002408 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2409 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2410 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2411 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2412 // If bring to front is requested, and no result is requested, and
2413 // we can find a task that was started with this same
2414 // component, then instead of launching bring that one to the front.
2415 if (r.resultTo == null) {
2416 // See if there is a task to bring to the front. If this is
2417 // a SINGLE_INSTANCE activity, there can be one and only one
2418 // instance of it in the history, and it is always in its own
2419 // unique task, so we do a special search.
2420 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2421 ? findTaskLocked(intent, r.info)
2422 : findActivityLocked(intent, r.info);
2423 if (taskTop != null) {
2424 if (taskTop.task.intent == null) {
2425 // This task was started because of movement of
2426 // the activity based on affinity... now that we
2427 // are actually launching it, we can assign the
2428 // base intent.
2429 taskTop.task.setIntent(intent, r.info);
2430 }
2431 // If the target task is not in the front, then we need
2432 // to bring it to the front... except... well, with
2433 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2434 // to have the same behavior as if a new instance was
2435 // being started, which means not bringing it to the front
2436 // if the caller is not itself in the front.
2437 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002438 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002439 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2440 boolean callerAtFront = sourceRecord == null
2441 || curTop.task == sourceRecord.task;
2442 if (callerAtFront) {
2443 // We really do want to push this one into the
2444 // user's face, right now.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002445 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002446 moveTaskToFrontLocked(taskTop.task, r);
2447 }
2448 }
2449 // If the caller has requested that the target task be
2450 // reset, then do so.
2451 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2452 taskTop = resetTaskIfNeededLocked(taskTop, r);
2453 }
2454 if (onlyIfNeeded) {
2455 // We don't need to start a new activity, and
2456 // the client said not to do anything if that
2457 // is the case, so this is it! And for paranoia, make
2458 // sure we have correctly resumed the top activity.
2459 if (doResume) {
2460 resumeTopActivityLocked(null);
2461 }
2462 return START_RETURN_INTENT_TO_CALLER;
2463 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002464 if ((launchFlags &
2465 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2466 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2467 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002468 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002469 // not be too hard...
2470 reuseTask = taskTop.task;
2471 performClearTaskLocked(taskTop.task.taskId);
2472 reuseTask.setIntent(r.intent, r.info);
2473 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002474 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2475 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2476 // In this situation we want to remove all activities
2477 // from the task up to the one being started. In most
2478 // cases this means we are resetting the task to its
2479 // initial state.
2480 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002481 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002482 if (top != null) {
2483 if (top.frontOfTask) {
2484 // Activity aliases may mean we use different
2485 // intents for the top activity, so make sure
2486 // the task now has the identity of the new
2487 // intent.
2488 top.task.setIntent(r.intent, r.info);
2489 }
2490 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002491 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002492 } else {
2493 // A special case: we need to
2494 // start the activity because it is not currently
2495 // running, and the caller has asked to clear the
2496 // current task to have this activity at the top.
2497 addingToTask = true;
2498 // Now pretend like this activity is being started
2499 // by the top of its task, so it is put in the
2500 // right place.
2501 sourceRecord = taskTop;
2502 }
2503 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2504 // In this case the top activity on the task is the
2505 // same as the one being launched, so we take that
2506 // as a request to bring the task to the foreground.
2507 // If the top activity in the task is the root
2508 // activity, deliver this new intent to it if it
2509 // desires.
2510 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2511 && taskTop.realActivity.equals(r.realActivity)) {
2512 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2513 if (taskTop.frontOfTask) {
2514 taskTop.task.setIntent(r.intent, r.info);
2515 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002516 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002517 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2518 // In this case we are launching the root activity
2519 // of the task, but with a different intent. We
2520 // should start a new instance on top.
2521 addingToTask = true;
2522 sourceRecord = taskTop;
2523 }
2524 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2525 // In this case an activity is being launched in to an
2526 // existing task, without resetting that task. This
2527 // is typically the situation of launching an activity
2528 // from a notification or shortcut. We want to place
2529 // the new activity on top of the current task.
2530 addingToTask = true;
2531 sourceRecord = taskTop;
2532 } else if (!taskTop.task.rootWasReset) {
2533 // In this case we are launching in to an existing task
2534 // that has not yet been started from its front door.
2535 // The current task has been brought to the front.
2536 // Ideally, we'd probably like to place this new task
2537 // at the bottom of its stack, but that's a little hard
2538 // to do with the current organization of the code so
2539 // for now we'll just drop it.
2540 taskTop.task.setIntent(r.intent, r.info);
2541 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002542 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002543 // We didn't do anything... but it was needed (a.k.a., client
2544 // don't use that intent!) And for paranoia, make
2545 // sure we have correctly resumed the top activity.
2546 if (doResume) {
2547 resumeTopActivityLocked(null);
2548 }
2549 return START_TASK_TO_FRONT;
2550 }
2551 }
2552 }
2553 }
2554
2555 //String uri = r.intent.toURI();
2556 //Intent intent2 = new Intent(uri);
2557 //Slog.i(TAG, "Given intent: " + r.intent);
2558 //Slog.i(TAG, "URI is: " + uri);
2559 //Slog.i(TAG, "To intent: " + intent2);
2560
2561 if (r.packageName != null) {
2562 // If the activity being launched is the same as the one currently
2563 // at the top, then we need to check if it should only be launched
2564 // once.
2565 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2566 if (top != null && r.resultTo == null) {
2567 if (top.realActivity.equals(r.realActivity)) {
2568 if (top.app != null && top.app.thread != null) {
2569 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2570 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2571 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2572 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2573 // For paranoia, make sure we have correctly
2574 // resumed the top activity.
2575 if (doResume) {
2576 resumeTopActivityLocked(null);
2577 }
2578 if (onlyIfNeeded) {
2579 // We don't need to start a new activity, and
2580 // the client said not to do anything if that
2581 // is the case, so this is it!
2582 return START_RETURN_INTENT_TO_CALLER;
2583 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002584 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002585 return START_DELIVERED_TO_TOP;
2586 }
2587 }
2588 }
2589 }
2590
2591 } else {
2592 if (r.resultTo != null) {
2593 sendActivityResultLocked(-1,
2594 r.resultTo, r.resultWho, r.requestCode,
2595 Activity.RESULT_CANCELED, null);
2596 }
2597 return START_CLASS_NOT_FOUND;
2598 }
2599
2600 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002601 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002602
2603 // Should this be considered a new task?
2604 if (r.resultTo == null && !addingToTask
2605 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002606 if (reuseTask == null) {
2607 // todo: should do better management of integers.
2608 mService.mCurTask++;
2609 if (mService.mCurTask <= 0) {
2610 mService.mCurTask = 1;
2611 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002612 r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002613 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2614 + " in new task " + r.task);
2615 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002616 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002617 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002618 newTask = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002619 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002620
2621 } else if (sourceRecord != null) {
2622 if (!addingToTask &&
2623 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2624 // In this case, we are adding the activity to an existing
2625 // task, but the caller has asked to clear that task if the
2626 // activity is already running.
2627 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002628 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002629 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002630 if (top != null) {
2631 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002632 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002633 // For paranoia, make sure we have correctly
2634 // resumed the top activity.
2635 if (doResume) {
2636 resumeTopActivityLocked(null);
2637 }
2638 return START_DELIVERED_TO_TOP;
2639 }
2640 } else if (!addingToTask &&
2641 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2642 // In this case, we are launching an activity in our own task
2643 // that may already be running somewhere in the history, and
2644 // we want to shuffle it to the front of the stack if so.
2645 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2646 if (where >= 0) {
2647 ActivityRecord top = moveActivityToFrontLocked(where);
2648 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002649 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002650 if (doResume) {
2651 resumeTopActivityLocked(null);
2652 }
2653 return START_DELIVERED_TO_TOP;
2654 }
2655 }
2656 // An existing activity is starting this new activity, so we want
2657 // to keep the new one in the same task as the one that is starting
2658 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002659 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002660 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2661 + " in existing task " + r.task);
2662
2663 } else {
2664 // This not being started from an existing activity, and not part
2665 // of a new task... just put it in the top task, though these days
2666 // this case should never happen.
2667 final int N = mHistory.size();
2668 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002669 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002670 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002671 ? prev.task
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002672 : new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002673 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2674 + " in new guessed " + r.task);
2675 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002676
2677 if (grantedUriPermissions != null && callingUid > 0) {
2678 for (int i=0; i<grantedUriPermissions.length; i++) {
2679 mService.grantUriPermissionLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002680 grantedUriPermissions[i], grantedMode, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002681 }
2682 }
2683
2684 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002685 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002686
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002687 if (newTask) {
2688 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
2689 }
2690 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002691 startActivityLocked(r, newTask, doResume, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002692 return START_SUCCESS;
2693 }
2694
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002695 ActivityInfo resolveActivity(Intent intent, String resolvedType, boolean debug,
2696 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002697 // Collect information about the target of the Intent.
2698 ActivityInfo aInfo;
2699 try {
2700 ResolveInfo rInfo =
2701 AppGlobals.getPackageManager().resolveIntent(
2702 intent, resolvedType,
2703 PackageManager.MATCH_DEFAULT_ONLY
2704 | ActivityManagerService.STOCK_PM_FLAGS);
2705 aInfo = rInfo != null ? rInfo.activityInfo : null;
2706 } catch (RemoteException e) {
2707 aInfo = null;
2708 }
2709
2710 if (aInfo != null) {
2711 // Store the found target back into the intent, because now that
2712 // we have it we never want to do this again. For example, if the
2713 // user navigates back to this point in the history, we should
2714 // always restart the exact same activity.
2715 intent.setComponent(new ComponentName(
2716 aInfo.applicationInfo.packageName, aInfo.name));
2717
2718 // Don't debug things in the system process
2719 if (debug) {
2720 if (!aInfo.processName.equals("system")) {
2721 mService.setDebugApp(aInfo.processName, true, false);
2722 }
2723 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002724
2725 if (profileFile != null) {
2726 if (!aInfo.processName.equals("system")) {
2727 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
2728 profileFile, profileFd, autoStopProfiler);
2729 }
2730 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002731 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002732 return aInfo;
2733 }
2734
2735 final int startActivityMayWait(IApplicationThread caller, int callingUid,
2736 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2737 int grantedMode, IBinder resultTo,
2738 String resultWho, int requestCode, boolean onlyIfNeeded,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002739 boolean debug, String profileFile, ParcelFileDescriptor profileFd,
2740 boolean autoStopProfiler, WaitResult outResult, Configuration config) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002741 // Refuse possible leaked file descriptors
2742 if (intent != null && intent.hasFileDescriptors()) {
2743 throw new IllegalArgumentException("File descriptors passed in Intent");
2744 }
2745
2746 boolean componentSpecified = intent.getComponent() != null;
2747
2748 // Don't modify the client's object!
2749 intent = new Intent(intent);
2750
2751 // Collect information about the target of the Intent.
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002752 ActivityInfo aInfo = resolveActivity(intent, resolvedType, debug,
2753 profileFile, profileFd, autoStopProfiler);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002754
2755 synchronized (mService) {
2756 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002757 if (callingUid >= 0) {
2758 callingPid = -1;
2759 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002760 callingPid = Binder.getCallingPid();
2761 callingUid = Binder.getCallingUid();
2762 } else {
2763 callingPid = callingUid = -1;
2764 }
2765
2766 mConfigWillChange = config != null
2767 && mService.mConfiguration.diff(config) != 0;
2768 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2769 "Starting activity when config will change = " + mConfigWillChange);
2770
2771 final long origId = Binder.clearCallingIdentity();
2772
2773 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07002774 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002775 // This may be a heavy-weight process! Check to see if we already
2776 // have another, different heavy-weight process running.
2777 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
2778 if (mService.mHeavyWeightProcess != null &&
2779 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
2780 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
2781 int realCallingPid = callingPid;
2782 int realCallingUid = callingUid;
2783 if (caller != null) {
2784 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
2785 if (callerApp != null) {
2786 realCallingPid = callerApp.pid;
2787 realCallingUid = callerApp.info.uid;
2788 } else {
2789 Slog.w(TAG, "Unable to find app for caller " + caller
2790 + " (pid=" + realCallingPid + ") when starting: "
2791 + intent.toString());
2792 return START_PERMISSION_DENIED;
2793 }
2794 }
2795
2796 IIntentSender target = mService.getIntentSenderLocked(
2797 IActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002798 realCallingUid, null, null, 0, new Intent[] { intent },
2799 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002800 | PendingIntent.FLAG_ONE_SHOT);
2801
2802 Intent newIntent = new Intent();
2803 if (requestCode >= 0) {
2804 // Caller is requesting a result.
2805 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
2806 }
2807 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
2808 new IntentSender(target));
2809 if (mService.mHeavyWeightProcess.activities.size() > 0) {
2810 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
2811 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
2812 hist.packageName);
2813 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
2814 hist.task.taskId);
2815 }
2816 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
2817 aInfo.packageName);
2818 newIntent.setFlags(intent.getFlags());
2819 newIntent.setClassName("android",
2820 HeavyWeightSwitcherActivity.class.getName());
2821 intent = newIntent;
2822 resolvedType = null;
2823 caller = null;
2824 callingUid = Binder.getCallingUid();
2825 callingPid = Binder.getCallingPid();
2826 componentSpecified = true;
2827 try {
2828 ResolveInfo rInfo =
2829 AppGlobals.getPackageManager().resolveIntent(
2830 intent, null,
2831 PackageManager.MATCH_DEFAULT_ONLY
2832 | ActivityManagerService.STOCK_PM_FLAGS);
2833 aInfo = rInfo != null ? rInfo.activityInfo : null;
2834 } catch (RemoteException e) {
2835 aInfo = null;
2836 }
2837 }
2838 }
2839 }
2840
2841 int res = startActivityLocked(caller, intent, resolvedType,
2842 grantedUriPermissions, grantedMode, aInfo,
2843 resultTo, resultWho, requestCode, callingPid, callingUid,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002844 onlyIfNeeded, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002845
2846 if (mConfigWillChange && mMainStack) {
2847 // If the caller also wants to switch to a new configuration,
2848 // do so now. This allows a clean switch, as we are waiting
2849 // for the current activity to pause (so we will not destroy
2850 // it), and have not yet started the next activity.
2851 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
2852 "updateConfiguration()");
2853 mConfigWillChange = false;
2854 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2855 "Updating to new configuration after starting activity.");
Dianne Hackborn31ca8542011-07-19 14:58:28 -07002856 mService.updateConfigurationLocked(config, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002857 }
2858
2859 Binder.restoreCallingIdentity(origId);
2860
2861 if (outResult != null) {
2862 outResult.result = res;
2863 if (res == IActivityManager.START_SUCCESS) {
2864 mWaitingActivityLaunched.add(outResult);
2865 do {
2866 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07002867 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002868 } catch (InterruptedException e) {
2869 }
2870 } while (!outResult.timeout && outResult.who == null);
2871 } else if (res == IActivityManager.START_TASK_TO_FRONT) {
2872 ActivityRecord r = this.topRunningActivityLocked(null);
2873 if (r.nowVisible) {
2874 outResult.timeout = false;
2875 outResult.who = new ComponentName(r.info.packageName, r.info.name);
2876 outResult.totalTime = 0;
2877 outResult.thisTime = 0;
2878 } else {
2879 outResult.thisTime = SystemClock.uptimeMillis();
2880 mWaitingActivityVisible.add(outResult);
2881 do {
2882 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07002883 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002884 } catch (InterruptedException e) {
2885 }
2886 } while (!outResult.timeout && outResult.who == null);
2887 }
2888 }
2889 }
2890
2891 return res;
2892 }
2893 }
2894
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002895 final int startActivities(IApplicationThread caller, int callingUid,
2896 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
2897 if (intents == null) {
2898 throw new NullPointerException("intents is null");
2899 }
2900 if (resolvedTypes == null) {
2901 throw new NullPointerException("resolvedTypes is null");
2902 }
2903 if (intents.length != resolvedTypes.length) {
2904 throw new IllegalArgumentException("intents are length different than resolvedTypes");
2905 }
2906
2907 ActivityRecord[] outActivity = new ActivityRecord[1];
2908
2909 int callingPid;
2910 if (callingUid >= 0) {
2911 callingPid = -1;
2912 } else if (caller == null) {
2913 callingPid = Binder.getCallingPid();
2914 callingUid = Binder.getCallingUid();
2915 } else {
2916 callingPid = callingUid = -1;
2917 }
2918 final long origId = Binder.clearCallingIdentity();
2919 try {
2920 synchronized (mService) {
2921
2922 for (int i=0; i<intents.length; i++) {
2923 Intent intent = intents[i];
2924 if (intent == null) {
2925 continue;
2926 }
2927
2928 // Refuse possible leaked file descriptors
2929 if (intent != null && intent.hasFileDescriptors()) {
2930 throw new IllegalArgumentException("File descriptors passed in Intent");
2931 }
2932
2933 boolean componentSpecified = intent.getComponent() != null;
2934
2935 // Don't modify the client's object!
2936 intent = new Intent(intent);
2937
2938 // Collect information about the target of the Intent.
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002939 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i], false,
2940 null, null, false);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002941
2942 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
2943 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
2944 throw new IllegalArgumentException(
2945 "FLAG_CANT_SAVE_STATE not supported here");
2946 }
2947
2948 int res = startActivityLocked(caller, intent, resolvedTypes[i],
2949 null, 0, aInfo, resultTo, null, -1, callingPid, callingUid,
2950 false, componentSpecified, outActivity);
2951 if (res < 0) {
2952 return res;
2953 }
2954
2955 resultTo = outActivity[0];
2956 }
2957 }
2958 } finally {
2959 Binder.restoreCallingIdentity(origId);
2960 }
2961
2962 return IActivityManager.START_SUCCESS;
2963 }
2964
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002965 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
2966 long thisTime, long totalTime) {
2967 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
2968 WaitResult w = mWaitingActivityLaunched.get(i);
2969 w.timeout = timeout;
2970 if (r != null) {
2971 w.who = new ComponentName(r.info.packageName, r.info.name);
2972 }
2973 w.thisTime = thisTime;
2974 w.totalTime = totalTime;
2975 }
2976 mService.notifyAll();
2977 }
2978
2979 void reportActivityVisibleLocked(ActivityRecord r) {
2980 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
2981 WaitResult w = mWaitingActivityVisible.get(i);
2982 w.timeout = false;
2983 if (r != null) {
2984 w.who = new ComponentName(r.info.packageName, r.info.name);
2985 }
2986 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
2987 w.thisTime = w.totalTime;
2988 }
2989 mService.notifyAll();
2990 }
2991
2992 void sendActivityResultLocked(int callingUid, ActivityRecord r,
2993 String resultWho, int requestCode, int resultCode, Intent data) {
2994
2995 if (callingUid > 0) {
2996 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002997 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002998 }
2999
3000 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3001 + " : who=" + resultWho + " req=" + requestCode
3002 + " res=" + resultCode + " data=" + data);
3003 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3004 try {
3005 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3006 list.add(new ResultInfo(resultWho, requestCode,
3007 resultCode, data));
3008 r.app.thread.scheduleSendResult(r, list);
3009 return;
3010 } catch (Exception e) {
3011 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3012 }
3013 }
3014
3015 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3016 }
3017
3018 private final void stopActivityLocked(ActivityRecord r) {
3019 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3020 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3021 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3022 if (!r.finishing) {
3023 requestFinishActivityLocked(r, Activity.RESULT_CANCELED, null,
3024 "no-history");
3025 }
3026 } else if (r.app != null && r.app.thread != null) {
3027 if (mMainStack) {
3028 if (mService.mFocusedActivity == r) {
3029 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3030 }
3031 }
3032 r.resumeKeyDispatchingLocked();
3033 try {
3034 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003035 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3036 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003037 r.state = ActivityState.STOPPING;
3038 if (DEBUG_VISBILITY) Slog.v(
3039 TAG, "Stopping visible=" + r.visible + " for " + r);
3040 if (!r.visible) {
3041 mService.mWindowManager.setAppVisibility(r, false);
3042 }
3043 r.app.thread.scheduleStopActivity(r, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003044 if (mService.isSleeping()) {
3045 r.setSleeping(true);
3046 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003047 } catch (Exception e) {
3048 // Maybe just ignore exceptions here... if the process
3049 // has crashed, our death notification will clean things
3050 // up.
3051 Slog.w(TAG, "Exception thrown during pause", e);
3052 // Just in case, assume it to be stopped.
3053 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003054 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003055 r.state = ActivityState.STOPPED;
3056 if (r.configDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003057 destroyActivityLocked(r, true, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003058 }
3059 }
3060 }
3061 }
3062
3063 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3064 boolean remove) {
3065 int N = mStoppingActivities.size();
3066 if (N <= 0) return null;
3067
3068 ArrayList<ActivityRecord> stops = null;
3069
3070 final boolean nowVisible = mResumedActivity != null
3071 && mResumedActivity.nowVisible
3072 && !mResumedActivity.waitingVisible;
3073 for (int i=0; i<N; i++) {
3074 ActivityRecord s = mStoppingActivities.get(i);
3075 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3076 + nowVisible + " waitingVisible=" + s.waitingVisible
3077 + " finishing=" + s.finishing);
3078 if (s.waitingVisible && nowVisible) {
3079 mWaitingVisibleActivities.remove(s);
3080 s.waitingVisible = false;
3081 if (s.finishing) {
3082 // If this activity is finishing, it is sitting on top of
3083 // everyone else but we now know it is no longer needed...
3084 // so get rid of it. Otherwise, we need to go through the
3085 // normal flow and hide it once we determine that it is
3086 // hidden by the activities in front of it.
3087 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
3088 mService.mWindowManager.setAppVisibility(s, false);
3089 }
3090 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003091 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003092 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3093 if (stops == null) {
3094 stops = new ArrayList<ActivityRecord>();
3095 }
3096 stops.add(s);
3097 mStoppingActivities.remove(i);
3098 N--;
3099 i--;
3100 }
3101 }
3102
3103 return stops;
3104 }
3105
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003106 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003107 Configuration config) {
3108 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3109
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003110 ActivityRecord res = null;
3111
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003112 ArrayList<ActivityRecord> stops = null;
3113 ArrayList<ActivityRecord> finishes = null;
3114 ArrayList<ActivityRecord> thumbnails = null;
3115 int NS = 0;
3116 int NF = 0;
3117 int NT = 0;
3118 IApplicationThread sendThumbnail = null;
3119 boolean booting = false;
3120 boolean enableScreen = false;
3121
3122 synchronized (mService) {
3123 if (token != null) {
3124 mHandler.removeMessages(IDLE_TIMEOUT_MSG, token);
3125 }
3126
3127 // Get the activity record.
3128 int index = indexOfTokenLocked(token);
3129 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003130 ActivityRecord r = mHistory.get(index);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003131 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003132
3133 if (fromTimeout) {
3134 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3135 }
3136
3137 // This is a hack to semi-deal with a race condition
3138 // in the client where it can be constructed with a
3139 // newer configuration from when we asked it to launch.
3140 // We'll update with whatever configuration it now says
3141 // it used to launch.
3142 if (config != null) {
3143 r.configuration = config;
3144 }
3145
3146 // No longer need to keep the device awake.
3147 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3148 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3149 mLaunchingActivity.release();
3150 }
3151
3152 // We are now idle. If someone is waiting for a thumbnail from
3153 // us, we can now deliver.
3154 r.idle = true;
3155 mService.scheduleAppGcsLocked();
3156 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3157 sendThumbnail = r.app.thread;
3158 r.thumbnailNeeded = false;
3159 }
3160
3161 // If this activity is fullscreen, set up to hide those under it.
3162
3163 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3164 ensureActivitiesVisibleLocked(null, 0);
3165
3166 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3167 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003168 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003169 mService.mBooted = true;
3170 enableScreen = true;
3171 }
3172 }
3173
3174 } else if (fromTimeout) {
3175 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3176 }
3177
3178 // Atomically retrieve all of the other things to do.
3179 stops = processStoppingActivitiesLocked(true);
3180 NS = stops != null ? stops.size() : 0;
3181 if ((NF=mFinishingActivities.size()) > 0) {
3182 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3183 mFinishingActivities.clear();
3184 }
3185 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3186 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3187 mService.mCancelledThumbnails.clear();
3188 }
3189
3190 if (mMainStack) {
3191 booting = mService.mBooting;
3192 mService.mBooting = false;
3193 }
3194 }
3195
3196 int i;
3197
3198 // Send thumbnail if requested.
3199 if (sendThumbnail != null) {
3200 try {
3201 sendThumbnail.requestThumbnail(token);
3202 } catch (Exception e) {
3203 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3204 mService.sendPendingThumbnail(null, token, null, null, true);
3205 }
3206 }
3207
3208 // Stop any activities that are scheduled to do so but have been
3209 // waiting for the next one to start.
3210 for (i=0; i<NS; i++) {
3211 ActivityRecord r = (ActivityRecord)stops.get(i);
3212 synchronized (mService) {
3213 if (r.finishing) {
3214 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY);
3215 } else {
3216 stopActivityLocked(r);
3217 }
3218 }
3219 }
3220
3221 // Finish any activities that are scheduled to do so but have been
3222 // waiting for the next one to start.
3223 for (i=0; i<NF; i++) {
3224 ActivityRecord r = (ActivityRecord)finishes.get(i);
3225 synchronized (mService) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003226 destroyActivityLocked(r, true, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003227 }
3228 }
3229
3230 // Report back to any thumbnail receivers.
3231 for (i=0; i<NT; i++) {
3232 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3233 mService.sendPendingThumbnail(r, null, null, null, true);
3234 }
3235
3236 if (booting) {
3237 mService.finishBooting();
3238 }
3239
3240 mService.trimApplications();
3241 //dump();
3242 //mWindowManager.dump();
3243
3244 if (enableScreen) {
3245 mService.enableScreenAfterBoot();
3246 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003247
3248 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003249 }
3250
3251 /**
3252 * @return Returns true if the activity is being finished, false if for
3253 * some reason it is being left as-is.
3254 */
3255 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
3256 Intent resultData, String reason) {
3257 if (DEBUG_RESULTS) Slog.v(
3258 TAG, "Finishing activity: token=" + token
3259 + ", result=" + resultCode + ", data=" + resultData);
3260
3261 int index = indexOfTokenLocked(token);
3262 if (index < 0) {
3263 return false;
3264 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003265 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003266
3267 // Is this the last activity left?
3268 boolean lastActivity = true;
3269 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003270 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003271 if (!p.finishing && p != r) {
3272 lastActivity = false;
3273 break;
3274 }
3275 }
3276
3277 // If this is the last activity, but it is the home activity, then
3278 // just don't finish it.
3279 if (lastActivity) {
3280 if (r.intent.hasCategory(Intent.CATEGORY_HOME)) {
3281 return false;
3282 }
3283 }
3284
3285 finishActivityLocked(r, index, resultCode, resultData, reason);
3286 return true;
3287 }
3288
3289 /**
3290 * @return Returns true if this activity has been removed from the history
3291 * list, or false if it is still in the list and will be removed later.
3292 */
3293 final boolean finishActivityLocked(ActivityRecord r, int index,
3294 int resultCode, Intent resultData, String reason) {
3295 if (r.finishing) {
3296 Slog.w(TAG, "Duplicate finish request for " + r);
3297 return false;
3298 }
3299
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003300 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003301 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3302 System.identityHashCode(r),
3303 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003304 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003305 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003306 if (next.task == r.task) {
3307 if (r.frontOfTask) {
3308 // The next activity is now the front of the task.
3309 next.frontOfTask = true;
3310 }
3311 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3312 // If the caller asked that this activity (and all above it)
3313 // be cleared when the task is reset, don't lose that information,
3314 // but propagate it up to the next activity.
3315 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3316 }
3317 }
3318 }
3319
3320 r.pauseKeyDispatchingLocked();
3321 if (mMainStack) {
3322 if (mService.mFocusedActivity == r) {
3323 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3324 }
3325 }
3326
3327 // send the result
3328 ActivityRecord resultTo = r.resultTo;
3329 if (resultTo != null) {
3330 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3331 + " who=" + r.resultWho + " req=" + r.requestCode
3332 + " res=" + resultCode + " data=" + resultData);
3333 if (r.info.applicationInfo.uid > 0) {
3334 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
Dianne Hackborna1c69e02010-09-01 22:55:02 -07003335 resultTo.packageName, resultData,
3336 resultTo.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003337 }
3338 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3339 resultData);
3340 r.resultTo = null;
3341 }
3342 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3343
3344 // Make sure this HistoryRecord is not holding on to other resources,
3345 // because clients have remote IPC references to this object so we
3346 // can't assume that will go away and want to avoid circular IPC refs.
3347 r.results = null;
3348 r.pendingResults = null;
3349 r.newIntents = null;
3350 r.icicle = null;
3351
3352 if (mService.mPendingThumbnails.size() > 0) {
3353 // There are clients waiting to receive thumbnails so, in case
3354 // this is an activity that someone is waiting for, add it
3355 // to the pending list so we can correctly update the clients.
3356 mService.mCancelledThumbnails.add(r);
3357 }
3358
3359 if (mResumedActivity == r) {
3360 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003361 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003362 if (DEBUG_TRANSITION) Slog.v(TAG,
3363 "Prepare close transition: finishing " + r);
3364 mService.mWindowManager.prepareAppTransition(endTask
3365 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003366 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003367
3368 // Tell window manager to prepare for this one to be removed.
3369 mService.mWindowManager.setAppVisibility(r, false);
3370
3371 if (mPausingActivity == null) {
3372 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3373 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3374 startPausingLocked(false, false);
3375 }
3376
3377 } else if (r.state != ActivityState.PAUSING) {
3378 // If the activity is PAUSING, we will complete the finish once
3379 // it is done pausing; else we can just directly finish it here.
3380 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3381 return finishCurrentActivityLocked(r, index,
3382 FINISH_AFTER_PAUSE) == null;
3383 } else {
3384 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3385 }
3386
3387 return false;
3388 }
3389
3390 private static final int FINISH_IMMEDIATELY = 0;
3391 private static final int FINISH_AFTER_PAUSE = 1;
3392 private static final int FINISH_AFTER_VISIBLE = 2;
3393
3394 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3395 int mode) {
3396 final int index = indexOfTokenLocked(r);
3397 if (index < 0) {
3398 return null;
3399 }
3400
3401 return finishCurrentActivityLocked(r, index, mode);
3402 }
3403
3404 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3405 int index, int mode) {
3406 // First things first: if this activity is currently visible,
3407 // and the resumed activity is not yet visible, then hold off on
3408 // finishing until the resumed one becomes visible.
3409 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3410 if (!mStoppingActivities.contains(r)) {
3411 mStoppingActivities.add(r);
3412 if (mStoppingActivities.size() > 3) {
3413 // If we already have a few activities waiting to stop,
3414 // then give up on things going idle and start clearing
3415 // them out.
3416 Message msg = Message.obtain();
3417 msg.what = IDLE_NOW_MSG;
3418 mHandler.sendMessage(msg);
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}