blob: 3a613bb11beed0ba2336ee9a3ae1b91d2ce86d30 [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
Dianne Hackborne7f97212011-02-24 14:40:20 -08001296 // Launching this app's activity, make sure the app is no longer
1297 // considered stopped.
1298 try {
1299 AppGlobals.getPackageManager().setPackageStoppedState(
1300 next.packageName, false);
1301 } catch (RemoteException e1) {
1302 }
1303
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001304 // We are starting up the next activity, so tell the window manager
1305 // that the previous one will be hidden soon. This way it can know
1306 // to ignore it when computing the desired screen orientation.
1307 if (prev != null) {
1308 if (prev.finishing) {
1309 if (DEBUG_TRANSITION) Slog.v(TAG,
1310 "Prepare close transition: prev=" + prev);
1311 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001312 mService.mWindowManager.prepareAppTransition(
1313 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001314 } else {
1315 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1316 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001317 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001318 }
1319 mService.mWindowManager.setAppWillBeHidden(prev);
1320 mService.mWindowManager.setAppVisibility(prev, false);
1321 } else {
1322 if (DEBUG_TRANSITION) Slog.v(TAG,
1323 "Prepare open transition: prev=" + prev);
1324 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001325 mService.mWindowManager.prepareAppTransition(
1326 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001327 } else {
1328 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1329 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001330 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001331 }
1332 }
1333 if (false) {
1334 mService.mWindowManager.setAppWillBeHidden(prev);
1335 mService.mWindowManager.setAppVisibility(prev, false);
1336 }
1337 } else if (mHistory.size() > 1) {
1338 if (DEBUG_TRANSITION) Slog.v(TAG,
1339 "Prepare open transition: no previous");
1340 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001341 mService.mWindowManager.prepareAppTransition(
1342 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001343 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001344 mService.mWindowManager.prepareAppTransition(
1345 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001346 }
1347 }
1348
1349 if (next.app != null && next.app.thread != null) {
1350 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1351
1352 // This activity is now becoming visible.
1353 mService.mWindowManager.setAppVisibility(next, true);
1354
1355 ActivityRecord lastResumedActivity = mResumedActivity;
1356 ActivityState lastState = next.state;
1357
1358 mService.updateCpuStats();
1359
1360 next.state = ActivityState.RESUMED;
1361 mResumedActivity = next;
1362 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001363 if (mMainStack) {
1364 mService.addRecentTaskLocked(next.task);
1365 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001366 mService.updateLruProcessLocked(next.app, true, true);
1367 updateLRUListLocked(next);
1368
1369 // Have the window manager re-evaluate the orientation of
1370 // the screen based on the new activity order.
1371 boolean updated = false;
1372 if (mMainStack) {
1373 synchronized (mService) {
1374 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1375 mService.mConfiguration,
1376 next.mayFreezeScreenLocked(next.app) ? next : null);
1377 if (config != null) {
1378 next.frozenBeforeDestroy = true;
1379 }
1380 updated = mService.updateConfigurationLocked(config, next);
1381 }
1382 }
1383 if (!updated) {
1384 // The configuration update wasn't able to keep the existing
1385 // instance of the activity, and instead started a new one.
1386 // We should be all done, but let's just make sure our activity
1387 // is still at the top and schedule another run if something
1388 // weird happened.
1389 ActivityRecord nextNext = topRunningActivityLocked(null);
1390 if (DEBUG_SWITCH) Slog.i(TAG,
1391 "Activity config changed during resume: " + next
1392 + ", new next: " + nextNext);
1393 if (nextNext != next) {
1394 // Do over!
1395 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1396 }
1397 if (mMainStack) {
1398 mService.setFocusedActivityLocked(next);
1399 }
1400 ensureActivitiesVisibleLocked(null, 0);
1401 mService.mWindowManager.executeAppTransition();
1402 mNoAnimActivities.clear();
1403 return true;
1404 }
1405
1406 try {
1407 // Deliver all pending results.
1408 ArrayList a = next.results;
1409 if (a != null) {
1410 final int N = a.size();
1411 if (!next.finishing && N > 0) {
1412 if (DEBUG_RESULTS) Slog.v(
1413 TAG, "Delivering results to " + next
1414 + ": " + a);
1415 next.app.thread.scheduleSendResult(next, a);
1416 }
1417 }
1418
1419 if (next.newIntents != null) {
1420 next.app.thread.scheduleNewIntent(next.newIntents, next);
1421 }
1422
1423 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
1424 System.identityHashCode(next),
1425 next.task.taskId, next.shortComponentName);
1426
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001427 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001428 next.app.thread.scheduleResumeActivity(next,
1429 mService.isNextTransitionForward());
1430
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001431 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001432
1433 } catch (Exception e) {
1434 // Whoops, need to restart this activity!
1435 next.state = lastState;
1436 mResumedActivity = lastResumedActivity;
1437 Slog.i(TAG, "Restarting because process died: " + next);
1438 if (!next.hasBeenLaunched) {
1439 next.hasBeenLaunched = true;
1440 } else {
1441 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1442 mService.mWindowManager.setAppStartingWindow(
1443 next, next.packageName, next.theme,
1444 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001445 next.labelRes, next.icon, next.windowFlags,
1446 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001447 }
1448 }
1449 startSpecificActivityLocked(next, true, false);
1450 return true;
1451 }
1452
1453 // From this point on, if something goes wrong there is no way
1454 // to recover the activity.
1455 try {
1456 next.visible = true;
1457 completeResumeLocked(next);
1458 } catch (Exception e) {
1459 // If any exception gets thrown, toss away this
1460 // activity and try the next one.
1461 Slog.w(TAG, "Exception thrown during resume of " + next, e);
1462 requestFinishActivityLocked(next, Activity.RESULT_CANCELED, null,
1463 "resume-exception");
1464 return true;
1465 }
1466
1467 // Didn't need to use the icicle, and it is now out of date.
1468 next.icicle = null;
1469 next.haveState = false;
1470 next.stopped = false;
1471
1472 } else {
1473 // Whoops, need to restart this activity!
1474 if (!next.hasBeenLaunched) {
1475 next.hasBeenLaunched = true;
1476 } else {
1477 if (SHOW_APP_STARTING_PREVIEW) {
1478 mService.mWindowManager.setAppStartingWindow(
1479 next, next.packageName, next.theme,
1480 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001481 next.labelRes, next.icon, next.windowFlags,
1482 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001483 }
1484 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1485 }
1486 startSpecificActivityLocked(next, true, true);
1487 }
1488
1489 return true;
1490 }
1491
1492 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001493 boolean doResume, boolean keepCurTransition) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001494 final int NH = mHistory.size();
1495
1496 int addPos = -1;
1497
1498 if (!newTask) {
1499 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001500 boolean startIt = true;
1501 for (int i = NH-1; i >= 0; i--) {
1502 ActivityRecord p = (ActivityRecord)mHistory.get(i);
1503 if (p.finishing) {
1504 continue;
1505 }
1506 if (p.task == r.task) {
1507 // Here it is! Now, if this is not yet visible to the
1508 // user, then just add it without starting; it will
1509 // get started when the user navigates back to it.
1510 addPos = i+1;
1511 if (!startIt) {
1512 mHistory.add(addPos, r);
1513 r.inHistory = true;
1514 r.task.numActivities++;
1515 mService.mWindowManager.addAppToken(addPos, r, r.task.taskId,
1516 r.info.screenOrientation, r.fullscreen);
1517 if (VALIDATE_TOKENS) {
1518 mService.mWindowManager.validateAppTokens(mHistory);
1519 }
1520 return;
1521 }
1522 break;
1523 }
1524 if (p.fullscreen) {
1525 startIt = false;
1526 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001527 }
1528 }
1529
1530 // Place a new activity at top of stack, so it is next to interact
1531 // with the user.
1532 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001533 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001534 }
1535
1536 // If we are not placing the new activity frontmost, we do not want
1537 // to deliver the onUserLeaving callback to the actual frontmost
1538 // activity
1539 if (addPos < NH) {
1540 mUserLeaving = false;
1541 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1542 }
1543
1544 // Slot the activity into the history stack and proceed
1545 mHistory.add(addPos, r);
1546 r.inHistory = true;
1547 r.frontOfTask = newTask;
1548 r.task.numActivities++;
1549 if (NH > 0) {
1550 // We want to show the starting preview window if we are
1551 // switching to a new task, or the next activity's process is
1552 // not currently running.
1553 boolean showStartingIcon = newTask;
1554 ProcessRecord proc = r.app;
1555 if (proc == null) {
1556 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1557 }
1558 if (proc == null || proc.thread == null) {
1559 showStartingIcon = true;
1560 }
1561 if (DEBUG_TRANSITION) Slog.v(TAG,
1562 "Prepare open transition: starting " + r);
1563 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001564 mService.mWindowManager.prepareAppTransition(
1565 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001566 mNoAnimActivities.add(r);
1567 } else if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
1568 mService.mWindowManager.prepareAppTransition(
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001569 WindowManagerPolicy.TRANSIT_TASK_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001570 mNoAnimActivities.remove(r);
1571 } else {
1572 mService.mWindowManager.prepareAppTransition(newTask
1573 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001574 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001575 mNoAnimActivities.remove(r);
1576 }
1577 mService.mWindowManager.addAppToken(
1578 addPos, r, r.task.taskId, r.info.screenOrientation, r.fullscreen);
1579 boolean doShow = true;
1580 if (newTask) {
1581 // Even though this activity is starting fresh, we still need
1582 // to reset it to make sure we apply affinities to move any
1583 // existing activities from other tasks in to it.
1584 // If the caller has requested that the target task be
1585 // reset, then do so.
1586 if ((r.intent.getFlags()
1587 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1588 resetTaskIfNeededLocked(r, r);
1589 doShow = topRunningNonDelayedActivityLocked(null) == r;
1590 }
1591 }
1592 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1593 // Figure out if we are transitioning from another activity that is
1594 // "has the same starting icon" as the next one. This allows the
1595 // window manager to keep the previous window it had previously
1596 // created, if it still had one.
1597 ActivityRecord prev = mResumedActivity;
1598 if (prev != null) {
1599 // We don't want to reuse the previous starting preview if:
1600 // (1) The current activity is in a different task.
1601 if (prev.task != r.task) prev = null;
1602 // (2) The current activity is already displayed.
1603 else if (prev.nowVisible) prev = null;
1604 }
1605 mService.mWindowManager.setAppStartingWindow(
1606 r, r.packageName, r.theme, r.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001607 r.labelRes, r.icon, r.windowFlags, prev, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001608 }
1609 } else {
1610 // If this is the first activity, don't do any fancy animations,
1611 // because there is nothing for it to animate on top of.
1612 mService.mWindowManager.addAppToken(addPos, r, r.task.taskId,
1613 r.info.screenOrientation, r.fullscreen);
1614 }
1615 if (VALIDATE_TOKENS) {
1616 mService.mWindowManager.validateAppTokens(mHistory);
1617 }
1618
1619 if (doResume) {
1620 resumeTopActivityLocked(null);
1621 }
1622 }
1623
1624 /**
1625 * Perform a reset of the given task, if needed as part of launching it.
1626 * Returns the new HistoryRecord at the top of the task.
1627 */
1628 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1629 ActivityRecord newActivity) {
1630 boolean forceReset = (newActivity.info.flags
1631 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001632 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1633 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001634 if ((newActivity.info.flags
1635 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1636 forceReset = true;
1637 }
1638 }
1639
1640 final TaskRecord task = taskTop.task;
1641
1642 // We are going to move through the history list so that we can look
1643 // at each activity 'target' with 'below' either the interesting
1644 // activity immediately below it in the stack or null.
1645 ActivityRecord target = null;
1646 int targetI = 0;
1647 int taskTopI = -1;
1648 int replyChainEnd = -1;
1649 int lastReparentPos = -1;
1650 for (int i=mHistory.size()-1; i>=-1; i--) {
1651 ActivityRecord below = i >= 0 ? (ActivityRecord)mHistory.get(i) : null;
1652
1653 if (below != null && below.finishing) {
1654 continue;
1655 }
1656 if (target == null) {
1657 target = below;
1658 targetI = i;
1659 // If we were in the middle of a reply chain before this
1660 // task, it doesn't appear like the root of the chain wants
1661 // anything interesting, so drop it.
1662 replyChainEnd = -1;
1663 continue;
1664 }
1665
1666 final int flags = target.info.flags;
1667
1668 final boolean finishOnTaskLaunch =
1669 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1670 final boolean allowTaskReparenting =
1671 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1672
1673 if (target.task == task) {
1674 // We are inside of the task being reset... we'll either
1675 // finish this activity, push it out for another task,
1676 // or leave it as-is. We only do this
1677 // for activities that are not the root of the task (since
1678 // if we finish the root, we may no longer have the task!).
1679 if (taskTopI < 0) {
1680 taskTopI = targetI;
1681 }
1682 if (below != null && below.task == task) {
1683 final boolean clearWhenTaskReset =
1684 (target.intent.getFlags()
1685 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
1686 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
1687 // If this activity is sending a reply to a previous
1688 // activity, we can't do anything with it now until
1689 // we reach the start of the reply chain.
1690 // XXX note that we are assuming the result is always
1691 // to the previous activity, which is almost always
1692 // the case but we really shouldn't count on.
1693 if (replyChainEnd < 0) {
1694 replyChainEnd = targetI;
1695 }
1696 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
1697 && target.taskAffinity != null
1698 && !target.taskAffinity.equals(task.affinity)) {
1699 // If this activity has an affinity for another
1700 // task, then we need to move it out of here. We will
1701 // move it as far out of the way as possible, to the
1702 // bottom of the activity stack. This also keeps it
1703 // correctly ordered with any activities we previously
1704 // moved.
1705 ActivityRecord p = (ActivityRecord)mHistory.get(0);
1706 if (target.taskAffinity != null
1707 && target.taskAffinity.equals(p.task.affinity)) {
1708 // If the activity currently at the bottom has the
1709 // same task affinity as the one we are moving,
1710 // then merge it into the same task.
1711 target.task = p.task;
1712 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1713 + " out to bottom task " + p.task);
1714 } else {
1715 mService.mCurTask++;
1716 if (mService.mCurTask <= 0) {
1717 mService.mCurTask = 1;
1718 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001719 target.task = new TaskRecord(mService.mCurTask, target.info, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001720 target.task.affinityIntent = target.intent;
1721 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1722 + " out to new task " + target.task);
1723 }
1724 mService.mWindowManager.setAppGroupId(target, task.taskId);
1725 if (replyChainEnd < 0) {
1726 replyChainEnd = targetI;
1727 }
1728 int dstPos = 0;
1729 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
1730 p = (ActivityRecord)mHistory.get(srcPos);
1731 if (p.finishing) {
1732 continue;
1733 }
1734 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
1735 + " out to target's task " + target.task);
1736 task.numActivities--;
1737 p.task = target.task;
1738 target.task.numActivities++;
1739 mHistory.remove(srcPos);
1740 mHistory.add(dstPos, p);
1741 mService.mWindowManager.moveAppToken(dstPos, p);
1742 mService.mWindowManager.setAppGroupId(p, p.task.taskId);
1743 dstPos++;
1744 if (VALIDATE_TOKENS) {
1745 mService.mWindowManager.validateAppTokens(mHistory);
1746 }
1747 i++;
1748 }
1749 if (taskTop == p) {
1750 taskTop = below;
1751 }
1752 if (taskTopI == replyChainEnd) {
1753 taskTopI = -1;
1754 }
1755 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001756 } else if (forceReset || finishOnTaskLaunch
1757 || clearWhenTaskReset) {
1758 // If the activity should just be removed -- either
1759 // because it asks for it, or the task should be
1760 // cleared -- then finish it and anything that is
1761 // part of its reply chain.
1762 if (clearWhenTaskReset) {
1763 // In this case, we want to finish this activity
1764 // and everything above it, so be sneaky and pretend
1765 // like these are all in the reply chain.
1766 replyChainEnd = targetI+1;
1767 while (replyChainEnd < mHistory.size() &&
1768 ((ActivityRecord)mHistory.get(
1769 replyChainEnd)).task == task) {
1770 replyChainEnd++;
1771 }
1772 replyChainEnd--;
1773 } else if (replyChainEnd < 0) {
1774 replyChainEnd = targetI;
1775 }
1776 ActivityRecord p = null;
1777 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
1778 p = (ActivityRecord)mHistory.get(srcPos);
1779 if (p.finishing) {
1780 continue;
1781 }
1782 if (finishActivityLocked(p, srcPos,
1783 Activity.RESULT_CANCELED, null, "reset")) {
1784 replyChainEnd--;
1785 srcPos--;
1786 }
1787 }
1788 if (taskTop == p) {
1789 taskTop = below;
1790 }
1791 if (taskTopI == replyChainEnd) {
1792 taskTopI = -1;
1793 }
1794 replyChainEnd = -1;
1795 } else {
1796 // If we were in the middle of a chain, well the
1797 // activity that started it all doesn't want anything
1798 // special, so leave it all as-is.
1799 replyChainEnd = -1;
1800 }
1801 } else {
1802 // Reached the bottom of the task -- any reply chain
1803 // should be left as-is.
1804 replyChainEnd = -1;
1805 }
1806
1807 } else if (target.resultTo != null) {
1808 // If this activity is sending a reply to a previous
1809 // activity, we can't do anything with it now until
1810 // we reach the start of the reply chain.
1811 // XXX note that we are assuming the result is always
1812 // to the previous activity, which is almost always
1813 // the case but we really shouldn't count on.
1814 if (replyChainEnd < 0) {
1815 replyChainEnd = targetI;
1816 }
1817
1818 } else if (taskTopI >= 0 && allowTaskReparenting
1819 && task.affinity != null
1820 && task.affinity.equals(target.taskAffinity)) {
1821 // We are inside of another task... if this activity has
1822 // an affinity for our task, then either remove it if we are
1823 // clearing or move it over to our task. Note that
1824 // we currently punt on the case where we are resetting a
1825 // task that is not at the top but who has activities above
1826 // with an affinity to it... this is really not a normal
1827 // case, and we will need to later pull that task to the front
1828 // and usually at that point we will do the reset and pick
1829 // up those remaining activities. (This only happens if
1830 // someone starts an activity in a new task from an activity
1831 // in a task that is not currently on top.)
1832 if (forceReset || finishOnTaskLaunch) {
1833 if (replyChainEnd < 0) {
1834 replyChainEnd = targetI;
1835 }
1836 ActivityRecord p = null;
1837 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
1838 p = (ActivityRecord)mHistory.get(srcPos);
1839 if (p.finishing) {
1840 continue;
1841 }
1842 if (finishActivityLocked(p, srcPos,
1843 Activity.RESULT_CANCELED, null, "reset")) {
1844 taskTopI--;
1845 lastReparentPos--;
1846 replyChainEnd--;
1847 srcPos--;
1848 }
1849 }
1850 replyChainEnd = -1;
1851 } else {
1852 if (replyChainEnd < 0) {
1853 replyChainEnd = targetI;
1854 }
1855 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
1856 ActivityRecord p = (ActivityRecord)mHistory.get(srcPos);
1857 if (p.finishing) {
1858 continue;
1859 }
1860 if (lastReparentPos < 0) {
1861 lastReparentPos = taskTopI;
1862 taskTop = p;
1863 } else {
1864 lastReparentPos--;
1865 }
1866 mHistory.remove(srcPos);
1867 p.task.numActivities--;
1868 p.task = task;
1869 mHistory.add(lastReparentPos, p);
1870 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
1871 + " in to resetting task " + task);
1872 task.numActivities++;
1873 mService.mWindowManager.moveAppToken(lastReparentPos, p);
1874 mService.mWindowManager.setAppGroupId(p, p.task.taskId);
1875 if (VALIDATE_TOKENS) {
1876 mService.mWindowManager.validateAppTokens(mHistory);
1877 }
1878 }
1879 replyChainEnd = -1;
1880
1881 // Now we've moved it in to place... but what if this is
1882 // a singleTop activity and we have put it on top of another
1883 // instance of the same activity? Then we drop the instance
1884 // below so it remains singleTop.
1885 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
1886 for (int j=lastReparentPos-1; j>=0; j--) {
1887 ActivityRecord p = (ActivityRecord)mHistory.get(j);
1888 if (p.finishing) {
1889 continue;
1890 }
1891 if (p.intent.getComponent().equals(target.intent.getComponent())) {
1892 if (finishActivityLocked(p, j,
1893 Activity.RESULT_CANCELED, null, "replace")) {
1894 taskTopI--;
1895 lastReparentPos--;
1896 }
1897 }
1898 }
1899 }
1900 }
1901 }
1902
1903 target = below;
1904 targetI = i;
1905 }
1906
1907 return taskTop;
1908 }
1909
1910 /**
1911 * Perform clear operation as requested by
1912 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
1913 * stack to the given task, then look for
1914 * an instance of that activity in the stack and, if found, finish all
1915 * activities on top of it and return the instance.
1916 *
1917 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001918 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001919 * or null if none was found.
1920 */
1921 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001922 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001923 int i = mHistory.size();
1924
1925 // First find the requested task.
1926 while (i > 0) {
1927 i--;
1928 ActivityRecord r = (ActivityRecord)mHistory.get(i);
1929 if (r.task.taskId == taskId) {
1930 i++;
1931 break;
1932 }
1933 }
1934
1935 // Now clear it.
1936 while (i > 0) {
1937 i--;
1938 ActivityRecord r = (ActivityRecord)mHistory.get(i);
1939 if (r.finishing) {
1940 continue;
1941 }
1942 if (r.task.taskId != taskId) {
1943 return null;
1944 }
1945 if (r.realActivity.equals(newR.realActivity)) {
1946 // Here it is! Now finish everything in front...
1947 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001948 while (i < (mHistory.size()-1)) {
1949 i++;
1950 r = (ActivityRecord)mHistory.get(i);
1951 if (r.task.taskId != taskId) {
1952 break;
1953 }
1954 if (r.finishing) {
1955 continue;
1956 }
1957 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
1958 null, "clear")) {
1959 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001960 }
1961 }
1962
1963 // Finally, if this is a normal launch mode (that is, not
1964 // expecting onNewIntent()), then we will finish the current
1965 // instance of the activity so a new fresh one can be started.
1966 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
1967 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
1968 if (!ret.finishing) {
1969 int index = indexOfTokenLocked(ret);
1970 if (index >= 0) {
1971 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
1972 null, "clear");
1973 }
1974 return null;
1975 }
1976 }
1977
1978 return ret;
1979 }
1980 }
1981
1982 return null;
1983 }
1984
1985 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001986 * Completely remove all activities associated with an existing task.
1987 */
1988 private final void performClearTaskLocked(int taskId) {
1989 int i = mHistory.size();
1990
1991 // First find the requested task.
1992 while (i > 0) {
1993 i--;
1994 ActivityRecord r = (ActivityRecord)mHistory.get(i);
1995 if (r.task.taskId == taskId) {
1996 i++;
1997 break;
1998 }
1999 }
2000
2001 // Now clear it.
2002 while (i > 0) {
2003 i--;
2004 ActivityRecord r = (ActivityRecord)mHistory.get(i);
2005 if (r.finishing) {
2006 continue;
2007 }
2008 if (r.task.taskId != taskId) {
2009 // We hit the bottom. Now finish it all...
2010 while (i < (mHistory.size()-1)) {
2011 i++;
2012 r = (ActivityRecord)mHistory.get(i);
2013 if (r.task.taskId != taskId) {
2014 // Whoops hit the end.
2015 return;
2016 }
2017 if (r.finishing) {
2018 continue;
2019 }
2020 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2021 null, "clear")) {
2022 i--;
2023 }
2024 }
2025 return;
2026 }
2027 }
2028 }
2029
2030 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002031 * Find the activity in the history stack within the given task. Returns
2032 * the index within the history at which it's found, or < 0 if not found.
2033 */
2034 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2035 int i = mHistory.size();
2036 while (i > 0) {
2037 i--;
2038 ActivityRecord candidate = (ActivityRecord)mHistory.get(i);
2039 if (candidate.task.taskId != task) {
2040 break;
2041 }
2042 if (candidate.realActivity.equals(r.realActivity)) {
2043 return i;
2044 }
2045 }
2046
2047 return -1;
2048 }
2049
2050 /**
2051 * Reorder the history stack so that the activity at the given index is
2052 * brought to the front.
2053 */
2054 private final ActivityRecord moveActivityToFrontLocked(int where) {
2055 ActivityRecord newTop = (ActivityRecord)mHistory.remove(where);
2056 int top = mHistory.size();
2057 ActivityRecord oldTop = (ActivityRecord)mHistory.get(top-1);
2058 mHistory.add(top, newTop);
2059 oldTop.frontOfTask = false;
2060 newTop.frontOfTask = true;
2061 return newTop;
2062 }
2063
2064 final int startActivityLocked(IApplicationThread caller,
2065 Intent intent, String resolvedType,
2066 Uri[] grantedUriPermissions,
2067 int grantedMode, ActivityInfo aInfo, IBinder resultTo,
2068 String resultWho, int requestCode,
2069 int callingPid, int callingUid, boolean onlyIfNeeded,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002070 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002071
2072 int err = START_SUCCESS;
2073
2074 ProcessRecord callerApp = null;
2075 if (caller != null) {
2076 callerApp = mService.getRecordForAppLocked(caller);
2077 if (callerApp != null) {
2078 callingPid = callerApp.pid;
2079 callingUid = callerApp.info.uid;
2080 } else {
2081 Slog.w(TAG, "Unable to find app for caller " + caller
2082 + " (pid=" + callingPid + ") when starting: "
2083 + intent.toString());
2084 err = START_PERMISSION_DENIED;
2085 }
2086 }
2087
2088 if (err == START_SUCCESS) {
2089 Slog.i(TAG, "Starting: " + intent + " from pid "
2090 + (callerApp != null ? callerApp.pid : callingPid));
2091 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002092
2093 ActivityRecord sourceRecord = null;
2094 ActivityRecord resultRecord = null;
2095 if (resultTo != null) {
2096 int index = indexOfTokenLocked(resultTo);
2097 if (DEBUG_RESULTS) Slog.v(
2098 TAG, "Sending result to " + resultTo + " (index " + index + ")");
2099 if (index >= 0) {
2100 sourceRecord = (ActivityRecord)mHistory.get(index);
2101 if (requestCode >= 0 && !sourceRecord.finishing) {
2102 resultRecord = sourceRecord;
2103 }
2104 }
2105 }
2106
2107 int launchFlags = intent.getFlags();
2108
2109 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2110 && sourceRecord != null) {
2111 // Transfer the result target from the source activity to the new
2112 // one being started, including any failures.
2113 if (requestCode >= 0) {
2114 return START_FORWARD_AND_REQUEST_CONFLICT;
2115 }
2116 resultRecord = sourceRecord.resultTo;
2117 resultWho = sourceRecord.resultWho;
2118 requestCode = sourceRecord.requestCode;
2119 sourceRecord.resultTo = null;
2120 if (resultRecord != null) {
2121 resultRecord.removeResultsLocked(
2122 sourceRecord, resultWho, requestCode);
2123 }
2124 }
2125
Dianne Hackbornefb58102010-10-14 16:47:34 -07002126 if (err == START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002127 // We couldn't find a class that can handle the given Intent.
2128 // That's the end of that!
2129 err = START_INTENT_NOT_RESOLVED;
2130 }
2131
2132 if (err == START_SUCCESS && aInfo == null) {
2133 // We couldn't find the specific class specified in the Intent.
2134 // Also the end of the line.
2135 err = START_CLASS_NOT_FOUND;
2136 }
2137
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002138 if (err != START_SUCCESS) {
2139 if (resultRecord != null) {
2140 sendActivityResultLocked(-1,
2141 resultRecord, resultWho, requestCode,
2142 Activity.RESULT_CANCELED, null);
2143 }
2144 return err;
2145 }
2146
2147 final int perm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002148 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002149 if (perm != PackageManager.PERMISSION_GRANTED) {
2150 if (resultRecord != null) {
2151 sendActivityResultLocked(-1,
2152 resultRecord, resultWho, requestCode,
2153 Activity.RESULT_CANCELED, null);
2154 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002155 String msg;
2156 if (!aInfo.exported) {
2157 msg = "Permission Denial: starting " + intent.toString()
2158 + " from " + callerApp + " (pid=" + callingPid
2159 + ", uid=" + callingUid + ")"
2160 + " not exported from uid " + aInfo.applicationInfo.uid;
2161 } else {
2162 msg = "Permission Denial: starting " + intent.toString()
2163 + " from " + callerApp + " (pid=" + callingPid
2164 + ", uid=" + callingUid + ")"
2165 + " requires " + aInfo.permission;
2166 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002167 Slog.w(TAG, msg);
2168 throw new SecurityException(msg);
2169 }
2170
2171 if (mMainStack) {
2172 if (mService.mController != null) {
2173 boolean abort = false;
2174 try {
2175 // The Intent we give to the watcher has the extra data
2176 // stripped off, since it can contain private information.
2177 Intent watchIntent = intent.cloneFilter();
2178 abort = !mService.mController.activityStarting(watchIntent,
2179 aInfo.applicationInfo.packageName);
2180 } catch (RemoteException e) {
2181 mService.mController = null;
2182 }
2183
2184 if (abort) {
2185 if (resultRecord != null) {
2186 sendActivityResultLocked(-1,
2187 resultRecord, resultWho, requestCode,
2188 Activity.RESULT_CANCELED, null);
2189 }
2190 // We pretend to the caller that it was really started, but
2191 // they will just get a cancel result.
2192 return START_SUCCESS;
2193 }
2194 }
2195 }
2196
2197 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2198 intent, resolvedType, aInfo, mService.mConfiguration,
2199 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002200 if (outActivity != null) {
2201 outActivity[0] = r;
2202 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002203
2204 if (mMainStack) {
2205 if (mResumedActivity == null
2206 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2207 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2208 PendingActivityLaunch pal = new PendingActivityLaunch();
2209 pal.r = r;
2210 pal.sourceRecord = sourceRecord;
2211 pal.grantedUriPermissions = grantedUriPermissions;
2212 pal.grantedMode = grantedMode;
2213 pal.onlyIfNeeded = onlyIfNeeded;
2214 mService.mPendingActivityLaunches.add(pal);
2215 return START_SWITCHES_CANCELED;
2216 }
2217 }
2218
2219 if (mService.mDidAppSwitch) {
2220 // This is the second allowed switch since we stopped switches,
2221 // so now just generally allow switches. Use case: user presses
2222 // home (switches disabled, switch to home, mDidAppSwitch now true);
2223 // user taps a home icon (coming from home so allowed, we hit here
2224 // and now allow anyone to switch again).
2225 mService.mAppSwitchesAllowedTime = 0;
2226 } else {
2227 mService.mDidAppSwitch = true;
2228 }
2229
2230 mService.doPendingActivityLaunchesLocked(false);
2231 }
2232
2233 return startActivityUncheckedLocked(r, sourceRecord,
2234 grantedUriPermissions, grantedMode, onlyIfNeeded, true);
2235 }
2236
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002237 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2238 if ((launchFlags &
2239 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2240 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2241 // Caller wants to appear on home activity, so before starting
2242 // their own activity we will bring home to the front.
2243 moveHomeToFrontLocked();
2244 }
2245 }
2246
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002247 final int startActivityUncheckedLocked(ActivityRecord r,
2248 ActivityRecord sourceRecord, Uri[] grantedUriPermissions,
2249 int grantedMode, boolean onlyIfNeeded, boolean doResume) {
2250 final Intent intent = r.intent;
2251 final int callingUid = r.launchedFromUid;
2252
2253 int launchFlags = intent.getFlags();
2254
2255 // We'll invoke onUserLeaving before onPause only if the launching
2256 // activity did not explicitly state that this is an automated launch.
2257 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2258 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2259 "startActivity() => mUserLeaving=" + mUserLeaving);
2260
2261 // If the caller has asked not to resume at this point, we make note
2262 // of this in the record so that we can skip it when trying to find
2263 // the top running activity.
2264 if (!doResume) {
2265 r.delayedResume = true;
2266 }
2267
2268 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2269 != 0 ? r : null;
2270
2271 // If the onlyIfNeeded flag is set, then we can do this if the activity
2272 // being launched is the same as the one making the call... or, as
2273 // a special case, if we do not know the caller then we count the
2274 // current top activity as the caller.
2275 if (onlyIfNeeded) {
2276 ActivityRecord checkedCaller = sourceRecord;
2277 if (checkedCaller == null) {
2278 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2279 }
2280 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2281 // Caller is not the same as launcher, so always needed.
2282 onlyIfNeeded = false;
2283 }
2284 }
2285
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002286 if (sourceRecord == null) {
2287 // This activity is not being started from another... in this
2288 // case we -always- start a new task.
2289 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2290 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2291 + intent);
2292 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2293 }
2294 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2295 // The original activity who is starting us is running as a single
2296 // instance... this new activity it is starting must go on its
2297 // own task.
2298 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2299 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2300 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2301 // The activity being started is a single instance... it always
2302 // gets launched into its own task.
2303 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2304 }
2305
2306 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2307 // For whatever reason this activity is being launched into a new
2308 // task... yet the caller has requested a result back. Well, that
2309 // is pretty messed up, so instead immediately send back a cancel
2310 // and let the new task continue launched as normal without a
2311 // dependency on its originator.
2312 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2313 sendActivityResultLocked(-1,
2314 r.resultTo, r.resultWho, r.requestCode,
2315 Activity.RESULT_CANCELED, null);
2316 r.resultTo = null;
2317 }
2318
2319 boolean addingToTask = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002320 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002321 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2322 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2323 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2324 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2325 // If bring to front is requested, and no result is requested, and
2326 // we can find a task that was started with this same
2327 // component, then instead of launching bring that one to the front.
2328 if (r.resultTo == null) {
2329 // See if there is a task to bring to the front. If this is
2330 // a SINGLE_INSTANCE activity, there can be one and only one
2331 // instance of it in the history, and it is always in its own
2332 // unique task, so we do a special search.
2333 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2334 ? findTaskLocked(intent, r.info)
2335 : findActivityLocked(intent, r.info);
2336 if (taskTop != null) {
2337 if (taskTop.task.intent == null) {
2338 // This task was started because of movement of
2339 // the activity based on affinity... now that we
2340 // are actually launching it, we can assign the
2341 // base intent.
2342 taskTop.task.setIntent(intent, r.info);
2343 }
2344 // If the target task is not in the front, then we need
2345 // to bring it to the front... except... well, with
2346 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2347 // to have the same behavior as if a new instance was
2348 // being started, which means not bringing it to the front
2349 // if the caller is not itself in the front.
2350 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002351 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002352 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2353 boolean callerAtFront = sourceRecord == null
2354 || curTop.task == sourceRecord.task;
2355 if (callerAtFront) {
2356 // We really do want to push this one into the
2357 // user's face, right now.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002358 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002359 moveTaskToFrontLocked(taskTop.task, r);
2360 }
2361 }
2362 // If the caller has requested that the target task be
2363 // reset, then do so.
2364 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2365 taskTop = resetTaskIfNeededLocked(taskTop, r);
2366 }
2367 if (onlyIfNeeded) {
2368 // We don't need to start a new activity, and
2369 // the client said not to do anything if that
2370 // is the case, so this is it! And for paranoia, make
2371 // sure we have correctly resumed the top activity.
2372 if (doResume) {
2373 resumeTopActivityLocked(null);
2374 }
2375 return START_RETURN_INTENT_TO_CALLER;
2376 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002377 if ((launchFlags &
2378 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2379 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2380 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002381 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002382 // not be too hard...
2383 reuseTask = taskTop.task;
2384 performClearTaskLocked(taskTop.task.taskId);
2385 reuseTask.setIntent(r.intent, r.info);
2386 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002387 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2388 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2389 // In this situation we want to remove all activities
2390 // from the task up to the one being started. In most
2391 // cases this means we are resetting the task to its
2392 // initial state.
2393 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002394 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002395 if (top != null) {
2396 if (top.frontOfTask) {
2397 // Activity aliases may mean we use different
2398 // intents for the top activity, so make sure
2399 // the task now has the identity of the new
2400 // intent.
2401 top.task.setIntent(r.intent, r.info);
2402 }
2403 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002404 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002405 } else {
2406 // A special case: we need to
2407 // start the activity because it is not currently
2408 // running, and the caller has asked to clear the
2409 // current task to have this activity at the top.
2410 addingToTask = true;
2411 // Now pretend like this activity is being started
2412 // by the top of its task, so it is put in the
2413 // right place.
2414 sourceRecord = taskTop;
2415 }
2416 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2417 // In this case the top activity on the task is the
2418 // same as the one being launched, so we take that
2419 // as a request to bring the task to the foreground.
2420 // If the top activity in the task is the root
2421 // activity, deliver this new intent to it if it
2422 // desires.
2423 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2424 && taskTop.realActivity.equals(r.realActivity)) {
2425 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2426 if (taskTop.frontOfTask) {
2427 taskTop.task.setIntent(r.intent, r.info);
2428 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002429 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002430 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2431 // In this case we are launching the root activity
2432 // of the task, but with a different intent. We
2433 // should start a new instance on top.
2434 addingToTask = true;
2435 sourceRecord = taskTop;
2436 }
2437 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2438 // In this case an activity is being launched in to an
2439 // existing task, without resetting that task. This
2440 // is typically the situation of launching an activity
2441 // from a notification or shortcut. We want to place
2442 // the new activity on top of the current task.
2443 addingToTask = true;
2444 sourceRecord = taskTop;
2445 } else if (!taskTop.task.rootWasReset) {
2446 // In this case we are launching in to an existing task
2447 // that has not yet been started from its front door.
2448 // The current task has been brought to the front.
2449 // Ideally, we'd probably like to place this new task
2450 // at the bottom of its stack, but that's a little hard
2451 // to do with the current organization of the code so
2452 // for now we'll just drop it.
2453 taskTop.task.setIntent(r.intent, r.info);
2454 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002455 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002456 // We didn't do anything... but it was needed (a.k.a., client
2457 // don't use that intent!) And for paranoia, make
2458 // sure we have correctly resumed the top activity.
2459 if (doResume) {
2460 resumeTopActivityLocked(null);
2461 }
2462 return START_TASK_TO_FRONT;
2463 }
2464 }
2465 }
2466 }
2467
2468 //String uri = r.intent.toURI();
2469 //Intent intent2 = new Intent(uri);
2470 //Slog.i(TAG, "Given intent: " + r.intent);
2471 //Slog.i(TAG, "URI is: " + uri);
2472 //Slog.i(TAG, "To intent: " + intent2);
2473
2474 if (r.packageName != null) {
2475 // If the activity being launched is the same as the one currently
2476 // at the top, then we need to check if it should only be launched
2477 // once.
2478 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2479 if (top != null && r.resultTo == null) {
2480 if (top.realActivity.equals(r.realActivity)) {
2481 if (top.app != null && top.app.thread != null) {
2482 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2483 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2484 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2485 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2486 // For paranoia, make sure we have correctly
2487 // resumed the top activity.
2488 if (doResume) {
2489 resumeTopActivityLocked(null);
2490 }
2491 if (onlyIfNeeded) {
2492 // We don't need to start a new activity, and
2493 // the client said not to do anything if that
2494 // is the case, so this is it!
2495 return START_RETURN_INTENT_TO_CALLER;
2496 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002497 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002498 return START_DELIVERED_TO_TOP;
2499 }
2500 }
2501 }
2502 }
2503
2504 } else {
2505 if (r.resultTo != null) {
2506 sendActivityResultLocked(-1,
2507 r.resultTo, r.resultWho, r.requestCode,
2508 Activity.RESULT_CANCELED, null);
2509 }
2510 return START_CLASS_NOT_FOUND;
2511 }
2512
2513 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002514 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002515
2516 // Should this be considered a new task?
2517 if (r.resultTo == null && !addingToTask
2518 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002519 if (reuseTask == null) {
2520 // todo: should do better management of integers.
2521 mService.mCurTask++;
2522 if (mService.mCurTask <= 0) {
2523 mService.mCurTask = 1;
2524 }
2525 r.task = new TaskRecord(mService.mCurTask, r.info, intent);
2526 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2527 + " in new task " + r.task);
2528 } else {
2529 r.task = reuseTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002530 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002531 newTask = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002532 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002533
2534 } else if (sourceRecord != null) {
2535 if (!addingToTask &&
2536 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2537 // In this case, we are adding the activity to an existing
2538 // task, but the caller has asked to clear that task if the
2539 // activity is already running.
2540 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002541 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002542 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002543 if (top != null) {
2544 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002545 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002546 // For paranoia, make sure we have correctly
2547 // resumed the top activity.
2548 if (doResume) {
2549 resumeTopActivityLocked(null);
2550 }
2551 return START_DELIVERED_TO_TOP;
2552 }
2553 } else if (!addingToTask &&
2554 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2555 // In this case, we are launching an activity in our own task
2556 // that may already be running somewhere in the history, and
2557 // we want to shuffle it to the front of the stack if so.
2558 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2559 if (where >= 0) {
2560 ActivityRecord top = moveActivityToFrontLocked(where);
2561 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002562 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002563 if (doResume) {
2564 resumeTopActivityLocked(null);
2565 }
2566 return START_DELIVERED_TO_TOP;
2567 }
2568 }
2569 // An existing activity is starting this new activity, so we want
2570 // to keep the new one in the same task as the one that is starting
2571 // it.
2572 r.task = sourceRecord.task;
2573 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2574 + " in existing task " + r.task);
2575
2576 } else {
2577 // This not being started from an existing activity, and not part
2578 // of a new task... just put it in the top task, though these days
2579 // this case should never happen.
2580 final int N = mHistory.size();
2581 ActivityRecord prev =
2582 N > 0 ? (ActivityRecord)mHistory.get(N-1) : null;
2583 r.task = prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002584 ? prev.task
2585 : new TaskRecord(mService.mCurTask, r.info, intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002586 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2587 + " in new guessed " + r.task);
2588 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002589
2590 if (grantedUriPermissions != null && callingUid > 0) {
2591 for (int i=0; i<grantedUriPermissions.length; i++) {
2592 mService.grantUriPermissionLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002593 grantedUriPermissions[i], grantedMode, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002594 }
2595 }
2596
2597 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002598 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002599
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002600 if (newTask) {
2601 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
2602 }
2603 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002604 startActivityLocked(r, newTask, doResume, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002605 return START_SUCCESS;
2606 }
2607
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002608 ActivityInfo resolveActivity(Intent intent, String resolvedType, boolean debug) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002609 // Collect information about the target of the Intent.
2610 ActivityInfo aInfo;
2611 try {
2612 ResolveInfo rInfo =
2613 AppGlobals.getPackageManager().resolveIntent(
2614 intent, resolvedType,
2615 PackageManager.MATCH_DEFAULT_ONLY
2616 | ActivityManagerService.STOCK_PM_FLAGS);
2617 aInfo = rInfo != null ? rInfo.activityInfo : null;
2618 } catch (RemoteException e) {
2619 aInfo = null;
2620 }
2621
2622 if (aInfo != null) {
2623 // Store the found target back into the intent, because now that
2624 // we have it we never want to do this again. For example, if the
2625 // user navigates back to this point in the history, we should
2626 // always restart the exact same activity.
2627 intent.setComponent(new ComponentName(
2628 aInfo.applicationInfo.packageName, aInfo.name));
2629
2630 // Don't debug things in the system process
2631 if (debug) {
2632 if (!aInfo.processName.equals("system")) {
2633 mService.setDebugApp(aInfo.processName, true, false);
2634 }
2635 }
2636 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002637 return aInfo;
2638 }
2639
2640 final int startActivityMayWait(IApplicationThread caller, int callingUid,
2641 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2642 int grantedMode, IBinder resultTo,
2643 String resultWho, int requestCode, boolean onlyIfNeeded,
2644 boolean debug, WaitResult outResult, Configuration config) {
2645 // Refuse possible leaked file descriptors
2646 if (intent != null && intent.hasFileDescriptors()) {
2647 throw new IllegalArgumentException("File descriptors passed in Intent");
2648 }
2649
2650 boolean componentSpecified = intent.getComponent() != null;
2651
2652 // Don't modify the client's object!
2653 intent = new Intent(intent);
2654
2655 // Collect information about the target of the Intent.
2656 ActivityInfo aInfo = resolveActivity(intent, resolvedType, debug);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002657
2658 synchronized (mService) {
2659 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002660 if (callingUid >= 0) {
2661 callingPid = -1;
2662 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002663 callingPid = Binder.getCallingPid();
2664 callingUid = Binder.getCallingUid();
2665 } else {
2666 callingPid = callingUid = -1;
2667 }
2668
2669 mConfigWillChange = config != null
2670 && mService.mConfiguration.diff(config) != 0;
2671 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2672 "Starting activity when config will change = " + mConfigWillChange);
2673
2674 final long origId = Binder.clearCallingIdentity();
2675
2676 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07002677 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002678 // This may be a heavy-weight process! Check to see if we already
2679 // have another, different heavy-weight process running.
2680 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
2681 if (mService.mHeavyWeightProcess != null &&
2682 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
2683 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
2684 int realCallingPid = callingPid;
2685 int realCallingUid = callingUid;
2686 if (caller != null) {
2687 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
2688 if (callerApp != null) {
2689 realCallingPid = callerApp.pid;
2690 realCallingUid = callerApp.info.uid;
2691 } else {
2692 Slog.w(TAG, "Unable to find app for caller " + caller
2693 + " (pid=" + realCallingPid + ") when starting: "
2694 + intent.toString());
2695 return START_PERMISSION_DENIED;
2696 }
2697 }
2698
2699 IIntentSender target = mService.getIntentSenderLocked(
2700 IActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002701 realCallingUid, null, null, 0, new Intent[] { intent },
2702 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002703 | PendingIntent.FLAG_ONE_SHOT);
2704
2705 Intent newIntent = new Intent();
2706 if (requestCode >= 0) {
2707 // Caller is requesting a result.
2708 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
2709 }
2710 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
2711 new IntentSender(target));
2712 if (mService.mHeavyWeightProcess.activities.size() > 0) {
2713 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
2714 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
2715 hist.packageName);
2716 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
2717 hist.task.taskId);
2718 }
2719 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
2720 aInfo.packageName);
2721 newIntent.setFlags(intent.getFlags());
2722 newIntent.setClassName("android",
2723 HeavyWeightSwitcherActivity.class.getName());
2724 intent = newIntent;
2725 resolvedType = null;
2726 caller = null;
2727 callingUid = Binder.getCallingUid();
2728 callingPid = Binder.getCallingPid();
2729 componentSpecified = true;
2730 try {
2731 ResolveInfo rInfo =
2732 AppGlobals.getPackageManager().resolveIntent(
2733 intent, null,
2734 PackageManager.MATCH_DEFAULT_ONLY
2735 | ActivityManagerService.STOCK_PM_FLAGS);
2736 aInfo = rInfo != null ? rInfo.activityInfo : null;
2737 } catch (RemoteException e) {
2738 aInfo = null;
2739 }
2740 }
2741 }
2742 }
2743
2744 int res = startActivityLocked(caller, intent, resolvedType,
2745 grantedUriPermissions, grantedMode, aInfo,
2746 resultTo, resultWho, requestCode, callingPid, callingUid,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002747 onlyIfNeeded, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002748
2749 if (mConfigWillChange && mMainStack) {
2750 // If the caller also wants to switch to a new configuration,
2751 // do so now. This allows a clean switch, as we are waiting
2752 // for the current activity to pause (so we will not destroy
2753 // it), and have not yet started the next activity.
2754 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
2755 "updateConfiguration()");
2756 mConfigWillChange = false;
2757 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2758 "Updating to new configuration after starting activity.");
2759 mService.updateConfigurationLocked(config, null);
2760 }
2761
2762 Binder.restoreCallingIdentity(origId);
2763
2764 if (outResult != null) {
2765 outResult.result = res;
2766 if (res == IActivityManager.START_SUCCESS) {
2767 mWaitingActivityLaunched.add(outResult);
2768 do {
2769 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07002770 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002771 } catch (InterruptedException e) {
2772 }
2773 } while (!outResult.timeout && outResult.who == null);
2774 } else if (res == IActivityManager.START_TASK_TO_FRONT) {
2775 ActivityRecord r = this.topRunningActivityLocked(null);
2776 if (r.nowVisible) {
2777 outResult.timeout = false;
2778 outResult.who = new ComponentName(r.info.packageName, r.info.name);
2779 outResult.totalTime = 0;
2780 outResult.thisTime = 0;
2781 } else {
2782 outResult.thisTime = SystemClock.uptimeMillis();
2783 mWaitingActivityVisible.add(outResult);
2784 do {
2785 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07002786 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002787 } catch (InterruptedException e) {
2788 }
2789 } while (!outResult.timeout && outResult.who == null);
2790 }
2791 }
2792 }
2793
2794 return res;
2795 }
2796 }
2797
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002798 final int startActivities(IApplicationThread caller, int callingUid,
2799 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
2800 if (intents == null) {
2801 throw new NullPointerException("intents is null");
2802 }
2803 if (resolvedTypes == null) {
2804 throw new NullPointerException("resolvedTypes is null");
2805 }
2806 if (intents.length != resolvedTypes.length) {
2807 throw new IllegalArgumentException("intents are length different than resolvedTypes");
2808 }
2809
2810 ActivityRecord[] outActivity = new ActivityRecord[1];
2811
2812 int callingPid;
2813 if (callingUid >= 0) {
2814 callingPid = -1;
2815 } else if (caller == null) {
2816 callingPid = Binder.getCallingPid();
2817 callingUid = Binder.getCallingUid();
2818 } else {
2819 callingPid = callingUid = -1;
2820 }
2821 final long origId = Binder.clearCallingIdentity();
2822 try {
2823 synchronized (mService) {
2824
2825 for (int i=0; i<intents.length; i++) {
2826 Intent intent = intents[i];
2827 if (intent == null) {
2828 continue;
2829 }
2830
2831 // Refuse possible leaked file descriptors
2832 if (intent != null && intent.hasFileDescriptors()) {
2833 throw new IllegalArgumentException("File descriptors passed in Intent");
2834 }
2835
2836 boolean componentSpecified = intent.getComponent() != null;
2837
2838 // Don't modify the client's object!
2839 intent = new Intent(intent);
2840
2841 // Collect information about the target of the Intent.
2842 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i], false);
2843
2844 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
2845 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
2846 throw new IllegalArgumentException(
2847 "FLAG_CANT_SAVE_STATE not supported here");
2848 }
2849
2850 int res = startActivityLocked(caller, intent, resolvedTypes[i],
2851 null, 0, aInfo, resultTo, null, -1, callingPid, callingUid,
2852 false, componentSpecified, outActivity);
2853 if (res < 0) {
2854 return res;
2855 }
2856
2857 resultTo = outActivity[0];
2858 }
2859 }
2860 } finally {
2861 Binder.restoreCallingIdentity(origId);
2862 }
2863
2864 return IActivityManager.START_SUCCESS;
2865 }
2866
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002867 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
2868 long thisTime, long totalTime) {
2869 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
2870 WaitResult w = mWaitingActivityLaunched.get(i);
2871 w.timeout = timeout;
2872 if (r != null) {
2873 w.who = new ComponentName(r.info.packageName, r.info.name);
2874 }
2875 w.thisTime = thisTime;
2876 w.totalTime = totalTime;
2877 }
2878 mService.notifyAll();
2879 }
2880
2881 void reportActivityVisibleLocked(ActivityRecord r) {
2882 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
2883 WaitResult w = mWaitingActivityVisible.get(i);
2884 w.timeout = false;
2885 if (r != null) {
2886 w.who = new ComponentName(r.info.packageName, r.info.name);
2887 }
2888 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
2889 w.thisTime = w.totalTime;
2890 }
2891 mService.notifyAll();
2892 }
2893
2894 void sendActivityResultLocked(int callingUid, ActivityRecord r,
2895 String resultWho, int requestCode, int resultCode, Intent data) {
2896
2897 if (callingUid > 0) {
2898 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002899 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002900 }
2901
2902 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
2903 + " : who=" + resultWho + " req=" + requestCode
2904 + " res=" + resultCode + " data=" + data);
2905 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
2906 try {
2907 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
2908 list.add(new ResultInfo(resultWho, requestCode,
2909 resultCode, data));
2910 r.app.thread.scheduleSendResult(r, list);
2911 return;
2912 } catch (Exception e) {
2913 Slog.w(TAG, "Exception thrown sending result to " + r, e);
2914 }
2915 }
2916
2917 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
2918 }
2919
2920 private final void stopActivityLocked(ActivityRecord r) {
2921 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
2922 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
2923 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
2924 if (!r.finishing) {
2925 requestFinishActivityLocked(r, Activity.RESULT_CANCELED, null,
2926 "no-history");
2927 }
2928 } else if (r.app != null && r.app.thread != null) {
2929 if (mMainStack) {
2930 if (mService.mFocusedActivity == r) {
2931 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
2932 }
2933 }
2934 r.resumeKeyDispatchingLocked();
2935 try {
2936 r.stopped = false;
2937 r.state = ActivityState.STOPPING;
2938 if (DEBUG_VISBILITY) Slog.v(
2939 TAG, "Stopping visible=" + r.visible + " for " + r);
2940 if (!r.visible) {
2941 mService.mWindowManager.setAppVisibility(r, false);
2942 }
2943 r.app.thread.scheduleStopActivity(r, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002944 if (mService.isSleeping()) {
2945 r.setSleeping(true);
2946 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002947 } catch (Exception e) {
2948 // Maybe just ignore exceptions here... if the process
2949 // has crashed, our death notification will clean things
2950 // up.
2951 Slog.w(TAG, "Exception thrown during pause", e);
2952 // Just in case, assume it to be stopped.
2953 r.stopped = true;
2954 r.state = ActivityState.STOPPED;
2955 if (r.configDestroy) {
2956 destroyActivityLocked(r, true);
2957 }
2958 }
2959 }
2960 }
2961
2962 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
2963 boolean remove) {
2964 int N = mStoppingActivities.size();
2965 if (N <= 0) return null;
2966
2967 ArrayList<ActivityRecord> stops = null;
2968
2969 final boolean nowVisible = mResumedActivity != null
2970 && mResumedActivity.nowVisible
2971 && !mResumedActivity.waitingVisible;
2972 for (int i=0; i<N; i++) {
2973 ActivityRecord s = mStoppingActivities.get(i);
2974 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
2975 + nowVisible + " waitingVisible=" + s.waitingVisible
2976 + " finishing=" + s.finishing);
2977 if (s.waitingVisible && nowVisible) {
2978 mWaitingVisibleActivities.remove(s);
2979 s.waitingVisible = false;
2980 if (s.finishing) {
2981 // If this activity is finishing, it is sitting on top of
2982 // everyone else but we now know it is no longer needed...
2983 // so get rid of it. Otherwise, we need to go through the
2984 // normal flow and hide it once we determine that it is
2985 // hidden by the activities in front of it.
2986 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
2987 mService.mWindowManager.setAppVisibility(s, false);
2988 }
2989 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002990 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002991 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
2992 if (stops == null) {
2993 stops = new ArrayList<ActivityRecord>();
2994 }
2995 stops.add(s);
2996 mStoppingActivities.remove(i);
2997 N--;
2998 i--;
2999 }
3000 }
3001
3002 return stops;
3003 }
3004
3005 final void activityIdleInternal(IBinder token, boolean fromTimeout,
3006 Configuration config) {
3007 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3008
3009 ArrayList<ActivityRecord> stops = null;
3010 ArrayList<ActivityRecord> finishes = null;
3011 ArrayList<ActivityRecord> thumbnails = null;
3012 int NS = 0;
3013 int NF = 0;
3014 int NT = 0;
3015 IApplicationThread sendThumbnail = null;
3016 boolean booting = false;
3017 boolean enableScreen = false;
3018
3019 synchronized (mService) {
3020 if (token != null) {
3021 mHandler.removeMessages(IDLE_TIMEOUT_MSG, token);
3022 }
3023
3024 // Get the activity record.
3025 int index = indexOfTokenLocked(token);
3026 if (index >= 0) {
3027 ActivityRecord r = (ActivityRecord)mHistory.get(index);
3028
3029 if (fromTimeout) {
3030 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3031 }
3032
3033 // This is a hack to semi-deal with a race condition
3034 // in the client where it can be constructed with a
3035 // newer configuration from when we asked it to launch.
3036 // We'll update with whatever configuration it now says
3037 // it used to launch.
3038 if (config != null) {
3039 r.configuration = config;
3040 }
3041
3042 // No longer need to keep the device awake.
3043 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3044 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3045 mLaunchingActivity.release();
3046 }
3047
3048 // We are now idle. If someone is waiting for a thumbnail from
3049 // us, we can now deliver.
3050 r.idle = true;
3051 mService.scheduleAppGcsLocked();
3052 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3053 sendThumbnail = r.app.thread;
3054 r.thumbnailNeeded = false;
3055 }
3056
3057 // If this activity is fullscreen, set up to hide those under it.
3058
3059 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3060 ensureActivitiesVisibleLocked(null, 0);
3061
3062 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3063 if (mMainStack) {
3064 if (!mService.mBooted && !fromTimeout) {
3065 mService.mBooted = true;
3066 enableScreen = true;
3067 }
3068 }
3069
3070 } else if (fromTimeout) {
3071 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3072 }
3073
3074 // Atomically retrieve all of the other things to do.
3075 stops = processStoppingActivitiesLocked(true);
3076 NS = stops != null ? stops.size() : 0;
3077 if ((NF=mFinishingActivities.size()) > 0) {
3078 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3079 mFinishingActivities.clear();
3080 }
3081 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3082 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3083 mService.mCancelledThumbnails.clear();
3084 }
3085
3086 if (mMainStack) {
3087 booting = mService.mBooting;
3088 mService.mBooting = false;
3089 }
3090 }
3091
3092 int i;
3093
3094 // Send thumbnail if requested.
3095 if (sendThumbnail != null) {
3096 try {
3097 sendThumbnail.requestThumbnail(token);
3098 } catch (Exception e) {
3099 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3100 mService.sendPendingThumbnail(null, token, null, null, true);
3101 }
3102 }
3103
3104 // Stop any activities that are scheduled to do so but have been
3105 // waiting for the next one to start.
3106 for (i=0; i<NS; i++) {
3107 ActivityRecord r = (ActivityRecord)stops.get(i);
3108 synchronized (mService) {
3109 if (r.finishing) {
3110 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY);
3111 } else {
3112 stopActivityLocked(r);
3113 }
3114 }
3115 }
3116
3117 // Finish any activities that are scheduled to do so but have been
3118 // waiting for the next one to start.
3119 for (i=0; i<NF; i++) {
3120 ActivityRecord r = (ActivityRecord)finishes.get(i);
3121 synchronized (mService) {
3122 destroyActivityLocked(r, true);
3123 }
3124 }
3125
3126 // Report back to any thumbnail receivers.
3127 for (i=0; i<NT; i++) {
3128 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3129 mService.sendPendingThumbnail(r, null, null, null, true);
3130 }
3131
3132 if (booting) {
3133 mService.finishBooting();
3134 }
3135
3136 mService.trimApplications();
3137 //dump();
3138 //mWindowManager.dump();
3139
3140 if (enableScreen) {
3141 mService.enableScreenAfterBoot();
3142 }
3143 }
3144
3145 /**
3146 * @return Returns true if the activity is being finished, false if for
3147 * some reason it is being left as-is.
3148 */
3149 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
3150 Intent resultData, String reason) {
3151 if (DEBUG_RESULTS) Slog.v(
3152 TAG, "Finishing activity: token=" + token
3153 + ", result=" + resultCode + ", data=" + resultData);
3154
3155 int index = indexOfTokenLocked(token);
3156 if (index < 0) {
3157 return false;
3158 }
3159 ActivityRecord r = (ActivityRecord)mHistory.get(index);
3160
3161 // Is this the last activity left?
3162 boolean lastActivity = true;
3163 for (int i=mHistory.size()-1; i>=0; i--) {
3164 ActivityRecord p = (ActivityRecord)mHistory.get(i);
3165 if (!p.finishing && p != r) {
3166 lastActivity = false;
3167 break;
3168 }
3169 }
3170
3171 // If this is the last activity, but it is the home activity, then
3172 // just don't finish it.
3173 if (lastActivity) {
3174 if (r.intent.hasCategory(Intent.CATEGORY_HOME)) {
3175 return false;
3176 }
3177 }
3178
3179 finishActivityLocked(r, index, resultCode, resultData, reason);
3180 return true;
3181 }
3182
3183 /**
3184 * @return Returns true if this activity has been removed from the history
3185 * list, or false if it is still in the list and will be removed later.
3186 */
3187 final boolean finishActivityLocked(ActivityRecord r, int index,
3188 int resultCode, Intent resultData, String reason) {
3189 if (r.finishing) {
3190 Slog.w(TAG, "Duplicate finish request for " + r);
3191 return false;
3192 }
3193
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003194 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003195 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3196 System.identityHashCode(r),
3197 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003198 if (index < (mHistory.size()-1)) {
3199 ActivityRecord next = (ActivityRecord)mHistory.get(index+1);
3200 if (next.task == r.task) {
3201 if (r.frontOfTask) {
3202 // The next activity is now the front of the task.
3203 next.frontOfTask = true;
3204 }
3205 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3206 // If the caller asked that this activity (and all above it)
3207 // be cleared when the task is reset, don't lose that information,
3208 // but propagate it up to the next activity.
3209 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3210 }
3211 }
3212 }
3213
3214 r.pauseKeyDispatchingLocked();
3215 if (mMainStack) {
3216 if (mService.mFocusedActivity == r) {
3217 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3218 }
3219 }
3220
3221 // send the result
3222 ActivityRecord resultTo = r.resultTo;
3223 if (resultTo != null) {
3224 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3225 + " who=" + r.resultWho + " req=" + r.requestCode
3226 + " res=" + resultCode + " data=" + resultData);
3227 if (r.info.applicationInfo.uid > 0) {
3228 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
Dianne Hackborna1c69e02010-09-01 22:55:02 -07003229 resultTo.packageName, resultData,
3230 resultTo.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003231 }
3232 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3233 resultData);
3234 r.resultTo = null;
3235 }
3236 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3237
3238 // Make sure this HistoryRecord is not holding on to other resources,
3239 // because clients have remote IPC references to this object so we
3240 // can't assume that will go away and want to avoid circular IPC refs.
3241 r.results = null;
3242 r.pendingResults = null;
3243 r.newIntents = null;
3244 r.icicle = null;
3245
3246 if (mService.mPendingThumbnails.size() > 0) {
3247 // There are clients waiting to receive thumbnails so, in case
3248 // this is an activity that someone is waiting for, add it
3249 // to the pending list so we can correctly update the clients.
3250 mService.mCancelledThumbnails.add(r);
3251 }
3252
3253 if (mResumedActivity == r) {
3254 boolean endTask = index <= 0
3255 || ((ActivityRecord)mHistory.get(index-1)).task != r.task;
3256 if (DEBUG_TRANSITION) Slog.v(TAG,
3257 "Prepare close transition: finishing " + r);
3258 mService.mWindowManager.prepareAppTransition(endTask
3259 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003260 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003261
3262 // Tell window manager to prepare for this one to be removed.
3263 mService.mWindowManager.setAppVisibility(r, false);
3264
3265 if (mPausingActivity == null) {
3266 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3267 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3268 startPausingLocked(false, false);
3269 }
3270
3271 } else if (r.state != ActivityState.PAUSING) {
3272 // If the activity is PAUSING, we will complete the finish once
3273 // it is done pausing; else we can just directly finish it here.
3274 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3275 return finishCurrentActivityLocked(r, index,
3276 FINISH_AFTER_PAUSE) == null;
3277 } else {
3278 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3279 }
3280
3281 return false;
3282 }
3283
3284 private static final int FINISH_IMMEDIATELY = 0;
3285 private static final int FINISH_AFTER_PAUSE = 1;
3286 private static final int FINISH_AFTER_VISIBLE = 2;
3287
3288 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3289 int mode) {
3290 final int index = indexOfTokenLocked(r);
3291 if (index < 0) {
3292 return null;
3293 }
3294
3295 return finishCurrentActivityLocked(r, index, mode);
3296 }
3297
3298 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3299 int index, int mode) {
3300 // First things first: if this activity is currently visible,
3301 // and the resumed activity is not yet visible, then hold off on
3302 // finishing until the resumed one becomes visible.
3303 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3304 if (!mStoppingActivities.contains(r)) {
3305 mStoppingActivities.add(r);
3306 if (mStoppingActivities.size() > 3) {
3307 // If we already have a few activities waiting to stop,
3308 // then give up on things going idle and start clearing
3309 // them out.
3310 Message msg = Message.obtain();
3311 msg.what = IDLE_NOW_MSG;
3312 mHandler.sendMessage(msg);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003313 } else {
3314 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003315 }
3316 }
3317 r.state = ActivityState.STOPPING;
3318 mService.updateOomAdjLocked();
3319 return r;
3320 }
3321
3322 // make sure the record is cleaned out of other places.
3323 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003324 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003325 mWaitingVisibleActivities.remove(r);
3326 if (mResumedActivity == r) {
3327 mResumedActivity = null;
3328 }
3329 final ActivityState prevState = r.state;
3330 r.state = ActivityState.FINISHING;
3331
3332 if (mode == FINISH_IMMEDIATELY
3333 || prevState == ActivityState.STOPPED
3334 || prevState == ActivityState.INITIALIZING) {
3335 // If this activity is already stopped, we can just finish
3336 // it right now.
3337 return destroyActivityLocked(r, true) ? null : r;
3338 } else {
3339 // Need to go through the full pause cycle to get this
3340 // activity into the stopped state and then finish it.
3341 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3342 mFinishingActivities.add(r);
3343 resumeTopActivityLocked(null);
3344 }
3345 return r;
3346 }
3347
3348 /**
3349 * Perform the common clean-up of an activity record. This is called both
3350 * as part of destroyActivityLocked() (when destroying the client-side
3351 * representation) and cleaning things up as a result of its hosting
3352 * processing going away, in which case there is no remaining client-side
3353 * state to destroy so only the cleanup here is needed.
3354 */
3355 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices) {
3356 if (mResumedActivity == r) {
3357 mResumedActivity = null;
3358 }
3359 if (mService.mFocusedActivity == r) {
3360 mService.mFocusedActivity = null;
3361 }
3362
3363 r.configDestroy = false;
3364 r.frozenBeforeDestroy = false;
3365
3366 // Make sure this record is no longer in the pending finishes list.
3367 // This could happen, for example, if we are trimming activities
3368 // down to the max limit while they are still waiting to finish.
3369 mFinishingActivities.remove(r);
3370 mWaitingVisibleActivities.remove(r);
3371
3372 // Remove any pending results.
3373 if (r.finishing && r.pendingResults != null) {
3374 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3375 PendingIntentRecord rec = apr.get();
3376 if (rec != null) {
3377 mService.cancelIntentSenderLocked(rec, false);
3378 }
3379 }
3380 r.pendingResults = null;
3381 }
3382
3383 if (cleanServices) {
3384 cleanUpActivityServicesLocked(r);
3385 }
3386
3387 if (mService.mPendingThumbnails.size() > 0) {
3388 // There are clients waiting to receive thumbnails so, in case
3389 // this is an activity that someone is waiting for, add it
3390 // to the pending list so we can correctly update the clients.
3391 mService.mCancelledThumbnails.add(r);
3392 }
3393
3394 // Get rid of any pending idle timeouts.
3395 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
3396 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
3397 }
3398
3399 private final void removeActivityFromHistoryLocked(ActivityRecord r) {
3400 if (r.state != ActivityState.DESTROYED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003401 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003402 mHistory.remove(r);
3403 r.inHistory = false;
3404 r.state = ActivityState.DESTROYED;
3405 mService.mWindowManager.removeAppToken(r);
3406 if (VALIDATE_TOKENS) {
3407 mService.mWindowManager.validateAppTokens(mHistory);
3408 }
3409 cleanUpActivityServicesLocked(r);
3410 r.removeUriPermissionsLocked();
3411 }
3412 }
3413
3414 /**
3415 * Perform clean-up of service connections in an activity record.
3416 */
3417 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3418 // Throw away any services that have been bound by this activity.
3419 if (r.connections != null) {
3420 Iterator<ConnectionRecord> it = r.connections.iterator();
3421 while (it.hasNext()) {
3422 ConnectionRecord c = it.next();
3423 mService.removeConnectionLocked(c, null, r);
3424 }
3425 r.connections = null;
3426 }
3427 }
3428
3429 /**
3430 * Destroy the current CLIENT SIDE instance of an activity. This may be
3431 * called both when actually finishing an activity, or when performing
3432 * a configuration switch where we destroy the current client-side object
3433 * but then create a new client-side object for this same HistoryRecord.
3434 */
3435 final boolean destroyActivityLocked(ActivityRecord r,
3436 boolean removeFromApp) {
3437 if (DEBUG_SWITCH) Slog.v(
3438 TAG, "Removing activity: token=" + r
3439 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3440 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3441 System.identityHashCode(r),
3442 r.task.taskId, r.shortComponentName);
3443
3444 boolean removedFromHistory = false;
3445
3446 cleanUpActivityLocked(r, false);
3447
3448 final boolean hadApp = r.app != null;
3449
3450 if (hadApp) {
3451 if (removeFromApp) {
3452 int idx = r.app.activities.indexOf(r);
3453 if (idx >= 0) {
3454 r.app.activities.remove(idx);
3455 }
3456 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
3457 mService.mHeavyWeightProcess = null;
3458 mService.mHandler.sendEmptyMessage(
3459 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
3460 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003461 if (r.app.activities.size() == 0) {
3462 // No longer have activities, so update location in
3463 // LRU list.
3464 mService.updateLruProcessLocked(r.app, true, false);
3465 }
3466 }
3467
3468 boolean skipDestroy = false;
3469
3470 try {
3471 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
3472 r.app.thread.scheduleDestroyActivity(r, r.finishing,
3473 r.configChangeFlags);
3474 } catch (Exception e) {
3475 // We can just ignore exceptions here... if the process
3476 // has crashed, our death notification will clean things
3477 // up.
3478 //Slog.w(TAG, "Exception thrown during finish", e);
3479 if (r.finishing) {
3480 removeActivityFromHistoryLocked(r);
3481 removedFromHistory = true;
3482 skipDestroy = true;
3483 }
3484 }
3485
3486 r.app = null;
3487 r.nowVisible = false;
3488
3489 if (r.finishing && !skipDestroy) {
3490 r.state = ActivityState.DESTROYING;
3491 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
3492 msg.obj = r;
3493 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
3494 } else {
3495 r.state = ActivityState.DESTROYED;
3496 }
3497 } else {
3498 // remove this record from the history.
3499 if (r.finishing) {
3500 removeActivityFromHistoryLocked(r);
3501 removedFromHistory = true;
3502 } else {
3503 r.state = ActivityState.DESTROYED;
3504 }
3505 }
3506
3507 r.configChangeFlags = 0;
3508
3509 if (!mLRUActivities.remove(r) && hadApp) {
3510 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
3511 }
3512
3513 return removedFromHistory;
3514 }
3515
3516 final void activityDestroyed(IBinder token) {
3517 synchronized (mService) {
3518 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, token);
3519
3520 int index = indexOfTokenLocked(token);
3521 if (index >= 0) {
3522 ActivityRecord r = (ActivityRecord)mHistory.get(index);
3523 if (r.state == ActivityState.DESTROYING) {
3524 final long origId = Binder.clearCallingIdentity();
3525 removeActivityFromHistoryLocked(r);
3526 Binder.restoreCallingIdentity(origId);
3527 }
3528 }
3529 }
3530 }
3531
3532 private static void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
3533 int i = list.size();
3534 if (localLOGV) Slog.v(
3535 TAG, "Removing app " + app + " from list " + list
3536 + " with " + i + " entries");
3537 while (i > 0) {
3538 i--;
3539 ActivityRecord r = (ActivityRecord)list.get(i);
3540 if (localLOGV) Slog.v(
3541 TAG, "Record #" + i + " " + r + ": app=" + r.app);
3542 if (r.app == app) {
3543 if (localLOGV) Slog.v(TAG, "Removing this entry!");
3544 list.remove(i);
3545 }
3546 }
3547 }
3548
3549 void removeHistoryRecordsForAppLocked(ProcessRecord app) {
3550 removeHistoryRecordsForAppLocked(mLRUActivities, app);
3551 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003552 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003553 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
3554 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
3555 }
3556
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003557 /**
3558 * Move the current home activity's task (if one exists) to the front
3559 * of the stack.
3560 */
3561 final void moveHomeToFrontLocked() {
3562 TaskRecord homeTask = null;
3563 for (int i=mHistory.size()-1; i>=0; i--) {
3564 ActivityRecord hr = (ActivityRecord)mHistory.get(i);
3565 if (hr.isHomeActivity) {
3566 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003567 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003568 }
3569 }
3570 if (homeTask != null) {
3571 moveTaskToFrontLocked(homeTask, null);
3572 }
3573 }
3574
3575
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003576 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason) {
3577 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
3578
3579 final int task = tr.taskId;
3580 int top = mHistory.size()-1;
3581
3582 if (top < 0 || ((ActivityRecord)mHistory.get(top)).task.taskId == task) {
3583 // nothing to do!
3584 return;
3585 }
3586
3587 ArrayList moved = new ArrayList();
3588
3589 // Applying the affinities may have removed entries from the history,
3590 // so get the size again.
3591 top = mHistory.size()-1;
3592 int pos = top;
3593
3594 // Shift all activities with this task up to the top
3595 // of the stack, keeping them in the same internal order.
3596 while (pos >= 0) {
3597 ActivityRecord r = (ActivityRecord)mHistory.get(pos);
3598 if (localLOGV) Slog.v(
3599 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003600 if (r.task.taskId == task) {
3601 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
3602 mHistory.remove(pos);
3603 mHistory.add(top, r);
3604 moved.add(0, r);
3605 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003606 }
3607 pos--;
3608 }
3609
3610 if (DEBUG_TRANSITION) Slog.v(TAG,
3611 "Prepare to front transition: task=" + tr);
3612 if (reason != null &&
3613 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003614 mService.mWindowManager.prepareAppTransition(
3615 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003616 ActivityRecord r = topRunningActivityLocked(null);
3617 if (r != null) {
3618 mNoAnimActivities.add(r);
3619 }
3620 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003621 mService.mWindowManager.prepareAppTransition(
3622 WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003623 }
3624
3625 mService.mWindowManager.moveAppTokensToTop(moved);
3626 if (VALIDATE_TOKENS) {
3627 mService.mWindowManager.validateAppTokens(mHistory);
3628 }
3629
3630 finishTaskMoveLocked(task);
3631 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
3632 }
3633
3634 private final void finishTaskMoveLocked(int task) {
3635 resumeTopActivityLocked(null);
3636 }
3637
3638 /**
3639 * Worker method for rearranging history stack. Implements the function of moving all
3640 * activities for a specific task (gathering them if disjoint) into a single group at the
3641 * bottom of the stack.
3642 *
3643 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
3644 * to premeptively cancel the move.
3645 *
3646 * @param task The taskId to collect and move to the bottom.
3647 * @return Returns true if the move completed, false if not.
3648 */
3649 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
3650 Slog.i(TAG, "moveTaskToBack: " + task);
3651
3652 // If we have a watcher, preflight the move before committing to it. First check
3653 // for *other* available tasks, but if none are available, then try again allowing the
3654 // current task to be selected.
3655 if (mMainStack && mService.mController != null) {
3656 ActivityRecord next = topRunningActivityLocked(null, task);
3657 if (next == null) {
3658 next = topRunningActivityLocked(null, 0);
3659 }
3660 if (next != null) {
3661 // ask watcher if this is allowed
3662 boolean moveOK = true;
3663 try {
3664 moveOK = mService.mController.activityResuming(next.packageName);
3665 } catch (RemoteException e) {
3666 mService.mController = null;
3667 }
3668 if (!moveOK) {
3669 return false;
3670 }
3671 }
3672 }
3673
3674 ArrayList moved = new ArrayList();
3675
3676 if (DEBUG_TRANSITION) Slog.v(TAG,
3677 "Prepare to back transition: task=" + task);
3678
3679 final int N = mHistory.size();
3680 int bottom = 0;
3681 int pos = 0;
3682
3683 // Shift all activities with this task down to the bottom
3684 // of the stack, keeping them in the same internal order.
3685 while (pos < N) {
3686 ActivityRecord r = (ActivityRecord)mHistory.get(pos);
3687 if (localLOGV) Slog.v(
3688 TAG, "At " + pos + " ckp " + r.task + ": " + r);
3689 if (r.task.taskId == task) {
3690 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
3691 mHistory.remove(pos);
3692 mHistory.add(bottom, r);
3693 moved.add(r);
3694 bottom++;
3695 }
3696 pos++;
3697 }
3698
3699 if (reason != null &&
3700 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003701 mService.mWindowManager.prepareAppTransition(
3702 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003703 ActivityRecord r = topRunningActivityLocked(null);
3704 if (r != null) {
3705 mNoAnimActivities.add(r);
3706 }
3707 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003708 mService.mWindowManager.prepareAppTransition(
3709 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003710 }
3711 mService.mWindowManager.moveAppTokensToBottom(moved);
3712 if (VALIDATE_TOKENS) {
3713 mService.mWindowManager.validateAppTokens(mHistory);
3714 }
3715
3716 finishTaskMoveLocked(task);
3717 return true;
3718 }
3719
3720 private final void logStartActivity(int tag, ActivityRecord r,
3721 TaskRecord task) {
3722 EventLog.writeEvent(tag,
3723 System.identityHashCode(r), task.taskId,
3724 r.shortComponentName, r.intent.getAction(),
3725 r.intent.getType(), r.intent.getDataString(),
3726 r.intent.getFlags());
3727 }
3728
3729 /**
3730 * Make sure the given activity matches the current configuration. Returns
3731 * false if the activity had to be destroyed. Returns true if the
3732 * configuration is the same, or the activity will remain running as-is
3733 * for whatever reason. Ensures the HistoryRecord is updated with the
3734 * correct configuration and all other bookkeeping is handled.
3735 */
3736 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
3737 int globalChanges) {
3738 if (mConfigWillChange) {
3739 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3740 "Skipping config check (will change): " + r);
3741 return true;
3742 }
3743
3744 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3745 "Ensuring correct configuration: " + r);
3746
3747 // Short circuit: if the two configurations are the exact same
3748 // object (the common case), then there is nothing to do.
3749 Configuration newConfig = mService.mConfiguration;
3750 if (r.configuration == newConfig) {
3751 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3752 "Configuration unchanged in " + r);
3753 return true;
3754 }
3755
3756 // We don't worry about activities that are finishing.
3757 if (r.finishing) {
3758 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3759 "Configuration doesn't matter in finishing " + r);
3760 r.stopFreezingScreenLocked(false);
3761 return true;
3762 }
3763
3764 // Okay we now are going to make this activity have the new config.
3765 // But then we need to figure out how it needs to deal with that.
3766 Configuration oldConfig = r.configuration;
3767 r.configuration = newConfig;
3768
3769 // If the activity isn't currently running, just leave the new
3770 // configuration and it will pick that up next time it starts.
3771 if (r.app == null || r.app.thread == null) {
3772 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3773 "Configuration doesn't matter not running " + r);
3774 r.stopFreezingScreenLocked(false);
3775 return true;
3776 }
3777
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07003778 // Figure out what has changed between the two configurations.
3779 int changes = oldConfig.diff(newConfig);
3780 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
3781 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
3782 + Integer.toHexString(changes) + ", handles=0x"
3783 + Integer.toHexString(r.info.configChanges)
3784 + ", newConfig=" + newConfig);
3785 }
3786 if ((changes&(~r.info.configChanges)) != 0) {
3787 // Aha, the activity isn't handling the change, so DIE DIE DIE.
3788 r.configChangeFlags |= changes;
3789 r.startFreezingScreenLocked(r.app, globalChanges);
3790 if (r.app == null || r.app.thread == null) {
3791 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3792 "Switch is destroying non-running " + r);
3793 destroyActivityLocked(r, true);
3794 } else if (r.state == ActivityState.PAUSING) {
3795 // A little annoying: we are waiting for this activity to
3796 // finish pausing. Let's not do anything now, but just
3797 // flag that it needs to be restarted when done pausing.
3798 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3799 "Switch is skipping already pausing " + r);
3800 r.configDestroy = true;
3801 return true;
3802 } else if (r.state == ActivityState.RESUMED) {
3803 // Try to optimize this case: the configuration is changing
3804 // and we need to restart the top, resumed activity.
3805 // Instead of doing the normal handshaking, just say
3806 // "restart!".
3807 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3808 "Switch is restarting resumed " + r);
3809 relaunchActivityLocked(r, r.configChangeFlags, true);
3810 r.configChangeFlags = 0;
3811 } else {
3812 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3813 "Switch is restarting non-resumed " + r);
3814 relaunchActivityLocked(r, r.configChangeFlags, false);
3815 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003816 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07003817
3818 // All done... tell the caller we weren't able to keep this
3819 // activity around.
3820 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003821 }
3822
3823 // Default case: the activity can handle this new configuration, so
3824 // hand it over. Note that we don't need to give it the new
3825 // configuration, since we always send configuration changes to all
3826 // process when they happen so it can just use whatever configuration
3827 // it last got.
3828 if (r.app != null && r.app.thread != null) {
3829 try {
3830 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
3831 r.app.thread.scheduleActivityConfigurationChanged(r);
3832 } catch (RemoteException e) {
3833 // If process died, whatever.
3834 }
3835 }
3836 r.stopFreezingScreenLocked(false);
3837
3838 return true;
3839 }
3840
3841 private final boolean relaunchActivityLocked(ActivityRecord r,
3842 int changes, boolean andResume) {
3843 List<ResultInfo> results = null;
3844 List<Intent> newIntents = null;
3845 if (andResume) {
3846 results = r.results;
3847 newIntents = r.newIntents;
3848 }
3849 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
3850 + " with results=" + results + " newIntents=" + newIntents
3851 + " andResume=" + andResume);
3852 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
3853 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
3854 r.task.taskId, r.shortComponentName);
3855
3856 r.startFreezingScreenLocked(r.app, 0);
3857
3858 try {
3859 if (DEBUG_SWITCH) Slog.i(TAG, "Switch is restarting resumed " + r);
3860 r.app.thread.scheduleRelaunchActivity(r, results, newIntents,
3861 changes, !andResume, mService.mConfiguration);
3862 // Note: don't need to call pauseIfSleepingLocked() here, because
3863 // the caller will only pass in 'andResume' if this activity is
3864 // currently resumed, which implies we aren't sleeping.
3865 } catch (RemoteException e) {
3866 return false;
3867 }
3868
3869 if (andResume) {
3870 r.results = null;
3871 r.newIntents = null;
3872 if (mMainStack) {
3873 mService.reportResumedActivityLocked(r);
3874 }
3875 }
3876
3877 return true;
3878 }
3879}