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