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