blob: 37619288d995eba03f09ae3a69b4109ffaee2e94 [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 Hackborn0aae2d42010-12-07 23:51:29 -0800753 Resources res = mService.mContext.getResources();
754 int w = mThumbnailWidth;
755 int h = mThumbnailHeight;
756 if (w < 0) {
757 mThumbnailWidth = w =
758 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
759 mThumbnailHeight = h =
760 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
761 }
762
763 if (w > 0) {
Dianne Hackborn7c8a4b32010-12-15 14:58:00 -0800764 return mService.mWindowManager.screenshotApplications(who, w, h);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800765 }
766 return null;
767 }
768
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700769 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
770 if (mPausingActivity != null) {
771 RuntimeException e = new RuntimeException();
772 Slog.e(TAG, "Trying to pause when pause is already pending for "
773 + mPausingActivity, e);
774 }
775 ActivityRecord prev = mResumedActivity;
776 if (prev == null) {
777 RuntimeException e = new RuntimeException();
778 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
779 resumeTopActivityLocked(null);
780 return;
781 }
782 if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
783 mResumedActivity = null;
784 mPausingActivity = prev;
785 mLastPausedActivity = prev;
786 prev.state = ActivityState.PAUSING;
787 prev.task.touchActiveTime();
Dianne Hackbornd2835932010-12-13 16:28:46 -0800788 prev.thumbnail = screenshotActivities(prev);
789 if (prev.task != null) {
790 prev.task.lastThumbnail = prev.thumbnail;
791 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700792
793 mService.updateCpuStats();
794
795 if (prev.app != null && prev.app.thread != null) {
796 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
797 try {
798 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
799 System.identityHashCode(prev),
800 prev.shortComponentName);
801 prev.app.thread.schedulePauseActivity(prev, prev.finishing, userLeaving,
802 prev.configChangeFlags);
803 if (mMainStack) {
804 mService.updateUsageStats(prev, false);
805 }
806 } catch (Exception e) {
807 // Ignore exception, if process died other code will cleanup.
808 Slog.w(TAG, "Exception thrown during pause", e);
809 mPausingActivity = null;
810 mLastPausedActivity = null;
811 }
812 } else {
813 mPausingActivity = null;
814 mLastPausedActivity = null;
815 }
816
817 // If we are not going to sleep, we want to ensure the device is
818 // awake until the next activity is started.
819 if (!mService.mSleeping && !mService.mShuttingDown) {
820 mLaunchingActivity.acquire();
821 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
822 // To be safe, don't allow the wake lock to be held for too long.
823 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
824 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
825 }
826 }
827
828
829 if (mPausingActivity != null) {
830 // Have the window manager pause its key dispatching until the new
831 // activity has started. If we're pausing the activity just because
832 // the screen is being turned off and the UI is sleeping, don't interrupt
833 // key dispatch; the same activity will pick it up again on wakeup.
834 if (!uiSleeping) {
835 prev.pauseKeyDispatchingLocked();
836 } else {
837 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
838 }
839
840 // Schedule a pause timeout in case the app doesn't respond.
841 // We don't give it much time because this directly impacts the
842 // responsiveness seen by the user.
843 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
844 msg.obj = prev;
845 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
846 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
847 } else {
848 // This activity failed to schedule the
849 // pause, so just treat it as being paused now.
850 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
851 resumeTopActivityLocked(null);
852 }
853 }
854
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800855 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700856 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800857 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700858
859 ActivityRecord r = null;
860
861 synchronized (mService) {
862 int index = indexOfTokenLocked(token);
863 if (index >= 0) {
864 r = (ActivityRecord)mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700865 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
866 if (mPausingActivity == r) {
867 r.state = ActivityState.PAUSED;
868 completePauseLocked();
869 } else {
870 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
871 System.identityHashCode(r), r.shortComponentName,
872 mPausingActivity != null
873 ? mPausingActivity.shortComponentName : "(none)");
874 }
875 }
876 }
877 }
878
879 private final void completePauseLocked() {
880 ActivityRecord prev = mPausingActivity;
881 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
882
883 if (prev != null) {
884 if (prev.finishing) {
885 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
886 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE);
887 } else if (prev.app != null) {
888 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
889 if (prev.waitingVisible) {
890 prev.waitingVisible = false;
891 mWaitingVisibleActivities.remove(prev);
892 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
893 TAG, "Complete pause, no longer waiting: " + prev);
894 }
895 if (prev.configDestroy) {
896 // The previous is being paused because the configuration
897 // is changing, which means it is actually stopping...
898 // To juggle the fact that we are also starting a new
899 // instance right now, we need to first completely stop
900 // the current instance before starting the new one.
901 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
902 destroyActivityLocked(prev, true);
903 } else {
904 mStoppingActivities.add(prev);
905 if (mStoppingActivities.size() > 3) {
906 // If we already have a few activities waiting to stop,
907 // then give up on things going idle and start clearing
908 // them out.
909 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
910 Message msg = Message.obtain();
911 msg.what = IDLE_NOW_MSG;
912 mHandler.sendMessage(msg);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800913 } else {
914 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700915 }
916 }
917 } else {
918 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
919 prev = null;
920 }
921 mPausingActivity = null;
922 }
923
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800924 if (!mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700925 resumeTopActivityLocked(prev);
926 } else {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800927 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700928 }
929
930 if (prev != null) {
931 prev.resumeKeyDispatchingLocked();
932 }
933
934 if (prev.app != null && prev.cpuTimeAtResume > 0
935 && mService.mBatteryStatsService.isOnBattery()) {
936 long diff = 0;
937 synchronized (mService.mProcessStatsThread) {
938 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
939 - prev.cpuTimeAtResume;
940 }
941 if (diff > 0) {
942 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
943 synchronized (bsi) {
944 BatteryStatsImpl.Uid.Proc ps =
945 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
946 prev.info.packageName);
947 if (ps != null) {
948 ps.addForegroundTimeLocked(diff);
949 }
950 }
951 }
952 }
953 prev.cpuTimeAtResume = 0; // reset it
954 }
955
956 /**
957 * Once we know that we have asked an application to put an activity in
958 * the resumed state (either by launching it or explicitly telling it),
959 * this function updates the rest of our state to match that fact.
960 */
961 private final void completeResumeLocked(ActivityRecord next) {
962 next.idle = false;
963 next.results = null;
964 next.newIntents = null;
965
966 // schedule an idle timeout in case the app doesn't do it for us.
967 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
968 msg.obj = next;
969 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
970
971 if (false) {
972 // The activity was never told to pause, so just keep
973 // things going as-is. To maintain our own state,
974 // we need to emulate it coming back and saying it is
975 // idle.
976 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
977 msg.obj = next;
978 mHandler.sendMessage(msg);
979 }
980
981 if (mMainStack) {
982 mService.reportResumedActivityLocked(next);
983 }
984
985 next.thumbnail = null;
986 if (mMainStack) {
987 mService.setFocusedActivityLocked(next);
988 }
989 next.resumeKeyDispatchingLocked();
990 ensureActivitiesVisibleLocked(null, 0);
991 mService.mWindowManager.executeAppTransition();
992 mNoAnimActivities.clear();
993
994 // Mark the point when the activity is resuming
995 // TODO: To be more accurate, the mark should be before the onCreate,
996 // not after the onResume. But for subsequent starts, onResume is fine.
997 if (next.app != null) {
998 synchronized (mService.mProcessStatsThread) {
999 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1000 }
1001 } else {
1002 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1003 }
1004 }
1005
1006 /**
1007 * Make sure that all activities that need to be visible (that is, they
1008 * currently can be seen by the user) actually are.
1009 */
1010 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1011 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1012 if (DEBUG_VISBILITY) Slog.v(
1013 TAG, "ensureActivitiesVisible behind " + top
1014 + " configChanges=0x" + Integer.toHexString(configChanges));
1015
1016 // If the top activity is not fullscreen, then we need to
1017 // make sure any activities under it are now visible.
1018 final int count = mHistory.size();
1019 int i = count-1;
1020 while (mHistory.get(i) != top) {
1021 i--;
1022 }
1023 ActivityRecord r;
1024 boolean behindFullscreen = false;
1025 for (; i>=0; i--) {
1026 r = (ActivityRecord)mHistory.get(i);
1027 if (DEBUG_VISBILITY) Slog.v(
1028 TAG, "Make visible? " + r + " finishing=" + r.finishing
1029 + " state=" + r.state);
1030 if (r.finishing) {
1031 continue;
1032 }
1033
1034 final boolean doThisProcess = onlyThisProcess == null
1035 || onlyThisProcess.equals(r.processName);
1036
1037 // First: if this is not the current activity being started, make
1038 // sure it matches the current configuration.
1039 if (r != starting && doThisProcess) {
1040 ensureActivityConfigurationLocked(r, 0);
1041 }
1042
1043 if (r.app == null || r.app.thread == null) {
1044 if (onlyThisProcess == null
1045 || onlyThisProcess.equals(r.processName)) {
1046 // This activity needs to be visible, but isn't even
1047 // running... get it started, but don't resume it
1048 // at this point.
1049 if (DEBUG_VISBILITY) Slog.v(
1050 TAG, "Start and freeze screen for " + r);
1051 if (r != starting) {
1052 r.startFreezingScreenLocked(r.app, configChanges);
1053 }
1054 if (!r.visible) {
1055 if (DEBUG_VISBILITY) Slog.v(
1056 TAG, "Starting and making visible: " + r);
1057 mService.mWindowManager.setAppVisibility(r, true);
1058 }
1059 if (r != starting) {
1060 startSpecificActivityLocked(r, false, false);
1061 }
1062 }
1063
1064 } else if (r.visible) {
1065 // If this activity is already visible, then there is nothing
1066 // else to do here.
1067 if (DEBUG_VISBILITY) Slog.v(
1068 TAG, "Skipping: already visible at " + r);
1069 r.stopFreezingScreenLocked(false);
1070
1071 } else if (onlyThisProcess == null) {
1072 // This activity is not currently visible, but is running.
1073 // Tell it to become visible.
1074 r.visible = true;
1075 if (r.state != ActivityState.RESUMED && r != starting) {
1076 // If this activity is paused, tell it
1077 // to now show its window.
1078 if (DEBUG_VISBILITY) Slog.v(
1079 TAG, "Making visible and scheduling visibility: " + r);
1080 try {
1081 mService.mWindowManager.setAppVisibility(r, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001082 r.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001083 r.app.thread.scheduleWindowVisibility(r, true);
1084 r.stopFreezingScreenLocked(false);
1085 } catch (Exception e) {
1086 // Just skip on any failure; we'll make it
1087 // visible when it next restarts.
1088 Slog.w(TAG, "Exception thrown making visibile: "
1089 + r.intent.getComponent(), e);
1090 }
1091 }
1092 }
1093
1094 // Aggregate current change flags.
1095 configChanges |= r.configChangeFlags;
1096
1097 if (r.fullscreen) {
1098 // At this point, nothing else needs to be shown
1099 if (DEBUG_VISBILITY) Slog.v(
1100 TAG, "Stopping: fullscreen at " + r);
1101 behindFullscreen = true;
1102 i--;
1103 break;
1104 }
1105 }
1106
1107 // Now for any activities that aren't visible to the user, make
1108 // sure they no longer are keeping the screen frozen.
1109 while (i >= 0) {
1110 r = (ActivityRecord)mHistory.get(i);
1111 if (DEBUG_VISBILITY) Slog.v(
1112 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1113 + " state=" + r.state
1114 + " behindFullscreen=" + behindFullscreen);
1115 if (!r.finishing) {
1116 if (behindFullscreen) {
1117 if (r.visible) {
1118 if (DEBUG_VISBILITY) Slog.v(
1119 TAG, "Making invisible: " + r);
1120 r.visible = false;
1121 try {
1122 mService.mWindowManager.setAppVisibility(r, false);
1123 if ((r.state == ActivityState.STOPPING
1124 || r.state == ActivityState.STOPPED)
1125 && r.app != null && r.app.thread != null) {
1126 if (DEBUG_VISBILITY) Slog.v(
1127 TAG, "Scheduling invisibility: " + r);
1128 r.app.thread.scheduleWindowVisibility(r, false);
1129 }
1130 } catch (Exception e) {
1131 // Just skip on any failure; we'll make it
1132 // visible when it next restarts.
1133 Slog.w(TAG, "Exception thrown making hidden: "
1134 + r.intent.getComponent(), e);
1135 }
1136 } else {
1137 if (DEBUG_VISBILITY) Slog.v(
1138 TAG, "Already invisible: " + r);
1139 }
1140 } else if (r.fullscreen) {
1141 if (DEBUG_VISBILITY) Slog.v(
1142 TAG, "Now behindFullscreen: " + r);
1143 behindFullscreen = true;
1144 }
1145 }
1146 i--;
1147 }
1148 }
1149
1150 /**
1151 * Version of ensureActivitiesVisible that can easily be called anywhere.
1152 */
1153 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1154 int configChanges) {
1155 ActivityRecord r = topRunningActivityLocked(null);
1156 if (r != null) {
1157 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1158 }
1159 }
1160
1161 /**
1162 * Ensure that the top activity in the stack is resumed.
1163 *
1164 * @param prev The previously resumed activity, for when in the process
1165 * of pausing; can be null to call from elsewhere.
1166 *
1167 * @return Returns true if something is being resumed, or false if
1168 * nothing happened.
1169 */
1170 final boolean resumeTopActivityLocked(ActivityRecord prev) {
1171 // Find the first activity that is not finishing.
1172 ActivityRecord next = topRunningActivityLocked(null);
1173
1174 // Remember how we'll process this pause/resume situation, and ensure
1175 // that the state is reset however we wind up proceeding.
1176 final boolean userLeaving = mUserLeaving;
1177 mUserLeaving = false;
1178
1179 if (next == null) {
1180 // There are no more activities! Let's just start up the
1181 // Launcher...
1182 if (mMainStack) {
1183 return mService.startHomeActivityLocked();
1184 }
1185 }
1186
1187 next.delayedResume = false;
1188
1189 // If the top activity is the resumed one, nothing to do.
1190 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1191 // Make sure we have executed any pending transitions, since there
1192 // should be nothing left to do at this point.
1193 mService.mWindowManager.executeAppTransition();
1194 mNoAnimActivities.clear();
1195 return false;
1196 }
1197
1198 // If we are sleeping, and there is no resumed activity, and the top
1199 // activity is paused, well that is the state we want.
1200 if ((mService.mSleeping || mService.mShuttingDown)
1201 && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
1202 // Make sure we have executed any pending transitions, since there
1203 // should be nothing left to do at this point.
1204 mService.mWindowManager.executeAppTransition();
1205 mNoAnimActivities.clear();
1206 return false;
1207 }
1208
1209 // The activity may be waiting for stop, but that is no longer
1210 // appropriate for it.
1211 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001212 mGoingToSleepActivities.remove(next);
1213 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001214 mWaitingVisibleActivities.remove(next);
1215
1216 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1217
1218 // If we are currently pausing an activity, then don't do anything
1219 // until that is done.
1220 if (mPausingActivity != null) {
1221 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
1222 return false;
1223 }
1224
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001225 // Okay we are now going to start a switch, to 'next'. We may first
1226 // have to pause the current activity, but this is an important point
1227 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001228 // XXX "App Redirected" dialog is getting too many false positives
1229 // at this point, so turn off for now.
1230 if (false) {
1231 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1232 long now = SystemClock.uptimeMillis();
1233 final boolean inTime = mLastStartedActivity.startTime != 0
1234 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1235 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1236 final int nextUid = next.info.applicationInfo.uid;
1237 if (inTime && lastUid != nextUid
1238 && lastUid != next.launchedFromUid
1239 && mService.checkPermission(
1240 android.Manifest.permission.STOP_APP_SWITCHES,
1241 -1, next.launchedFromUid)
1242 != PackageManager.PERMISSION_GRANTED) {
1243 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1244 } else {
1245 next.startTime = now;
1246 mLastStartedActivity = next;
1247 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001248 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001249 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001250 mLastStartedActivity = next;
1251 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001252 }
1253
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001254 // We need to start pausing the current activity so the top one
1255 // can be resumed...
1256 if (mResumedActivity != null) {
1257 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
1258 startPausingLocked(userLeaving, false);
1259 return true;
1260 }
1261
1262 if (prev != null && prev != next) {
1263 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1264 prev.waitingVisible = true;
1265 mWaitingVisibleActivities.add(prev);
1266 if (DEBUG_SWITCH) Slog.v(
1267 TAG, "Resuming top, waiting visible to hide: " + prev);
1268 } else {
1269 // The next activity is already visible, so hide the previous
1270 // activity's windows right now so we can show the new one ASAP.
1271 // We only do this if the previous is finishing, which should mean
1272 // it is on top of the one being resumed so hiding it quickly
1273 // is good. Otherwise, we want to do the normal route of allowing
1274 // the resumed activity to be shown so we can decide if the
1275 // previous should actually be hidden depending on whether the
1276 // new one is found to be full-screen or not.
1277 if (prev.finishing) {
1278 mService.mWindowManager.setAppVisibility(prev, false);
1279 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1280 + prev + ", waitingVisible="
1281 + (prev != null ? prev.waitingVisible : null)
1282 + ", nowVisible=" + next.nowVisible);
1283 } else {
1284 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1285 + prev + ", waitingVisible="
1286 + (prev != null ? prev.waitingVisible : null)
1287 + ", nowVisible=" + next.nowVisible);
1288 }
1289 }
1290 }
1291
1292 // We are starting up the next activity, so tell the window manager
1293 // that the previous one will be hidden soon. This way it can know
1294 // to ignore it when computing the desired screen orientation.
1295 if (prev != null) {
1296 if (prev.finishing) {
1297 if (DEBUG_TRANSITION) Slog.v(TAG,
1298 "Prepare close transition: prev=" + prev);
1299 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001300 mService.mWindowManager.prepareAppTransition(
1301 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001302 } else {
1303 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1304 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001305 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001306 }
1307 mService.mWindowManager.setAppWillBeHidden(prev);
1308 mService.mWindowManager.setAppVisibility(prev, false);
1309 } else {
1310 if (DEBUG_TRANSITION) Slog.v(TAG,
1311 "Prepare open transition: prev=" + prev);
1312 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001313 mService.mWindowManager.prepareAppTransition(
1314 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001315 } else {
1316 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1317 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001318 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001319 }
1320 }
1321 if (false) {
1322 mService.mWindowManager.setAppWillBeHidden(prev);
1323 mService.mWindowManager.setAppVisibility(prev, false);
1324 }
1325 } else if (mHistory.size() > 1) {
1326 if (DEBUG_TRANSITION) Slog.v(TAG,
1327 "Prepare open transition: no previous");
1328 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001329 mService.mWindowManager.prepareAppTransition(
1330 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001331 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001332 mService.mWindowManager.prepareAppTransition(
1333 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001334 }
1335 }
1336
1337 if (next.app != null && next.app.thread != null) {
1338 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1339
1340 // This activity is now becoming visible.
1341 mService.mWindowManager.setAppVisibility(next, true);
1342
1343 ActivityRecord lastResumedActivity = mResumedActivity;
1344 ActivityState lastState = next.state;
1345
1346 mService.updateCpuStats();
1347
1348 next.state = ActivityState.RESUMED;
1349 mResumedActivity = next;
1350 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001351 if (mMainStack) {
1352 mService.addRecentTaskLocked(next.task);
1353 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001354 mService.updateLruProcessLocked(next.app, true, true);
1355 updateLRUListLocked(next);
1356
1357 // Have the window manager re-evaluate the orientation of
1358 // the screen based on the new activity order.
1359 boolean updated = false;
1360 if (mMainStack) {
1361 synchronized (mService) {
1362 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1363 mService.mConfiguration,
1364 next.mayFreezeScreenLocked(next.app) ? next : null);
1365 if (config != null) {
1366 next.frozenBeforeDestroy = true;
1367 }
1368 updated = mService.updateConfigurationLocked(config, next);
1369 }
1370 }
1371 if (!updated) {
1372 // The configuration update wasn't able to keep the existing
1373 // instance of the activity, and instead started a new one.
1374 // We should be all done, but let's just make sure our activity
1375 // is still at the top and schedule another run if something
1376 // weird happened.
1377 ActivityRecord nextNext = topRunningActivityLocked(null);
1378 if (DEBUG_SWITCH) Slog.i(TAG,
1379 "Activity config changed during resume: " + next
1380 + ", new next: " + nextNext);
1381 if (nextNext != next) {
1382 // Do over!
1383 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1384 }
1385 if (mMainStack) {
1386 mService.setFocusedActivityLocked(next);
1387 }
1388 ensureActivitiesVisibleLocked(null, 0);
1389 mService.mWindowManager.executeAppTransition();
1390 mNoAnimActivities.clear();
1391 return true;
1392 }
1393
1394 try {
1395 // Deliver all pending results.
1396 ArrayList a = next.results;
1397 if (a != null) {
1398 final int N = a.size();
1399 if (!next.finishing && N > 0) {
1400 if (DEBUG_RESULTS) Slog.v(
1401 TAG, "Delivering results to " + next
1402 + ": " + a);
1403 next.app.thread.scheduleSendResult(next, a);
1404 }
1405 }
1406
1407 if (next.newIntents != null) {
1408 next.app.thread.scheduleNewIntent(next.newIntents, next);
1409 }
1410
1411 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
1412 System.identityHashCode(next),
1413 next.task.taskId, next.shortComponentName);
1414
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001415 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001416 next.app.thread.scheduleResumeActivity(next,
1417 mService.isNextTransitionForward());
1418
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001419 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001420
1421 } catch (Exception e) {
1422 // Whoops, need to restart this activity!
1423 next.state = lastState;
1424 mResumedActivity = lastResumedActivity;
1425 Slog.i(TAG, "Restarting because process died: " + next);
1426 if (!next.hasBeenLaunched) {
1427 next.hasBeenLaunched = true;
1428 } else {
1429 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1430 mService.mWindowManager.setAppStartingWindow(
1431 next, next.packageName, next.theme,
1432 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001433 next.labelRes, next.icon, next.windowFlags,
1434 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001435 }
1436 }
1437 startSpecificActivityLocked(next, true, false);
1438 return true;
1439 }
1440
1441 // From this point on, if something goes wrong there is no way
1442 // to recover the activity.
1443 try {
1444 next.visible = true;
1445 completeResumeLocked(next);
1446 } catch (Exception e) {
1447 // If any exception gets thrown, toss away this
1448 // activity and try the next one.
1449 Slog.w(TAG, "Exception thrown during resume of " + next, e);
1450 requestFinishActivityLocked(next, Activity.RESULT_CANCELED, null,
1451 "resume-exception");
1452 return true;
1453 }
1454
1455 // Didn't need to use the icicle, and it is now out of date.
1456 next.icicle = null;
1457 next.haveState = false;
1458 next.stopped = false;
1459
1460 } else {
1461 // Whoops, need to restart this activity!
1462 if (!next.hasBeenLaunched) {
1463 next.hasBeenLaunched = true;
1464 } else {
1465 if (SHOW_APP_STARTING_PREVIEW) {
1466 mService.mWindowManager.setAppStartingWindow(
1467 next, next.packageName, next.theme,
1468 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001469 next.labelRes, next.icon, next.windowFlags,
1470 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001471 }
1472 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1473 }
1474 startSpecificActivityLocked(next, true, true);
1475 }
1476
1477 return true;
1478 }
1479
1480 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001481 boolean doResume, boolean keepCurTransition) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001482 final int NH = mHistory.size();
1483
1484 int addPos = -1;
1485
1486 if (!newTask) {
1487 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001488 boolean startIt = true;
1489 for (int i = NH-1; i >= 0; i--) {
1490 ActivityRecord p = (ActivityRecord)mHistory.get(i);
1491 if (p.finishing) {
1492 continue;
1493 }
1494 if (p.task == r.task) {
1495 // Here it is! Now, if this is not yet visible to the
1496 // user, then just add it without starting; it will
1497 // get started when the user navigates back to it.
1498 addPos = i+1;
1499 if (!startIt) {
1500 mHistory.add(addPos, r);
1501 r.inHistory = true;
1502 r.task.numActivities++;
1503 mService.mWindowManager.addAppToken(addPos, r, r.task.taskId,
1504 r.info.screenOrientation, r.fullscreen);
1505 if (VALIDATE_TOKENS) {
1506 mService.mWindowManager.validateAppTokens(mHistory);
1507 }
1508 return;
1509 }
1510 break;
1511 }
1512 if (p.fullscreen) {
1513 startIt = false;
1514 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001515 }
1516 }
1517
1518 // Place a new activity at top of stack, so it is next to interact
1519 // with the user.
1520 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001521 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001522 }
1523
1524 // If we are not placing the new activity frontmost, we do not want
1525 // to deliver the onUserLeaving callback to the actual frontmost
1526 // activity
1527 if (addPos < NH) {
1528 mUserLeaving = false;
1529 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1530 }
1531
1532 // Slot the activity into the history stack and proceed
1533 mHistory.add(addPos, r);
1534 r.inHistory = true;
1535 r.frontOfTask = newTask;
1536 r.task.numActivities++;
1537 if (NH > 0) {
1538 // We want to show the starting preview window if we are
1539 // switching to a new task, or the next activity's process is
1540 // not currently running.
1541 boolean showStartingIcon = newTask;
1542 ProcessRecord proc = r.app;
1543 if (proc == null) {
1544 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1545 }
1546 if (proc == null || proc.thread == null) {
1547 showStartingIcon = true;
1548 }
1549 if (DEBUG_TRANSITION) Slog.v(TAG,
1550 "Prepare open transition: starting " + r);
1551 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001552 mService.mWindowManager.prepareAppTransition(
1553 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001554 mNoAnimActivities.add(r);
1555 } else if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
1556 mService.mWindowManager.prepareAppTransition(
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001557 WindowManagerPolicy.TRANSIT_TASK_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001558 mNoAnimActivities.remove(r);
1559 } else {
1560 mService.mWindowManager.prepareAppTransition(newTask
1561 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001562 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001563 mNoAnimActivities.remove(r);
1564 }
1565 mService.mWindowManager.addAppToken(
1566 addPos, r, r.task.taskId, r.info.screenOrientation, r.fullscreen);
1567 boolean doShow = true;
1568 if (newTask) {
1569 // Even though this activity is starting fresh, we still need
1570 // to reset it to make sure we apply affinities to move any
1571 // existing activities from other tasks in to it.
1572 // If the caller has requested that the target task be
1573 // reset, then do so.
1574 if ((r.intent.getFlags()
1575 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1576 resetTaskIfNeededLocked(r, r);
1577 doShow = topRunningNonDelayedActivityLocked(null) == r;
1578 }
1579 }
1580 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1581 // Figure out if we are transitioning from another activity that is
1582 // "has the same starting icon" as the next one. This allows the
1583 // window manager to keep the previous window it had previously
1584 // created, if it still had one.
1585 ActivityRecord prev = mResumedActivity;
1586 if (prev != null) {
1587 // We don't want to reuse the previous starting preview if:
1588 // (1) The current activity is in a different task.
1589 if (prev.task != r.task) prev = null;
1590 // (2) The current activity is already displayed.
1591 else if (prev.nowVisible) prev = null;
1592 }
1593 mService.mWindowManager.setAppStartingWindow(
1594 r, r.packageName, r.theme, r.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001595 r.labelRes, r.icon, r.windowFlags, prev, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001596 }
1597 } else {
1598 // If this is the first activity, don't do any fancy animations,
1599 // because there is nothing for it to animate on top of.
1600 mService.mWindowManager.addAppToken(addPos, r, r.task.taskId,
1601 r.info.screenOrientation, r.fullscreen);
1602 }
1603 if (VALIDATE_TOKENS) {
1604 mService.mWindowManager.validateAppTokens(mHistory);
1605 }
1606
1607 if (doResume) {
1608 resumeTopActivityLocked(null);
1609 }
1610 }
1611
1612 /**
1613 * Perform a reset of the given task, if needed as part of launching it.
1614 * Returns the new HistoryRecord at the top of the task.
1615 */
1616 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1617 ActivityRecord newActivity) {
1618 boolean forceReset = (newActivity.info.flags
1619 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001620 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1621 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001622 if ((newActivity.info.flags
1623 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1624 forceReset = true;
1625 }
1626 }
1627
1628 final TaskRecord task = taskTop.task;
1629
1630 // We are going to move through the history list so that we can look
1631 // at each activity 'target' with 'below' either the interesting
1632 // activity immediately below it in the stack or null.
1633 ActivityRecord target = null;
1634 int targetI = 0;
1635 int taskTopI = -1;
1636 int replyChainEnd = -1;
1637 int lastReparentPos = -1;
1638 for (int i=mHistory.size()-1; i>=-1; i--) {
1639 ActivityRecord below = i >= 0 ? (ActivityRecord)mHistory.get(i) : null;
1640
1641 if (below != null && below.finishing) {
1642 continue;
1643 }
1644 if (target == null) {
1645 target = below;
1646 targetI = i;
1647 // If we were in the middle of a reply chain before this
1648 // task, it doesn't appear like the root of the chain wants
1649 // anything interesting, so drop it.
1650 replyChainEnd = -1;
1651 continue;
1652 }
1653
1654 final int flags = target.info.flags;
1655
1656 final boolean finishOnTaskLaunch =
1657 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1658 final boolean allowTaskReparenting =
1659 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1660
1661 if (target.task == task) {
1662 // We are inside of the task being reset... we'll either
1663 // finish this activity, push it out for another task,
1664 // or leave it as-is. We only do this
1665 // for activities that are not the root of the task (since
1666 // if we finish the root, we may no longer have the task!).
1667 if (taskTopI < 0) {
1668 taskTopI = targetI;
1669 }
1670 if (below != null && below.task == task) {
1671 final boolean clearWhenTaskReset =
1672 (target.intent.getFlags()
1673 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
1674 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
1675 // If this activity is sending a reply to a previous
1676 // activity, we can't do anything with it now until
1677 // we reach the start of the reply chain.
1678 // XXX note that we are assuming the result is always
1679 // to the previous activity, which is almost always
1680 // the case but we really shouldn't count on.
1681 if (replyChainEnd < 0) {
1682 replyChainEnd = targetI;
1683 }
1684 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
1685 && target.taskAffinity != null
1686 && !target.taskAffinity.equals(task.affinity)) {
1687 // If this activity has an affinity for another
1688 // task, then we need to move it out of here. We will
1689 // move it as far out of the way as possible, to the
1690 // bottom of the activity stack. This also keeps it
1691 // correctly ordered with any activities we previously
1692 // moved.
1693 ActivityRecord p = (ActivityRecord)mHistory.get(0);
1694 if (target.taskAffinity != null
1695 && target.taskAffinity.equals(p.task.affinity)) {
1696 // If the activity currently at the bottom has the
1697 // same task affinity as the one we are moving,
1698 // then merge it into the same task.
1699 target.task = p.task;
1700 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1701 + " out to bottom task " + p.task);
1702 } else {
1703 mService.mCurTask++;
1704 if (mService.mCurTask <= 0) {
1705 mService.mCurTask = 1;
1706 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001707 target.task = new TaskRecord(mService.mCurTask, target.info, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001708 target.task.affinityIntent = target.intent;
1709 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1710 + " out to new task " + target.task);
1711 }
1712 mService.mWindowManager.setAppGroupId(target, task.taskId);
1713 if (replyChainEnd < 0) {
1714 replyChainEnd = targetI;
1715 }
1716 int dstPos = 0;
1717 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
1718 p = (ActivityRecord)mHistory.get(srcPos);
1719 if (p.finishing) {
1720 continue;
1721 }
1722 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
1723 + " out to target's task " + target.task);
1724 task.numActivities--;
1725 p.task = target.task;
1726 target.task.numActivities++;
1727 mHistory.remove(srcPos);
1728 mHistory.add(dstPos, p);
1729 mService.mWindowManager.moveAppToken(dstPos, p);
1730 mService.mWindowManager.setAppGroupId(p, p.task.taskId);
1731 dstPos++;
1732 if (VALIDATE_TOKENS) {
1733 mService.mWindowManager.validateAppTokens(mHistory);
1734 }
1735 i++;
1736 }
1737 if (taskTop == p) {
1738 taskTop = below;
1739 }
1740 if (taskTopI == replyChainEnd) {
1741 taskTopI = -1;
1742 }
1743 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001744 } else if (forceReset || finishOnTaskLaunch
1745 || clearWhenTaskReset) {
1746 // If the activity should just be removed -- either
1747 // because it asks for it, or the task should be
1748 // cleared -- then finish it and anything that is
1749 // part of its reply chain.
1750 if (clearWhenTaskReset) {
1751 // In this case, we want to finish this activity
1752 // and everything above it, so be sneaky and pretend
1753 // like these are all in the reply chain.
1754 replyChainEnd = targetI+1;
1755 while (replyChainEnd < mHistory.size() &&
1756 ((ActivityRecord)mHistory.get(
1757 replyChainEnd)).task == task) {
1758 replyChainEnd++;
1759 }
1760 replyChainEnd--;
1761 } else if (replyChainEnd < 0) {
1762 replyChainEnd = targetI;
1763 }
1764 ActivityRecord p = null;
1765 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
1766 p = (ActivityRecord)mHistory.get(srcPos);
1767 if (p.finishing) {
1768 continue;
1769 }
1770 if (finishActivityLocked(p, srcPos,
1771 Activity.RESULT_CANCELED, null, "reset")) {
1772 replyChainEnd--;
1773 srcPos--;
1774 }
1775 }
1776 if (taskTop == p) {
1777 taskTop = below;
1778 }
1779 if (taskTopI == replyChainEnd) {
1780 taskTopI = -1;
1781 }
1782 replyChainEnd = -1;
1783 } else {
1784 // If we were in the middle of a chain, well the
1785 // activity that started it all doesn't want anything
1786 // special, so leave it all as-is.
1787 replyChainEnd = -1;
1788 }
1789 } else {
1790 // Reached the bottom of the task -- any reply chain
1791 // should be left as-is.
1792 replyChainEnd = -1;
1793 }
1794
1795 } else if (target.resultTo != null) {
1796 // If this activity is sending a reply to a previous
1797 // activity, we can't do anything with it now until
1798 // we reach the start of the reply chain.
1799 // XXX note that we are assuming the result is always
1800 // to the previous activity, which is almost always
1801 // the case but we really shouldn't count on.
1802 if (replyChainEnd < 0) {
1803 replyChainEnd = targetI;
1804 }
1805
1806 } else if (taskTopI >= 0 && allowTaskReparenting
1807 && task.affinity != null
1808 && task.affinity.equals(target.taskAffinity)) {
1809 // We are inside of another task... if this activity has
1810 // an affinity for our task, then either remove it if we are
1811 // clearing or move it over to our task. Note that
1812 // we currently punt on the case where we are resetting a
1813 // task that is not at the top but who has activities above
1814 // with an affinity to it... this is really not a normal
1815 // case, and we will need to later pull that task to the front
1816 // and usually at that point we will do the reset and pick
1817 // up those remaining activities. (This only happens if
1818 // someone starts an activity in a new task from an activity
1819 // in a task that is not currently on top.)
1820 if (forceReset || finishOnTaskLaunch) {
1821 if (replyChainEnd < 0) {
1822 replyChainEnd = targetI;
1823 }
1824 ActivityRecord p = null;
1825 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
1826 p = (ActivityRecord)mHistory.get(srcPos);
1827 if (p.finishing) {
1828 continue;
1829 }
1830 if (finishActivityLocked(p, srcPos,
1831 Activity.RESULT_CANCELED, null, "reset")) {
1832 taskTopI--;
1833 lastReparentPos--;
1834 replyChainEnd--;
1835 srcPos--;
1836 }
1837 }
1838 replyChainEnd = -1;
1839 } else {
1840 if (replyChainEnd < 0) {
1841 replyChainEnd = targetI;
1842 }
1843 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
1844 ActivityRecord p = (ActivityRecord)mHistory.get(srcPos);
1845 if (p.finishing) {
1846 continue;
1847 }
1848 if (lastReparentPos < 0) {
1849 lastReparentPos = taskTopI;
1850 taskTop = p;
1851 } else {
1852 lastReparentPos--;
1853 }
1854 mHistory.remove(srcPos);
1855 p.task.numActivities--;
1856 p.task = task;
1857 mHistory.add(lastReparentPos, p);
1858 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
1859 + " in to resetting task " + task);
1860 task.numActivities++;
1861 mService.mWindowManager.moveAppToken(lastReparentPos, p);
1862 mService.mWindowManager.setAppGroupId(p, p.task.taskId);
1863 if (VALIDATE_TOKENS) {
1864 mService.mWindowManager.validateAppTokens(mHistory);
1865 }
1866 }
1867 replyChainEnd = -1;
1868
1869 // Now we've moved it in to place... but what if this is
1870 // a singleTop activity and we have put it on top of another
1871 // instance of the same activity? Then we drop the instance
1872 // below so it remains singleTop.
1873 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
1874 for (int j=lastReparentPos-1; j>=0; j--) {
1875 ActivityRecord p = (ActivityRecord)mHistory.get(j);
1876 if (p.finishing) {
1877 continue;
1878 }
1879 if (p.intent.getComponent().equals(target.intent.getComponent())) {
1880 if (finishActivityLocked(p, j,
1881 Activity.RESULT_CANCELED, null, "replace")) {
1882 taskTopI--;
1883 lastReparentPos--;
1884 }
1885 }
1886 }
1887 }
1888 }
1889 }
1890
1891 target = below;
1892 targetI = i;
1893 }
1894
1895 return taskTop;
1896 }
1897
1898 /**
1899 * Perform clear operation as requested by
1900 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
1901 * stack to the given task, then look for
1902 * an instance of that activity in the stack and, if found, finish all
1903 * activities on top of it and return the instance.
1904 *
1905 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001906 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001907 * or null if none was found.
1908 */
1909 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001910 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001911 int i = mHistory.size();
1912
1913 // First find the requested task.
1914 while (i > 0) {
1915 i--;
1916 ActivityRecord r = (ActivityRecord)mHistory.get(i);
1917 if (r.task.taskId == taskId) {
1918 i++;
1919 break;
1920 }
1921 }
1922
1923 // Now clear it.
1924 while (i > 0) {
1925 i--;
1926 ActivityRecord r = (ActivityRecord)mHistory.get(i);
1927 if (r.finishing) {
1928 continue;
1929 }
1930 if (r.task.taskId != taskId) {
1931 return null;
1932 }
1933 if (r.realActivity.equals(newR.realActivity)) {
1934 // Here it is! Now finish everything in front...
1935 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001936 while (i < (mHistory.size()-1)) {
1937 i++;
1938 r = (ActivityRecord)mHistory.get(i);
1939 if (r.task.taskId != taskId) {
1940 break;
1941 }
1942 if (r.finishing) {
1943 continue;
1944 }
1945 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
1946 null, "clear")) {
1947 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001948 }
1949 }
1950
1951 // Finally, if this is a normal launch mode (that is, not
1952 // expecting onNewIntent()), then we will finish the current
1953 // instance of the activity so a new fresh one can be started.
1954 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
1955 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
1956 if (!ret.finishing) {
1957 int index = indexOfTokenLocked(ret);
1958 if (index >= 0) {
1959 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
1960 null, "clear");
1961 }
1962 return null;
1963 }
1964 }
1965
1966 return ret;
1967 }
1968 }
1969
1970 return null;
1971 }
1972
1973 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001974 * Completely remove all activities associated with an existing task.
1975 */
1976 private final void performClearTaskLocked(int taskId) {
1977 int i = mHistory.size();
1978
1979 // First find the requested task.
1980 while (i > 0) {
1981 i--;
1982 ActivityRecord r = (ActivityRecord)mHistory.get(i);
1983 if (r.task.taskId == taskId) {
1984 i++;
1985 break;
1986 }
1987 }
1988
1989 // Now clear it.
1990 while (i > 0) {
1991 i--;
1992 ActivityRecord r = (ActivityRecord)mHistory.get(i);
1993 if (r.finishing) {
1994 continue;
1995 }
1996 if (r.task.taskId != taskId) {
1997 // We hit the bottom. Now finish it all...
1998 while (i < (mHistory.size()-1)) {
1999 i++;
2000 r = (ActivityRecord)mHistory.get(i);
2001 if (r.task.taskId != taskId) {
2002 // Whoops hit the end.
2003 return;
2004 }
2005 if (r.finishing) {
2006 continue;
2007 }
2008 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2009 null, "clear")) {
2010 i--;
2011 }
2012 }
2013 return;
2014 }
2015 }
2016 }
2017
2018 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002019 * Find the activity in the history stack within the given task. Returns
2020 * the index within the history at which it's found, or < 0 if not found.
2021 */
2022 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2023 int i = mHistory.size();
2024 while (i > 0) {
2025 i--;
2026 ActivityRecord candidate = (ActivityRecord)mHistory.get(i);
2027 if (candidate.task.taskId != task) {
2028 break;
2029 }
2030 if (candidate.realActivity.equals(r.realActivity)) {
2031 return i;
2032 }
2033 }
2034
2035 return -1;
2036 }
2037
2038 /**
2039 * Reorder the history stack so that the activity at the given index is
2040 * brought to the front.
2041 */
2042 private final ActivityRecord moveActivityToFrontLocked(int where) {
2043 ActivityRecord newTop = (ActivityRecord)mHistory.remove(where);
2044 int top = mHistory.size();
2045 ActivityRecord oldTop = (ActivityRecord)mHistory.get(top-1);
2046 mHistory.add(top, newTop);
2047 oldTop.frontOfTask = false;
2048 newTop.frontOfTask = true;
2049 return newTop;
2050 }
2051
2052 final int startActivityLocked(IApplicationThread caller,
2053 Intent intent, String resolvedType,
2054 Uri[] grantedUriPermissions,
2055 int grantedMode, ActivityInfo aInfo, IBinder resultTo,
2056 String resultWho, int requestCode,
2057 int callingPid, int callingUid, boolean onlyIfNeeded,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002058 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002059
2060 int err = START_SUCCESS;
2061
2062 ProcessRecord callerApp = null;
2063 if (caller != null) {
2064 callerApp = mService.getRecordForAppLocked(caller);
2065 if (callerApp != null) {
2066 callingPid = callerApp.pid;
2067 callingUid = callerApp.info.uid;
2068 } else {
2069 Slog.w(TAG, "Unable to find app for caller " + caller
2070 + " (pid=" + callingPid + ") when starting: "
2071 + intent.toString());
2072 err = START_PERMISSION_DENIED;
2073 }
2074 }
2075
2076 if (err == START_SUCCESS) {
2077 Slog.i(TAG, "Starting: " + intent + " from pid "
2078 + (callerApp != null ? callerApp.pid : callingPid));
2079 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002080
2081 ActivityRecord sourceRecord = null;
2082 ActivityRecord resultRecord = null;
2083 if (resultTo != null) {
2084 int index = indexOfTokenLocked(resultTo);
2085 if (DEBUG_RESULTS) Slog.v(
2086 TAG, "Sending result to " + resultTo + " (index " + index + ")");
2087 if (index >= 0) {
2088 sourceRecord = (ActivityRecord)mHistory.get(index);
2089 if (requestCode >= 0 && !sourceRecord.finishing) {
2090 resultRecord = sourceRecord;
2091 }
2092 }
2093 }
2094
2095 int launchFlags = intent.getFlags();
2096
2097 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2098 && sourceRecord != null) {
2099 // Transfer the result target from the source activity to the new
2100 // one being started, including any failures.
2101 if (requestCode >= 0) {
2102 return START_FORWARD_AND_REQUEST_CONFLICT;
2103 }
2104 resultRecord = sourceRecord.resultTo;
2105 resultWho = sourceRecord.resultWho;
2106 requestCode = sourceRecord.requestCode;
2107 sourceRecord.resultTo = null;
2108 if (resultRecord != null) {
2109 resultRecord.removeResultsLocked(
2110 sourceRecord, resultWho, requestCode);
2111 }
2112 }
2113
Dianne Hackbornefb58102010-10-14 16:47:34 -07002114 if (err == START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002115 // We couldn't find a class that can handle the given Intent.
2116 // That's the end of that!
2117 err = START_INTENT_NOT_RESOLVED;
2118 }
2119
2120 if (err == START_SUCCESS && aInfo == null) {
2121 // We couldn't find the specific class specified in the Intent.
2122 // Also the end of the line.
2123 err = START_CLASS_NOT_FOUND;
2124 }
2125
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002126 if (err != START_SUCCESS) {
2127 if (resultRecord != null) {
2128 sendActivityResultLocked(-1,
2129 resultRecord, resultWho, requestCode,
2130 Activity.RESULT_CANCELED, null);
2131 }
2132 return err;
2133 }
2134
2135 final int perm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002136 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002137 if (perm != PackageManager.PERMISSION_GRANTED) {
2138 if (resultRecord != null) {
2139 sendActivityResultLocked(-1,
2140 resultRecord, resultWho, requestCode,
2141 Activity.RESULT_CANCELED, null);
2142 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002143 String msg;
2144 if (!aInfo.exported) {
2145 msg = "Permission Denial: starting " + intent.toString()
2146 + " from " + callerApp + " (pid=" + callingPid
2147 + ", uid=" + callingUid + ")"
2148 + " not exported from uid " + aInfo.applicationInfo.uid;
2149 } else {
2150 msg = "Permission Denial: starting " + intent.toString()
2151 + " from " + callerApp + " (pid=" + callingPid
2152 + ", uid=" + callingUid + ")"
2153 + " requires " + aInfo.permission;
2154 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002155 Slog.w(TAG, msg);
2156 throw new SecurityException(msg);
2157 }
2158
2159 if (mMainStack) {
2160 if (mService.mController != null) {
2161 boolean abort = false;
2162 try {
2163 // The Intent we give to the watcher has the extra data
2164 // stripped off, since it can contain private information.
2165 Intent watchIntent = intent.cloneFilter();
2166 abort = !mService.mController.activityStarting(watchIntent,
2167 aInfo.applicationInfo.packageName);
2168 } catch (RemoteException e) {
2169 mService.mController = null;
2170 }
2171
2172 if (abort) {
2173 if (resultRecord != null) {
2174 sendActivityResultLocked(-1,
2175 resultRecord, resultWho, requestCode,
2176 Activity.RESULT_CANCELED, null);
2177 }
2178 // We pretend to the caller that it was really started, but
2179 // they will just get a cancel result.
2180 return START_SUCCESS;
2181 }
2182 }
2183 }
2184
2185 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2186 intent, resolvedType, aInfo, mService.mConfiguration,
2187 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002188 if (outActivity != null) {
2189 outActivity[0] = r;
2190 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002191
2192 if (mMainStack) {
2193 if (mResumedActivity == null
2194 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2195 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2196 PendingActivityLaunch pal = new PendingActivityLaunch();
2197 pal.r = r;
2198 pal.sourceRecord = sourceRecord;
2199 pal.grantedUriPermissions = grantedUriPermissions;
2200 pal.grantedMode = grantedMode;
2201 pal.onlyIfNeeded = onlyIfNeeded;
2202 mService.mPendingActivityLaunches.add(pal);
2203 return START_SWITCHES_CANCELED;
2204 }
2205 }
2206
2207 if (mService.mDidAppSwitch) {
2208 // This is the second allowed switch since we stopped switches,
2209 // so now just generally allow switches. Use case: user presses
2210 // home (switches disabled, switch to home, mDidAppSwitch now true);
2211 // user taps a home icon (coming from home so allowed, we hit here
2212 // and now allow anyone to switch again).
2213 mService.mAppSwitchesAllowedTime = 0;
2214 } else {
2215 mService.mDidAppSwitch = true;
2216 }
2217
2218 mService.doPendingActivityLaunchesLocked(false);
2219 }
2220
2221 return startActivityUncheckedLocked(r, sourceRecord,
2222 grantedUriPermissions, grantedMode, onlyIfNeeded, true);
2223 }
2224
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002225 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2226 if ((launchFlags &
2227 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2228 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2229 // Caller wants to appear on home activity, so before starting
2230 // their own activity we will bring home to the front.
2231 moveHomeToFrontLocked();
2232 }
2233 }
2234
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002235 final int startActivityUncheckedLocked(ActivityRecord r,
2236 ActivityRecord sourceRecord, Uri[] grantedUriPermissions,
2237 int grantedMode, boolean onlyIfNeeded, boolean doResume) {
2238 final Intent intent = r.intent;
2239 final int callingUid = r.launchedFromUid;
2240
2241 int launchFlags = intent.getFlags();
2242
2243 // We'll invoke onUserLeaving before onPause only if the launching
2244 // activity did not explicitly state that this is an automated launch.
2245 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2246 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2247 "startActivity() => mUserLeaving=" + mUserLeaving);
2248
2249 // If the caller has asked not to resume at this point, we make note
2250 // of this in the record so that we can skip it when trying to find
2251 // the top running activity.
2252 if (!doResume) {
2253 r.delayedResume = true;
2254 }
2255
2256 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2257 != 0 ? r : null;
2258
2259 // If the onlyIfNeeded flag is set, then we can do this if the activity
2260 // being launched is the same as the one making the call... or, as
2261 // a special case, if we do not know the caller then we count the
2262 // current top activity as the caller.
2263 if (onlyIfNeeded) {
2264 ActivityRecord checkedCaller = sourceRecord;
2265 if (checkedCaller == null) {
2266 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2267 }
2268 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2269 // Caller is not the same as launcher, so always needed.
2270 onlyIfNeeded = false;
2271 }
2272 }
2273
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002274 if (sourceRecord == null) {
2275 // This activity is not being started from another... in this
2276 // case we -always- start a new task.
2277 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2278 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2279 + intent);
2280 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2281 }
2282 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2283 // The original activity who is starting us is running as a single
2284 // instance... this new activity it is starting must go on its
2285 // own task.
2286 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2287 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2288 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2289 // The activity being started is a single instance... it always
2290 // gets launched into its own task.
2291 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2292 }
2293
2294 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2295 // For whatever reason this activity is being launched into a new
2296 // task... yet the caller has requested a result back. Well, that
2297 // is pretty messed up, so instead immediately send back a cancel
2298 // and let the new task continue launched as normal without a
2299 // dependency on its originator.
2300 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2301 sendActivityResultLocked(-1,
2302 r.resultTo, r.resultWho, r.requestCode,
2303 Activity.RESULT_CANCELED, null);
2304 r.resultTo = null;
2305 }
2306
2307 boolean addingToTask = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002308 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002309 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2310 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2311 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2312 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2313 // If bring to front is requested, and no result is requested, and
2314 // we can find a task that was started with this same
2315 // component, then instead of launching bring that one to the front.
2316 if (r.resultTo == null) {
2317 // See if there is a task to bring to the front. If this is
2318 // a SINGLE_INSTANCE activity, there can be one and only one
2319 // instance of it in the history, and it is always in its own
2320 // unique task, so we do a special search.
2321 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2322 ? findTaskLocked(intent, r.info)
2323 : findActivityLocked(intent, r.info);
2324 if (taskTop != null) {
2325 if (taskTop.task.intent == null) {
2326 // This task was started because of movement of
2327 // the activity based on affinity... now that we
2328 // are actually launching it, we can assign the
2329 // base intent.
2330 taskTop.task.setIntent(intent, r.info);
2331 }
2332 // If the target task is not in the front, then we need
2333 // to bring it to the front... except... well, with
2334 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2335 // to have the same behavior as if a new instance was
2336 // being started, which means not bringing it to the front
2337 // if the caller is not itself in the front.
2338 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002339 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002340 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2341 boolean callerAtFront = sourceRecord == null
2342 || curTop.task == sourceRecord.task;
2343 if (callerAtFront) {
2344 // We really do want to push this one into the
2345 // user's face, right now.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002346 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002347 moveTaskToFrontLocked(taskTop.task, r);
2348 }
2349 }
2350 // If the caller has requested that the target task be
2351 // reset, then do so.
2352 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2353 taskTop = resetTaskIfNeededLocked(taskTop, r);
2354 }
2355 if (onlyIfNeeded) {
2356 // We don't need to start a new activity, and
2357 // the client said not to do anything if that
2358 // is the case, so this is it! And for paranoia, make
2359 // sure we have correctly resumed the top activity.
2360 if (doResume) {
2361 resumeTopActivityLocked(null);
2362 }
2363 return START_RETURN_INTENT_TO_CALLER;
2364 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002365 if ((launchFlags &
2366 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2367 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2368 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002369 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002370 // not be too hard...
2371 reuseTask = taskTop.task;
2372 performClearTaskLocked(taskTop.task.taskId);
2373 reuseTask.setIntent(r.intent, r.info);
2374 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002375 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2376 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2377 // In this situation we want to remove all activities
2378 // from the task up to the one being started. In most
2379 // cases this means we are resetting the task to its
2380 // initial state.
2381 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002382 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002383 if (top != null) {
2384 if (top.frontOfTask) {
2385 // Activity aliases may mean we use different
2386 // intents for the top activity, so make sure
2387 // the task now has the identity of the new
2388 // intent.
2389 top.task.setIntent(r.intent, r.info);
2390 }
2391 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002392 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002393 } else {
2394 // A special case: we need to
2395 // start the activity because it is not currently
2396 // running, and the caller has asked to clear the
2397 // current task to have this activity at the top.
2398 addingToTask = true;
2399 // Now pretend like this activity is being started
2400 // by the top of its task, so it is put in the
2401 // right place.
2402 sourceRecord = taskTop;
2403 }
2404 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2405 // In this case the top activity on the task is the
2406 // same as the one being launched, so we take that
2407 // as a request to bring the task to the foreground.
2408 // If the top activity in the task is the root
2409 // activity, deliver this new intent to it if it
2410 // desires.
2411 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2412 && taskTop.realActivity.equals(r.realActivity)) {
2413 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2414 if (taskTop.frontOfTask) {
2415 taskTop.task.setIntent(r.intent, r.info);
2416 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002417 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002418 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2419 // In this case we are launching the root activity
2420 // of the task, but with a different intent. We
2421 // should start a new instance on top.
2422 addingToTask = true;
2423 sourceRecord = taskTop;
2424 }
2425 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2426 // In this case an activity is being launched in to an
2427 // existing task, without resetting that task. This
2428 // is typically the situation of launching an activity
2429 // from a notification or shortcut. We want to place
2430 // the new activity on top of the current task.
2431 addingToTask = true;
2432 sourceRecord = taskTop;
2433 } else if (!taskTop.task.rootWasReset) {
2434 // In this case we are launching in to an existing task
2435 // that has not yet been started from its front door.
2436 // The current task has been brought to the front.
2437 // Ideally, we'd probably like to place this new task
2438 // at the bottom of its stack, but that's a little hard
2439 // to do with the current organization of the code so
2440 // for now we'll just drop it.
2441 taskTop.task.setIntent(r.intent, r.info);
2442 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002443 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002444 // We didn't do anything... but it was needed (a.k.a., client
2445 // don't use that intent!) And for paranoia, make
2446 // sure we have correctly resumed the top activity.
2447 if (doResume) {
2448 resumeTopActivityLocked(null);
2449 }
2450 return START_TASK_TO_FRONT;
2451 }
2452 }
2453 }
2454 }
2455
2456 //String uri = r.intent.toURI();
2457 //Intent intent2 = new Intent(uri);
2458 //Slog.i(TAG, "Given intent: " + r.intent);
2459 //Slog.i(TAG, "URI is: " + uri);
2460 //Slog.i(TAG, "To intent: " + intent2);
2461
2462 if (r.packageName != null) {
2463 // If the activity being launched is the same as the one currently
2464 // at the top, then we need to check if it should only be launched
2465 // once.
2466 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2467 if (top != null && r.resultTo == null) {
2468 if (top.realActivity.equals(r.realActivity)) {
2469 if (top.app != null && top.app.thread != null) {
2470 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2471 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2472 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2473 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2474 // For paranoia, make sure we have correctly
2475 // resumed the top activity.
2476 if (doResume) {
2477 resumeTopActivityLocked(null);
2478 }
2479 if (onlyIfNeeded) {
2480 // We don't need to start a new activity, and
2481 // the client said not to do anything if that
2482 // is the case, so this is it!
2483 return START_RETURN_INTENT_TO_CALLER;
2484 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002485 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002486 return START_DELIVERED_TO_TOP;
2487 }
2488 }
2489 }
2490 }
2491
2492 } else {
2493 if (r.resultTo != null) {
2494 sendActivityResultLocked(-1,
2495 r.resultTo, r.resultWho, r.requestCode,
2496 Activity.RESULT_CANCELED, null);
2497 }
2498 return START_CLASS_NOT_FOUND;
2499 }
2500
2501 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002502 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002503
2504 // Should this be considered a new task?
2505 if (r.resultTo == null && !addingToTask
2506 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002507 if (reuseTask == null) {
2508 // todo: should do better management of integers.
2509 mService.mCurTask++;
2510 if (mService.mCurTask <= 0) {
2511 mService.mCurTask = 1;
2512 }
2513 r.task = new TaskRecord(mService.mCurTask, r.info, intent);
2514 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2515 + " in new task " + r.task);
2516 } else {
2517 r.task = reuseTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002518 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002519 newTask = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002520 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002521
2522 } else if (sourceRecord != null) {
2523 if (!addingToTask &&
2524 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2525 // In this case, we are adding the activity to an existing
2526 // task, but the caller has asked to clear that task if the
2527 // activity is already running.
2528 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002529 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002530 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002531 if (top != null) {
2532 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002533 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002534 // For paranoia, make sure we have correctly
2535 // resumed the top activity.
2536 if (doResume) {
2537 resumeTopActivityLocked(null);
2538 }
2539 return START_DELIVERED_TO_TOP;
2540 }
2541 } else if (!addingToTask &&
2542 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2543 // In this case, we are launching an activity in our own task
2544 // that may already be running somewhere in the history, and
2545 // we want to shuffle it to the front of the stack if so.
2546 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2547 if (where >= 0) {
2548 ActivityRecord top = moveActivityToFrontLocked(where);
2549 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002550 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002551 if (doResume) {
2552 resumeTopActivityLocked(null);
2553 }
2554 return START_DELIVERED_TO_TOP;
2555 }
2556 }
2557 // An existing activity is starting this new activity, so we want
2558 // to keep the new one in the same task as the one that is starting
2559 // it.
2560 r.task = sourceRecord.task;
2561 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2562 + " in existing task " + r.task);
2563
2564 } else {
2565 // This not being started from an existing activity, and not part
2566 // of a new task... just put it in the top task, though these days
2567 // this case should never happen.
2568 final int N = mHistory.size();
2569 ActivityRecord prev =
2570 N > 0 ? (ActivityRecord)mHistory.get(N-1) : null;
2571 r.task = prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002572 ? prev.task
2573 : new TaskRecord(mService.mCurTask, r.info, intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002574 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2575 + " in new guessed " + r.task);
2576 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002577
2578 if (grantedUriPermissions != null && callingUid > 0) {
2579 for (int i=0; i<grantedUriPermissions.length; i++) {
2580 mService.grantUriPermissionLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002581 grantedUriPermissions[i], grantedMode, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002582 }
2583 }
2584
2585 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002586 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002587
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002588 if (newTask) {
2589 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
2590 }
2591 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002592 startActivityLocked(r, newTask, doResume, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002593 return START_SUCCESS;
2594 }
2595
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002596 ActivityInfo resolveActivity(Intent intent, String resolvedType, boolean debug) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002597 // Collect information about the target of the Intent.
2598 ActivityInfo aInfo;
2599 try {
2600 ResolveInfo rInfo =
2601 AppGlobals.getPackageManager().resolveIntent(
2602 intent, resolvedType,
2603 PackageManager.MATCH_DEFAULT_ONLY
2604 | ActivityManagerService.STOCK_PM_FLAGS);
2605 aInfo = rInfo != null ? rInfo.activityInfo : null;
2606 } catch (RemoteException e) {
2607 aInfo = null;
2608 }
2609
2610 if (aInfo != null) {
2611 // Store the found target back into the intent, because now that
2612 // we have it we never want to do this again. For example, if the
2613 // user navigates back to this point in the history, we should
2614 // always restart the exact same activity.
2615 intent.setComponent(new ComponentName(
2616 aInfo.applicationInfo.packageName, aInfo.name));
2617
2618 // Don't debug things in the system process
2619 if (debug) {
2620 if (!aInfo.processName.equals("system")) {
2621 mService.setDebugApp(aInfo.processName, true, false);
2622 }
2623 }
2624 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002625 return aInfo;
2626 }
2627
2628 final int startActivityMayWait(IApplicationThread caller, int callingUid,
2629 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2630 int grantedMode, IBinder resultTo,
2631 String resultWho, int requestCode, boolean onlyIfNeeded,
2632 boolean debug, WaitResult outResult, Configuration config) {
2633 // Refuse possible leaked file descriptors
2634 if (intent != null && intent.hasFileDescriptors()) {
2635 throw new IllegalArgumentException("File descriptors passed in Intent");
2636 }
2637
2638 boolean componentSpecified = intent.getComponent() != null;
2639
2640 // Don't modify the client's object!
2641 intent = new Intent(intent);
2642
2643 // Collect information about the target of the Intent.
2644 ActivityInfo aInfo = resolveActivity(intent, resolvedType, debug);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002645
2646 synchronized (mService) {
2647 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002648 if (callingUid >= 0) {
2649 callingPid = -1;
2650 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002651 callingPid = Binder.getCallingPid();
2652 callingUid = Binder.getCallingUid();
2653 } else {
2654 callingPid = callingUid = -1;
2655 }
2656
2657 mConfigWillChange = config != null
2658 && mService.mConfiguration.diff(config) != 0;
2659 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2660 "Starting activity when config will change = " + mConfigWillChange);
2661
2662 final long origId = Binder.clearCallingIdentity();
2663
2664 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07002665 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002666 // This may be a heavy-weight process! Check to see if we already
2667 // have another, different heavy-weight process running.
2668 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
2669 if (mService.mHeavyWeightProcess != null &&
2670 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
2671 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
2672 int realCallingPid = callingPid;
2673 int realCallingUid = callingUid;
2674 if (caller != null) {
2675 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
2676 if (callerApp != null) {
2677 realCallingPid = callerApp.pid;
2678 realCallingUid = callerApp.info.uid;
2679 } else {
2680 Slog.w(TAG, "Unable to find app for caller " + caller
2681 + " (pid=" + realCallingPid + ") when starting: "
2682 + intent.toString());
2683 return START_PERMISSION_DENIED;
2684 }
2685 }
2686
2687 IIntentSender target = mService.getIntentSenderLocked(
2688 IActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002689 realCallingUid, null, null, 0, new Intent[] { intent },
2690 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002691 | PendingIntent.FLAG_ONE_SHOT);
2692
2693 Intent newIntent = new Intent();
2694 if (requestCode >= 0) {
2695 // Caller is requesting a result.
2696 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
2697 }
2698 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
2699 new IntentSender(target));
2700 if (mService.mHeavyWeightProcess.activities.size() > 0) {
2701 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
2702 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
2703 hist.packageName);
2704 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
2705 hist.task.taskId);
2706 }
2707 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
2708 aInfo.packageName);
2709 newIntent.setFlags(intent.getFlags());
2710 newIntent.setClassName("android",
2711 HeavyWeightSwitcherActivity.class.getName());
2712 intent = newIntent;
2713 resolvedType = null;
2714 caller = null;
2715 callingUid = Binder.getCallingUid();
2716 callingPid = Binder.getCallingPid();
2717 componentSpecified = true;
2718 try {
2719 ResolveInfo rInfo =
2720 AppGlobals.getPackageManager().resolveIntent(
2721 intent, null,
2722 PackageManager.MATCH_DEFAULT_ONLY
2723 | ActivityManagerService.STOCK_PM_FLAGS);
2724 aInfo = rInfo != null ? rInfo.activityInfo : null;
2725 } catch (RemoteException e) {
2726 aInfo = null;
2727 }
2728 }
2729 }
2730 }
2731
2732 int res = startActivityLocked(caller, intent, resolvedType,
2733 grantedUriPermissions, grantedMode, aInfo,
2734 resultTo, resultWho, requestCode, callingPid, callingUid,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002735 onlyIfNeeded, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002736
2737 if (mConfigWillChange && mMainStack) {
2738 // If the caller also wants to switch to a new configuration,
2739 // do so now. This allows a clean switch, as we are waiting
2740 // for the current activity to pause (so we will not destroy
2741 // it), and have not yet started the next activity.
2742 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
2743 "updateConfiguration()");
2744 mConfigWillChange = false;
2745 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2746 "Updating to new configuration after starting activity.");
2747 mService.updateConfigurationLocked(config, null);
2748 }
2749
2750 Binder.restoreCallingIdentity(origId);
2751
2752 if (outResult != null) {
2753 outResult.result = res;
2754 if (res == IActivityManager.START_SUCCESS) {
2755 mWaitingActivityLaunched.add(outResult);
2756 do {
2757 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07002758 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002759 } catch (InterruptedException e) {
2760 }
2761 } while (!outResult.timeout && outResult.who == null);
2762 } else if (res == IActivityManager.START_TASK_TO_FRONT) {
2763 ActivityRecord r = this.topRunningActivityLocked(null);
2764 if (r.nowVisible) {
2765 outResult.timeout = false;
2766 outResult.who = new ComponentName(r.info.packageName, r.info.name);
2767 outResult.totalTime = 0;
2768 outResult.thisTime = 0;
2769 } else {
2770 outResult.thisTime = SystemClock.uptimeMillis();
2771 mWaitingActivityVisible.add(outResult);
2772 do {
2773 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07002774 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002775 } catch (InterruptedException e) {
2776 }
2777 } while (!outResult.timeout && outResult.who == null);
2778 }
2779 }
2780 }
2781
2782 return res;
2783 }
2784 }
2785
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002786 final int startActivities(IApplicationThread caller, int callingUid,
2787 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
2788 if (intents == null) {
2789 throw new NullPointerException("intents is null");
2790 }
2791 if (resolvedTypes == null) {
2792 throw new NullPointerException("resolvedTypes is null");
2793 }
2794 if (intents.length != resolvedTypes.length) {
2795 throw new IllegalArgumentException("intents are length different than resolvedTypes");
2796 }
2797
2798 ActivityRecord[] outActivity = new ActivityRecord[1];
2799
2800 int callingPid;
2801 if (callingUid >= 0) {
2802 callingPid = -1;
2803 } else if (caller == null) {
2804 callingPid = Binder.getCallingPid();
2805 callingUid = Binder.getCallingUid();
2806 } else {
2807 callingPid = callingUid = -1;
2808 }
2809 final long origId = Binder.clearCallingIdentity();
2810 try {
2811 synchronized (mService) {
2812
2813 for (int i=0; i<intents.length; i++) {
2814 Intent intent = intents[i];
2815 if (intent == null) {
2816 continue;
2817 }
2818
2819 // Refuse possible leaked file descriptors
2820 if (intent != null && intent.hasFileDescriptors()) {
2821 throw new IllegalArgumentException("File descriptors passed in Intent");
2822 }
2823
2824 boolean componentSpecified = intent.getComponent() != null;
2825
2826 // Don't modify the client's object!
2827 intent = new Intent(intent);
2828
2829 // Collect information about the target of the Intent.
2830 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i], false);
2831
2832 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
2833 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
2834 throw new IllegalArgumentException(
2835 "FLAG_CANT_SAVE_STATE not supported here");
2836 }
2837
2838 int res = startActivityLocked(caller, intent, resolvedTypes[i],
2839 null, 0, aInfo, resultTo, null, -1, callingPid, callingUid,
2840 false, componentSpecified, outActivity);
2841 if (res < 0) {
2842 return res;
2843 }
2844
2845 resultTo = outActivity[0];
2846 }
2847 }
2848 } finally {
2849 Binder.restoreCallingIdentity(origId);
2850 }
2851
2852 return IActivityManager.START_SUCCESS;
2853 }
2854
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002855 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
2856 long thisTime, long totalTime) {
2857 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
2858 WaitResult w = mWaitingActivityLaunched.get(i);
2859 w.timeout = timeout;
2860 if (r != null) {
2861 w.who = new ComponentName(r.info.packageName, r.info.name);
2862 }
2863 w.thisTime = thisTime;
2864 w.totalTime = totalTime;
2865 }
2866 mService.notifyAll();
2867 }
2868
2869 void reportActivityVisibleLocked(ActivityRecord r) {
2870 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
2871 WaitResult w = mWaitingActivityVisible.get(i);
2872 w.timeout = false;
2873 if (r != null) {
2874 w.who = new ComponentName(r.info.packageName, r.info.name);
2875 }
2876 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
2877 w.thisTime = w.totalTime;
2878 }
2879 mService.notifyAll();
2880 }
2881
2882 void sendActivityResultLocked(int callingUid, ActivityRecord r,
2883 String resultWho, int requestCode, int resultCode, Intent data) {
2884
2885 if (callingUid > 0) {
2886 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002887 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002888 }
2889
2890 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
2891 + " : who=" + resultWho + " req=" + requestCode
2892 + " res=" + resultCode + " data=" + data);
2893 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
2894 try {
2895 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
2896 list.add(new ResultInfo(resultWho, requestCode,
2897 resultCode, data));
2898 r.app.thread.scheduleSendResult(r, list);
2899 return;
2900 } catch (Exception e) {
2901 Slog.w(TAG, "Exception thrown sending result to " + r, e);
2902 }
2903 }
2904
2905 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
2906 }
2907
2908 private final void stopActivityLocked(ActivityRecord r) {
2909 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
2910 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
2911 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
2912 if (!r.finishing) {
2913 requestFinishActivityLocked(r, Activity.RESULT_CANCELED, null,
2914 "no-history");
2915 }
2916 } else if (r.app != null && r.app.thread != null) {
2917 if (mMainStack) {
2918 if (mService.mFocusedActivity == r) {
2919 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
2920 }
2921 }
2922 r.resumeKeyDispatchingLocked();
2923 try {
2924 r.stopped = false;
2925 r.state = ActivityState.STOPPING;
2926 if (DEBUG_VISBILITY) Slog.v(
2927 TAG, "Stopping visible=" + r.visible + " for " + r);
2928 if (!r.visible) {
2929 mService.mWindowManager.setAppVisibility(r, false);
2930 }
2931 r.app.thread.scheduleStopActivity(r, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002932 if (mService.isSleeping()) {
2933 r.setSleeping(true);
2934 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002935 } catch (Exception e) {
2936 // Maybe just ignore exceptions here... if the process
2937 // has crashed, our death notification will clean things
2938 // up.
2939 Slog.w(TAG, "Exception thrown during pause", e);
2940 // Just in case, assume it to be stopped.
2941 r.stopped = true;
2942 r.state = ActivityState.STOPPED;
2943 if (r.configDestroy) {
2944 destroyActivityLocked(r, true);
2945 }
2946 }
2947 }
2948 }
2949
2950 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
2951 boolean remove) {
2952 int N = mStoppingActivities.size();
2953 if (N <= 0) return null;
2954
2955 ArrayList<ActivityRecord> stops = null;
2956
2957 final boolean nowVisible = mResumedActivity != null
2958 && mResumedActivity.nowVisible
2959 && !mResumedActivity.waitingVisible;
2960 for (int i=0; i<N; i++) {
2961 ActivityRecord s = mStoppingActivities.get(i);
2962 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
2963 + nowVisible + " waitingVisible=" + s.waitingVisible
2964 + " finishing=" + s.finishing);
2965 if (s.waitingVisible && nowVisible) {
2966 mWaitingVisibleActivities.remove(s);
2967 s.waitingVisible = false;
2968 if (s.finishing) {
2969 // If this activity is finishing, it is sitting on top of
2970 // everyone else but we now know it is no longer needed...
2971 // so get rid of it. Otherwise, we need to go through the
2972 // normal flow and hide it once we determine that it is
2973 // hidden by the activities in front of it.
2974 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
2975 mService.mWindowManager.setAppVisibility(s, false);
2976 }
2977 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002978 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002979 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
2980 if (stops == null) {
2981 stops = new ArrayList<ActivityRecord>();
2982 }
2983 stops.add(s);
2984 mStoppingActivities.remove(i);
2985 N--;
2986 i--;
2987 }
2988 }
2989
2990 return stops;
2991 }
2992
2993 final void activityIdleInternal(IBinder token, boolean fromTimeout,
2994 Configuration config) {
2995 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
2996
2997 ArrayList<ActivityRecord> stops = null;
2998 ArrayList<ActivityRecord> finishes = null;
2999 ArrayList<ActivityRecord> thumbnails = null;
3000 int NS = 0;
3001 int NF = 0;
3002 int NT = 0;
3003 IApplicationThread sendThumbnail = null;
3004 boolean booting = false;
3005 boolean enableScreen = false;
3006
3007 synchronized (mService) {
3008 if (token != null) {
3009 mHandler.removeMessages(IDLE_TIMEOUT_MSG, token);
3010 }
3011
3012 // Get the activity record.
3013 int index = indexOfTokenLocked(token);
3014 if (index >= 0) {
3015 ActivityRecord r = (ActivityRecord)mHistory.get(index);
3016
3017 if (fromTimeout) {
3018 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3019 }
3020
3021 // This is a hack to semi-deal with a race condition
3022 // in the client where it can be constructed with a
3023 // newer configuration from when we asked it to launch.
3024 // We'll update with whatever configuration it now says
3025 // it used to launch.
3026 if (config != null) {
3027 r.configuration = config;
3028 }
3029
3030 // No longer need to keep the device awake.
3031 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3032 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3033 mLaunchingActivity.release();
3034 }
3035
3036 // We are now idle. If someone is waiting for a thumbnail from
3037 // us, we can now deliver.
3038 r.idle = true;
3039 mService.scheduleAppGcsLocked();
3040 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3041 sendThumbnail = r.app.thread;
3042 r.thumbnailNeeded = false;
3043 }
3044
3045 // If this activity is fullscreen, set up to hide those under it.
3046
3047 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3048 ensureActivitiesVisibleLocked(null, 0);
3049
3050 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3051 if (mMainStack) {
3052 if (!mService.mBooted && !fromTimeout) {
3053 mService.mBooted = true;
3054 enableScreen = true;
3055 }
3056 }
3057
3058 } else if (fromTimeout) {
3059 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3060 }
3061
3062 // Atomically retrieve all of the other things to do.
3063 stops = processStoppingActivitiesLocked(true);
3064 NS = stops != null ? stops.size() : 0;
3065 if ((NF=mFinishingActivities.size()) > 0) {
3066 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3067 mFinishingActivities.clear();
3068 }
3069 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3070 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3071 mService.mCancelledThumbnails.clear();
3072 }
3073
3074 if (mMainStack) {
3075 booting = mService.mBooting;
3076 mService.mBooting = false;
3077 }
3078 }
3079
3080 int i;
3081
3082 // Send thumbnail if requested.
3083 if (sendThumbnail != null) {
3084 try {
3085 sendThumbnail.requestThumbnail(token);
3086 } catch (Exception e) {
3087 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3088 mService.sendPendingThumbnail(null, token, null, null, true);
3089 }
3090 }
3091
3092 // Stop any activities that are scheduled to do so but have been
3093 // waiting for the next one to start.
3094 for (i=0; i<NS; i++) {
3095 ActivityRecord r = (ActivityRecord)stops.get(i);
3096 synchronized (mService) {
3097 if (r.finishing) {
3098 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY);
3099 } else {
3100 stopActivityLocked(r);
3101 }
3102 }
3103 }
3104
3105 // Finish any activities that are scheduled to do so but have been
3106 // waiting for the next one to start.
3107 for (i=0; i<NF; i++) {
3108 ActivityRecord r = (ActivityRecord)finishes.get(i);
3109 synchronized (mService) {
3110 destroyActivityLocked(r, true);
3111 }
3112 }
3113
3114 // Report back to any thumbnail receivers.
3115 for (i=0; i<NT; i++) {
3116 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3117 mService.sendPendingThumbnail(r, null, null, null, true);
3118 }
3119
3120 if (booting) {
3121 mService.finishBooting();
3122 }
3123
3124 mService.trimApplications();
3125 //dump();
3126 //mWindowManager.dump();
3127
3128 if (enableScreen) {
3129 mService.enableScreenAfterBoot();
3130 }
3131 }
3132
3133 /**
3134 * @return Returns true if the activity is being finished, false if for
3135 * some reason it is being left as-is.
3136 */
3137 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
3138 Intent resultData, String reason) {
3139 if (DEBUG_RESULTS) Slog.v(
3140 TAG, "Finishing activity: token=" + token
3141 + ", result=" + resultCode + ", data=" + resultData);
3142
3143 int index = indexOfTokenLocked(token);
3144 if (index < 0) {
3145 return false;
3146 }
3147 ActivityRecord r = (ActivityRecord)mHistory.get(index);
3148
3149 // Is this the last activity left?
3150 boolean lastActivity = true;
3151 for (int i=mHistory.size()-1; i>=0; i--) {
3152 ActivityRecord p = (ActivityRecord)mHistory.get(i);
3153 if (!p.finishing && p != r) {
3154 lastActivity = false;
3155 break;
3156 }
3157 }
3158
3159 // If this is the last activity, but it is the home activity, then
3160 // just don't finish it.
3161 if (lastActivity) {
3162 if (r.intent.hasCategory(Intent.CATEGORY_HOME)) {
3163 return false;
3164 }
3165 }
3166
3167 finishActivityLocked(r, index, resultCode, resultData, reason);
3168 return true;
3169 }
3170
3171 /**
3172 * @return Returns true if this activity has been removed from the history
3173 * list, or false if it is still in the list and will be removed later.
3174 */
3175 final boolean finishActivityLocked(ActivityRecord r, int index,
3176 int resultCode, Intent resultData, String reason) {
3177 if (r.finishing) {
3178 Slog.w(TAG, "Duplicate finish request for " + r);
3179 return false;
3180 }
3181
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003182 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003183 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3184 System.identityHashCode(r),
3185 r.task.taskId, r.shortComponentName, reason);
3186 r.task.numActivities--;
3187 if (index < (mHistory.size()-1)) {
3188 ActivityRecord next = (ActivityRecord)mHistory.get(index+1);
3189 if (next.task == r.task) {
3190 if (r.frontOfTask) {
3191 // The next activity is now the front of the task.
3192 next.frontOfTask = true;
3193 }
3194 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3195 // If the caller asked that this activity (and all above it)
3196 // be cleared when the task is reset, don't lose that information,
3197 // but propagate it up to the next activity.
3198 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3199 }
3200 }
3201 }
3202
3203 r.pauseKeyDispatchingLocked();
3204 if (mMainStack) {
3205 if (mService.mFocusedActivity == r) {
3206 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3207 }
3208 }
3209
3210 // send the result
3211 ActivityRecord resultTo = r.resultTo;
3212 if (resultTo != null) {
3213 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3214 + " who=" + r.resultWho + " req=" + r.requestCode
3215 + " res=" + resultCode + " data=" + resultData);
3216 if (r.info.applicationInfo.uid > 0) {
3217 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
Dianne Hackborna1c69e02010-09-01 22:55:02 -07003218 resultTo.packageName, resultData,
3219 resultTo.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003220 }
3221 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3222 resultData);
3223 r.resultTo = null;
3224 }
3225 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3226
3227 // Make sure this HistoryRecord is not holding on to other resources,
3228 // because clients have remote IPC references to this object so we
3229 // can't assume that will go away and want to avoid circular IPC refs.
3230 r.results = null;
3231 r.pendingResults = null;
3232 r.newIntents = null;
3233 r.icicle = null;
3234
3235 if (mService.mPendingThumbnails.size() > 0) {
3236 // There are clients waiting to receive thumbnails so, in case
3237 // this is an activity that someone is waiting for, add it
3238 // to the pending list so we can correctly update the clients.
3239 mService.mCancelledThumbnails.add(r);
3240 }
3241
3242 if (mResumedActivity == r) {
3243 boolean endTask = index <= 0
3244 || ((ActivityRecord)mHistory.get(index-1)).task != r.task;
3245 if (DEBUG_TRANSITION) Slog.v(TAG,
3246 "Prepare close transition: finishing " + r);
3247 mService.mWindowManager.prepareAppTransition(endTask
3248 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003249 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003250
3251 // Tell window manager to prepare for this one to be removed.
3252 mService.mWindowManager.setAppVisibility(r, false);
3253
3254 if (mPausingActivity == null) {
3255 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3256 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3257 startPausingLocked(false, false);
3258 }
3259
3260 } else if (r.state != ActivityState.PAUSING) {
3261 // If the activity is PAUSING, we will complete the finish once
3262 // it is done pausing; else we can just directly finish it here.
3263 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3264 return finishCurrentActivityLocked(r, index,
3265 FINISH_AFTER_PAUSE) == null;
3266 } else {
3267 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3268 }
3269
3270 return false;
3271 }
3272
3273 private static final int FINISH_IMMEDIATELY = 0;
3274 private static final int FINISH_AFTER_PAUSE = 1;
3275 private static final int FINISH_AFTER_VISIBLE = 2;
3276
3277 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3278 int mode) {
3279 final int index = indexOfTokenLocked(r);
3280 if (index < 0) {
3281 return null;
3282 }
3283
3284 return finishCurrentActivityLocked(r, index, mode);
3285 }
3286
3287 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3288 int index, int mode) {
3289 // First things first: if this activity is currently visible,
3290 // and the resumed activity is not yet visible, then hold off on
3291 // finishing until the resumed one becomes visible.
3292 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3293 if (!mStoppingActivities.contains(r)) {
3294 mStoppingActivities.add(r);
3295 if (mStoppingActivities.size() > 3) {
3296 // If we already have a few activities waiting to stop,
3297 // then give up on things going idle and start clearing
3298 // them out.
3299 Message msg = Message.obtain();
3300 msg.what = IDLE_NOW_MSG;
3301 mHandler.sendMessage(msg);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003302 } else {
3303 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003304 }
3305 }
3306 r.state = ActivityState.STOPPING;
3307 mService.updateOomAdjLocked();
3308 return r;
3309 }
3310
3311 // make sure the record is cleaned out of other places.
3312 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003313 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003314 mWaitingVisibleActivities.remove(r);
3315 if (mResumedActivity == r) {
3316 mResumedActivity = null;
3317 }
3318 final ActivityState prevState = r.state;
3319 r.state = ActivityState.FINISHING;
3320
3321 if (mode == FINISH_IMMEDIATELY
3322 || prevState == ActivityState.STOPPED
3323 || prevState == ActivityState.INITIALIZING) {
3324 // If this activity is already stopped, we can just finish
3325 // it right now.
3326 return destroyActivityLocked(r, true) ? null : r;
3327 } else {
3328 // Need to go through the full pause cycle to get this
3329 // activity into the stopped state and then finish it.
3330 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3331 mFinishingActivities.add(r);
3332 resumeTopActivityLocked(null);
3333 }
3334 return r;
3335 }
3336
3337 /**
3338 * Perform the common clean-up of an activity record. This is called both
3339 * as part of destroyActivityLocked() (when destroying the client-side
3340 * representation) and cleaning things up as a result of its hosting
3341 * processing going away, in which case there is no remaining client-side
3342 * state to destroy so only the cleanup here is needed.
3343 */
3344 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices) {
3345 if (mResumedActivity == r) {
3346 mResumedActivity = null;
3347 }
3348 if (mService.mFocusedActivity == r) {
3349 mService.mFocusedActivity = null;
3350 }
3351
3352 r.configDestroy = false;
3353 r.frozenBeforeDestroy = false;
3354
3355 // Make sure this record is no longer in the pending finishes list.
3356 // This could happen, for example, if we are trimming activities
3357 // down to the max limit while they are still waiting to finish.
3358 mFinishingActivities.remove(r);
3359 mWaitingVisibleActivities.remove(r);
3360
3361 // Remove any pending results.
3362 if (r.finishing && r.pendingResults != null) {
3363 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3364 PendingIntentRecord rec = apr.get();
3365 if (rec != null) {
3366 mService.cancelIntentSenderLocked(rec, false);
3367 }
3368 }
3369 r.pendingResults = null;
3370 }
3371
3372 if (cleanServices) {
3373 cleanUpActivityServicesLocked(r);
3374 }
3375
3376 if (mService.mPendingThumbnails.size() > 0) {
3377 // There are clients waiting to receive thumbnails so, in case
3378 // this is an activity that someone is waiting for, add it
3379 // to the pending list so we can correctly update the clients.
3380 mService.mCancelledThumbnails.add(r);
3381 }
3382
3383 // Get rid of any pending idle timeouts.
3384 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
3385 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
3386 }
3387
3388 private final void removeActivityFromHistoryLocked(ActivityRecord r) {
3389 if (r.state != ActivityState.DESTROYED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003390 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003391 mHistory.remove(r);
3392 r.inHistory = false;
3393 r.state = ActivityState.DESTROYED;
3394 mService.mWindowManager.removeAppToken(r);
3395 if (VALIDATE_TOKENS) {
3396 mService.mWindowManager.validateAppTokens(mHistory);
3397 }
3398 cleanUpActivityServicesLocked(r);
3399 r.removeUriPermissionsLocked();
3400 }
3401 }
3402
3403 /**
3404 * Perform clean-up of service connections in an activity record.
3405 */
3406 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3407 // Throw away any services that have been bound by this activity.
3408 if (r.connections != null) {
3409 Iterator<ConnectionRecord> it = r.connections.iterator();
3410 while (it.hasNext()) {
3411 ConnectionRecord c = it.next();
3412 mService.removeConnectionLocked(c, null, r);
3413 }
3414 r.connections = null;
3415 }
3416 }
3417
3418 /**
3419 * Destroy the current CLIENT SIDE instance of an activity. This may be
3420 * called both when actually finishing an activity, or when performing
3421 * a configuration switch where we destroy the current client-side object
3422 * but then create a new client-side object for this same HistoryRecord.
3423 */
3424 final boolean destroyActivityLocked(ActivityRecord r,
3425 boolean removeFromApp) {
3426 if (DEBUG_SWITCH) Slog.v(
3427 TAG, "Removing activity: token=" + r
3428 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3429 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3430 System.identityHashCode(r),
3431 r.task.taskId, r.shortComponentName);
3432
3433 boolean removedFromHistory = false;
3434
3435 cleanUpActivityLocked(r, false);
3436
3437 final boolean hadApp = r.app != null;
3438
3439 if (hadApp) {
3440 if (removeFromApp) {
3441 int idx = r.app.activities.indexOf(r);
3442 if (idx >= 0) {
3443 r.app.activities.remove(idx);
3444 }
3445 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
3446 mService.mHeavyWeightProcess = null;
3447 mService.mHandler.sendEmptyMessage(
3448 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
3449 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003450 if (r.app.activities.size() == 0) {
3451 // No longer have activities, so update location in
3452 // LRU list.
3453 mService.updateLruProcessLocked(r.app, true, false);
3454 }
3455 }
3456
3457 boolean skipDestroy = false;
3458
3459 try {
3460 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
3461 r.app.thread.scheduleDestroyActivity(r, r.finishing,
3462 r.configChangeFlags);
3463 } catch (Exception e) {
3464 // We can just ignore exceptions here... if the process
3465 // has crashed, our death notification will clean things
3466 // up.
3467 //Slog.w(TAG, "Exception thrown during finish", e);
3468 if (r.finishing) {
3469 removeActivityFromHistoryLocked(r);
3470 removedFromHistory = true;
3471 skipDestroy = true;
3472 }
3473 }
3474
3475 r.app = null;
3476 r.nowVisible = false;
3477
3478 if (r.finishing && !skipDestroy) {
3479 r.state = ActivityState.DESTROYING;
3480 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
3481 msg.obj = r;
3482 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
3483 } else {
3484 r.state = ActivityState.DESTROYED;
3485 }
3486 } else {
3487 // remove this record from the history.
3488 if (r.finishing) {
3489 removeActivityFromHistoryLocked(r);
3490 removedFromHistory = true;
3491 } else {
3492 r.state = ActivityState.DESTROYED;
3493 }
3494 }
3495
3496 r.configChangeFlags = 0;
3497
3498 if (!mLRUActivities.remove(r) && hadApp) {
3499 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
3500 }
3501
3502 return removedFromHistory;
3503 }
3504
3505 final void activityDestroyed(IBinder token) {
3506 synchronized (mService) {
3507 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, token);
3508
3509 int index = indexOfTokenLocked(token);
3510 if (index >= 0) {
3511 ActivityRecord r = (ActivityRecord)mHistory.get(index);
3512 if (r.state == ActivityState.DESTROYING) {
3513 final long origId = Binder.clearCallingIdentity();
3514 removeActivityFromHistoryLocked(r);
3515 Binder.restoreCallingIdentity(origId);
3516 }
3517 }
3518 }
3519 }
3520
3521 private static void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
3522 int i = list.size();
3523 if (localLOGV) Slog.v(
3524 TAG, "Removing app " + app + " from list " + list
3525 + " with " + i + " entries");
3526 while (i > 0) {
3527 i--;
3528 ActivityRecord r = (ActivityRecord)list.get(i);
3529 if (localLOGV) Slog.v(
3530 TAG, "Record #" + i + " " + r + ": app=" + r.app);
3531 if (r.app == app) {
3532 if (localLOGV) Slog.v(TAG, "Removing this entry!");
3533 list.remove(i);
3534 }
3535 }
3536 }
3537
3538 void removeHistoryRecordsForAppLocked(ProcessRecord app) {
3539 removeHistoryRecordsForAppLocked(mLRUActivities, app);
3540 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003541 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003542 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
3543 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
3544 }
3545
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003546 /**
3547 * Move the current home activity's task (if one exists) to the front
3548 * of the stack.
3549 */
3550 final void moveHomeToFrontLocked() {
3551 TaskRecord homeTask = null;
3552 for (int i=mHistory.size()-1; i>=0; i--) {
3553 ActivityRecord hr = (ActivityRecord)mHistory.get(i);
3554 if (hr.isHomeActivity) {
3555 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003556 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003557 }
3558 }
3559 if (homeTask != null) {
3560 moveTaskToFrontLocked(homeTask, null);
3561 }
3562 }
3563
3564
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003565 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason) {
3566 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
3567
3568 final int task = tr.taskId;
3569 int top = mHistory.size()-1;
3570
3571 if (top < 0 || ((ActivityRecord)mHistory.get(top)).task.taskId == task) {
3572 // nothing to do!
3573 return;
3574 }
3575
3576 ArrayList moved = new ArrayList();
3577
3578 // Applying the affinities may have removed entries from the history,
3579 // so get the size again.
3580 top = mHistory.size()-1;
3581 int pos = top;
3582
3583 // Shift all activities with this task up to the top
3584 // of the stack, keeping them in the same internal order.
3585 while (pos >= 0) {
3586 ActivityRecord r = (ActivityRecord)mHistory.get(pos);
3587 if (localLOGV) Slog.v(
3588 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003589 if (r.task.taskId == task) {
3590 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
3591 mHistory.remove(pos);
3592 mHistory.add(top, r);
3593 moved.add(0, r);
3594 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003595 }
3596 pos--;
3597 }
3598
3599 if (DEBUG_TRANSITION) Slog.v(TAG,
3600 "Prepare to front transition: task=" + tr);
3601 if (reason != null &&
3602 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003603 mService.mWindowManager.prepareAppTransition(
3604 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003605 ActivityRecord r = topRunningActivityLocked(null);
3606 if (r != null) {
3607 mNoAnimActivities.add(r);
3608 }
3609 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003610 mService.mWindowManager.prepareAppTransition(
3611 WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003612 }
3613
3614 mService.mWindowManager.moveAppTokensToTop(moved);
3615 if (VALIDATE_TOKENS) {
3616 mService.mWindowManager.validateAppTokens(mHistory);
3617 }
3618
3619 finishTaskMoveLocked(task);
3620 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
3621 }
3622
3623 private final void finishTaskMoveLocked(int task) {
3624 resumeTopActivityLocked(null);
3625 }
3626
3627 /**
3628 * Worker method for rearranging history stack. Implements the function of moving all
3629 * activities for a specific task (gathering them if disjoint) into a single group at the
3630 * bottom of the stack.
3631 *
3632 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
3633 * to premeptively cancel the move.
3634 *
3635 * @param task The taskId to collect and move to the bottom.
3636 * @return Returns true if the move completed, false if not.
3637 */
3638 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
3639 Slog.i(TAG, "moveTaskToBack: " + task);
3640
3641 // If we have a watcher, preflight the move before committing to it. First check
3642 // for *other* available tasks, but if none are available, then try again allowing the
3643 // current task to be selected.
3644 if (mMainStack && mService.mController != null) {
3645 ActivityRecord next = topRunningActivityLocked(null, task);
3646 if (next == null) {
3647 next = topRunningActivityLocked(null, 0);
3648 }
3649 if (next != null) {
3650 // ask watcher if this is allowed
3651 boolean moveOK = true;
3652 try {
3653 moveOK = mService.mController.activityResuming(next.packageName);
3654 } catch (RemoteException e) {
3655 mService.mController = null;
3656 }
3657 if (!moveOK) {
3658 return false;
3659 }
3660 }
3661 }
3662
3663 ArrayList moved = new ArrayList();
3664
3665 if (DEBUG_TRANSITION) Slog.v(TAG,
3666 "Prepare to back transition: task=" + task);
3667
3668 final int N = mHistory.size();
3669 int bottom = 0;
3670 int pos = 0;
3671
3672 // Shift all activities with this task down to the bottom
3673 // of the stack, keeping them in the same internal order.
3674 while (pos < N) {
3675 ActivityRecord r = (ActivityRecord)mHistory.get(pos);
3676 if (localLOGV) Slog.v(
3677 TAG, "At " + pos + " ckp " + r.task + ": " + r);
3678 if (r.task.taskId == task) {
3679 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
3680 mHistory.remove(pos);
3681 mHistory.add(bottom, r);
3682 moved.add(r);
3683 bottom++;
3684 }
3685 pos++;
3686 }
3687
3688 if (reason != null &&
3689 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003690 mService.mWindowManager.prepareAppTransition(
3691 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003692 ActivityRecord r = topRunningActivityLocked(null);
3693 if (r != null) {
3694 mNoAnimActivities.add(r);
3695 }
3696 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003697 mService.mWindowManager.prepareAppTransition(
3698 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003699 }
3700 mService.mWindowManager.moveAppTokensToBottom(moved);
3701 if (VALIDATE_TOKENS) {
3702 mService.mWindowManager.validateAppTokens(mHistory);
3703 }
3704
3705 finishTaskMoveLocked(task);
3706 return true;
3707 }
3708
3709 private final void logStartActivity(int tag, ActivityRecord r,
3710 TaskRecord task) {
3711 EventLog.writeEvent(tag,
3712 System.identityHashCode(r), task.taskId,
3713 r.shortComponentName, r.intent.getAction(),
3714 r.intent.getType(), r.intent.getDataString(),
3715 r.intent.getFlags());
3716 }
3717
3718 /**
3719 * Make sure the given activity matches the current configuration. Returns
3720 * false if the activity had to be destroyed. Returns true if the
3721 * configuration is the same, or the activity will remain running as-is
3722 * for whatever reason. Ensures the HistoryRecord is updated with the
3723 * correct configuration and all other bookkeeping is handled.
3724 */
3725 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
3726 int globalChanges) {
3727 if (mConfigWillChange) {
3728 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3729 "Skipping config check (will change): " + r);
3730 return true;
3731 }
3732
3733 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3734 "Ensuring correct configuration: " + r);
3735
3736 // Short circuit: if the two configurations are the exact same
3737 // object (the common case), then there is nothing to do.
3738 Configuration newConfig = mService.mConfiguration;
3739 if (r.configuration == newConfig) {
3740 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3741 "Configuration unchanged in " + r);
3742 return true;
3743 }
3744
3745 // We don't worry about activities that are finishing.
3746 if (r.finishing) {
3747 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3748 "Configuration doesn't matter in finishing " + r);
3749 r.stopFreezingScreenLocked(false);
3750 return true;
3751 }
3752
3753 // Okay we now are going to make this activity have the new config.
3754 // But then we need to figure out how it needs to deal with that.
3755 Configuration oldConfig = r.configuration;
3756 r.configuration = newConfig;
3757
3758 // If the activity isn't currently running, just leave the new
3759 // configuration and it will pick that up next time it starts.
3760 if (r.app == null || r.app.thread == null) {
3761 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3762 "Configuration doesn't matter not running " + r);
3763 r.stopFreezingScreenLocked(false);
3764 return true;
3765 }
3766
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07003767 // Figure out what has changed between the two configurations.
3768 int changes = oldConfig.diff(newConfig);
3769 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
3770 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
3771 + Integer.toHexString(changes) + ", handles=0x"
3772 + Integer.toHexString(r.info.configChanges)
3773 + ", newConfig=" + newConfig);
3774 }
3775 if ((changes&(~r.info.configChanges)) != 0) {
3776 // Aha, the activity isn't handling the change, so DIE DIE DIE.
3777 r.configChangeFlags |= changes;
3778 r.startFreezingScreenLocked(r.app, globalChanges);
3779 if (r.app == null || r.app.thread == null) {
3780 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3781 "Switch is destroying non-running " + r);
3782 destroyActivityLocked(r, true);
3783 } else if (r.state == ActivityState.PAUSING) {
3784 // A little annoying: we are waiting for this activity to
3785 // finish pausing. Let's not do anything now, but just
3786 // flag that it needs to be restarted when done pausing.
3787 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3788 "Switch is skipping already pausing " + r);
3789 r.configDestroy = true;
3790 return true;
3791 } else if (r.state == ActivityState.RESUMED) {
3792 // Try to optimize this case: the configuration is changing
3793 // and we need to restart the top, resumed activity.
3794 // Instead of doing the normal handshaking, just say
3795 // "restart!".
3796 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3797 "Switch is restarting resumed " + r);
3798 relaunchActivityLocked(r, r.configChangeFlags, true);
3799 r.configChangeFlags = 0;
3800 } else {
3801 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3802 "Switch is restarting non-resumed " + r);
3803 relaunchActivityLocked(r, r.configChangeFlags, false);
3804 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003805 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07003806
3807 // All done... tell the caller we weren't able to keep this
3808 // activity around.
3809 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003810 }
3811
3812 // Default case: the activity can handle this new configuration, so
3813 // hand it over. Note that we don't need to give it the new
3814 // configuration, since we always send configuration changes to all
3815 // process when they happen so it can just use whatever configuration
3816 // it last got.
3817 if (r.app != null && r.app.thread != null) {
3818 try {
3819 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
3820 r.app.thread.scheduleActivityConfigurationChanged(r);
3821 } catch (RemoteException e) {
3822 // If process died, whatever.
3823 }
3824 }
3825 r.stopFreezingScreenLocked(false);
3826
3827 return true;
3828 }
3829
3830 private final boolean relaunchActivityLocked(ActivityRecord r,
3831 int changes, boolean andResume) {
3832 List<ResultInfo> results = null;
3833 List<Intent> newIntents = null;
3834 if (andResume) {
3835 results = r.results;
3836 newIntents = r.newIntents;
3837 }
3838 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
3839 + " with results=" + results + " newIntents=" + newIntents
3840 + " andResume=" + andResume);
3841 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
3842 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
3843 r.task.taskId, r.shortComponentName);
3844
3845 r.startFreezingScreenLocked(r.app, 0);
3846
3847 try {
3848 if (DEBUG_SWITCH) Slog.i(TAG, "Switch is restarting resumed " + r);
3849 r.app.thread.scheduleRelaunchActivity(r, results, newIntents,
3850 changes, !andResume, mService.mConfiguration);
3851 // Note: don't need to call pauseIfSleepingLocked() here, because
3852 // the caller will only pass in 'andResume' if this activity is
3853 // currently resumed, which implies we aren't sleeping.
3854 } catch (RemoteException e) {
3855 return false;
3856 }
3857
3858 if (andResume) {
3859 r.results = null;
3860 r.newIntents = null;
3861 if (mMainStack) {
3862 mService.reportResumedActivityLocked(r);
3863 }
3864 }
3865
3866 return true;
3867 }
3868}