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