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