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