blob: f38504227d4ff47f2b6e78285ea98b554a5852de [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;
24import android.app.AppGlobals;
25import android.app.IActivityManager;
26import static android.app.IActivityManager.START_CLASS_NOT_FOUND;
27import static android.app.IActivityManager.START_DELIVERED_TO_TOP;
28import static android.app.IActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
29import static android.app.IActivityManager.START_INTENT_NOT_RESOLVED;
30import static android.app.IActivityManager.START_PERMISSION_DENIED;
31import static android.app.IActivityManager.START_RETURN_INTENT_TO_CALLER;
32import static android.app.IActivityManager.START_SUCCESS;
33import static android.app.IActivityManager.START_SWITCHES_CANCELED;
34import static android.app.IActivityManager.START_TASK_TO_FRONT;
35import android.app.IApplicationThread;
36import android.app.PendingIntent;
37import android.app.ResultInfo;
38import android.app.IActivityManager.WaitResult;
39import android.content.ComponentName;
40import android.content.Context;
41import android.content.IIntentSender;
42import android.content.Intent;
43import android.content.IntentSender;
44import android.content.pm.ActivityInfo;
45import android.content.pm.ApplicationInfo;
46import android.content.pm.PackageManager;
47import android.content.pm.ResolveInfo;
48import android.content.res.Configuration;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -080049import android.content.res.Resources;
50import android.graphics.Bitmap;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070051import android.net.Uri;
52import android.os.Binder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070053import android.os.Handler;
54import android.os.IBinder;
55import android.os.Message;
56import android.os.PowerManager;
57import android.os.RemoteException;
58import android.os.SystemClock;
59import android.util.EventLog;
60import android.util.Log;
61import android.util.Slog;
62import android.view.WindowManagerPolicy;
63
64import java.lang.ref.WeakReference;
65import java.util.ArrayList;
66import java.util.Iterator;
67import java.util.List;
68
69/**
70 * State and management of a single stack of activities.
71 */
72public class ActivityStack {
73 static final String TAG = ActivityManagerService.TAG;
74 static final boolean localLOGV = ActivityManagerService.localLOGV;
75 static final boolean DEBUG_SWITCH = ActivityManagerService.DEBUG_SWITCH;
76 static final boolean DEBUG_PAUSE = ActivityManagerService.DEBUG_PAUSE;
77 static final boolean DEBUG_VISBILITY = ActivityManagerService.DEBUG_VISBILITY;
78 static final boolean DEBUG_USER_LEAVING = ActivityManagerService.DEBUG_USER_LEAVING;
79 static final boolean DEBUG_TRANSITION = ActivityManagerService.DEBUG_TRANSITION;
80 static final boolean DEBUG_RESULTS = ActivityManagerService.DEBUG_RESULTS;
81 static final boolean DEBUG_CONFIGURATION = ActivityManagerService.DEBUG_CONFIGURATION;
82 static final boolean DEBUG_TASKS = ActivityManagerService.DEBUG_TASKS;
83
84 static final boolean VALIDATE_TOKENS = ActivityManagerService.VALIDATE_TOKENS;
85
86 // How long we wait until giving up on the last activity telling us it
87 // is idle.
88 static final int IDLE_TIMEOUT = 10*1000;
89
90 // How long we wait until giving up on the last activity to pause. This
91 // is short because it directly impacts the responsiveness of starting the
92 // next activity.
93 static final int PAUSE_TIMEOUT = 500;
94
Dianne Hackborn4eba96b2011-01-21 13:34:36 -080095 // How long we can hold the sleep wake lock before giving up.
96 static final int SLEEP_TIMEOUT = 5*1000;
97
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070098 // How long we can hold the launch wake lock before giving up.
99 static final int LAUNCH_TIMEOUT = 10*1000;
100
101 // How long we wait until giving up on an activity telling us it has
102 // finished destroying itself.
103 static final int DESTROY_TIMEOUT = 10*1000;
104
105 // How long until we reset a task when the user returns to it. Currently
Dianne Hackborn621e17d2010-11-22 15:59:56 -0800106 // disabled.
107 static final long ACTIVITY_INACTIVE_RESET_TIME = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700108
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700109 // How long between activity launches that we consider safe to not warn
110 // the user about an unexpected activity being launched on top.
111 static final long START_WARN_TIME = 5*1000;
112
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700113 // Set to false to disable the preview that is shown while a new activity
114 // is being started.
115 static final boolean SHOW_APP_STARTING_PREVIEW = true;
116
117 enum ActivityState {
118 INITIALIZING,
119 RESUMED,
120 PAUSING,
121 PAUSED,
122 STOPPING,
123 STOPPED,
124 FINISHING,
125 DESTROYING,
126 DESTROYED
127 }
128
129 final ActivityManagerService mService;
130 final boolean mMainStack;
131
132 final Context mContext;
133
134 /**
135 * The back history of all previous (and possibly still
136 * running) activities. It contains HistoryRecord objects.
137 */
138 final ArrayList mHistory = new ArrayList();
139
140 /**
141 * List of running activities, sorted by recent usage.
142 * The first entry in the list is the least recently used.
143 * It contains HistoryRecord objects.
144 */
145 final ArrayList mLRUActivities = new ArrayList();
146
147 /**
148 * List of activities that are waiting for a new activity
149 * to become visible before completing whatever operation they are
150 * supposed to do.
151 */
152 final ArrayList<ActivityRecord> mWaitingVisibleActivities
153 = new ArrayList<ActivityRecord>();
154
155 /**
156 * List of activities that are ready to be stopped, but waiting
157 * for the next activity to settle down before doing so. It contains
158 * HistoryRecord objects.
159 */
160 final ArrayList<ActivityRecord> mStoppingActivities
161 = new ArrayList<ActivityRecord>();
162
163 /**
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800164 * List of activities that are in the process of going to sleep.
165 */
166 final ArrayList<ActivityRecord> mGoingToSleepActivities
167 = new ArrayList<ActivityRecord>();
168
169 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700170 * Animations that for the current transition have requested not to
171 * be considered for the transition animation.
172 */
173 final ArrayList<ActivityRecord> mNoAnimActivities
174 = new ArrayList<ActivityRecord>();
175
176 /**
177 * List of activities that are ready to be finished, but waiting
178 * for the previous activity to settle down before doing so. It contains
179 * HistoryRecord objects.
180 */
181 final ArrayList<ActivityRecord> mFinishingActivities
182 = new ArrayList<ActivityRecord>();
183
184 /**
185 * List of people waiting to find out about the next launched activity.
186 */
187 final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched
188 = new ArrayList<IActivityManager.WaitResult>();
189
190 /**
191 * List of people waiting to find out about the next visible activity.
192 */
193 final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible
194 = new ArrayList<IActivityManager.WaitResult>();
195
196 /**
197 * Set when the system is going to sleep, until we have
198 * successfully paused the current activity and released our wake lock.
199 * At that point the system is allowed to actually sleep.
200 */
201 final PowerManager.WakeLock mGoingToSleep;
202
203 /**
204 * We don't want to allow the device to go to sleep while in the process
205 * of launching an activity. This is primarily to allow alarm intent
206 * receivers to launch an activity and get that to run before the device
207 * goes back to sleep.
208 */
209 final PowerManager.WakeLock mLaunchingActivity;
210
211 /**
212 * When we are in the process of pausing an activity, before starting the
213 * next one, this variable holds the activity that is currently being paused.
214 */
215 ActivityRecord mPausingActivity = null;
216
217 /**
218 * This is the last activity that we put into the paused state. This is
219 * used to determine if we need to do an activity transition while sleeping,
220 * when we normally hold the top activity paused.
221 */
222 ActivityRecord mLastPausedActivity = null;
223
224 /**
225 * Current activity that is resumed, or null if there is none.
226 */
227 ActivityRecord mResumedActivity = null;
228
229 /**
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700230 * This is the last activity that has been started. It is only used to
231 * identify when multiple activities are started at once so that the user
232 * can be warned they may not be in the activity they think they are.
233 */
234 ActivityRecord mLastStartedActivity = null;
235
236 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700237 * Set when we know we are going to be calling updateConfiguration()
238 * soon, so want to skip intermediate config checks.
239 */
240 boolean mConfigWillChange;
241
242 /**
243 * Set to indicate whether to issue an onUserLeaving callback when a
244 * newly launched activity is being brought in front of us.
245 */
246 boolean mUserLeaving = false;
247
248 long mInitialStartTime = 0;
249
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800250 /**
251 * Set when we have taken too long waiting to go to sleep.
252 */
253 boolean mSleepTimeout = false;
254
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800255 int mThumbnailWidth = -1;
256 int mThumbnailHeight = -1;
257
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800258 static final int SLEEP_TIMEOUT_MSG = 8;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700259 static final int PAUSE_TIMEOUT_MSG = 9;
260 static final int IDLE_TIMEOUT_MSG = 10;
261 static final int IDLE_NOW_MSG = 11;
262 static final int LAUNCH_TIMEOUT_MSG = 16;
263 static final int DESTROY_TIMEOUT_MSG = 17;
264 static final int RESUME_TOP_ACTIVITY_MSG = 19;
265
266 final Handler mHandler = new Handler() {
267 //public Handler() {
268 // if (localLOGV) Slog.v(TAG, "Handler started!");
269 //}
270
271 public void handleMessage(Message msg) {
272 switch (msg.what) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800273 case SLEEP_TIMEOUT_MSG: {
274 if (mService.isSleeping()) {
275 Slog.w(TAG, "Sleep timeout! Sleeping now.");
276 mSleepTimeout = true;
277 checkReadyForSleepLocked();
278 }
279 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700280 case PAUSE_TIMEOUT_MSG: {
281 IBinder token = (IBinder)msg.obj;
282 // We don't at this point know if the activity is fullscreen,
283 // so we need to be conservative and assume it isn't.
284 Slog.w(TAG, "Activity pause timeout for " + token);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800285 activityPaused(token, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700286 } break;
287 case IDLE_TIMEOUT_MSG: {
288 if (mService.mDidDexOpt) {
289 mService.mDidDexOpt = false;
290 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
291 nmsg.obj = msg.obj;
292 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
293 return;
294 }
295 // We don't at this point know if the activity is fullscreen,
296 // so we need to be conservative and assume it isn't.
297 IBinder token = (IBinder)msg.obj;
298 Slog.w(TAG, "Activity idle timeout for " + token);
299 activityIdleInternal(token, true, null);
300 } break;
301 case DESTROY_TIMEOUT_MSG: {
302 IBinder token = (IBinder)msg.obj;
303 // We don't at this point know if the activity is fullscreen,
304 // so we need to be conservative and assume it isn't.
305 Slog.w(TAG, "Activity destroy timeout for " + token);
306 activityDestroyed(token);
307 } break;
308 case IDLE_NOW_MSG: {
309 IBinder token = (IBinder)msg.obj;
310 activityIdleInternal(token, false, null);
311 } break;
312 case LAUNCH_TIMEOUT_MSG: {
313 if (mService.mDidDexOpt) {
314 mService.mDidDexOpt = false;
315 Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
316 mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
317 return;
318 }
319 synchronized (mService) {
320 if (mLaunchingActivity.isHeld()) {
321 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
322 mLaunchingActivity.release();
323 }
324 }
325 } break;
326 case RESUME_TOP_ACTIVITY_MSG: {
327 synchronized (mService) {
328 resumeTopActivityLocked(null);
329 }
330 } break;
331 }
332 }
333 };
334
335 ActivityStack(ActivityManagerService service, Context context, boolean mainStack) {
336 mService = service;
337 mContext = context;
338 mMainStack = mainStack;
339 PowerManager pm =
340 (PowerManager)context.getSystemService(Context.POWER_SERVICE);
341 mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
342 mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
343 mLaunchingActivity.setReferenceCounted(false);
344 }
345
346 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
347 int i = mHistory.size()-1;
348 while (i >= 0) {
349 ActivityRecord r = (ActivityRecord)mHistory.get(i);
350 if (!r.finishing && r != notTop) {
351 return r;
352 }
353 i--;
354 }
355 return null;
356 }
357
358 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
359 int i = mHistory.size()-1;
360 while (i >= 0) {
361 ActivityRecord r = (ActivityRecord)mHistory.get(i);
362 if (!r.finishing && !r.delayedResume && r != notTop) {
363 return r;
364 }
365 i--;
366 }
367 return null;
368 }
369
370 /**
371 * This is a simplified version of topRunningActivityLocked that provides a number of
372 * optional skip-over modes. It is intended for use with the ActivityController hook only.
373 *
374 * @param token If non-null, any history records matching this token will be skipped.
375 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
376 *
377 * @return Returns the HistoryRecord of the next activity on the stack.
378 */
379 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
380 int i = mHistory.size()-1;
381 while (i >= 0) {
382 ActivityRecord r = (ActivityRecord)mHistory.get(i);
383 // Note: the taskId check depends on real taskId fields being non-zero
384 if (!r.finishing && (token != r) && (taskId != r.task.taskId)) {
385 return r;
386 }
387 i--;
388 }
389 return null;
390 }
391
392 final int indexOfTokenLocked(IBinder token) {
393 int count = mHistory.size();
394
395 // convert the token to an entry in the history.
396 int index = -1;
397 for (int i=count-1; i>=0; i--) {
398 Object o = mHistory.get(i);
399 if (o == token) {
400 index = i;
401 break;
402 }
403 }
404
405 return index;
406 }
407
408 private final boolean updateLRUListLocked(ActivityRecord r) {
409 final boolean hadit = mLRUActivities.remove(r);
410 mLRUActivities.add(r);
411 return hadit;
412 }
413
414 /**
415 * Returns the top activity in any existing task matching the given
416 * Intent. Returns null if no such task is found.
417 */
418 private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
419 ComponentName cls = intent.getComponent();
420 if (info.targetActivity != null) {
421 cls = new ComponentName(info.packageName, info.targetActivity);
422 }
423
424 TaskRecord cp = null;
425
426 final int N = mHistory.size();
427 for (int i=(N-1); i>=0; i--) {
428 ActivityRecord r = (ActivityRecord)mHistory.get(i);
429 if (!r.finishing && r.task != cp
430 && r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
431 cp = r.task;
432 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
433 // + "/aff=" + r.task.affinity + " to new cls="
434 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
435 if (r.task.affinity != null) {
436 if (r.task.affinity.equals(info.taskAffinity)) {
437 //Slog.i(TAG, "Found matching affinity!");
438 return r;
439 }
440 } else if (r.task.intent != null
441 && r.task.intent.getComponent().equals(cls)) {
442 //Slog.i(TAG, "Found matching class!");
443 //dump();
444 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
445 return r;
446 } else if (r.task.affinityIntent != null
447 && r.task.affinityIntent.getComponent().equals(cls)) {
448 //Slog.i(TAG, "Found matching class!");
449 //dump();
450 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
451 return r;
452 }
453 }
454 }
455
456 return null;
457 }
458
459 /**
460 * Returns the first activity (starting from the top of the stack) that
461 * is the same as the given activity. Returns null if no such activity
462 * is found.
463 */
464 private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
465 ComponentName cls = intent.getComponent();
466 if (info.targetActivity != null) {
467 cls = new ComponentName(info.packageName, info.targetActivity);
468 }
469
470 final int N = mHistory.size();
471 for (int i=(N-1); i>=0; i--) {
472 ActivityRecord r = (ActivityRecord)mHistory.get(i);
473 if (!r.finishing) {
474 if (r.intent.getComponent().equals(cls)) {
475 //Slog.i(TAG, "Found matching class!");
476 //dump();
477 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
478 return r;
479 }
480 }
481 }
482
483 return null;
484 }
485
486 final boolean realStartActivityLocked(ActivityRecord r,
487 ProcessRecord app, boolean andResume, boolean checkConfig)
488 throws RemoteException {
489
490 r.startFreezingScreenLocked(app, 0);
491 mService.mWindowManager.setAppVisibility(r, true);
492
493 // Have the window manager re-evaluate the orientation of
494 // the screen based on the new activity order. Note that
495 // as a result of this, it can call back into the activity
496 // manager with a new orientation. We don't care about that,
497 // because the activity is not currently running so we are
498 // just restarting it anyway.
499 if (checkConfig) {
500 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
501 mService.mConfiguration,
502 r.mayFreezeScreenLocked(app) ? r : null);
503 mService.updateConfigurationLocked(config, r);
504 }
505
506 r.app = app;
507
508 if (localLOGV) Slog.v(TAG, "Launching: " + r);
509
510 int idx = app.activities.indexOf(r);
511 if (idx < 0) {
512 app.activities.add(r);
513 }
514 mService.updateLruProcessLocked(app, true, true);
515
516 try {
517 if (app.thread == null) {
518 throw new RemoteException();
519 }
520 List<ResultInfo> results = null;
521 List<Intent> newIntents = null;
522 if (andResume) {
523 results = r.results;
524 newIntents = r.newIntents;
525 }
526 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
527 + " icicle=" + r.icicle
528 + " with results=" + results + " newIntents=" + newIntents
529 + " andResume=" + andResume);
530 if (andResume) {
531 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
532 System.identityHashCode(r),
533 r.task.taskId, r.shortComponentName);
534 }
535 if (r.isHomeActivity) {
536 mService.mHomeProcess = app;
537 }
538 mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800539 r.sleeping = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400540 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700541 app.thread.scheduleLaunchActivity(new Intent(r.intent), r,
542 System.identityHashCode(r),
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400543 r.info, mService.compatibilityInfoForPackageLocked(r.info.applicationInfo),
544 r.icicle, results, newIntents, !andResume,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700545 mService.isNextTransitionForward());
546
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700547 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700548 // This may be a heavy-weight process! Note that the package
549 // manager will ensure that only activity can run in the main
550 // process of the .apk, which is the only thing that will be
551 // considered heavy-weight.
552 if (app.processName.equals(app.info.packageName)) {
553 if (mService.mHeavyWeightProcess != null
554 && mService.mHeavyWeightProcess != app) {
555 Log.w(TAG, "Starting new heavy weight process " + app
556 + " when already running "
557 + mService.mHeavyWeightProcess);
558 }
559 mService.mHeavyWeightProcess = app;
560 Message msg = mService.mHandler.obtainMessage(
561 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
562 msg.obj = r;
563 mService.mHandler.sendMessage(msg);
564 }
565 }
566
567 } catch (RemoteException e) {
568 if (r.launchFailed) {
569 // This is the second time we failed -- finish activity
570 // and give up.
571 Slog.e(TAG, "Second failure launching "
572 + r.intent.getComponent().flattenToShortString()
573 + ", giving up", e);
574 mService.appDiedLocked(app, app.pid, app.thread);
575 requestFinishActivityLocked(r, Activity.RESULT_CANCELED, null,
576 "2nd-crash");
577 return false;
578 }
579
580 // This is the first time we failed -- restart process and
581 // retry.
582 app.activities.remove(r);
583 throw e;
584 }
585
586 r.launchFailed = false;
587 if (updateLRUListLocked(r)) {
588 Slog.w(TAG, "Activity " + r
589 + " being launched, but already in LRU list");
590 }
591
592 if (andResume) {
593 // As part of the process of launching, ActivityThread also performs
594 // a resume.
595 r.state = ActivityState.RESUMED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700596 r.stopped = false;
597 mResumedActivity = r;
598 r.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -0800599 if (mMainStack) {
600 mService.addRecentTaskLocked(r.task);
601 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700602 completeResumeLocked(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800603 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700604 } else {
605 // This activity is not starting in the resumed state... which
606 // should look like we asked it to pause+stop (but remain visible),
607 // and it has done so and reported back the current icicle and
608 // other state.
609 r.state = ActivityState.STOPPED;
610 r.stopped = true;
611 }
612
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800613 r.icicle = null;
614 r.haveState = false;
615
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700616 // Launch the new version setup screen if needed. We do this -after-
617 // launching the initial activity (that is, home), so that it can have
618 // a chance to initialize itself while in the background, making the
619 // switch back to it faster and look better.
620 if (mMainStack) {
621 mService.startSetupActivityLocked();
622 }
623
624 return true;
625 }
626
627 private final void startSpecificActivityLocked(ActivityRecord r,
628 boolean andResume, boolean checkConfig) {
629 // Is this activity's application already running?
630 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
631 r.info.applicationInfo.uid);
632
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700633 if (r.launchTime == 0) {
634 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700635 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700636 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700637 }
638 } else if (mInitialStartTime == 0) {
639 mInitialStartTime = SystemClock.uptimeMillis();
640 }
641
642 if (app != null && app.thread != null) {
643 try {
644 realStartActivityLocked(r, app, andResume, checkConfig);
645 return;
646 } catch (RemoteException e) {
647 Slog.w(TAG, "Exception when starting activity "
648 + r.intent.getComponent().flattenToShortString(), e);
649 }
650
651 // If a dead object exception was thrown -- fall through to
652 // restart the application.
653 }
654
655 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
656 "activity", r.intent.getComponent(), false);
657 }
658
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800659 void stopIfSleepingLocked() {
660 if (mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700661 if (!mGoingToSleep.isHeld()) {
662 mGoingToSleep.acquire();
663 if (mLaunchingActivity.isHeld()) {
664 mLaunchingActivity.release();
665 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
666 }
667 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800668 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
669 Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
670 mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
671 checkReadyForSleepLocked();
672 }
673 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700674
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800675 void awakeFromSleepingLocked() {
676 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
677 mSleepTimeout = false;
678 if (mGoingToSleep.isHeld()) {
679 mGoingToSleep.release();
680 }
681 // Ensure activities are no longer sleeping.
682 for (int i=mHistory.size()-1; i>=0; i--) {
683 ActivityRecord r = (ActivityRecord)mHistory.get(i);
684 r.setSleeping(false);
685 }
686 mGoingToSleepActivities.clear();
687 }
688
689 void activitySleptLocked(ActivityRecord r) {
690 mGoingToSleepActivities.remove(r);
691 checkReadyForSleepLocked();
692 }
693
694 void checkReadyForSleepLocked() {
695 if (!mService.isSleeping()) {
696 // Do not care.
697 return;
698 }
699
700 if (!mSleepTimeout) {
701 if (mResumedActivity != null) {
702 // Still have something resumed; can't sleep until it is paused.
703 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700704 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
705 startPausingLocked(false, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800706 return;
707 }
708 if (mPausingActivity != null) {
709 // Still waiting for something to pause; can't sleep yet.
710 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
711 return;
712 }
713
714 if (mStoppingActivities.size() > 0) {
715 // Still need to tell some activities to stop; can't sleep yet.
716 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
717 + mStoppingActivities.size() + " activities");
718 Message msg = Message.obtain();
719 msg.what = IDLE_NOW_MSG;
720 mHandler.sendMessage(msg);
721 return;
722 }
723
724 ensureActivitiesVisibleLocked(null, 0);
725
726 // Make sure any stopped but visible activities are now sleeping.
727 // This ensures that the activity's onStop() is called.
728 for (int i=mHistory.size()-1; i>=0; i--) {
729 ActivityRecord r = (ActivityRecord)mHistory.get(i);
730 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
731 r.setSleeping(true);
732 }
733 }
734
735 if (mGoingToSleepActivities.size() > 0) {
736 // Still need to tell some activities to sleep; can't sleep yet.
737 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
738 + mGoingToSleepActivities.size() + " activities");
739 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700740 }
741 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800742
743 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
744
745 if (mGoingToSleep.isHeld()) {
746 mGoingToSleep.release();
747 }
748 if (mService.mShuttingDown) {
749 mService.notifyAll();
750 }
751
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700752 }
753
Dianne Hackbornd2835932010-12-13 16:28:46 -0800754 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -0800755 if (who.noDisplay) {
756 return null;
757 }
758
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800759 Resources res = mService.mContext.getResources();
760 int w = mThumbnailWidth;
761 int h = mThumbnailHeight;
762 if (w < 0) {
763 mThumbnailWidth = w =
764 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
765 mThumbnailHeight = h =
766 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
767 }
768
769 if (w > 0) {
Dianne Hackborn7c8a4b32010-12-15 14:58:00 -0800770 return mService.mWindowManager.screenshotApplications(who, w, h);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800771 }
772 return null;
773 }
774
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700775 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
776 if (mPausingActivity != null) {
777 RuntimeException e = new RuntimeException();
778 Slog.e(TAG, "Trying to pause when pause is already pending for "
779 + mPausingActivity, e);
780 }
781 ActivityRecord prev = mResumedActivity;
782 if (prev == null) {
783 RuntimeException e = new RuntimeException();
784 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
785 resumeTopActivityLocked(null);
786 return;
787 }
788 if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
789 mResumedActivity = null;
790 mPausingActivity = prev;
791 mLastPausedActivity = prev;
792 prev.state = ActivityState.PAUSING;
793 prev.task.touchActiveTime();
Dianne Hackbornd2835932010-12-13 16:28:46 -0800794 prev.thumbnail = screenshotActivities(prev);
795 if (prev.task != null) {
796 prev.task.lastThumbnail = prev.thumbnail;
797 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700798
799 mService.updateCpuStats();
800
801 if (prev.app != null && prev.app.thread != null) {
802 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
803 try {
804 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
805 System.identityHashCode(prev),
806 prev.shortComponentName);
807 prev.app.thread.schedulePauseActivity(prev, prev.finishing, userLeaving,
808 prev.configChangeFlags);
809 if (mMainStack) {
810 mService.updateUsageStats(prev, false);
811 }
812 } catch (Exception e) {
813 // Ignore exception, if process died other code will cleanup.
814 Slog.w(TAG, "Exception thrown during pause", e);
815 mPausingActivity = null;
816 mLastPausedActivity = null;
817 }
818 } else {
819 mPausingActivity = null;
820 mLastPausedActivity = null;
821 }
822
823 // If we are not going to sleep, we want to ensure the device is
824 // awake until the next activity is started.
825 if (!mService.mSleeping && !mService.mShuttingDown) {
826 mLaunchingActivity.acquire();
827 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
828 // To be safe, don't allow the wake lock to be held for too long.
829 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
830 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
831 }
832 }
833
834
835 if (mPausingActivity != null) {
836 // Have the window manager pause its key dispatching until the new
837 // activity has started. If we're pausing the activity just because
838 // the screen is being turned off and the UI is sleeping, don't interrupt
839 // key dispatch; the same activity will pick it up again on wakeup.
840 if (!uiSleeping) {
841 prev.pauseKeyDispatchingLocked();
842 } else {
843 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
844 }
845
846 // Schedule a pause timeout in case the app doesn't respond.
847 // We don't give it much time because this directly impacts the
848 // responsiveness seen by the user.
849 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
850 msg.obj = prev;
851 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
852 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
853 } else {
854 // This activity failed to schedule the
855 // pause, so just treat it as being paused now.
856 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
857 resumeTopActivityLocked(null);
858 }
859 }
860
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800861 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700862 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800863 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700864
865 ActivityRecord r = null;
866
867 synchronized (mService) {
868 int index = indexOfTokenLocked(token);
869 if (index >= 0) {
870 r = (ActivityRecord)mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700871 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
872 if (mPausingActivity == r) {
873 r.state = ActivityState.PAUSED;
874 completePauseLocked();
875 } else {
876 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
877 System.identityHashCode(r), r.shortComponentName,
878 mPausingActivity != null
879 ? mPausingActivity.shortComponentName : "(none)");
880 }
881 }
882 }
883 }
884
885 private final void completePauseLocked() {
886 ActivityRecord prev = mPausingActivity;
887 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
888
889 if (prev != null) {
890 if (prev.finishing) {
891 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
892 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE);
893 } else if (prev.app != null) {
894 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
895 if (prev.waitingVisible) {
896 prev.waitingVisible = false;
897 mWaitingVisibleActivities.remove(prev);
898 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
899 TAG, "Complete pause, no longer waiting: " + prev);
900 }
901 if (prev.configDestroy) {
902 // The previous is being paused because the configuration
903 // is changing, which means it is actually stopping...
904 // To juggle the fact that we are also starting a new
905 // instance right now, we need to first completely stop
906 // the current instance before starting the new one.
907 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
908 destroyActivityLocked(prev, true);
909 } else {
910 mStoppingActivities.add(prev);
911 if (mStoppingActivities.size() > 3) {
912 // If we already have a few activities waiting to stop,
913 // then give up on things going idle and start clearing
914 // them out.
915 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
916 Message msg = Message.obtain();
917 msg.what = IDLE_NOW_MSG;
918 mHandler.sendMessage(msg);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800919 } else {
920 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700921 }
922 }
923 } else {
924 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
925 prev = null;
926 }
927 mPausingActivity = null;
928 }
929
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800930 if (!mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700931 resumeTopActivityLocked(prev);
932 } else {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800933 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700934 }
935
936 if (prev != null) {
937 prev.resumeKeyDispatchingLocked();
938 }
939
940 if (prev.app != null && prev.cpuTimeAtResume > 0
941 && mService.mBatteryStatsService.isOnBattery()) {
942 long diff = 0;
943 synchronized (mService.mProcessStatsThread) {
944 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
945 - prev.cpuTimeAtResume;
946 }
947 if (diff > 0) {
948 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
949 synchronized (bsi) {
950 BatteryStatsImpl.Uid.Proc ps =
951 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
952 prev.info.packageName);
953 if (ps != null) {
954 ps.addForegroundTimeLocked(diff);
955 }
956 }
957 }
958 }
959 prev.cpuTimeAtResume = 0; // reset it
960 }
961
962 /**
963 * Once we know that we have asked an application to put an activity in
964 * the resumed state (either by launching it or explicitly telling it),
965 * this function updates the rest of our state to match that fact.
966 */
967 private final void completeResumeLocked(ActivityRecord next) {
968 next.idle = false;
969 next.results = null;
970 next.newIntents = null;
971
972 // schedule an idle timeout in case the app doesn't do it for us.
973 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
974 msg.obj = next;
975 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
976
977 if (false) {
978 // The activity was never told to pause, so just keep
979 // things going as-is. To maintain our own state,
980 // we need to emulate it coming back and saying it is
981 // idle.
982 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
983 msg.obj = next;
984 mHandler.sendMessage(msg);
985 }
986
987 if (mMainStack) {
988 mService.reportResumedActivityLocked(next);
989 }
990
991 next.thumbnail = null;
992 if (mMainStack) {
993 mService.setFocusedActivityLocked(next);
994 }
995 next.resumeKeyDispatchingLocked();
996 ensureActivitiesVisibleLocked(null, 0);
997 mService.mWindowManager.executeAppTransition();
998 mNoAnimActivities.clear();
999
1000 // Mark the point when the activity is resuming
1001 // TODO: To be more accurate, the mark should be before the onCreate,
1002 // not after the onResume. But for subsequent starts, onResume is fine.
1003 if (next.app != null) {
1004 synchronized (mService.mProcessStatsThread) {
1005 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1006 }
1007 } else {
1008 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1009 }
1010 }
1011
1012 /**
1013 * Make sure that all activities that need to be visible (that is, they
1014 * currently can be seen by the user) actually are.
1015 */
1016 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1017 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1018 if (DEBUG_VISBILITY) Slog.v(
1019 TAG, "ensureActivitiesVisible behind " + top
1020 + " configChanges=0x" + Integer.toHexString(configChanges));
1021
1022 // If the top activity is not fullscreen, then we need to
1023 // make sure any activities under it are now visible.
1024 final int count = mHistory.size();
1025 int i = count-1;
1026 while (mHistory.get(i) != top) {
1027 i--;
1028 }
1029 ActivityRecord r;
1030 boolean behindFullscreen = false;
1031 for (; i>=0; i--) {
1032 r = (ActivityRecord)mHistory.get(i);
1033 if (DEBUG_VISBILITY) Slog.v(
1034 TAG, "Make visible? " + r + " finishing=" + r.finishing
1035 + " state=" + r.state);
1036 if (r.finishing) {
1037 continue;
1038 }
1039
1040 final boolean doThisProcess = onlyThisProcess == null
1041 || onlyThisProcess.equals(r.processName);
1042
1043 // First: if this is not the current activity being started, make
1044 // sure it matches the current configuration.
1045 if (r != starting && doThisProcess) {
1046 ensureActivityConfigurationLocked(r, 0);
1047 }
1048
1049 if (r.app == null || r.app.thread == null) {
1050 if (onlyThisProcess == null
1051 || onlyThisProcess.equals(r.processName)) {
1052 // This activity needs to be visible, but isn't even
1053 // running... get it started, but don't resume it
1054 // at this point.
1055 if (DEBUG_VISBILITY) Slog.v(
1056 TAG, "Start and freeze screen for " + r);
1057 if (r != starting) {
1058 r.startFreezingScreenLocked(r.app, configChanges);
1059 }
1060 if (!r.visible) {
1061 if (DEBUG_VISBILITY) Slog.v(
1062 TAG, "Starting and making visible: " + r);
1063 mService.mWindowManager.setAppVisibility(r, true);
1064 }
1065 if (r != starting) {
1066 startSpecificActivityLocked(r, false, false);
1067 }
1068 }
1069
1070 } else if (r.visible) {
1071 // If this activity is already visible, then there is nothing
1072 // else to do here.
1073 if (DEBUG_VISBILITY) Slog.v(
1074 TAG, "Skipping: already visible at " + r);
1075 r.stopFreezingScreenLocked(false);
1076
1077 } else if (onlyThisProcess == null) {
1078 // This activity is not currently visible, but is running.
1079 // Tell it to become visible.
1080 r.visible = true;
1081 if (r.state != ActivityState.RESUMED && r != starting) {
1082 // If this activity is paused, tell it
1083 // to now show its window.
1084 if (DEBUG_VISBILITY) Slog.v(
1085 TAG, "Making visible and scheduling visibility: " + r);
1086 try {
1087 mService.mWindowManager.setAppVisibility(r, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001088 r.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001089 r.app.thread.scheduleWindowVisibility(r, true);
1090 r.stopFreezingScreenLocked(false);
1091 } catch (Exception e) {
1092 // Just skip on any failure; we'll make it
1093 // visible when it next restarts.
1094 Slog.w(TAG, "Exception thrown making visibile: "
1095 + r.intent.getComponent(), e);
1096 }
1097 }
1098 }
1099
1100 // Aggregate current change flags.
1101 configChanges |= r.configChangeFlags;
1102
1103 if (r.fullscreen) {
1104 // At this point, nothing else needs to be shown
1105 if (DEBUG_VISBILITY) Slog.v(
1106 TAG, "Stopping: fullscreen at " + r);
1107 behindFullscreen = true;
1108 i--;
1109 break;
1110 }
1111 }
1112
1113 // Now for any activities that aren't visible to the user, make
1114 // sure they no longer are keeping the screen frozen.
1115 while (i >= 0) {
1116 r = (ActivityRecord)mHistory.get(i);
1117 if (DEBUG_VISBILITY) Slog.v(
1118 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1119 + " state=" + r.state
1120 + " behindFullscreen=" + behindFullscreen);
1121 if (!r.finishing) {
1122 if (behindFullscreen) {
1123 if (r.visible) {
1124 if (DEBUG_VISBILITY) Slog.v(
1125 TAG, "Making invisible: " + r);
1126 r.visible = false;
1127 try {
1128 mService.mWindowManager.setAppVisibility(r, false);
1129 if ((r.state == ActivityState.STOPPING
1130 || r.state == ActivityState.STOPPED)
1131 && r.app != null && r.app.thread != null) {
1132 if (DEBUG_VISBILITY) Slog.v(
1133 TAG, "Scheduling invisibility: " + r);
1134 r.app.thread.scheduleWindowVisibility(r, false);
1135 }
1136 } catch (Exception e) {
1137 // Just skip on any failure; we'll make it
1138 // visible when it next restarts.
1139 Slog.w(TAG, "Exception thrown making hidden: "
1140 + r.intent.getComponent(), e);
1141 }
1142 } else {
1143 if (DEBUG_VISBILITY) Slog.v(
1144 TAG, "Already invisible: " + r);
1145 }
1146 } else if (r.fullscreen) {
1147 if (DEBUG_VISBILITY) Slog.v(
1148 TAG, "Now behindFullscreen: " + r);
1149 behindFullscreen = true;
1150 }
1151 }
1152 i--;
1153 }
1154 }
1155
1156 /**
1157 * Version of ensureActivitiesVisible that can easily be called anywhere.
1158 */
1159 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1160 int configChanges) {
1161 ActivityRecord r = topRunningActivityLocked(null);
1162 if (r != null) {
1163 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1164 }
1165 }
1166
1167 /**
1168 * Ensure that the top activity in the stack is resumed.
1169 *
1170 * @param prev The previously resumed activity, for when in the process
1171 * of pausing; can be null to call from elsewhere.
1172 *
1173 * @return Returns true if something is being resumed, or false if
1174 * nothing happened.
1175 */
1176 final boolean resumeTopActivityLocked(ActivityRecord prev) {
1177 // Find the first activity that is not finishing.
1178 ActivityRecord next = topRunningActivityLocked(null);
1179
1180 // Remember how we'll process this pause/resume situation, and ensure
1181 // that the state is reset however we wind up proceeding.
1182 final boolean userLeaving = mUserLeaving;
1183 mUserLeaving = false;
1184
1185 if (next == null) {
1186 // There are no more activities! Let's just start up the
1187 // Launcher...
1188 if (mMainStack) {
1189 return mService.startHomeActivityLocked();
1190 }
1191 }
1192
1193 next.delayedResume = false;
1194
1195 // If the top activity is the resumed one, nothing to do.
1196 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1197 // Make sure we have executed any pending transitions, since there
1198 // should be nothing left to do at this point.
1199 mService.mWindowManager.executeAppTransition();
1200 mNoAnimActivities.clear();
1201 return false;
1202 }
1203
1204 // If we are sleeping, and there is no resumed activity, and the top
1205 // activity is paused, well that is the state we want.
1206 if ((mService.mSleeping || mService.mShuttingDown)
1207 && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
1208 // Make sure we have executed any pending transitions, since there
1209 // should be nothing left to do at this point.
1210 mService.mWindowManager.executeAppTransition();
1211 mNoAnimActivities.clear();
1212 return false;
1213 }
1214
1215 // The activity may be waiting for stop, but that is no longer
1216 // appropriate for it.
1217 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001218 mGoingToSleepActivities.remove(next);
1219 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001220 mWaitingVisibleActivities.remove(next);
1221
1222 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1223
1224 // If we are currently pausing an activity, then don't do anything
1225 // until that is done.
1226 if (mPausingActivity != null) {
1227 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
1228 return false;
1229 }
1230
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001231 // Okay we are now going to start a switch, to 'next'. We may first
1232 // have to pause the current activity, but this is an important point
1233 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001234 // XXX "App Redirected" dialog is getting too many false positives
1235 // at this point, so turn off for now.
1236 if (false) {
1237 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1238 long now = SystemClock.uptimeMillis();
1239 final boolean inTime = mLastStartedActivity.startTime != 0
1240 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1241 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1242 final int nextUid = next.info.applicationInfo.uid;
1243 if (inTime && lastUid != nextUid
1244 && lastUid != next.launchedFromUid
1245 && mService.checkPermission(
1246 android.Manifest.permission.STOP_APP_SWITCHES,
1247 -1, next.launchedFromUid)
1248 != PackageManager.PERMISSION_GRANTED) {
1249 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1250 } else {
1251 next.startTime = now;
1252 mLastStartedActivity = next;
1253 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001254 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001255 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001256 mLastStartedActivity = next;
1257 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001258 }
1259
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001260 // We need to start pausing the current activity so the top one
1261 // can be resumed...
1262 if (mResumedActivity != null) {
1263 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
1264 startPausingLocked(userLeaving, false);
1265 return true;
1266 }
1267
1268 if (prev != null && prev != next) {
1269 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1270 prev.waitingVisible = true;
1271 mWaitingVisibleActivities.add(prev);
1272 if (DEBUG_SWITCH) Slog.v(
1273 TAG, "Resuming top, waiting visible to hide: " + prev);
1274 } else {
1275 // The next activity is already visible, so hide the previous
1276 // activity's windows right now so we can show the new one ASAP.
1277 // We only do this if the previous is finishing, which should mean
1278 // it is on top of the one being resumed so hiding it quickly
1279 // is good. Otherwise, we want to do the normal route of allowing
1280 // the resumed activity to be shown so we can decide if the
1281 // previous should actually be hidden depending on whether the
1282 // new one is found to be full-screen or not.
1283 if (prev.finishing) {
1284 mService.mWindowManager.setAppVisibility(prev, false);
1285 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1286 + prev + ", waitingVisible="
1287 + (prev != null ? prev.waitingVisible : null)
1288 + ", nowVisible=" + next.nowVisible);
1289 } else {
1290 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1291 + prev + ", waitingVisible="
1292 + (prev != null ? prev.waitingVisible : null)
1293 + ", nowVisible=" + next.nowVisible);
1294 }
1295 }
1296 }
1297
Dianne Hackborne7f97212011-02-24 14:40:20 -08001298 // Launching this app's activity, make sure the app is no longer
1299 // considered stopped.
1300 try {
1301 AppGlobals.getPackageManager().setPackageStoppedState(
1302 next.packageName, false);
1303 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001304 } catch (IllegalArgumentException e) {
1305 Slog.w(TAG, "Failed trying to unstop package "
1306 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001307 }
1308
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001309 // We are starting up the next activity, so tell the window manager
1310 // that the previous one will be hidden soon. This way it can know
1311 // to ignore it when computing the desired screen orientation.
1312 if (prev != null) {
1313 if (prev.finishing) {
1314 if (DEBUG_TRANSITION) Slog.v(TAG,
1315 "Prepare close transition: prev=" + prev);
1316 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001317 mService.mWindowManager.prepareAppTransition(
1318 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001319 } else {
1320 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1321 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001322 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001323 }
1324 mService.mWindowManager.setAppWillBeHidden(prev);
1325 mService.mWindowManager.setAppVisibility(prev, false);
1326 } else {
1327 if (DEBUG_TRANSITION) Slog.v(TAG,
1328 "Prepare open transition: prev=" + prev);
1329 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001330 mService.mWindowManager.prepareAppTransition(
1331 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001332 } else {
1333 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1334 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001335 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001336 }
1337 }
1338 if (false) {
1339 mService.mWindowManager.setAppWillBeHidden(prev);
1340 mService.mWindowManager.setAppVisibility(prev, false);
1341 }
1342 } else if (mHistory.size() > 1) {
1343 if (DEBUG_TRANSITION) Slog.v(TAG,
1344 "Prepare open transition: no previous");
1345 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001346 mService.mWindowManager.prepareAppTransition(
1347 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001348 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001349 mService.mWindowManager.prepareAppTransition(
1350 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001351 }
1352 }
1353
1354 if (next.app != null && next.app.thread != null) {
1355 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1356
1357 // This activity is now becoming visible.
1358 mService.mWindowManager.setAppVisibility(next, true);
1359
1360 ActivityRecord lastResumedActivity = mResumedActivity;
1361 ActivityState lastState = next.state;
1362
1363 mService.updateCpuStats();
1364
1365 next.state = ActivityState.RESUMED;
1366 mResumedActivity = next;
1367 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001368 if (mMainStack) {
1369 mService.addRecentTaskLocked(next.task);
1370 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001371 mService.updateLruProcessLocked(next.app, true, true);
1372 updateLRUListLocked(next);
1373
1374 // Have the window manager re-evaluate the orientation of
1375 // the screen based on the new activity order.
1376 boolean updated = false;
1377 if (mMainStack) {
1378 synchronized (mService) {
1379 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1380 mService.mConfiguration,
1381 next.mayFreezeScreenLocked(next.app) ? next : null);
1382 if (config != null) {
1383 next.frozenBeforeDestroy = true;
1384 }
1385 updated = mService.updateConfigurationLocked(config, next);
1386 }
1387 }
1388 if (!updated) {
1389 // The configuration update wasn't able to keep the existing
1390 // instance of the activity, and instead started a new one.
1391 // We should be all done, but let's just make sure our activity
1392 // is still at the top and schedule another run if something
1393 // weird happened.
1394 ActivityRecord nextNext = topRunningActivityLocked(null);
1395 if (DEBUG_SWITCH) Slog.i(TAG,
1396 "Activity config changed during resume: " + next
1397 + ", new next: " + nextNext);
1398 if (nextNext != next) {
1399 // Do over!
1400 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1401 }
1402 if (mMainStack) {
1403 mService.setFocusedActivityLocked(next);
1404 }
1405 ensureActivitiesVisibleLocked(null, 0);
1406 mService.mWindowManager.executeAppTransition();
1407 mNoAnimActivities.clear();
1408 return true;
1409 }
1410
1411 try {
1412 // Deliver all pending results.
1413 ArrayList a = next.results;
1414 if (a != null) {
1415 final int N = a.size();
1416 if (!next.finishing && N > 0) {
1417 if (DEBUG_RESULTS) Slog.v(
1418 TAG, "Delivering results to " + next
1419 + ": " + a);
1420 next.app.thread.scheduleSendResult(next, a);
1421 }
1422 }
1423
1424 if (next.newIntents != null) {
1425 next.app.thread.scheduleNewIntent(next.newIntents, next);
1426 }
1427
1428 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
1429 System.identityHashCode(next),
1430 next.task.taskId, next.shortComponentName);
1431
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001432 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001433 next.app.thread.scheduleResumeActivity(next,
1434 mService.isNextTransitionForward());
1435
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001436 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001437
1438 } catch (Exception e) {
1439 // Whoops, need to restart this activity!
1440 next.state = lastState;
1441 mResumedActivity = lastResumedActivity;
1442 Slog.i(TAG, "Restarting because process died: " + next);
1443 if (!next.hasBeenLaunched) {
1444 next.hasBeenLaunched = true;
1445 } else {
1446 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1447 mService.mWindowManager.setAppStartingWindow(
1448 next, next.packageName, next.theme,
1449 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001450 next.labelRes, next.icon, next.windowFlags,
1451 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001452 }
1453 }
1454 startSpecificActivityLocked(next, true, false);
1455 return true;
1456 }
1457
1458 // From this point on, if something goes wrong there is no way
1459 // to recover the activity.
1460 try {
1461 next.visible = true;
1462 completeResumeLocked(next);
1463 } catch (Exception e) {
1464 // If any exception gets thrown, toss away this
1465 // activity and try the next one.
1466 Slog.w(TAG, "Exception thrown during resume of " + next, e);
1467 requestFinishActivityLocked(next, Activity.RESULT_CANCELED, null,
1468 "resume-exception");
1469 return true;
1470 }
1471
1472 // Didn't need to use the icicle, and it is now out of date.
1473 next.icicle = null;
1474 next.haveState = false;
1475 next.stopped = false;
1476
1477 } else {
1478 // Whoops, need to restart this activity!
1479 if (!next.hasBeenLaunched) {
1480 next.hasBeenLaunched = true;
1481 } else {
1482 if (SHOW_APP_STARTING_PREVIEW) {
1483 mService.mWindowManager.setAppStartingWindow(
1484 next, next.packageName, next.theme,
1485 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001486 next.labelRes, next.icon, next.windowFlags,
1487 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001488 }
1489 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1490 }
1491 startSpecificActivityLocked(next, true, true);
1492 }
1493
1494 return true;
1495 }
1496
1497 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001498 boolean doResume, boolean keepCurTransition) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001499 final int NH = mHistory.size();
1500
1501 int addPos = -1;
1502
1503 if (!newTask) {
1504 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001505 boolean startIt = true;
1506 for (int i = NH-1; i >= 0; i--) {
1507 ActivityRecord p = (ActivityRecord)mHistory.get(i);
1508 if (p.finishing) {
1509 continue;
1510 }
1511 if (p.task == r.task) {
1512 // Here it is! Now, if this is not yet visible to the
1513 // user, then just add it without starting; it will
1514 // get started when the user navigates back to it.
1515 addPos = i+1;
1516 if (!startIt) {
1517 mHistory.add(addPos, r);
1518 r.inHistory = true;
1519 r.task.numActivities++;
1520 mService.mWindowManager.addAppToken(addPos, r, r.task.taskId,
1521 r.info.screenOrientation, r.fullscreen);
1522 if (VALIDATE_TOKENS) {
1523 mService.mWindowManager.validateAppTokens(mHistory);
1524 }
1525 return;
1526 }
1527 break;
1528 }
1529 if (p.fullscreen) {
1530 startIt = false;
1531 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001532 }
1533 }
1534
1535 // Place a new activity at top of stack, so it is next to interact
1536 // with the user.
1537 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001538 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001539 }
1540
1541 // If we are not placing the new activity frontmost, we do not want
1542 // to deliver the onUserLeaving callback to the actual frontmost
1543 // activity
1544 if (addPos < NH) {
1545 mUserLeaving = false;
1546 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1547 }
1548
1549 // Slot the activity into the history stack and proceed
1550 mHistory.add(addPos, r);
1551 r.inHistory = true;
1552 r.frontOfTask = newTask;
1553 r.task.numActivities++;
1554 if (NH > 0) {
1555 // We want to show the starting preview window if we are
1556 // switching to a new task, or the next activity's process is
1557 // not currently running.
1558 boolean showStartingIcon = newTask;
1559 ProcessRecord proc = r.app;
1560 if (proc == null) {
1561 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1562 }
1563 if (proc == null || proc.thread == null) {
1564 showStartingIcon = true;
1565 }
1566 if (DEBUG_TRANSITION) Slog.v(TAG,
1567 "Prepare open transition: starting " + r);
1568 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001569 mService.mWindowManager.prepareAppTransition(
1570 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001571 mNoAnimActivities.add(r);
1572 } else if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
1573 mService.mWindowManager.prepareAppTransition(
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001574 WindowManagerPolicy.TRANSIT_TASK_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001575 mNoAnimActivities.remove(r);
1576 } else {
1577 mService.mWindowManager.prepareAppTransition(newTask
1578 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001579 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001580 mNoAnimActivities.remove(r);
1581 }
1582 mService.mWindowManager.addAppToken(
1583 addPos, r, r.task.taskId, r.info.screenOrientation, r.fullscreen);
1584 boolean doShow = true;
1585 if (newTask) {
1586 // Even though this activity is starting fresh, we still need
1587 // to reset it to make sure we apply affinities to move any
1588 // existing activities from other tasks in to it.
1589 // If the caller has requested that the target task be
1590 // reset, then do so.
1591 if ((r.intent.getFlags()
1592 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1593 resetTaskIfNeededLocked(r, r);
1594 doShow = topRunningNonDelayedActivityLocked(null) == r;
1595 }
1596 }
1597 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1598 // Figure out if we are transitioning from another activity that is
1599 // "has the same starting icon" as the next one. This allows the
1600 // window manager to keep the previous window it had previously
1601 // created, if it still had one.
1602 ActivityRecord prev = mResumedActivity;
1603 if (prev != null) {
1604 // We don't want to reuse the previous starting preview if:
1605 // (1) The current activity is in a different task.
1606 if (prev.task != r.task) prev = null;
1607 // (2) The current activity is already displayed.
1608 else if (prev.nowVisible) prev = null;
1609 }
1610 mService.mWindowManager.setAppStartingWindow(
1611 r, r.packageName, r.theme, r.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001612 r.labelRes, r.icon, r.windowFlags, prev, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001613 }
1614 } else {
1615 // If this is the first activity, don't do any fancy animations,
1616 // because there is nothing for it to animate on top of.
1617 mService.mWindowManager.addAppToken(addPos, r, r.task.taskId,
1618 r.info.screenOrientation, r.fullscreen);
1619 }
1620 if (VALIDATE_TOKENS) {
1621 mService.mWindowManager.validateAppTokens(mHistory);
1622 }
1623
1624 if (doResume) {
1625 resumeTopActivityLocked(null);
1626 }
1627 }
1628
1629 /**
1630 * Perform a reset of the given task, if needed as part of launching it.
1631 * Returns the new HistoryRecord at the top of the task.
1632 */
1633 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1634 ActivityRecord newActivity) {
1635 boolean forceReset = (newActivity.info.flags
1636 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001637 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1638 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001639 if ((newActivity.info.flags
1640 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1641 forceReset = true;
1642 }
1643 }
1644
1645 final TaskRecord task = taskTop.task;
1646
1647 // We are going to move through the history list so that we can look
1648 // at each activity 'target' with 'below' either the interesting
1649 // activity immediately below it in the stack or null.
1650 ActivityRecord target = null;
1651 int targetI = 0;
1652 int taskTopI = -1;
1653 int replyChainEnd = -1;
1654 int lastReparentPos = -1;
1655 for (int i=mHistory.size()-1; i>=-1; i--) {
1656 ActivityRecord below = i >= 0 ? (ActivityRecord)mHistory.get(i) : null;
1657
1658 if (below != null && below.finishing) {
1659 continue;
1660 }
1661 if (target == null) {
1662 target = below;
1663 targetI = i;
1664 // If we were in the middle of a reply chain before this
1665 // task, it doesn't appear like the root of the chain wants
1666 // anything interesting, so drop it.
1667 replyChainEnd = -1;
1668 continue;
1669 }
1670
1671 final int flags = target.info.flags;
1672
1673 final boolean finishOnTaskLaunch =
1674 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1675 final boolean allowTaskReparenting =
1676 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1677
1678 if (target.task == task) {
1679 // We are inside of the task being reset... we'll either
1680 // finish this activity, push it out for another task,
1681 // or leave it as-is. We only do this
1682 // for activities that are not the root of the task (since
1683 // if we finish the root, we may no longer have the task!).
1684 if (taskTopI < 0) {
1685 taskTopI = targetI;
1686 }
1687 if (below != null && below.task == task) {
1688 final boolean clearWhenTaskReset =
1689 (target.intent.getFlags()
1690 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
1691 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
1692 // If this activity is sending a reply to a previous
1693 // activity, we can't do anything with it now until
1694 // we reach the start of the reply chain.
1695 // XXX note that we are assuming the result is always
1696 // to the previous activity, which is almost always
1697 // the case but we really shouldn't count on.
1698 if (replyChainEnd < 0) {
1699 replyChainEnd = targetI;
1700 }
1701 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
1702 && target.taskAffinity != null
1703 && !target.taskAffinity.equals(task.affinity)) {
1704 // If this activity has an affinity for another
1705 // task, then we need to move it out of here. We will
1706 // move it as far out of the way as possible, to the
1707 // bottom of the activity stack. This also keeps it
1708 // correctly ordered with any activities we previously
1709 // moved.
1710 ActivityRecord p = (ActivityRecord)mHistory.get(0);
1711 if (target.taskAffinity != null
1712 && target.taskAffinity.equals(p.task.affinity)) {
1713 // If the activity currently at the bottom has the
1714 // same task affinity as the one we are moving,
1715 // then merge it into the same task.
1716 target.task = p.task;
1717 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1718 + " out to bottom task " + p.task);
1719 } else {
1720 mService.mCurTask++;
1721 if (mService.mCurTask <= 0) {
1722 mService.mCurTask = 1;
1723 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001724 target.task = new TaskRecord(mService.mCurTask, target.info, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001725 target.task.affinityIntent = target.intent;
1726 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1727 + " out to new task " + target.task);
1728 }
1729 mService.mWindowManager.setAppGroupId(target, task.taskId);
1730 if (replyChainEnd < 0) {
1731 replyChainEnd = targetI;
1732 }
1733 int dstPos = 0;
1734 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
1735 p = (ActivityRecord)mHistory.get(srcPos);
1736 if (p.finishing) {
1737 continue;
1738 }
1739 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
1740 + " out to target's task " + target.task);
1741 task.numActivities--;
1742 p.task = target.task;
1743 target.task.numActivities++;
1744 mHistory.remove(srcPos);
1745 mHistory.add(dstPos, p);
1746 mService.mWindowManager.moveAppToken(dstPos, p);
1747 mService.mWindowManager.setAppGroupId(p, p.task.taskId);
1748 dstPos++;
1749 if (VALIDATE_TOKENS) {
1750 mService.mWindowManager.validateAppTokens(mHistory);
1751 }
1752 i++;
1753 }
1754 if (taskTop == p) {
1755 taskTop = below;
1756 }
1757 if (taskTopI == replyChainEnd) {
1758 taskTopI = -1;
1759 }
1760 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001761 } else if (forceReset || finishOnTaskLaunch
1762 || clearWhenTaskReset) {
1763 // If the activity should just be removed -- either
1764 // because it asks for it, or the task should be
1765 // cleared -- then finish it and anything that is
1766 // part of its reply chain.
1767 if (clearWhenTaskReset) {
1768 // In this case, we want to finish this activity
1769 // and everything above it, so be sneaky and pretend
1770 // like these are all in the reply chain.
1771 replyChainEnd = targetI+1;
1772 while (replyChainEnd < mHistory.size() &&
1773 ((ActivityRecord)mHistory.get(
1774 replyChainEnd)).task == task) {
1775 replyChainEnd++;
1776 }
1777 replyChainEnd--;
1778 } else if (replyChainEnd < 0) {
1779 replyChainEnd = targetI;
1780 }
1781 ActivityRecord p = null;
1782 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
1783 p = (ActivityRecord)mHistory.get(srcPos);
1784 if (p.finishing) {
1785 continue;
1786 }
1787 if (finishActivityLocked(p, srcPos,
1788 Activity.RESULT_CANCELED, null, "reset")) {
1789 replyChainEnd--;
1790 srcPos--;
1791 }
1792 }
1793 if (taskTop == p) {
1794 taskTop = below;
1795 }
1796 if (taskTopI == replyChainEnd) {
1797 taskTopI = -1;
1798 }
1799 replyChainEnd = -1;
1800 } else {
1801 // If we were in the middle of a chain, well the
1802 // activity that started it all doesn't want anything
1803 // special, so leave it all as-is.
1804 replyChainEnd = -1;
1805 }
1806 } else {
1807 // Reached the bottom of the task -- any reply chain
1808 // should be left as-is.
1809 replyChainEnd = -1;
1810 }
1811
1812 } else if (target.resultTo != null) {
1813 // If this activity is sending a reply to a previous
1814 // activity, we can't do anything with it now until
1815 // we reach the start of the reply chain.
1816 // XXX note that we are assuming the result is always
1817 // to the previous activity, which is almost always
1818 // the case but we really shouldn't count on.
1819 if (replyChainEnd < 0) {
1820 replyChainEnd = targetI;
1821 }
1822
1823 } else if (taskTopI >= 0 && allowTaskReparenting
1824 && task.affinity != null
1825 && task.affinity.equals(target.taskAffinity)) {
1826 // We are inside of another task... if this activity has
1827 // an affinity for our task, then either remove it if we are
1828 // clearing or move it over to our task. Note that
1829 // we currently punt on the case where we are resetting a
1830 // task that is not at the top but who has activities above
1831 // with an affinity to it... this is really not a normal
1832 // case, and we will need to later pull that task to the front
1833 // and usually at that point we will do the reset and pick
1834 // up those remaining activities. (This only happens if
1835 // someone starts an activity in a new task from an activity
1836 // in a task that is not currently on top.)
1837 if (forceReset || finishOnTaskLaunch) {
1838 if (replyChainEnd < 0) {
1839 replyChainEnd = targetI;
1840 }
1841 ActivityRecord p = null;
1842 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
1843 p = (ActivityRecord)mHistory.get(srcPos);
1844 if (p.finishing) {
1845 continue;
1846 }
1847 if (finishActivityLocked(p, srcPos,
1848 Activity.RESULT_CANCELED, null, "reset")) {
1849 taskTopI--;
1850 lastReparentPos--;
1851 replyChainEnd--;
1852 srcPos--;
1853 }
1854 }
1855 replyChainEnd = -1;
1856 } else {
1857 if (replyChainEnd < 0) {
1858 replyChainEnd = targetI;
1859 }
1860 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
1861 ActivityRecord p = (ActivityRecord)mHistory.get(srcPos);
1862 if (p.finishing) {
1863 continue;
1864 }
1865 if (lastReparentPos < 0) {
1866 lastReparentPos = taskTopI;
1867 taskTop = p;
1868 } else {
1869 lastReparentPos--;
1870 }
1871 mHistory.remove(srcPos);
1872 p.task.numActivities--;
1873 p.task = task;
1874 mHistory.add(lastReparentPos, p);
1875 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
1876 + " in to resetting task " + task);
1877 task.numActivities++;
1878 mService.mWindowManager.moveAppToken(lastReparentPos, p);
1879 mService.mWindowManager.setAppGroupId(p, p.task.taskId);
1880 if (VALIDATE_TOKENS) {
1881 mService.mWindowManager.validateAppTokens(mHistory);
1882 }
1883 }
1884 replyChainEnd = -1;
1885
1886 // Now we've moved it in to place... but what if this is
1887 // a singleTop activity and we have put it on top of another
1888 // instance of the same activity? Then we drop the instance
1889 // below so it remains singleTop.
1890 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
1891 for (int j=lastReparentPos-1; j>=0; j--) {
1892 ActivityRecord p = (ActivityRecord)mHistory.get(j);
1893 if (p.finishing) {
1894 continue;
1895 }
1896 if (p.intent.getComponent().equals(target.intent.getComponent())) {
1897 if (finishActivityLocked(p, j,
1898 Activity.RESULT_CANCELED, null, "replace")) {
1899 taskTopI--;
1900 lastReparentPos--;
1901 }
1902 }
1903 }
1904 }
1905 }
1906 }
1907
1908 target = below;
1909 targetI = i;
1910 }
1911
1912 return taskTop;
1913 }
1914
1915 /**
1916 * Perform clear operation as requested by
1917 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
1918 * stack to the given task, then look for
1919 * an instance of that activity in the stack and, if found, finish all
1920 * activities on top of it and return the instance.
1921 *
1922 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001923 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001924 * or null if none was found.
1925 */
1926 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001927 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001928 int i = mHistory.size();
1929
1930 // First find the requested task.
1931 while (i > 0) {
1932 i--;
1933 ActivityRecord r = (ActivityRecord)mHistory.get(i);
1934 if (r.task.taskId == taskId) {
1935 i++;
1936 break;
1937 }
1938 }
1939
1940 // Now clear it.
1941 while (i > 0) {
1942 i--;
1943 ActivityRecord r = (ActivityRecord)mHistory.get(i);
1944 if (r.finishing) {
1945 continue;
1946 }
1947 if (r.task.taskId != taskId) {
1948 return null;
1949 }
1950 if (r.realActivity.equals(newR.realActivity)) {
1951 // Here it is! Now finish everything in front...
1952 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001953 while (i < (mHistory.size()-1)) {
1954 i++;
1955 r = (ActivityRecord)mHistory.get(i);
1956 if (r.task.taskId != taskId) {
1957 break;
1958 }
1959 if (r.finishing) {
1960 continue;
1961 }
1962 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
1963 null, "clear")) {
1964 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001965 }
1966 }
1967
1968 // Finally, if this is a normal launch mode (that is, not
1969 // expecting onNewIntent()), then we will finish the current
1970 // instance of the activity so a new fresh one can be started.
1971 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
1972 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
1973 if (!ret.finishing) {
1974 int index = indexOfTokenLocked(ret);
1975 if (index >= 0) {
1976 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
1977 null, "clear");
1978 }
1979 return null;
1980 }
1981 }
1982
1983 return ret;
1984 }
1985 }
1986
1987 return null;
1988 }
1989
1990 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001991 * Completely remove all activities associated with an existing task.
1992 */
1993 private final void performClearTaskLocked(int taskId) {
1994 int i = mHistory.size();
1995
1996 // First find the requested task.
1997 while (i > 0) {
1998 i--;
1999 ActivityRecord r = (ActivityRecord)mHistory.get(i);
2000 if (r.task.taskId == taskId) {
2001 i++;
2002 break;
2003 }
2004 }
2005
2006 // Now clear it.
2007 while (i > 0) {
2008 i--;
2009 ActivityRecord r = (ActivityRecord)mHistory.get(i);
2010 if (r.finishing) {
2011 continue;
2012 }
2013 if (r.task.taskId != taskId) {
2014 // We hit the bottom. Now finish it all...
2015 while (i < (mHistory.size()-1)) {
2016 i++;
2017 r = (ActivityRecord)mHistory.get(i);
2018 if (r.task.taskId != taskId) {
2019 // Whoops hit the end.
2020 return;
2021 }
2022 if (r.finishing) {
2023 continue;
2024 }
2025 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2026 null, "clear")) {
2027 i--;
2028 }
2029 }
2030 return;
2031 }
2032 }
2033 }
2034
2035 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002036 * Find the activity in the history stack within the given task. Returns
2037 * the index within the history at which it's found, or < 0 if not found.
2038 */
2039 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2040 int i = mHistory.size();
2041 while (i > 0) {
2042 i--;
2043 ActivityRecord candidate = (ActivityRecord)mHistory.get(i);
2044 if (candidate.task.taskId != task) {
2045 break;
2046 }
2047 if (candidate.realActivity.equals(r.realActivity)) {
2048 return i;
2049 }
2050 }
2051
2052 return -1;
2053 }
2054
2055 /**
2056 * Reorder the history stack so that the activity at the given index is
2057 * brought to the front.
2058 */
2059 private final ActivityRecord moveActivityToFrontLocked(int where) {
2060 ActivityRecord newTop = (ActivityRecord)mHistory.remove(where);
2061 int top = mHistory.size();
2062 ActivityRecord oldTop = (ActivityRecord)mHistory.get(top-1);
2063 mHistory.add(top, newTop);
2064 oldTop.frontOfTask = false;
2065 newTop.frontOfTask = true;
2066 return newTop;
2067 }
2068
2069 final int startActivityLocked(IApplicationThread caller,
2070 Intent intent, String resolvedType,
2071 Uri[] grantedUriPermissions,
2072 int grantedMode, ActivityInfo aInfo, IBinder resultTo,
2073 String resultWho, int requestCode,
2074 int callingPid, int callingUid, boolean onlyIfNeeded,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002075 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002076
2077 int err = START_SUCCESS;
2078
2079 ProcessRecord callerApp = null;
2080 if (caller != null) {
2081 callerApp = mService.getRecordForAppLocked(caller);
2082 if (callerApp != null) {
2083 callingPid = callerApp.pid;
2084 callingUid = callerApp.info.uid;
2085 } else {
2086 Slog.w(TAG, "Unable to find app for caller " + caller
2087 + " (pid=" + callingPid + ") when starting: "
2088 + intent.toString());
2089 err = START_PERMISSION_DENIED;
2090 }
2091 }
2092
2093 if (err == START_SUCCESS) {
2094 Slog.i(TAG, "Starting: " + intent + " from pid "
2095 + (callerApp != null ? callerApp.pid : callingPid));
2096 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002097
2098 ActivityRecord sourceRecord = null;
2099 ActivityRecord resultRecord = null;
2100 if (resultTo != null) {
2101 int index = indexOfTokenLocked(resultTo);
2102 if (DEBUG_RESULTS) Slog.v(
2103 TAG, "Sending result to " + resultTo + " (index " + index + ")");
2104 if (index >= 0) {
2105 sourceRecord = (ActivityRecord)mHistory.get(index);
2106 if (requestCode >= 0 && !sourceRecord.finishing) {
2107 resultRecord = sourceRecord;
2108 }
2109 }
2110 }
2111
2112 int launchFlags = intent.getFlags();
2113
2114 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2115 && sourceRecord != null) {
2116 // Transfer the result target from the source activity to the new
2117 // one being started, including any failures.
2118 if (requestCode >= 0) {
2119 return START_FORWARD_AND_REQUEST_CONFLICT;
2120 }
2121 resultRecord = sourceRecord.resultTo;
2122 resultWho = sourceRecord.resultWho;
2123 requestCode = sourceRecord.requestCode;
2124 sourceRecord.resultTo = null;
2125 if (resultRecord != null) {
2126 resultRecord.removeResultsLocked(
2127 sourceRecord, resultWho, requestCode);
2128 }
2129 }
2130
Dianne Hackbornefb58102010-10-14 16:47:34 -07002131 if (err == START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002132 // We couldn't find a class that can handle the given Intent.
2133 // That's the end of that!
2134 err = START_INTENT_NOT_RESOLVED;
2135 }
2136
2137 if (err == START_SUCCESS && aInfo == null) {
2138 // We couldn't find the specific class specified in the Intent.
2139 // Also the end of the line.
2140 err = START_CLASS_NOT_FOUND;
2141 }
2142
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002143 if (err != START_SUCCESS) {
2144 if (resultRecord != null) {
2145 sendActivityResultLocked(-1,
2146 resultRecord, resultWho, requestCode,
2147 Activity.RESULT_CANCELED, null);
2148 }
2149 return err;
2150 }
2151
2152 final int perm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002153 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002154 if (perm != PackageManager.PERMISSION_GRANTED) {
2155 if (resultRecord != null) {
2156 sendActivityResultLocked(-1,
2157 resultRecord, resultWho, requestCode,
2158 Activity.RESULT_CANCELED, null);
2159 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002160 String msg;
2161 if (!aInfo.exported) {
2162 msg = "Permission Denial: starting " + intent.toString()
2163 + " from " + callerApp + " (pid=" + callingPid
2164 + ", uid=" + callingUid + ")"
2165 + " not exported from uid " + aInfo.applicationInfo.uid;
2166 } else {
2167 msg = "Permission Denial: starting " + intent.toString()
2168 + " from " + callerApp + " (pid=" + callingPid
2169 + ", uid=" + callingUid + ")"
2170 + " requires " + aInfo.permission;
2171 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002172 Slog.w(TAG, msg);
2173 throw new SecurityException(msg);
2174 }
2175
2176 if (mMainStack) {
2177 if (mService.mController != null) {
2178 boolean abort = false;
2179 try {
2180 // The Intent we give to the watcher has the extra data
2181 // stripped off, since it can contain private information.
2182 Intent watchIntent = intent.cloneFilter();
2183 abort = !mService.mController.activityStarting(watchIntent,
2184 aInfo.applicationInfo.packageName);
2185 } catch (RemoteException e) {
2186 mService.mController = null;
2187 }
2188
2189 if (abort) {
2190 if (resultRecord != null) {
2191 sendActivityResultLocked(-1,
2192 resultRecord, resultWho, requestCode,
2193 Activity.RESULT_CANCELED, null);
2194 }
2195 // We pretend to the caller that it was really started, but
2196 // they will just get a cancel result.
2197 return START_SUCCESS;
2198 }
2199 }
2200 }
2201
2202 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2203 intent, resolvedType, aInfo, mService.mConfiguration,
2204 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002205 if (outActivity != null) {
2206 outActivity[0] = r;
2207 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002208
2209 if (mMainStack) {
2210 if (mResumedActivity == null
2211 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2212 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2213 PendingActivityLaunch pal = new PendingActivityLaunch();
2214 pal.r = r;
2215 pal.sourceRecord = sourceRecord;
2216 pal.grantedUriPermissions = grantedUriPermissions;
2217 pal.grantedMode = grantedMode;
2218 pal.onlyIfNeeded = onlyIfNeeded;
2219 mService.mPendingActivityLaunches.add(pal);
2220 return START_SWITCHES_CANCELED;
2221 }
2222 }
2223
2224 if (mService.mDidAppSwitch) {
2225 // This is the second allowed switch since we stopped switches,
2226 // so now just generally allow switches. Use case: user presses
2227 // home (switches disabled, switch to home, mDidAppSwitch now true);
2228 // user taps a home icon (coming from home so allowed, we hit here
2229 // and now allow anyone to switch again).
2230 mService.mAppSwitchesAllowedTime = 0;
2231 } else {
2232 mService.mDidAppSwitch = true;
2233 }
2234
2235 mService.doPendingActivityLaunchesLocked(false);
2236 }
2237
2238 return startActivityUncheckedLocked(r, sourceRecord,
2239 grantedUriPermissions, grantedMode, onlyIfNeeded, true);
2240 }
2241
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002242 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2243 if ((launchFlags &
2244 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2245 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2246 // Caller wants to appear on home activity, so before starting
2247 // their own activity we will bring home to the front.
2248 moveHomeToFrontLocked();
2249 }
2250 }
2251
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002252 final int startActivityUncheckedLocked(ActivityRecord r,
2253 ActivityRecord sourceRecord, Uri[] grantedUriPermissions,
2254 int grantedMode, boolean onlyIfNeeded, boolean doResume) {
2255 final Intent intent = r.intent;
2256 final int callingUid = r.launchedFromUid;
2257
2258 int launchFlags = intent.getFlags();
2259
2260 // We'll invoke onUserLeaving before onPause only if the launching
2261 // activity did not explicitly state that this is an automated launch.
2262 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2263 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2264 "startActivity() => mUserLeaving=" + mUserLeaving);
2265
2266 // If the caller has asked not to resume at this point, we make note
2267 // of this in the record so that we can skip it when trying to find
2268 // the top running activity.
2269 if (!doResume) {
2270 r.delayedResume = true;
2271 }
2272
2273 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2274 != 0 ? r : null;
2275
2276 // If the onlyIfNeeded flag is set, then we can do this if the activity
2277 // being launched is the same as the one making the call... or, as
2278 // a special case, if we do not know the caller then we count the
2279 // current top activity as the caller.
2280 if (onlyIfNeeded) {
2281 ActivityRecord checkedCaller = sourceRecord;
2282 if (checkedCaller == null) {
2283 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2284 }
2285 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2286 // Caller is not the same as launcher, so always needed.
2287 onlyIfNeeded = false;
2288 }
2289 }
2290
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002291 if (sourceRecord == null) {
2292 // This activity is not being started from another... in this
2293 // case we -always- start a new task.
2294 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2295 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2296 + intent);
2297 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2298 }
2299 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2300 // The original activity who is starting us is running as a single
2301 // instance... this new activity it is starting must go on its
2302 // own task.
2303 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2304 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2305 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2306 // The activity being started is a single instance... it always
2307 // gets launched into its own task.
2308 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2309 }
2310
2311 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2312 // For whatever reason this activity is being launched into a new
2313 // task... yet the caller has requested a result back. Well, that
2314 // is pretty messed up, so instead immediately send back a cancel
2315 // and let the new task continue launched as normal without a
2316 // dependency on its originator.
2317 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2318 sendActivityResultLocked(-1,
2319 r.resultTo, r.resultWho, r.requestCode,
2320 Activity.RESULT_CANCELED, null);
2321 r.resultTo = null;
2322 }
2323
2324 boolean addingToTask = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002325 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002326 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2327 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2328 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2329 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2330 // If bring to front is requested, and no result is requested, and
2331 // we can find a task that was started with this same
2332 // component, then instead of launching bring that one to the front.
2333 if (r.resultTo == null) {
2334 // See if there is a task to bring to the front. If this is
2335 // a SINGLE_INSTANCE activity, there can be one and only one
2336 // instance of it in the history, and it is always in its own
2337 // unique task, so we do a special search.
2338 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2339 ? findTaskLocked(intent, r.info)
2340 : findActivityLocked(intent, r.info);
2341 if (taskTop != null) {
2342 if (taskTop.task.intent == null) {
2343 // This task was started because of movement of
2344 // the activity based on affinity... now that we
2345 // are actually launching it, we can assign the
2346 // base intent.
2347 taskTop.task.setIntent(intent, r.info);
2348 }
2349 // If the target task is not in the front, then we need
2350 // to bring it to the front... except... well, with
2351 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2352 // to have the same behavior as if a new instance was
2353 // being started, which means not bringing it to the front
2354 // if the caller is not itself in the front.
2355 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002356 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002357 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2358 boolean callerAtFront = sourceRecord == null
2359 || curTop.task == sourceRecord.task;
2360 if (callerAtFront) {
2361 // We really do want to push this one into the
2362 // user's face, right now.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002363 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002364 moveTaskToFrontLocked(taskTop.task, r);
2365 }
2366 }
2367 // If the caller has requested that the target task be
2368 // reset, then do so.
2369 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2370 taskTop = resetTaskIfNeededLocked(taskTop, r);
2371 }
2372 if (onlyIfNeeded) {
2373 // We don't need to start a new activity, and
2374 // the client said not to do anything if that
2375 // is the case, so this is it! And for paranoia, make
2376 // sure we have correctly resumed the top activity.
2377 if (doResume) {
2378 resumeTopActivityLocked(null);
2379 }
2380 return START_RETURN_INTENT_TO_CALLER;
2381 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002382 if ((launchFlags &
2383 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2384 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2385 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002386 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002387 // not be too hard...
2388 reuseTask = taskTop.task;
2389 performClearTaskLocked(taskTop.task.taskId);
2390 reuseTask.setIntent(r.intent, r.info);
2391 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002392 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2393 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2394 // In this situation we want to remove all activities
2395 // from the task up to the one being started. In most
2396 // cases this means we are resetting the task to its
2397 // initial state.
2398 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002399 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002400 if (top != null) {
2401 if (top.frontOfTask) {
2402 // Activity aliases may mean we use different
2403 // intents for the top activity, so make sure
2404 // the task now has the identity of the new
2405 // intent.
2406 top.task.setIntent(r.intent, r.info);
2407 }
2408 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002409 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002410 } else {
2411 // A special case: we need to
2412 // start the activity because it is not currently
2413 // running, and the caller has asked to clear the
2414 // current task to have this activity at the top.
2415 addingToTask = true;
2416 // Now pretend like this activity is being started
2417 // by the top of its task, so it is put in the
2418 // right place.
2419 sourceRecord = taskTop;
2420 }
2421 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2422 // In this case the top activity on the task is the
2423 // same as the one being launched, so we take that
2424 // as a request to bring the task to the foreground.
2425 // If the top activity in the task is the root
2426 // activity, deliver this new intent to it if it
2427 // desires.
2428 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2429 && taskTop.realActivity.equals(r.realActivity)) {
2430 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2431 if (taskTop.frontOfTask) {
2432 taskTop.task.setIntent(r.intent, r.info);
2433 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002434 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002435 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2436 // In this case we are launching the root activity
2437 // of the task, but with a different intent. We
2438 // should start a new instance on top.
2439 addingToTask = true;
2440 sourceRecord = taskTop;
2441 }
2442 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2443 // In this case an activity is being launched in to an
2444 // existing task, without resetting that task. This
2445 // is typically the situation of launching an activity
2446 // from a notification or shortcut. We want to place
2447 // the new activity on top of the current task.
2448 addingToTask = true;
2449 sourceRecord = taskTop;
2450 } else if (!taskTop.task.rootWasReset) {
2451 // In this case we are launching in to an existing task
2452 // that has not yet been started from its front door.
2453 // The current task has been brought to the front.
2454 // Ideally, we'd probably like to place this new task
2455 // at the bottom of its stack, but that's a little hard
2456 // to do with the current organization of the code so
2457 // for now we'll just drop it.
2458 taskTop.task.setIntent(r.intent, r.info);
2459 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002460 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002461 // We didn't do anything... but it was needed (a.k.a., client
2462 // don't use that intent!) And for paranoia, make
2463 // sure we have correctly resumed the top activity.
2464 if (doResume) {
2465 resumeTopActivityLocked(null);
2466 }
2467 return START_TASK_TO_FRONT;
2468 }
2469 }
2470 }
2471 }
2472
2473 //String uri = r.intent.toURI();
2474 //Intent intent2 = new Intent(uri);
2475 //Slog.i(TAG, "Given intent: " + r.intent);
2476 //Slog.i(TAG, "URI is: " + uri);
2477 //Slog.i(TAG, "To intent: " + intent2);
2478
2479 if (r.packageName != null) {
2480 // If the activity being launched is the same as the one currently
2481 // at the top, then we need to check if it should only be launched
2482 // once.
2483 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2484 if (top != null && r.resultTo == null) {
2485 if (top.realActivity.equals(r.realActivity)) {
2486 if (top.app != null && top.app.thread != null) {
2487 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2488 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2489 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2490 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2491 // For paranoia, make sure we have correctly
2492 // resumed the top activity.
2493 if (doResume) {
2494 resumeTopActivityLocked(null);
2495 }
2496 if (onlyIfNeeded) {
2497 // We don't need to start a new activity, and
2498 // the client said not to do anything if that
2499 // is the case, so this is it!
2500 return START_RETURN_INTENT_TO_CALLER;
2501 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002502 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002503 return START_DELIVERED_TO_TOP;
2504 }
2505 }
2506 }
2507 }
2508
2509 } else {
2510 if (r.resultTo != null) {
2511 sendActivityResultLocked(-1,
2512 r.resultTo, r.resultWho, r.requestCode,
2513 Activity.RESULT_CANCELED, null);
2514 }
2515 return START_CLASS_NOT_FOUND;
2516 }
2517
2518 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002519 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002520
2521 // Should this be considered a new task?
2522 if (r.resultTo == null && !addingToTask
2523 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002524 if (reuseTask == null) {
2525 // todo: should do better management of integers.
2526 mService.mCurTask++;
2527 if (mService.mCurTask <= 0) {
2528 mService.mCurTask = 1;
2529 }
2530 r.task = new TaskRecord(mService.mCurTask, r.info, intent);
2531 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2532 + " in new task " + r.task);
2533 } else {
2534 r.task = reuseTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002535 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002536 newTask = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002537 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002538
2539 } else if (sourceRecord != null) {
2540 if (!addingToTask &&
2541 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2542 // In this case, we are adding the activity to an existing
2543 // task, but the caller has asked to clear that task if the
2544 // activity is already running.
2545 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002546 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002547 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002548 if (top != null) {
2549 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002550 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002551 // For paranoia, make sure we have correctly
2552 // resumed the top activity.
2553 if (doResume) {
2554 resumeTopActivityLocked(null);
2555 }
2556 return START_DELIVERED_TO_TOP;
2557 }
2558 } else if (!addingToTask &&
2559 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2560 // In this case, we are launching an activity in our own task
2561 // that may already be running somewhere in the history, and
2562 // we want to shuffle it to the front of the stack if so.
2563 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2564 if (where >= 0) {
2565 ActivityRecord top = moveActivityToFrontLocked(where);
2566 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002567 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002568 if (doResume) {
2569 resumeTopActivityLocked(null);
2570 }
2571 return START_DELIVERED_TO_TOP;
2572 }
2573 }
2574 // An existing activity is starting this new activity, so we want
2575 // to keep the new one in the same task as the one that is starting
2576 // it.
2577 r.task = sourceRecord.task;
2578 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2579 + " in existing task " + r.task);
2580
2581 } else {
2582 // This not being started from an existing activity, and not part
2583 // of a new task... just put it in the top task, though these days
2584 // this case should never happen.
2585 final int N = mHistory.size();
2586 ActivityRecord prev =
2587 N > 0 ? (ActivityRecord)mHistory.get(N-1) : null;
2588 r.task = prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002589 ? prev.task
2590 : new TaskRecord(mService.mCurTask, r.info, intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002591 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2592 + " in new guessed " + r.task);
2593 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002594
2595 if (grantedUriPermissions != null && callingUid > 0) {
2596 for (int i=0; i<grantedUriPermissions.length; i++) {
2597 mService.grantUriPermissionLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002598 grantedUriPermissions[i], grantedMode, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002599 }
2600 }
2601
2602 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002603 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002604
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002605 if (newTask) {
2606 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
2607 }
2608 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002609 startActivityLocked(r, newTask, doResume, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002610 return START_SUCCESS;
2611 }
2612
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002613 ActivityInfo resolveActivity(Intent intent, String resolvedType, boolean debug) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002614 // Collect information about the target of the Intent.
2615 ActivityInfo aInfo;
2616 try {
2617 ResolveInfo rInfo =
2618 AppGlobals.getPackageManager().resolveIntent(
2619 intent, resolvedType,
2620 PackageManager.MATCH_DEFAULT_ONLY
2621 | ActivityManagerService.STOCK_PM_FLAGS);
2622 aInfo = rInfo != null ? rInfo.activityInfo : null;
2623 } catch (RemoteException e) {
2624 aInfo = null;
2625 }
2626
2627 if (aInfo != null) {
2628 // Store the found target back into the intent, because now that
2629 // we have it we never want to do this again. For example, if the
2630 // user navigates back to this point in the history, we should
2631 // always restart the exact same activity.
2632 intent.setComponent(new ComponentName(
2633 aInfo.applicationInfo.packageName, aInfo.name));
2634
2635 // Don't debug things in the system process
2636 if (debug) {
2637 if (!aInfo.processName.equals("system")) {
2638 mService.setDebugApp(aInfo.processName, true, false);
2639 }
2640 }
2641 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002642 return aInfo;
2643 }
2644
2645 final int startActivityMayWait(IApplicationThread caller, int callingUid,
2646 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2647 int grantedMode, IBinder resultTo,
2648 String resultWho, int requestCode, boolean onlyIfNeeded,
2649 boolean debug, WaitResult outResult, Configuration config) {
2650 // Refuse possible leaked file descriptors
2651 if (intent != null && intent.hasFileDescriptors()) {
2652 throw new IllegalArgumentException("File descriptors passed in Intent");
2653 }
2654
2655 boolean componentSpecified = intent.getComponent() != null;
2656
2657 // Don't modify the client's object!
2658 intent = new Intent(intent);
2659
2660 // Collect information about the target of the Intent.
2661 ActivityInfo aInfo = resolveActivity(intent, resolvedType, debug);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002662
2663 synchronized (mService) {
2664 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002665 if (callingUid >= 0) {
2666 callingPid = -1;
2667 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002668 callingPid = Binder.getCallingPid();
2669 callingUid = Binder.getCallingUid();
2670 } else {
2671 callingPid = callingUid = -1;
2672 }
2673
2674 mConfigWillChange = config != null
2675 && mService.mConfiguration.diff(config) != 0;
2676 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2677 "Starting activity when config will change = " + mConfigWillChange);
2678
2679 final long origId = Binder.clearCallingIdentity();
2680
2681 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07002682 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002683 // This may be a heavy-weight process! Check to see if we already
2684 // have another, different heavy-weight process running.
2685 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
2686 if (mService.mHeavyWeightProcess != null &&
2687 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
2688 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
2689 int realCallingPid = callingPid;
2690 int realCallingUid = callingUid;
2691 if (caller != null) {
2692 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
2693 if (callerApp != null) {
2694 realCallingPid = callerApp.pid;
2695 realCallingUid = callerApp.info.uid;
2696 } else {
2697 Slog.w(TAG, "Unable to find app for caller " + caller
2698 + " (pid=" + realCallingPid + ") when starting: "
2699 + intent.toString());
2700 return START_PERMISSION_DENIED;
2701 }
2702 }
2703
2704 IIntentSender target = mService.getIntentSenderLocked(
2705 IActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002706 realCallingUid, null, null, 0, new Intent[] { intent },
2707 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002708 | PendingIntent.FLAG_ONE_SHOT);
2709
2710 Intent newIntent = new Intent();
2711 if (requestCode >= 0) {
2712 // Caller is requesting a result.
2713 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
2714 }
2715 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
2716 new IntentSender(target));
2717 if (mService.mHeavyWeightProcess.activities.size() > 0) {
2718 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
2719 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
2720 hist.packageName);
2721 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
2722 hist.task.taskId);
2723 }
2724 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
2725 aInfo.packageName);
2726 newIntent.setFlags(intent.getFlags());
2727 newIntent.setClassName("android",
2728 HeavyWeightSwitcherActivity.class.getName());
2729 intent = newIntent;
2730 resolvedType = null;
2731 caller = null;
2732 callingUid = Binder.getCallingUid();
2733 callingPid = Binder.getCallingPid();
2734 componentSpecified = true;
2735 try {
2736 ResolveInfo rInfo =
2737 AppGlobals.getPackageManager().resolveIntent(
2738 intent, null,
2739 PackageManager.MATCH_DEFAULT_ONLY
2740 | ActivityManagerService.STOCK_PM_FLAGS);
2741 aInfo = rInfo != null ? rInfo.activityInfo : null;
2742 } catch (RemoteException e) {
2743 aInfo = null;
2744 }
2745 }
2746 }
2747 }
2748
2749 int res = startActivityLocked(caller, intent, resolvedType,
2750 grantedUriPermissions, grantedMode, aInfo,
2751 resultTo, resultWho, requestCode, callingPid, callingUid,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002752 onlyIfNeeded, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002753
2754 if (mConfigWillChange && mMainStack) {
2755 // If the caller also wants to switch to a new configuration,
2756 // do so now. This allows a clean switch, as we are waiting
2757 // for the current activity to pause (so we will not destroy
2758 // it), and have not yet started the next activity.
2759 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
2760 "updateConfiguration()");
2761 mConfigWillChange = false;
2762 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2763 "Updating to new configuration after starting activity.");
2764 mService.updateConfigurationLocked(config, null);
2765 }
2766
2767 Binder.restoreCallingIdentity(origId);
2768
2769 if (outResult != null) {
2770 outResult.result = res;
2771 if (res == IActivityManager.START_SUCCESS) {
2772 mWaitingActivityLaunched.add(outResult);
2773 do {
2774 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07002775 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002776 } catch (InterruptedException e) {
2777 }
2778 } while (!outResult.timeout && outResult.who == null);
2779 } else if (res == IActivityManager.START_TASK_TO_FRONT) {
2780 ActivityRecord r = this.topRunningActivityLocked(null);
2781 if (r.nowVisible) {
2782 outResult.timeout = false;
2783 outResult.who = new ComponentName(r.info.packageName, r.info.name);
2784 outResult.totalTime = 0;
2785 outResult.thisTime = 0;
2786 } else {
2787 outResult.thisTime = SystemClock.uptimeMillis();
2788 mWaitingActivityVisible.add(outResult);
2789 do {
2790 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07002791 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002792 } catch (InterruptedException e) {
2793 }
2794 } while (!outResult.timeout && outResult.who == null);
2795 }
2796 }
2797 }
2798
2799 return res;
2800 }
2801 }
2802
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002803 final int startActivities(IApplicationThread caller, int callingUid,
2804 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
2805 if (intents == null) {
2806 throw new NullPointerException("intents is null");
2807 }
2808 if (resolvedTypes == null) {
2809 throw new NullPointerException("resolvedTypes is null");
2810 }
2811 if (intents.length != resolvedTypes.length) {
2812 throw new IllegalArgumentException("intents are length different than resolvedTypes");
2813 }
2814
2815 ActivityRecord[] outActivity = new ActivityRecord[1];
2816
2817 int callingPid;
2818 if (callingUid >= 0) {
2819 callingPid = -1;
2820 } else if (caller == null) {
2821 callingPid = Binder.getCallingPid();
2822 callingUid = Binder.getCallingUid();
2823 } else {
2824 callingPid = callingUid = -1;
2825 }
2826 final long origId = Binder.clearCallingIdentity();
2827 try {
2828 synchronized (mService) {
2829
2830 for (int i=0; i<intents.length; i++) {
2831 Intent intent = intents[i];
2832 if (intent == null) {
2833 continue;
2834 }
2835
2836 // Refuse possible leaked file descriptors
2837 if (intent != null && intent.hasFileDescriptors()) {
2838 throw new IllegalArgumentException("File descriptors passed in Intent");
2839 }
2840
2841 boolean componentSpecified = intent.getComponent() != null;
2842
2843 // Don't modify the client's object!
2844 intent = new Intent(intent);
2845
2846 // Collect information about the target of the Intent.
2847 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i], false);
2848
2849 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
2850 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
2851 throw new IllegalArgumentException(
2852 "FLAG_CANT_SAVE_STATE not supported here");
2853 }
2854
2855 int res = startActivityLocked(caller, intent, resolvedTypes[i],
2856 null, 0, aInfo, resultTo, null, -1, callingPid, callingUid,
2857 false, componentSpecified, outActivity);
2858 if (res < 0) {
2859 return res;
2860 }
2861
2862 resultTo = outActivity[0];
2863 }
2864 }
2865 } finally {
2866 Binder.restoreCallingIdentity(origId);
2867 }
2868
2869 return IActivityManager.START_SUCCESS;
2870 }
2871
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002872 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
2873 long thisTime, long totalTime) {
2874 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
2875 WaitResult w = mWaitingActivityLaunched.get(i);
2876 w.timeout = timeout;
2877 if (r != null) {
2878 w.who = new ComponentName(r.info.packageName, r.info.name);
2879 }
2880 w.thisTime = thisTime;
2881 w.totalTime = totalTime;
2882 }
2883 mService.notifyAll();
2884 }
2885
2886 void reportActivityVisibleLocked(ActivityRecord r) {
2887 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
2888 WaitResult w = mWaitingActivityVisible.get(i);
2889 w.timeout = false;
2890 if (r != null) {
2891 w.who = new ComponentName(r.info.packageName, r.info.name);
2892 }
2893 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
2894 w.thisTime = w.totalTime;
2895 }
2896 mService.notifyAll();
2897 }
2898
2899 void sendActivityResultLocked(int callingUid, ActivityRecord r,
2900 String resultWho, int requestCode, int resultCode, Intent data) {
2901
2902 if (callingUid > 0) {
2903 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002904 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002905 }
2906
2907 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
2908 + " : who=" + resultWho + " req=" + requestCode
2909 + " res=" + resultCode + " data=" + data);
2910 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
2911 try {
2912 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
2913 list.add(new ResultInfo(resultWho, requestCode,
2914 resultCode, data));
2915 r.app.thread.scheduleSendResult(r, list);
2916 return;
2917 } catch (Exception e) {
2918 Slog.w(TAG, "Exception thrown sending result to " + r, e);
2919 }
2920 }
2921
2922 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
2923 }
2924
2925 private final void stopActivityLocked(ActivityRecord r) {
2926 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
2927 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
2928 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
2929 if (!r.finishing) {
2930 requestFinishActivityLocked(r, Activity.RESULT_CANCELED, null,
2931 "no-history");
2932 }
2933 } else if (r.app != null && r.app.thread != null) {
2934 if (mMainStack) {
2935 if (mService.mFocusedActivity == r) {
2936 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
2937 }
2938 }
2939 r.resumeKeyDispatchingLocked();
2940 try {
2941 r.stopped = false;
2942 r.state = ActivityState.STOPPING;
2943 if (DEBUG_VISBILITY) Slog.v(
2944 TAG, "Stopping visible=" + r.visible + " for " + r);
2945 if (!r.visible) {
2946 mService.mWindowManager.setAppVisibility(r, false);
2947 }
2948 r.app.thread.scheduleStopActivity(r, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002949 if (mService.isSleeping()) {
2950 r.setSleeping(true);
2951 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002952 } catch (Exception e) {
2953 // Maybe just ignore exceptions here... if the process
2954 // has crashed, our death notification will clean things
2955 // up.
2956 Slog.w(TAG, "Exception thrown during pause", e);
2957 // Just in case, assume it to be stopped.
2958 r.stopped = true;
2959 r.state = ActivityState.STOPPED;
2960 if (r.configDestroy) {
2961 destroyActivityLocked(r, true);
2962 }
2963 }
2964 }
2965 }
2966
2967 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
2968 boolean remove) {
2969 int N = mStoppingActivities.size();
2970 if (N <= 0) return null;
2971
2972 ArrayList<ActivityRecord> stops = null;
2973
2974 final boolean nowVisible = mResumedActivity != null
2975 && mResumedActivity.nowVisible
2976 && !mResumedActivity.waitingVisible;
2977 for (int i=0; i<N; i++) {
2978 ActivityRecord s = mStoppingActivities.get(i);
2979 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
2980 + nowVisible + " waitingVisible=" + s.waitingVisible
2981 + " finishing=" + s.finishing);
2982 if (s.waitingVisible && nowVisible) {
2983 mWaitingVisibleActivities.remove(s);
2984 s.waitingVisible = false;
2985 if (s.finishing) {
2986 // If this activity is finishing, it is sitting on top of
2987 // everyone else but we now know it is no longer needed...
2988 // so get rid of it. Otherwise, we need to go through the
2989 // normal flow and hide it once we determine that it is
2990 // hidden by the activities in front of it.
2991 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
2992 mService.mWindowManager.setAppVisibility(s, false);
2993 }
2994 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002995 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002996 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
2997 if (stops == null) {
2998 stops = new ArrayList<ActivityRecord>();
2999 }
3000 stops.add(s);
3001 mStoppingActivities.remove(i);
3002 N--;
3003 i--;
3004 }
3005 }
3006
3007 return stops;
3008 }
3009
3010 final void activityIdleInternal(IBinder token, boolean fromTimeout,
3011 Configuration config) {
3012 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3013
3014 ArrayList<ActivityRecord> stops = null;
3015 ArrayList<ActivityRecord> finishes = null;
3016 ArrayList<ActivityRecord> thumbnails = null;
3017 int NS = 0;
3018 int NF = 0;
3019 int NT = 0;
3020 IApplicationThread sendThumbnail = null;
3021 boolean booting = false;
3022 boolean enableScreen = false;
3023
3024 synchronized (mService) {
3025 if (token != null) {
3026 mHandler.removeMessages(IDLE_TIMEOUT_MSG, token);
3027 }
3028
3029 // Get the activity record.
3030 int index = indexOfTokenLocked(token);
3031 if (index >= 0) {
3032 ActivityRecord r = (ActivityRecord)mHistory.get(index);
3033
3034 if (fromTimeout) {
3035 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3036 }
3037
3038 // This is a hack to semi-deal with a race condition
3039 // in the client where it can be constructed with a
3040 // newer configuration from when we asked it to launch.
3041 // We'll update with whatever configuration it now says
3042 // it used to launch.
3043 if (config != null) {
3044 r.configuration = config;
3045 }
3046
3047 // No longer need to keep the device awake.
3048 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3049 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3050 mLaunchingActivity.release();
3051 }
3052
3053 // We are now idle. If someone is waiting for a thumbnail from
3054 // us, we can now deliver.
3055 r.idle = true;
3056 mService.scheduleAppGcsLocked();
3057 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3058 sendThumbnail = r.app.thread;
3059 r.thumbnailNeeded = false;
3060 }
3061
3062 // If this activity is fullscreen, set up to hide those under it.
3063
3064 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3065 ensureActivitiesVisibleLocked(null, 0);
3066
3067 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3068 if (mMainStack) {
3069 if (!mService.mBooted && !fromTimeout) {
3070 mService.mBooted = true;
3071 enableScreen = true;
3072 }
3073 }
3074
3075 } else if (fromTimeout) {
3076 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3077 }
3078
3079 // Atomically retrieve all of the other things to do.
3080 stops = processStoppingActivitiesLocked(true);
3081 NS = stops != null ? stops.size() : 0;
3082 if ((NF=mFinishingActivities.size()) > 0) {
3083 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3084 mFinishingActivities.clear();
3085 }
3086 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3087 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3088 mService.mCancelledThumbnails.clear();
3089 }
3090
3091 if (mMainStack) {
3092 booting = mService.mBooting;
3093 mService.mBooting = false;
3094 }
3095 }
3096
3097 int i;
3098
3099 // Send thumbnail if requested.
3100 if (sendThumbnail != null) {
3101 try {
3102 sendThumbnail.requestThumbnail(token);
3103 } catch (Exception e) {
3104 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3105 mService.sendPendingThumbnail(null, token, null, null, true);
3106 }
3107 }
3108
3109 // Stop any activities that are scheduled to do so but have been
3110 // waiting for the next one to start.
3111 for (i=0; i<NS; i++) {
3112 ActivityRecord r = (ActivityRecord)stops.get(i);
3113 synchronized (mService) {
3114 if (r.finishing) {
3115 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY);
3116 } else {
3117 stopActivityLocked(r);
3118 }
3119 }
3120 }
3121
3122 // Finish any activities that are scheduled to do so but have been
3123 // waiting for the next one to start.
3124 for (i=0; i<NF; i++) {
3125 ActivityRecord r = (ActivityRecord)finishes.get(i);
3126 synchronized (mService) {
3127 destroyActivityLocked(r, true);
3128 }
3129 }
3130
3131 // Report back to any thumbnail receivers.
3132 for (i=0; i<NT; i++) {
3133 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3134 mService.sendPendingThumbnail(r, null, null, null, true);
3135 }
3136
3137 if (booting) {
3138 mService.finishBooting();
3139 }
3140
3141 mService.trimApplications();
3142 //dump();
3143 //mWindowManager.dump();
3144
3145 if (enableScreen) {
3146 mService.enableScreenAfterBoot();
3147 }
3148 }
3149
3150 /**
3151 * @return Returns true if the activity is being finished, false if for
3152 * some reason it is being left as-is.
3153 */
3154 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
3155 Intent resultData, String reason) {
3156 if (DEBUG_RESULTS) Slog.v(
3157 TAG, "Finishing activity: token=" + token
3158 + ", result=" + resultCode + ", data=" + resultData);
3159
3160 int index = indexOfTokenLocked(token);
3161 if (index < 0) {
3162 return false;
3163 }
3164 ActivityRecord r = (ActivityRecord)mHistory.get(index);
3165
3166 // Is this the last activity left?
3167 boolean lastActivity = true;
3168 for (int i=mHistory.size()-1; i>=0; i--) {
3169 ActivityRecord p = (ActivityRecord)mHistory.get(i);
3170 if (!p.finishing && p != r) {
3171 lastActivity = false;
3172 break;
3173 }
3174 }
3175
3176 // If this is the last activity, but it is the home activity, then
3177 // just don't finish it.
3178 if (lastActivity) {
3179 if (r.intent.hasCategory(Intent.CATEGORY_HOME)) {
3180 return false;
3181 }
3182 }
3183
3184 finishActivityLocked(r, index, resultCode, resultData, reason);
3185 return true;
3186 }
3187
3188 /**
3189 * @return Returns true if this activity has been removed from the history
3190 * list, or false if it is still in the list and will be removed later.
3191 */
3192 final boolean finishActivityLocked(ActivityRecord r, int index,
3193 int resultCode, Intent resultData, String reason) {
3194 if (r.finishing) {
3195 Slog.w(TAG, "Duplicate finish request for " + r);
3196 return false;
3197 }
3198
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003199 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003200 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3201 System.identityHashCode(r),
3202 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003203 if (index < (mHistory.size()-1)) {
3204 ActivityRecord next = (ActivityRecord)mHistory.get(index+1);
3205 if (next.task == r.task) {
3206 if (r.frontOfTask) {
3207 // The next activity is now the front of the task.
3208 next.frontOfTask = true;
3209 }
3210 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3211 // If the caller asked that this activity (and all above it)
3212 // be cleared when the task is reset, don't lose that information,
3213 // but propagate it up to the next activity.
3214 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3215 }
3216 }
3217 }
3218
3219 r.pauseKeyDispatchingLocked();
3220 if (mMainStack) {
3221 if (mService.mFocusedActivity == r) {
3222 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3223 }
3224 }
3225
3226 // send the result
3227 ActivityRecord resultTo = r.resultTo;
3228 if (resultTo != null) {
3229 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3230 + " who=" + r.resultWho + " req=" + r.requestCode
3231 + " res=" + resultCode + " data=" + resultData);
3232 if (r.info.applicationInfo.uid > 0) {
3233 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
Dianne Hackborna1c69e02010-09-01 22:55:02 -07003234 resultTo.packageName, resultData,
3235 resultTo.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003236 }
3237 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3238 resultData);
3239 r.resultTo = null;
3240 }
3241 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3242
3243 // Make sure this HistoryRecord is not holding on to other resources,
3244 // because clients have remote IPC references to this object so we
3245 // can't assume that will go away and want to avoid circular IPC refs.
3246 r.results = null;
3247 r.pendingResults = null;
3248 r.newIntents = null;
3249 r.icicle = null;
3250
3251 if (mService.mPendingThumbnails.size() > 0) {
3252 // There are clients waiting to receive thumbnails so, in case
3253 // this is an activity that someone is waiting for, add it
3254 // to the pending list so we can correctly update the clients.
3255 mService.mCancelledThumbnails.add(r);
3256 }
3257
3258 if (mResumedActivity == r) {
3259 boolean endTask = index <= 0
3260 || ((ActivityRecord)mHistory.get(index-1)).task != r.task;
3261 if (DEBUG_TRANSITION) Slog.v(TAG,
3262 "Prepare close transition: finishing " + r);
3263 mService.mWindowManager.prepareAppTransition(endTask
3264 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003265 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003266
3267 // Tell window manager to prepare for this one to be removed.
3268 mService.mWindowManager.setAppVisibility(r, false);
3269
3270 if (mPausingActivity == null) {
3271 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3272 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3273 startPausingLocked(false, false);
3274 }
3275
3276 } else if (r.state != ActivityState.PAUSING) {
3277 // If the activity is PAUSING, we will complete the finish once
3278 // it is done pausing; else we can just directly finish it here.
3279 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3280 return finishCurrentActivityLocked(r, index,
3281 FINISH_AFTER_PAUSE) == null;
3282 } else {
3283 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3284 }
3285
3286 return false;
3287 }
3288
3289 private static final int FINISH_IMMEDIATELY = 0;
3290 private static final int FINISH_AFTER_PAUSE = 1;
3291 private static final int FINISH_AFTER_VISIBLE = 2;
3292
3293 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3294 int mode) {
3295 final int index = indexOfTokenLocked(r);
3296 if (index < 0) {
3297 return null;
3298 }
3299
3300 return finishCurrentActivityLocked(r, index, mode);
3301 }
3302
3303 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3304 int index, int mode) {
3305 // First things first: if this activity is currently visible,
3306 // and the resumed activity is not yet visible, then hold off on
3307 // finishing until the resumed one becomes visible.
3308 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3309 if (!mStoppingActivities.contains(r)) {
3310 mStoppingActivities.add(r);
3311 if (mStoppingActivities.size() > 3) {
3312 // If we already have a few activities waiting to stop,
3313 // then give up on things going idle and start clearing
3314 // them out.
3315 Message msg = Message.obtain();
3316 msg.what = IDLE_NOW_MSG;
3317 mHandler.sendMessage(msg);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003318 } else {
3319 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003320 }
3321 }
3322 r.state = ActivityState.STOPPING;
3323 mService.updateOomAdjLocked();
3324 return r;
3325 }
3326
3327 // make sure the record is cleaned out of other places.
3328 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003329 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003330 mWaitingVisibleActivities.remove(r);
3331 if (mResumedActivity == r) {
3332 mResumedActivity = null;
3333 }
3334 final ActivityState prevState = r.state;
3335 r.state = ActivityState.FINISHING;
3336
3337 if (mode == FINISH_IMMEDIATELY
3338 || prevState == ActivityState.STOPPED
3339 || prevState == ActivityState.INITIALIZING) {
3340 // If this activity is already stopped, we can just finish
3341 // it right now.
3342 return destroyActivityLocked(r, true) ? null : r;
3343 } else {
3344 // Need to go through the full pause cycle to get this
3345 // activity into the stopped state and then finish it.
3346 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3347 mFinishingActivities.add(r);
3348 resumeTopActivityLocked(null);
3349 }
3350 return r;
3351 }
3352
3353 /**
3354 * Perform the common clean-up of an activity record. This is called both
3355 * as part of destroyActivityLocked() (when destroying the client-side
3356 * representation) and cleaning things up as a result of its hosting
3357 * processing going away, in which case there is no remaining client-side
3358 * state to destroy so only the cleanup here is needed.
3359 */
3360 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices) {
3361 if (mResumedActivity == r) {
3362 mResumedActivity = null;
3363 }
3364 if (mService.mFocusedActivity == r) {
3365 mService.mFocusedActivity = null;
3366 }
3367
3368 r.configDestroy = false;
3369 r.frozenBeforeDestroy = false;
3370
3371 // Make sure this record is no longer in the pending finishes list.
3372 // This could happen, for example, if we are trimming activities
3373 // down to the max limit while they are still waiting to finish.
3374 mFinishingActivities.remove(r);
3375 mWaitingVisibleActivities.remove(r);
3376
3377 // Remove any pending results.
3378 if (r.finishing && r.pendingResults != null) {
3379 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3380 PendingIntentRecord rec = apr.get();
3381 if (rec != null) {
3382 mService.cancelIntentSenderLocked(rec, false);
3383 }
3384 }
3385 r.pendingResults = null;
3386 }
3387
3388 if (cleanServices) {
3389 cleanUpActivityServicesLocked(r);
3390 }
3391
3392 if (mService.mPendingThumbnails.size() > 0) {
3393 // There are clients waiting to receive thumbnails so, in case
3394 // this is an activity that someone is waiting for, add it
3395 // to the pending list so we can correctly update the clients.
3396 mService.mCancelledThumbnails.add(r);
3397 }
3398
3399 // Get rid of any pending idle timeouts.
3400 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
3401 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
3402 }
3403
3404 private final void removeActivityFromHistoryLocked(ActivityRecord r) {
3405 if (r.state != ActivityState.DESTROYED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003406 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003407 mHistory.remove(r);
3408 r.inHistory = false;
3409 r.state = ActivityState.DESTROYED;
3410 mService.mWindowManager.removeAppToken(r);
3411 if (VALIDATE_TOKENS) {
3412 mService.mWindowManager.validateAppTokens(mHistory);
3413 }
3414 cleanUpActivityServicesLocked(r);
3415 r.removeUriPermissionsLocked();
3416 }
3417 }
3418
3419 /**
3420 * Perform clean-up of service connections in an activity record.
3421 */
3422 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3423 // Throw away any services that have been bound by this activity.
3424 if (r.connections != null) {
3425 Iterator<ConnectionRecord> it = r.connections.iterator();
3426 while (it.hasNext()) {
3427 ConnectionRecord c = it.next();
3428 mService.removeConnectionLocked(c, null, r);
3429 }
3430 r.connections = null;
3431 }
3432 }
3433
3434 /**
3435 * Destroy the current CLIENT SIDE instance of an activity. This may be
3436 * called both when actually finishing an activity, or when performing
3437 * a configuration switch where we destroy the current client-side object
3438 * but then create a new client-side object for this same HistoryRecord.
3439 */
3440 final boolean destroyActivityLocked(ActivityRecord r,
3441 boolean removeFromApp) {
3442 if (DEBUG_SWITCH) Slog.v(
3443 TAG, "Removing activity: token=" + r
3444 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3445 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3446 System.identityHashCode(r),
3447 r.task.taskId, r.shortComponentName);
3448
3449 boolean removedFromHistory = false;
3450
3451 cleanUpActivityLocked(r, false);
3452
3453 final boolean hadApp = r.app != null;
3454
3455 if (hadApp) {
3456 if (removeFromApp) {
3457 int idx = r.app.activities.indexOf(r);
3458 if (idx >= 0) {
3459 r.app.activities.remove(idx);
3460 }
3461 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
3462 mService.mHeavyWeightProcess = null;
3463 mService.mHandler.sendEmptyMessage(
3464 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
3465 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003466 if (r.app.activities.size() == 0) {
3467 // No longer have activities, so update location in
3468 // LRU list.
3469 mService.updateLruProcessLocked(r.app, true, false);
3470 }
3471 }
3472
3473 boolean skipDestroy = false;
3474
3475 try {
3476 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
3477 r.app.thread.scheduleDestroyActivity(r, r.finishing,
3478 r.configChangeFlags);
3479 } catch (Exception e) {
3480 // We can just ignore exceptions here... if the process
3481 // has crashed, our death notification will clean things
3482 // up.
3483 //Slog.w(TAG, "Exception thrown during finish", e);
3484 if (r.finishing) {
3485 removeActivityFromHistoryLocked(r);
3486 removedFromHistory = true;
3487 skipDestroy = true;
3488 }
3489 }
3490
3491 r.app = null;
3492 r.nowVisible = false;
3493
3494 if (r.finishing && !skipDestroy) {
3495 r.state = ActivityState.DESTROYING;
3496 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
3497 msg.obj = r;
3498 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
3499 } else {
3500 r.state = ActivityState.DESTROYED;
3501 }
3502 } else {
3503 // remove this record from the history.
3504 if (r.finishing) {
3505 removeActivityFromHistoryLocked(r);
3506 removedFromHistory = true;
3507 } else {
3508 r.state = ActivityState.DESTROYED;
3509 }
3510 }
3511
3512 r.configChangeFlags = 0;
3513
3514 if (!mLRUActivities.remove(r) && hadApp) {
3515 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
3516 }
3517
3518 return removedFromHistory;
3519 }
3520
3521 final void activityDestroyed(IBinder token) {
3522 synchronized (mService) {
3523 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, token);
3524
3525 int index = indexOfTokenLocked(token);
3526 if (index >= 0) {
3527 ActivityRecord r = (ActivityRecord)mHistory.get(index);
3528 if (r.state == ActivityState.DESTROYING) {
3529 final long origId = Binder.clearCallingIdentity();
3530 removeActivityFromHistoryLocked(r);
3531 Binder.restoreCallingIdentity(origId);
3532 }
3533 }
3534 }
3535 }
3536
3537 private static void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
3538 int i = list.size();
3539 if (localLOGV) Slog.v(
3540 TAG, "Removing app " + app + " from list " + list
3541 + " with " + i + " entries");
3542 while (i > 0) {
3543 i--;
3544 ActivityRecord r = (ActivityRecord)list.get(i);
3545 if (localLOGV) Slog.v(
3546 TAG, "Record #" + i + " " + r + ": app=" + r.app);
3547 if (r.app == app) {
3548 if (localLOGV) Slog.v(TAG, "Removing this entry!");
3549 list.remove(i);
3550 }
3551 }
3552 }
3553
3554 void removeHistoryRecordsForAppLocked(ProcessRecord app) {
3555 removeHistoryRecordsForAppLocked(mLRUActivities, app);
3556 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003557 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003558 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
3559 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
3560 }
3561
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003562 /**
3563 * Move the current home activity's task (if one exists) to the front
3564 * of the stack.
3565 */
3566 final void moveHomeToFrontLocked() {
3567 TaskRecord homeTask = null;
3568 for (int i=mHistory.size()-1; i>=0; i--) {
3569 ActivityRecord hr = (ActivityRecord)mHistory.get(i);
3570 if (hr.isHomeActivity) {
3571 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003572 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003573 }
3574 }
3575 if (homeTask != null) {
3576 moveTaskToFrontLocked(homeTask, null);
3577 }
3578 }
3579
3580
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003581 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason) {
3582 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
3583
3584 final int task = tr.taskId;
3585 int top = mHistory.size()-1;
3586
3587 if (top < 0 || ((ActivityRecord)mHistory.get(top)).task.taskId == task) {
3588 // nothing to do!
3589 return;
3590 }
3591
3592 ArrayList moved = new ArrayList();
3593
3594 // Applying the affinities may have removed entries from the history,
3595 // so get the size again.
3596 top = mHistory.size()-1;
3597 int pos = top;
3598
3599 // Shift all activities with this task up to the top
3600 // of the stack, keeping them in the same internal order.
3601 while (pos >= 0) {
3602 ActivityRecord r = (ActivityRecord)mHistory.get(pos);
3603 if (localLOGV) Slog.v(
3604 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003605 if (r.task.taskId == task) {
3606 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
3607 mHistory.remove(pos);
3608 mHistory.add(top, r);
3609 moved.add(0, r);
3610 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003611 }
3612 pos--;
3613 }
3614
3615 if (DEBUG_TRANSITION) Slog.v(TAG,
3616 "Prepare to front transition: task=" + tr);
3617 if (reason != null &&
3618 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003619 mService.mWindowManager.prepareAppTransition(
3620 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003621 ActivityRecord r = topRunningActivityLocked(null);
3622 if (r != null) {
3623 mNoAnimActivities.add(r);
3624 }
3625 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003626 mService.mWindowManager.prepareAppTransition(
3627 WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003628 }
3629
3630 mService.mWindowManager.moveAppTokensToTop(moved);
3631 if (VALIDATE_TOKENS) {
3632 mService.mWindowManager.validateAppTokens(mHistory);
3633 }
3634
3635 finishTaskMoveLocked(task);
3636 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
3637 }
3638
3639 private final void finishTaskMoveLocked(int task) {
3640 resumeTopActivityLocked(null);
3641 }
3642
3643 /**
3644 * Worker method for rearranging history stack. Implements the function of moving all
3645 * activities for a specific task (gathering them if disjoint) into a single group at the
3646 * bottom of the stack.
3647 *
3648 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
3649 * to premeptively cancel the move.
3650 *
3651 * @param task The taskId to collect and move to the bottom.
3652 * @return Returns true if the move completed, false if not.
3653 */
3654 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
3655 Slog.i(TAG, "moveTaskToBack: " + task);
3656
3657 // If we have a watcher, preflight the move before committing to it. First check
3658 // for *other* available tasks, but if none are available, then try again allowing the
3659 // current task to be selected.
3660 if (mMainStack && mService.mController != null) {
3661 ActivityRecord next = topRunningActivityLocked(null, task);
3662 if (next == null) {
3663 next = topRunningActivityLocked(null, 0);
3664 }
3665 if (next != null) {
3666 // ask watcher if this is allowed
3667 boolean moveOK = true;
3668 try {
3669 moveOK = mService.mController.activityResuming(next.packageName);
3670 } catch (RemoteException e) {
3671 mService.mController = null;
3672 }
3673 if (!moveOK) {
3674 return false;
3675 }
3676 }
3677 }
3678
3679 ArrayList moved = new ArrayList();
3680
3681 if (DEBUG_TRANSITION) Slog.v(TAG,
3682 "Prepare to back transition: task=" + task);
3683
3684 final int N = mHistory.size();
3685 int bottom = 0;
3686 int pos = 0;
3687
3688 // Shift all activities with this task down to the bottom
3689 // of the stack, keeping them in the same internal order.
3690 while (pos < N) {
3691 ActivityRecord r = (ActivityRecord)mHistory.get(pos);
3692 if (localLOGV) Slog.v(
3693 TAG, "At " + pos + " ckp " + r.task + ": " + r);
3694 if (r.task.taskId == task) {
3695 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
3696 mHistory.remove(pos);
3697 mHistory.add(bottom, r);
3698 moved.add(r);
3699 bottom++;
3700 }
3701 pos++;
3702 }
3703
3704 if (reason != null &&
3705 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003706 mService.mWindowManager.prepareAppTransition(
3707 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003708 ActivityRecord r = topRunningActivityLocked(null);
3709 if (r != null) {
3710 mNoAnimActivities.add(r);
3711 }
3712 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003713 mService.mWindowManager.prepareAppTransition(
3714 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003715 }
3716 mService.mWindowManager.moveAppTokensToBottom(moved);
3717 if (VALIDATE_TOKENS) {
3718 mService.mWindowManager.validateAppTokens(mHistory);
3719 }
3720
3721 finishTaskMoveLocked(task);
3722 return true;
3723 }
3724
3725 private final void logStartActivity(int tag, ActivityRecord r,
3726 TaskRecord task) {
3727 EventLog.writeEvent(tag,
3728 System.identityHashCode(r), task.taskId,
3729 r.shortComponentName, r.intent.getAction(),
3730 r.intent.getType(), r.intent.getDataString(),
3731 r.intent.getFlags());
3732 }
3733
3734 /**
3735 * Make sure the given activity matches the current configuration. Returns
3736 * false if the activity had to be destroyed. Returns true if the
3737 * configuration is the same, or the activity will remain running as-is
3738 * for whatever reason. Ensures the HistoryRecord is updated with the
3739 * correct configuration and all other bookkeeping is handled.
3740 */
3741 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
3742 int globalChanges) {
3743 if (mConfigWillChange) {
3744 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3745 "Skipping config check (will change): " + r);
3746 return true;
3747 }
3748
3749 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3750 "Ensuring correct configuration: " + r);
3751
3752 // Short circuit: if the two configurations are the exact same
3753 // object (the common case), then there is nothing to do.
3754 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003755 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003756 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3757 "Configuration unchanged in " + r);
3758 return true;
3759 }
3760
3761 // We don't worry about activities that are finishing.
3762 if (r.finishing) {
3763 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3764 "Configuration doesn't matter in finishing " + r);
3765 r.stopFreezingScreenLocked(false);
3766 return true;
3767 }
3768
3769 // Okay we now are going to make this activity have the new config.
3770 // But then we need to figure out how it needs to deal with that.
3771 Configuration oldConfig = r.configuration;
3772 r.configuration = newConfig;
3773
3774 // If the activity isn't currently running, just leave the new
3775 // configuration and it will pick that up next time it starts.
3776 if (r.app == null || r.app.thread == null) {
3777 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3778 "Configuration doesn't matter not running " + r);
3779 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003780 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003781 return true;
3782 }
3783
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07003784 // Figure out what has changed between the two configurations.
3785 int changes = oldConfig.diff(newConfig);
3786 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
3787 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
3788 + Integer.toHexString(changes) + ", handles=0x"
3789 + Integer.toHexString(r.info.configChanges)
3790 + ", newConfig=" + newConfig);
3791 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003792 if ((changes&(~r.info.configChanges)) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07003793 // Aha, the activity isn't handling the change, so DIE DIE DIE.
3794 r.configChangeFlags |= changes;
3795 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003796 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07003797 if (r.app == null || r.app.thread == null) {
3798 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3799 "Switch is destroying non-running " + r);
3800 destroyActivityLocked(r, true);
3801 } else if (r.state == ActivityState.PAUSING) {
3802 // A little annoying: we are waiting for this activity to
3803 // finish pausing. Let's not do anything now, but just
3804 // flag that it needs to be restarted when done pausing.
3805 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3806 "Switch is skipping already pausing " + r);
3807 r.configDestroy = true;
3808 return true;
3809 } else if (r.state == ActivityState.RESUMED) {
3810 // Try to optimize this case: the configuration is changing
3811 // and we need to restart the top, resumed activity.
3812 // Instead of doing the normal handshaking, just say
3813 // "restart!".
3814 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3815 "Switch is restarting resumed " + r);
3816 relaunchActivityLocked(r, r.configChangeFlags, true);
3817 r.configChangeFlags = 0;
3818 } else {
3819 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3820 "Switch is restarting non-resumed " + r);
3821 relaunchActivityLocked(r, r.configChangeFlags, false);
3822 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003823 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07003824
3825 // All done... tell the caller we weren't able to keep this
3826 // activity around.
3827 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003828 }
3829
3830 // Default case: the activity can handle this new configuration, so
3831 // hand it over. Note that we don't need to give it the new
3832 // configuration, since we always send configuration changes to all
3833 // process when they happen so it can just use whatever configuration
3834 // it last got.
3835 if (r.app != null && r.app.thread != null) {
3836 try {
3837 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
3838 r.app.thread.scheduleActivityConfigurationChanged(r);
3839 } catch (RemoteException e) {
3840 // If process died, whatever.
3841 }
3842 }
3843 r.stopFreezingScreenLocked(false);
3844
3845 return true;
3846 }
3847
3848 private final boolean relaunchActivityLocked(ActivityRecord r,
3849 int changes, boolean andResume) {
3850 List<ResultInfo> results = null;
3851 List<Intent> newIntents = null;
3852 if (andResume) {
3853 results = r.results;
3854 newIntents = r.newIntents;
3855 }
3856 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
3857 + " with results=" + results + " newIntents=" + newIntents
3858 + " andResume=" + andResume);
3859 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
3860 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
3861 r.task.taskId, r.shortComponentName);
3862
3863 r.startFreezingScreenLocked(r.app, 0);
3864
3865 try {
3866 if (DEBUG_SWITCH) Slog.i(TAG, "Switch is restarting resumed " + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003867 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003868 r.app.thread.scheduleRelaunchActivity(r, results, newIntents,
3869 changes, !andResume, mService.mConfiguration);
3870 // Note: don't need to call pauseIfSleepingLocked() here, because
3871 // the caller will only pass in 'andResume' if this activity is
3872 // currently resumed, which implies we aren't sleeping.
3873 } catch (RemoteException e) {
3874 return false;
3875 }
3876
3877 if (andResume) {
3878 r.results = null;
3879 r.newIntents = null;
3880 if (mMainStack) {
3881 mService.reportResumedActivityLocked(r);
3882 }
3883 }
3884
3885 return true;
3886 }
3887}