blob: a01ed25bb703b0e069f70aeeeaba026c89dd7d18 [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;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070024import android.app.ActivityManager;
Dianne Hackborn7a2195c2012-03-19 17:38:00 -070025import android.app.ActivityOptions;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070026import android.app.AppGlobals;
27import android.app.IActivityManager;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070028import android.app.IThumbnailRetriever;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070029import android.app.IApplicationThread;
30import android.app.PendingIntent;
31import android.app.ResultInfo;
32import android.app.IActivityManager.WaitResult;
33import android.content.ComponentName;
34import android.content.Context;
35import android.content.IIntentSender;
36import android.content.Intent;
37import android.content.IntentSender;
38import android.content.pm.ActivityInfo;
39import android.content.pm.ApplicationInfo;
40import android.content.pm.PackageManager;
41import android.content.pm.ResolveInfo;
42import android.content.res.Configuration;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -080043import android.content.res.Resources;
44import android.graphics.Bitmap;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070045import android.net.Uri;
46import android.os.Binder;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070047import android.os.Bundle;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070048import android.os.Handler;
49import android.os.IBinder;
50import android.os.Message;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070051import android.os.ParcelFileDescriptor;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070052import android.os.PowerManager;
53import android.os.RemoteException;
54import android.os.SystemClock;
Amith Yamasani742a6712011-05-04 14:49:28 -070055import android.os.UserId;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070056import android.util.EventLog;
57import android.util.Log;
58import android.util.Slog;
59import android.view.WindowManagerPolicy;
60
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070061import java.io.IOException;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070062import java.lang.ref.WeakReference;
63import java.util.ArrayList;
64import java.util.Iterator;
65import java.util.List;
66
67/**
68 * State and management of a single stack of activities.
69 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070070final class ActivityStack {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070071 static final String TAG = ActivityManagerService.TAG;
Dianne Hackbornb961cd22011-06-21 12:13:37 -070072 static final boolean localLOGV = ActivityManagerService.localLOGV;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070073 static final boolean DEBUG_SWITCH = ActivityManagerService.DEBUG_SWITCH;
74 static final boolean DEBUG_PAUSE = ActivityManagerService.DEBUG_PAUSE;
75 static final boolean DEBUG_VISBILITY = ActivityManagerService.DEBUG_VISBILITY;
76 static final boolean DEBUG_USER_LEAVING = ActivityManagerService.DEBUG_USER_LEAVING;
77 static final boolean DEBUG_TRANSITION = ActivityManagerService.DEBUG_TRANSITION;
78 static final boolean DEBUG_RESULTS = ActivityManagerService.DEBUG_RESULTS;
79 static final boolean DEBUG_CONFIGURATION = ActivityManagerService.DEBUG_CONFIGURATION;
80 static final boolean DEBUG_TASKS = ActivityManagerService.DEBUG_TASKS;
81
Dianne Hackbornce86ba82011-07-13 19:33:41 -070082 static final boolean DEBUG_STATES = false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070083 static final boolean DEBUG_ADD_REMOVE = false;
84 static final boolean DEBUG_SAVED_STATE = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070085
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070086 static final boolean VALIDATE_TOKENS = ActivityManagerService.VALIDATE_TOKENS;
87
88 // How long we wait until giving up on the last activity telling us it
89 // is idle.
90 static final int IDLE_TIMEOUT = 10*1000;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -070091
92 // Ticks during which we check progress while waiting for an app to launch.
93 static final int LAUNCH_TICK = 500;
94
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070095 // How long we wait until giving up on the last activity to pause. This
96 // is short because it directly impacts the responsiveness of starting the
97 // next activity.
98 static final int PAUSE_TIMEOUT = 500;
99
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800100 // How long we can hold the sleep wake lock before giving up.
101 static final int SLEEP_TIMEOUT = 5*1000;
102
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700103 // How long we can hold the launch wake lock before giving up.
104 static final int LAUNCH_TIMEOUT = 10*1000;
105
106 // How long we wait until giving up on an activity telling us it has
107 // finished destroying itself.
108 static final int DESTROY_TIMEOUT = 10*1000;
109
110 // How long until we reset a task when the user returns to it. Currently
Dianne Hackborn621e17d2010-11-22 15:59:56 -0800111 // disabled.
112 static final long ACTIVITY_INACTIVE_RESET_TIME = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700113
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700114 // How long between activity launches that we consider safe to not warn
115 // the user about an unexpected activity being launched on top.
116 static final long START_WARN_TIME = 5*1000;
117
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700118 // Set to false to disable the preview that is shown while a new activity
119 // is being started.
120 static final boolean SHOW_APP_STARTING_PREVIEW = true;
121
122 enum ActivityState {
123 INITIALIZING,
124 RESUMED,
125 PAUSING,
126 PAUSED,
127 STOPPING,
128 STOPPED,
129 FINISHING,
130 DESTROYING,
131 DESTROYED
132 }
133
134 final ActivityManagerService mService;
135 final boolean mMainStack;
136
137 final Context mContext;
138
139 /**
140 * The back history of all previous (and possibly still
141 * running) activities. It contains HistoryRecord objects.
142 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700143 final ArrayList<ActivityRecord> mHistory = new ArrayList<ActivityRecord>();
Dianne Hackbornbe707852011-11-11 14:32:10 -0800144
145 /**
146 * Used for validating app tokens with window manager.
147 */
148 final ArrayList<IBinder> mValidateAppTokens = new ArrayList<IBinder>();
149
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700150 /**
151 * List of running activities, sorted by recent usage.
152 * The first entry in the list is the least recently used.
153 * It contains HistoryRecord objects.
154 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700155 final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700156
157 /**
158 * List of activities that are waiting for a new activity
159 * to become visible before completing whatever operation they are
160 * supposed to do.
161 */
162 final ArrayList<ActivityRecord> mWaitingVisibleActivities
163 = new ArrayList<ActivityRecord>();
164
165 /**
166 * List of activities that are ready to be stopped, but waiting
167 * for the next activity to settle down before doing so. It contains
168 * HistoryRecord objects.
169 */
170 final ArrayList<ActivityRecord> mStoppingActivities
171 = new ArrayList<ActivityRecord>();
172
173 /**
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800174 * List of activities that are in the process of going to sleep.
175 */
176 final ArrayList<ActivityRecord> mGoingToSleepActivities
177 = new ArrayList<ActivityRecord>();
178
179 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700180 * Animations that for the current transition have requested not to
181 * be considered for the transition animation.
182 */
183 final ArrayList<ActivityRecord> mNoAnimActivities
184 = new ArrayList<ActivityRecord>();
185
186 /**
187 * List of activities that are ready to be finished, but waiting
188 * for the previous activity to settle down before doing so. It contains
189 * HistoryRecord objects.
190 */
191 final ArrayList<ActivityRecord> mFinishingActivities
192 = new ArrayList<ActivityRecord>();
193
194 /**
195 * List of people waiting to find out about the next launched activity.
196 */
197 final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched
198 = new ArrayList<IActivityManager.WaitResult>();
199
200 /**
201 * List of people waiting to find out about the next visible activity.
202 */
203 final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible
204 = new ArrayList<IActivityManager.WaitResult>();
205
206 /**
207 * Set when the system is going to sleep, until we have
208 * successfully paused the current activity and released our wake lock.
209 * At that point the system is allowed to actually sleep.
210 */
211 final PowerManager.WakeLock mGoingToSleep;
212
213 /**
214 * We don't want to allow the device to go to sleep while in the process
215 * of launching an activity. This is primarily to allow alarm intent
216 * receivers to launch an activity and get that to run before the device
217 * goes back to sleep.
218 */
219 final PowerManager.WakeLock mLaunchingActivity;
220
221 /**
222 * When we are in the process of pausing an activity, before starting the
223 * next one, this variable holds the activity that is currently being paused.
224 */
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800225 ActivityRecord mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700226
227 /**
228 * This is the last activity that we put into the paused state. This is
229 * used to determine if we need to do an activity transition while sleeping,
230 * when we normally hold the top activity paused.
231 */
232 ActivityRecord mLastPausedActivity = null;
233
234 /**
235 * Current activity that is resumed, or null if there is none.
236 */
237 ActivityRecord mResumedActivity = null;
238
239 /**
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700240 * This is the last activity that has been started. It is only used to
241 * identify when multiple activities are started at once so that the user
242 * can be warned they may not be in the activity they think they are.
243 */
244 ActivityRecord mLastStartedActivity = null;
245
246 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700247 * Set when we know we are going to be calling updateConfiguration()
248 * soon, so want to skip intermediate config checks.
249 */
250 boolean mConfigWillChange;
251
252 /**
253 * Set to indicate whether to issue an onUserLeaving callback when a
254 * newly launched activity is being brought in front of us.
255 */
256 boolean mUserLeaving = false;
257
258 long mInitialStartTime = 0;
259
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800260 /**
261 * Set when we have taken too long waiting to go to sleep.
262 */
263 boolean mSleepTimeout = false;
264
Dianne Hackborn90c52de2011-09-23 12:57:44 -0700265 /**
266 * Dismiss the keyguard after the next activity is displayed?
267 */
268 boolean mDismissKeyguardOnNextActivity = false;
269
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800270 int mThumbnailWidth = -1;
271 int mThumbnailHeight = -1;
272
Amith Yamasani742a6712011-05-04 14:49:28 -0700273 private int mCurrentUser;
274
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800275 static final int SLEEP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG;
276 static final int PAUSE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 1;
277 static final int IDLE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 2;
278 static final int IDLE_NOW_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 3;
279 static final int LAUNCH_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 4;
280 static final int DESTROY_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 5;
281 static final int RESUME_TOP_ACTIVITY_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 6;
Dianne Hackborn29ba7e62012-03-16 15:03:36 -0700282 static final int LAUNCH_TICK_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 7;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700283
284 final Handler mHandler = new Handler() {
285 //public Handler() {
286 // if (localLOGV) Slog.v(TAG, "Handler started!");
287 //}
288
289 public void handleMessage(Message msg) {
290 switch (msg.what) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800291 case SLEEP_TIMEOUT_MSG: {
Dianne Hackborn8e8d65f2011-08-11 19:36:18 -0700292 synchronized (mService) {
293 if (mService.isSleeping()) {
294 Slog.w(TAG, "Sleep timeout! Sleeping now.");
295 mSleepTimeout = true;
296 checkReadyForSleepLocked();
297 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800298 }
299 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700300 case PAUSE_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800301 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700302 // We don't at this point know if the activity is fullscreen,
303 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800304 Slog.w(TAG, "Activity pause timeout for " + r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700305 synchronized (mService) {
306 if (r.app != null) {
307 mService.logAppTooSlow(r.app, r.pauseTime,
308 "pausing " + r);
309 }
310 }
311
Dianne Hackbornbe707852011-11-11 14:32:10 -0800312 activityPaused(r != null ? r.appToken : null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700313 } break;
314 case IDLE_TIMEOUT_MSG: {
315 if (mService.mDidDexOpt) {
316 mService.mDidDexOpt = false;
317 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
318 nmsg.obj = msg.obj;
319 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
320 return;
321 }
322 // We don't at this point know if the activity is fullscreen,
323 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800324 ActivityRecord r = (ActivityRecord)msg.obj;
325 Slog.w(TAG, "Activity idle timeout for " + r);
326 activityIdleInternal(r != null ? r.appToken : null, true, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700327 } break;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700328 case LAUNCH_TICK_MSG: {
329 ActivityRecord r = (ActivityRecord)msg.obj;
330 synchronized (mService) {
331 if (r.continueLaunchTickingLocked()) {
332 mService.logAppTooSlow(r.app, r.launchTickTime,
333 "launching " + r);
334 }
335 }
336 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700337 case DESTROY_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800338 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700339 // We don't at this point know if the activity is fullscreen,
340 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800341 Slog.w(TAG, "Activity destroy timeout for " + r);
342 activityDestroyed(r != null ? r.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700343 } break;
344 case IDLE_NOW_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800345 ActivityRecord r = (ActivityRecord)msg.obj;
346 activityIdleInternal(r != null ? r.appToken : null, false, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700347 } break;
348 case LAUNCH_TIMEOUT_MSG: {
349 if (mService.mDidDexOpt) {
350 mService.mDidDexOpt = false;
351 Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
352 mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
353 return;
354 }
355 synchronized (mService) {
356 if (mLaunchingActivity.isHeld()) {
357 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
358 mLaunchingActivity.release();
359 }
360 }
361 } break;
362 case RESUME_TOP_ACTIVITY_MSG: {
363 synchronized (mService) {
364 resumeTopActivityLocked(null);
365 }
366 } break;
367 }
368 }
369 };
370
371 ActivityStack(ActivityManagerService service, Context context, boolean mainStack) {
372 mService = service;
373 mContext = context;
374 mMainStack = mainStack;
375 PowerManager pm =
376 (PowerManager)context.getSystemService(Context.POWER_SERVICE);
377 mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
378 mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
379 mLaunchingActivity.setReferenceCounted(false);
380 }
381
382 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700383 // TODO: Don't look for any tasks from other users
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700384 int i = mHistory.size()-1;
385 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700386 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700387 if (!r.finishing && r != notTop) {
388 return r;
389 }
390 i--;
391 }
392 return null;
393 }
394
395 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700396 // TODO: Don't look for any tasks from other users
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700397 int i = mHistory.size()-1;
398 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700399 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700400 if (!r.finishing && !r.delayedResume && r != notTop) {
401 return r;
402 }
403 i--;
404 }
405 return null;
406 }
407
408 /**
409 * This is a simplified version of topRunningActivityLocked that provides a number of
410 * optional skip-over modes. It is intended for use with the ActivityController hook only.
411 *
412 * @param token If non-null, any history records matching this token will be skipped.
413 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
414 *
415 * @return Returns the HistoryRecord of the next activity on the stack.
416 */
417 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700418 // TODO: Don't look for any tasks from other users
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700419 int i = mHistory.size()-1;
420 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700421 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700422 // Note: the taskId check depends on real taskId fields being non-zero
Dianne Hackbornbe707852011-11-11 14:32:10 -0800423 if (!r.finishing && (token != r.appToken) && (taskId != r.task.taskId)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700424 return r;
425 }
426 i--;
427 }
428 return null;
429 }
430
431 final int indexOfTokenLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800432 return mHistory.indexOf(ActivityRecord.forToken(token));
433 }
434
435 final int indexOfActivityLocked(ActivityRecord r) {
436 return mHistory.indexOf(r);
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700437 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700438
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700439 final ActivityRecord isInStackLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800440 ActivityRecord r = ActivityRecord.forToken(token);
441 if (mHistory.contains(r)) {
442 return r;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700443 }
444 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700445 }
446
447 private final boolean updateLRUListLocked(ActivityRecord r) {
448 final boolean hadit = mLRUActivities.remove(r);
449 mLRUActivities.add(r);
450 return hadit;
451 }
452
453 /**
454 * Returns the top activity in any existing task matching the given
455 * Intent. Returns null if no such task is found.
456 */
457 private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
458 ComponentName cls = intent.getComponent();
459 if (info.targetActivity != null) {
460 cls = new ComponentName(info.packageName, info.targetActivity);
461 }
462
463 TaskRecord cp = null;
464
Amith Yamasani742a6712011-05-04 14:49:28 -0700465 final int userId = UserId.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700466 final int N = mHistory.size();
467 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700468 ActivityRecord r = mHistory.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -0700469 if (!r.finishing && r.task != cp && r.userId == userId
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700470 && r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
471 cp = r.task;
472 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
473 // + "/aff=" + r.task.affinity + " to new cls="
474 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
475 if (r.task.affinity != null) {
476 if (r.task.affinity.equals(info.taskAffinity)) {
477 //Slog.i(TAG, "Found matching affinity!");
478 return r;
479 }
480 } else if (r.task.intent != null
481 && r.task.intent.getComponent().equals(cls)) {
482 //Slog.i(TAG, "Found matching class!");
483 //dump();
484 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
485 return r;
486 } else if (r.task.affinityIntent != null
487 && r.task.affinityIntent.getComponent().equals(cls)) {
488 //Slog.i(TAG, "Found matching class!");
489 //dump();
490 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
491 return r;
492 }
493 }
494 }
495
496 return null;
497 }
498
499 /**
500 * Returns the first activity (starting from the top of the stack) that
501 * is the same as the given activity. Returns null if no such activity
502 * is found.
503 */
504 private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
505 ComponentName cls = intent.getComponent();
506 if (info.targetActivity != null) {
507 cls = new ComponentName(info.packageName, info.targetActivity);
508 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700509 final int userId = UserId.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700510
511 final int N = mHistory.size();
512 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700513 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700514 if (!r.finishing) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700515 if (r.intent.getComponent().equals(cls) && r.userId == userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700516 //Slog.i(TAG, "Found matching class!");
517 //dump();
518 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
519 return r;
520 }
521 }
522 }
523
524 return null;
525 }
526
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700527 final void showAskCompatModeDialogLocked(ActivityRecord r) {
528 Message msg = Message.obtain();
529 msg.what = ActivityManagerService.SHOW_COMPAT_MODE_DIALOG_MSG;
530 msg.obj = r.task.askedCompatMode ? null : r;
531 mService.mHandler.sendMessage(msg);
532 }
533
Amith Yamasani742a6712011-05-04 14:49:28 -0700534 /*
535 * Move the activities around in the stack to bring a user to the foreground.
536 * @return whether there are any activities for the specified user.
537 */
538 final boolean switchUser(int userId) {
539 synchronized (mService) {
540 mCurrentUser = userId;
541
542 // Only one activity? Nothing to do...
543 if (mHistory.size() < 2)
544 return false;
545
546 boolean haveActivities = false;
547 // Check if the top activity is from the new user.
548 ActivityRecord top = mHistory.get(mHistory.size() - 1);
549 if (top.userId == userId) return true;
550 // Otherwise, move the user's activities to the top.
551 int N = mHistory.size();
552 int i = 0;
553 while (i < N) {
554 ActivityRecord r = mHistory.get(i);
555 if (r.userId == userId) {
556 ActivityRecord moveToTop = mHistory.remove(i);
557 mHistory.add(moveToTop);
558 // No need to check the top one now
559 N--;
560 haveActivities = true;
561 } else {
562 i++;
563 }
564 }
565 // Transition from the old top to the new top
566 resumeTopActivityLocked(top);
567 return haveActivities;
568 }
569 }
570
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700571 final boolean realStartActivityLocked(ActivityRecord r,
572 ProcessRecord app, boolean andResume, boolean checkConfig)
573 throws RemoteException {
574
575 r.startFreezingScreenLocked(app, 0);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800576 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700577
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700578 // schedule launch ticks to collect information about slow apps.
579 r.startLaunchTickingLocked();
580
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700581 // Have the window manager re-evaluate the orientation of
582 // the screen based on the new activity order. Note that
583 // as a result of this, it can call back into the activity
584 // manager with a new orientation. We don't care about that,
585 // because the activity is not currently running so we are
586 // just restarting it anyway.
587 if (checkConfig) {
588 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
589 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -0800590 r.mayFreezeScreenLocked(app) ? r.appToken : null);
Dianne Hackborn813075a62011-11-14 17:45:19 -0800591 mService.updateConfigurationLocked(config, r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700592 }
593
594 r.app = app;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700595 app.waitingToKill = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700596
597 if (localLOGV) Slog.v(TAG, "Launching: " + r);
598
599 int idx = app.activities.indexOf(r);
600 if (idx < 0) {
601 app.activities.add(r);
602 }
603 mService.updateLruProcessLocked(app, true, true);
604
605 try {
606 if (app.thread == null) {
607 throw new RemoteException();
608 }
609 List<ResultInfo> results = null;
610 List<Intent> newIntents = null;
611 if (andResume) {
612 results = r.results;
613 newIntents = r.newIntents;
614 }
615 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
616 + " icicle=" + r.icicle
617 + " with results=" + results + " newIntents=" + newIntents
618 + " andResume=" + andResume);
619 if (andResume) {
620 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
621 System.identityHashCode(r),
622 r.task.taskId, r.shortComponentName);
623 }
624 if (r.isHomeActivity) {
625 mService.mHomeProcess = app;
626 }
627 mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800628 r.sleeping = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400629 r.forceNewConfig = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700630 showAskCompatModeDialogLocked(r);
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700631 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700632 String profileFile = null;
633 ParcelFileDescriptor profileFd = null;
634 boolean profileAutoStop = false;
635 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
636 if (mService.mProfileProc == null || mService.mProfileProc == app) {
637 mService.mProfileProc = app;
638 profileFile = mService.mProfileFile;
639 profileFd = mService.mProfileFd;
640 profileAutoStop = mService.mAutoStopProfiler;
641 }
642 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -0700643 app.hasShownUi = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700644 app.pendingUiClean = true;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700645 if (profileFd != null) {
646 try {
647 profileFd = profileFd.dup();
648 } catch (IOException e) {
649 profileFd = null;
650 }
651 }
Dianne Hackbornbe707852011-11-11 14:32:10 -0800652 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
Dianne Hackborn813075a62011-11-14 17:45:19 -0800653 System.identityHashCode(r), r.info,
654 new Configuration(mService.mConfiguration),
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700655 r.compat, r.icicle, results, newIntents, !andResume,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700656 mService.isNextTransitionForward(), profileFile, profileFd,
657 profileAutoStop);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700658
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700659 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700660 // This may be a heavy-weight process! Note that the package
661 // manager will ensure that only activity can run in the main
662 // process of the .apk, which is the only thing that will be
663 // considered heavy-weight.
664 if (app.processName.equals(app.info.packageName)) {
665 if (mService.mHeavyWeightProcess != null
666 && mService.mHeavyWeightProcess != app) {
667 Log.w(TAG, "Starting new heavy weight process " + app
668 + " when already running "
669 + mService.mHeavyWeightProcess);
670 }
671 mService.mHeavyWeightProcess = app;
672 Message msg = mService.mHandler.obtainMessage(
673 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
674 msg.obj = r;
675 mService.mHandler.sendMessage(msg);
676 }
677 }
678
679 } catch (RemoteException e) {
680 if (r.launchFailed) {
681 // This is the second time we failed -- finish activity
682 // and give up.
683 Slog.e(TAG, "Second failure launching "
684 + r.intent.getComponent().flattenToShortString()
685 + ", giving up", e);
686 mService.appDiedLocked(app, app.pid, app.thread);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800687 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700688 "2nd-crash");
689 return false;
690 }
691
692 // This is the first time we failed -- restart process and
693 // retry.
694 app.activities.remove(r);
695 throw e;
696 }
697
698 r.launchFailed = false;
699 if (updateLRUListLocked(r)) {
700 Slog.w(TAG, "Activity " + r
701 + " being launched, but already in LRU list");
702 }
703
704 if (andResume) {
705 // As part of the process of launching, ActivityThread also performs
706 // a resume.
707 r.state = ActivityState.RESUMED;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700708 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
709 + " (starting new instance)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700710 r.stopped = false;
711 mResumedActivity = r;
712 r.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -0800713 if (mMainStack) {
714 mService.addRecentTaskLocked(r.task);
715 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700716 completeResumeLocked(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800717 checkReadyForSleepLocked();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700718 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Launch completed; removing icicle of " + r.icicle);
719 r.icicle = null;
720 r.haveState = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700721 } else {
722 // This activity is not starting in the resumed state... which
723 // should look like we asked it to pause+stop (but remain visible),
724 // and it has done so and reported back the current icicle and
725 // other state.
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700726 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
727 + " (starting in stopped state)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700728 r.state = ActivityState.STOPPED;
729 r.stopped = true;
730 }
731
732 // Launch the new version setup screen if needed. We do this -after-
733 // launching the initial activity (that is, home), so that it can have
734 // a chance to initialize itself while in the background, making the
735 // switch back to it faster and look better.
736 if (mMainStack) {
737 mService.startSetupActivityLocked();
738 }
739
740 return true;
741 }
742
743 private final void startSpecificActivityLocked(ActivityRecord r,
744 boolean andResume, boolean checkConfig) {
745 // Is this activity's application already running?
746 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
747 r.info.applicationInfo.uid);
748
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700749 if (r.launchTime == 0) {
750 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700751 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700752 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700753 }
754 } else if (mInitialStartTime == 0) {
755 mInitialStartTime = SystemClock.uptimeMillis();
756 }
757
758 if (app != null && app.thread != null) {
759 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700760 app.addPackage(r.info.packageName);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700761 realStartActivityLocked(r, app, andResume, checkConfig);
762 return;
763 } catch (RemoteException e) {
764 Slog.w(TAG, "Exception when starting activity "
765 + r.intent.getComponent().flattenToShortString(), e);
766 }
767
768 // If a dead object exception was thrown -- fall through to
769 // restart the application.
770 }
771
772 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800773 "activity", r.intent.getComponent(), false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700774 }
775
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800776 void stopIfSleepingLocked() {
777 if (mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700778 if (!mGoingToSleep.isHeld()) {
779 mGoingToSleep.acquire();
780 if (mLaunchingActivity.isHeld()) {
781 mLaunchingActivity.release();
782 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
783 }
784 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800785 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
786 Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
787 mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
788 checkReadyForSleepLocked();
789 }
790 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700791
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800792 void awakeFromSleepingLocked() {
793 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
794 mSleepTimeout = false;
795 if (mGoingToSleep.isHeld()) {
796 mGoingToSleep.release();
797 }
798 // Ensure activities are no longer sleeping.
799 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700800 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800801 r.setSleeping(false);
802 }
803 mGoingToSleepActivities.clear();
804 }
805
806 void activitySleptLocked(ActivityRecord r) {
807 mGoingToSleepActivities.remove(r);
808 checkReadyForSleepLocked();
809 }
810
811 void checkReadyForSleepLocked() {
812 if (!mService.isSleeping()) {
813 // Do not care.
814 return;
815 }
816
817 if (!mSleepTimeout) {
818 if (mResumedActivity != null) {
819 // Still have something resumed; can't sleep until it is paused.
820 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700821 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
822 startPausingLocked(false, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800823 return;
824 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800825 if (mPausingActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800826 // Still waiting for something to pause; can't sleep yet.
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800827 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800828 return;
829 }
830
831 if (mStoppingActivities.size() > 0) {
832 // Still need to tell some activities to stop; can't sleep yet.
833 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
834 + mStoppingActivities.size() + " activities");
Dianne Hackborn80a7ac12011-09-22 18:32:52 -0700835 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800836 return;
837 }
838
839 ensureActivitiesVisibleLocked(null, 0);
840
841 // Make sure any stopped but visible activities are now sleeping.
842 // This ensures that the activity's onStop() is called.
843 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700844 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800845 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
846 r.setSleeping(true);
847 }
848 }
849
850 if (mGoingToSleepActivities.size() > 0) {
851 // Still need to tell some activities to sleep; can't sleep yet.
852 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
853 + mGoingToSleepActivities.size() + " activities");
854 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700855 }
856 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800857
858 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
859
860 if (mGoingToSleep.isHeld()) {
861 mGoingToSleep.release();
862 }
863 if (mService.mShuttingDown) {
864 mService.notifyAll();
865 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700866 }
867
Dianne Hackbornd2835932010-12-13 16:28:46 -0800868 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -0800869 if (who.noDisplay) {
870 return null;
871 }
872
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800873 Resources res = mService.mContext.getResources();
874 int w = mThumbnailWidth;
875 int h = mThumbnailHeight;
876 if (w < 0) {
877 mThumbnailWidth = w =
878 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
879 mThumbnailHeight = h =
880 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
881 }
882
883 if (w > 0) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800884 return mService.mWindowManager.screenshotApplications(who.appToken, w, h);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800885 }
886 return null;
887 }
888
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700889 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800890 if (mPausingActivity != null) {
891 RuntimeException e = new RuntimeException();
892 Slog.e(TAG, "Trying to pause when pause is already pending for "
893 + mPausingActivity, e);
894 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700895 ActivityRecord prev = mResumedActivity;
896 if (prev == null) {
897 RuntimeException e = new RuntimeException();
898 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
899 resumeTopActivityLocked(null);
900 return;
901 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700902 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
903 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700904 mResumedActivity = null;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800905 mPausingActivity = prev;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700906 mLastPausedActivity = prev;
907 prev.state = ActivityState.PAUSING;
908 prev.task.touchActiveTime();
Dianne Hackbornf26fd992011-04-08 18:14:09 -0700909 prev.updateThumbnail(screenshotActivities(prev), null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700910
911 mService.updateCpuStats();
912
913 if (prev.app != null && prev.app.thread != null) {
914 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
915 try {
916 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
917 System.identityHashCode(prev),
918 prev.shortComponentName);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800919 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
920 userLeaving, prev.configChangeFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700921 if (mMainStack) {
922 mService.updateUsageStats(prev, false);
923 }
924 } catch (Exception e) {
925 // Ignore exception, if process died other code will cleanup.
926 Slog.w(TAG, "Exception thrown during pause", e);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800927 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700928 mLastPausedActivity = null;
929 }
930 } else {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800931 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700932 mLastPausedActivity = null;
933 }
934
935 // If we are not going to sleep, we want to ensure the device is
936 // awake until the next activity is started.
937 if (!mService.mSleeping && !mService.mShuttingDown) {
938 mLaunchingActivity.acquire();
939 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
940 // To be safe, don't allow the wake lock to be held for too long.
941 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
942 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
943 }
944 }
945
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800946
947 if (mPausingActivity != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700948 // Have the window manager pause its key dispatching until the new
949 // activity has started. If we're pausing the activity just because
950 // the screen is being turned off and the UI is sleeping, don't interrupt
951 // key dispatch; the same activity will pick it up again on wakeup.
952 if (!uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800953 prev.pauseKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700954 } else {
955 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
956 }
957
958 // Schedule a pause timeout in case the app doesn't respond.
959 // We don't give it much time because this directly impacts the
960 // responsiveness seen by the user.
961 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
962 msg.obj = prev;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700963 prev.pauseTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700964 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
965 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
966 } else {
967 // This activity failed to schedule the
968 // pause, so just treat it as being paused now.
969 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800970 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700971 }
972 }
973
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800974 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700975 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800976 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700977
978 ActivityRecord r = null;
979
980 synchronized (mService) {
981 int index = indexOfTokenLocked(token);
982 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700983 r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700984 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800985 if (mPausingActivity == r) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700986 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
987 + (timeout ? " (due to timeout)" : " (pause complete)"));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700988 r.state = ActivityState.PAUSED;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800989 completePauseLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700990 } else {
991 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
992 System.identityHashCode(r), r.shortComponentName,
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800993 mPausingActivity != null
994 ? mPausingActivity.shortComponentName : "(none)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700995 }
996 }
997 }
998 }
999
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001000 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
1001 CharSequence description) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001002 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Saving icicle of " + r + ": " + icicle);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001003 r.icicle = icicle;
1004 r.haveState = true;
1005 r.updateThumbnail(thumbnail, description);
1006 r.stopped = true;
1007 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
1008 r.state = ActivityState.STOPPED;
1009 if (!r.finishing) {
1010 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07001011 destroyActivityLocked(r, true, false, "stop-config");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001012 resumeTopActivityLocked(null);
Dianne Hackborn50685602011-12-01 12:23:37 -08001013 } else {
1014 // Now that this process has stopped, we may want to consider
1015 // it to be the previous app to try to keep around in case
1016 // the user wants to return to it.
1017 ProcessRecord fgApp = null;
1018 if (mResumedActivity != null) {
1019 fgApp = mResumedActivity.app;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001020 } else if (mPausingActivity != null) {
1021 fgApp = mPausingActivity.app;
Dianne Hackborn50685602011-12-01 12:23:37 -08001022 }
1023 if (r.app != null && fgApp != null && r.app != fgApp
1024 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
1025 && r.app != mService.mHomeProcess) {
1026 mService.mPreviousProcess = r.app;
1027 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
1028 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001029 }
1030 }
1031 }
1032
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001033 private final void completePauseLocked() {
1034 ActivityRecord prev = mPausingActivity;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001035 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
1036
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001037 if (prev != null) {
1038 if (prev.finishing) {
1039 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
1040 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE);
1041 } else if (prev.app != null) {
1042 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
1043 if (prev.waitingVisible) {
1044 prev.waitingVisible = false;
1045 mWaitingVisibleActivities.remove(prev);
1046 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
1047 TAG, "Complete pause, no longer waiting: " + prev);
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001048 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001049 if (prev.configDestroy) {
1050 // The previous is being paused because the configuration
1051 // is changing, which means it is actually stopping...
1052 // To juggle the fact that we are also starting a new
1053 // instance right now, we need to first completely stop
1054 // the current instance before starting the new one.
1055 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
1056 destroyActivityLocked(prev, true, false, "pause-config");
1057 } else {
1058 mStoppingActivities.add(prev);
1059 if (mStoppingActivities.size() > 3) {
1060 // If we already have a few activities waiting to stop,
1061 // then give up on things going idle and start clearing
1062 // them out.
1063 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
1064 scheduleIdleLocked();
1065 } else {
1066 checkReadyForSleepLocked();
1067 }
1068 }
1069 } else {
1070 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
1071 prev = null;
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001072 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001073 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001074 }
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001075
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001076 if (!mService.isSleeping()) {
1077 resumeTopActivityLocked(prev);
1078 } else {
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001079 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001080 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001081
1082 if (prev != null) {
1083 prev.resumeKeyDispatchingLocked();
1084 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001085
1086 if (prev.app != null && prev.cpuTimeAtResume > 0
1087 && mService.mBatteryStatsService.isOnBattery()) {
1088 long diff = 0;
1089 synchronized (mService.mProcessStatsThread) {
1090 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
1091 - prev.cpuTimeAtResume;
1092 }
1093 if (diff > 0) {
1094 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
1095 synchronized (bsi) {
1096 BatteryStatsImpl.Uid.Proc ps =
1097 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
1098 prev.info.packageName);
1099 if (ps != null) {
1100 ps.addForegroundTimeLocked(diff);
1101 }
1102 }
1103 }
1104 }
1105 prev.cpuTimeAtResume = 0; // reset it
1106 }
1107
1108 /**
1109 * Once we know that we have asked an application to put an activity in
1110 * the resumed state (either by launching it or explicitly telling it),
1111 * this function updates the rest of our state to match that fact.
1112 */
1113 private final void completeResumeLocked(ActivityRecord next) {
1114 next.idle = false;
1115 next.results = null;
1116 next.newIntents = null;
1117
1118 // schedule an idle timeout in case the app doesn't do it for us.
1119 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1120 msg.obj = next;
1121 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
1122
1123 if (false) {
1124 // The activity was never told to pause, so just keep
1125 // things going as-is. To maintain our own state,
1126 // we need to emulate it coming back and saying it is
1127 // idle.
1128 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
1129 msg.obj = next;
1130 mHandler.sendMessage(msg);
1131 }
1132
1133 if (mMainStack) {
1134 mService.reportResumedActivityLocked(next);
1135 }
1136
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001137 next.clearThumbnail();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001138 if (mMainStack) {
1139 mService.setFocusedActivityLocked(next);
1140 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001141 next.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001142 ensureActivitiesVisibleLocked(null, 0);
1143 mService.mWindowManager.executeAppTransition();
1144 mNoAnimActivities.clear();
1145
1146 // Mark the point when the activity is resuming
1147 // TODO: To be more accurate, the mark should be before the onCreate,
1148 // not after the onResume. But for subsequent starts, onResume is fine.
1149 if (next.app != null) {
1150 synchronized (mService.mProcessStatsThread) {
1151 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1152 }
1153 } else {
1154 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1155 }
1156 }
1157
1158 /**
1159 * Make sure that all activities that need to be visible (that is, they
1160 * currently can be seen by the user) actually are.
1161 */
1162 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1163 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1164 if (DEBUG_VISBILITY) Slog.v(
1165 TAG, "ensureActivitiesVisible behind " + top
1166 + " configChanges=0x" + Integer.toHexString(configChanges));
1167
1168 // If the top activity is not fullscreen, then we need to
1169 // make sure any activities under it are now visible.
1170 final int count = mHistory.size();
1171 int i = count-1;
1172 while (mHistory.get(i) != top) {
1173 i--;
1174 }
1175 ActivityRecord r;
1176 boolean behindFullscreen = false;
1177 for (; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001178 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001179 if (DEBUG_VISBILITY) Slog.v(
1180 TAG, "Make visible? " + r + " finishing=" + r.finishing
1181 + " state=" + r.state);
1182 if (r.finishing) {
1183 continue;
1184 }
1185
1186 final boolean doThisProcess = onlyThisProcess == null
1187 || onlyThisProcess.equals(r.processName);
1188
1189 // First: if this is not the current activity being started, make
1190 // sure it matches the current configuration.
1191 if (r != starting && doThisProcess) {
1192 ensureActivityConfigurationLocked(r, 0);
1193 }
1194
1195 if (r.app == null || r.app.thread == null) {
1196 if (onlyThisProcess == null
1197 || onlyThisProcess.equals(r.processName)) {
1198 // This activity needs to be visible, but isn't even
1199 // running... get it started, but don't resume it
1200 // at this point.
1201 if (DEBUG_VISBILITY) Slog.v(
1202 TAG, "Start and freeze screen for " + r);
1203 if (r != starting) {
1204 r.startFreezingScreenLocked(r.app, configChanges);
1205 }
1206 if (!r.visible) {
1207 if (DEBUG_VISBILITY) Slog.v(
1208 TAG, "Starting and making visible: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001209 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001210 }
1211 if (r != starting) {
1212 startSpecificActivityLocked(r, false, false);
1213 }
1214 }
1215
1216 } else if (r.visible) {
1217 // If this activity is already visible, then there is nothing
1218 // else to do here.
1219 if (DEBUG_VISBILITY) Slog.v(
1220 TAG, "Skipping: already visible at " + r);
1221 r.stopFreezingScreenLocked(false);
1222
1223 } else if (onlyThisProcess == null) {
1224 // This activity is not currently visible, but is running.
1225 // Tell it to become visible.
1226 r.visible = true;
1227 if (r.state != ActivityState.RESUMED && r != starting) {
1228 // If this activity is paused, tell it
1229 // to now show its window.
1230 if (DEBUG_VISBILITY) Slog.v(
1231 TAG, "Making visible and scheduling visibility: " + r);
1232 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001233 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001234 r.sleeping = false;
Dianne Hackborn905577f2011-09-07 18:31:28 -07001235 r.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001236 r.app.thread.scheduleWindowVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001237 r.stopFreezingScreenLocked(false);
1238 } catch (Exception e) {
1239 // Just skip on any failure; we'll make it
1240 // visible when it next restarts.
1241 Slog.w(TAG, "Exception thrown making visibile: "
1242 + r.intent.getComponent(), e);
1243 }
1244 }
1245 }
1246
1247 // Aggregate current change flags.
1248 configChanges |= r.configChangeFlags;
1249
1250 if (r.fullscreen) {
1251 // At this point, nothing else needs to be shown
1252 if (DEBUG_VISBILITY) Slog.v(
1253 TAG, "Stopping: fullscreen at " + r);
1254 behindFullscreen = true;
1255 i--;
1256 break;
1257 }
1258 }
1259
1260 // Now for any activities that aren't visible to the user, make
1261 // sure they no longer are keeping the screen frozen.
1262 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001263 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001264 if (DEBUG_VISBILITY) Slog.v(
1265 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1266 + " state=" + r.state
1267 + " behindFullscreen=" + behindFullscreen);
1268 if (!r.finishing) {
1269 if (behindFullscreen) {
1270 if (r.visible) {
1271 if (DEBUG_VISBILITY) Slog.v(
1272 TAG, "Making invisible: " + r);
1273 r.visible = false;
1274 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001275 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001276 if ((r.state == ActivityState.STOPPING
1277 || r.state == ActivityState.STOPPED)
1278 && r.app != null && r.app.thread != null) {
1279 if (DEBUG_VISBILITY) Slog.v(
1280 TAG, "Scheduling invisibility: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001281 r.app.thread.scheduleWindowVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001282 }
1283 } catch (Exception e) {
1284 // Just skip on any failure; we'll make it
1285 // visible when it next restarts.
1286 Slog.w(TAG, "Exception thrown making hidden: "
1287 + r.intent.getComponent(), e);
1288 }
1289 } else {
1290 if (DEBUG_VISBILITY) Slog.v(
1291 TAG, "Already invisible: " + r);
1292 }
1293 } else if (r.fullscreen) {
1294 if (DEBUG_VISBILITY) Slog.v(
1295 TAG, "Now behindFullscreen: " + r);
1296 behindFullscreen = true;
1297 }
1298 }
1299 i--;
1300 }
1301 }
1302
1303 /**
1304 * Version of ensureActivitiesVisible that can easily be called anywhere.
1305 */
1306 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1307 int configChanges) {
1308 ActivityRecord r = topRunningActivityLocked(null);
1309 if (r != null) {
1310 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1311 }
1312 }
1313
1314 /**
1315 * Ensure that the top activity in the stack is resumed.
1316 *
1317 * @param prev The previously resumed activity, for when in the process
1318 * of pausing; can be null to call from elsewhere.
1319 *
1320 * @return Returns true if something is being resumed, or false if
1321 * nothing happened.
1322 */
1323 final boolean resumeTopActivityLocked(ActivityRecord prev) {
1324 // Find the first activity that is not finishing.
1325 ActivityRecord next = topRunningActivityLocked(null);
1326
1327 // Remember how we'll process this pause/resume situation, and ensure
1328 // that the state is reset however we wind up proceeding.
1329 final boolean userLeaving = mUserLeaving;
1330 mUserLeaving = false;
1331
1332 if (next == null) {
1333 // There are no more activities! Let's just start up the
1334 // Launcher...
1335 if (mMainStack) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001336 return mService.startHomeActivityLocked(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001337 }
1338 }
1339
1340 next.delayedResume = false;
1341
1342 // If the top activity is the resumed one, nothing to do.
1343 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1344 // Make sure we have executed any pending transitions, since there
1345 // should be nothing left to do at this point.
1346 mService.mWindowManager.executeAppTransition();
1347 mNoAnimActivities.clear();
1348 return false;
1349 }
1350
1351 // If we are sleeping, and there is no resumed activity, and the top
1352 // activity is paused, well that is the state we want.
1353 if ((mService.mSleeping || mService.mShuttingDown)
1354 && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
1355 // Make sure we have executed any pending transitions, since there
1356 // should be nothing left to do at this point.
1357 mService.mWindowManager.executeAppTransition();
1358 mNoAnimActivities.clear();
1359 return false;
1360 }
1361
1362 // The activity may be waiting for stop, but that is no longer
1363 // appropriate for it.
1364 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001365 mGoingToSleepActivities.remove(next);
1366 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001367 mWaitingVisibleActivities.remove(next);
1368
1369 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1370
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001371 // If we are currently pausing an activity, then don't do anything
1372 // until that is done.
1373 if (mPausingActivity != null) {
1374 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
1375 return false;
1376 }
1377
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001378 // Okay we are now going to start a switch, to 'next'. We may first
1379 // have to pause the current activity, but this is an important point
1380 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001381 // XXX "App Redirected" dialog is getting too many false positives
1382 // at this point, so turn off for now.
1383 if (false) {
1384 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1385 long now = SystemClock.uptimeMillis();
1386 final boolean inTime = mLastStartedActivity.startTime != 0
1387 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1388 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1389 final int nextUid = next.info.applicationInfo.uid;
1390 if (inTime && lastUid != nextUid
1391 && lastUid != next.launchedFromUid
1392 && mService.checkPermission(
1393 android.Manifest.permission.STOP_APP_SWITCHES,
1394 -1, next.launchedFromUid)
1395 != PackageManager.PERMISSION_GRANTED) {
1396 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1397 } else {
1398 next.startTime = now;
1399 mLastStartedActivity = next;
1400 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001401 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001402 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001403 mLastStartedActivity = next;
1404 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001405 }
1406
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001407 // We need to start pausing the current activity so the top one
1408 // can be resumed...
1409 if (mResumedActivity != null) {
1410 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
1411 startPausingLocked(userLeaving, false);
1412 return true;
1413 }
1414
1415 if (prev != null && prev != next) {
1416 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1417 prev.waitingVisible = true;
1418 mWaitingVisibleActivities.add(prev);
1419 if (DEBUG_SWITCH) Slog.v(
1420 TAG, "Resuming top, waiting visible to hide: " + prev);
1421 } else {
1422 // The next activity is already visible, so hide the previous
1423 // activity's windows right now so we can show the new one ASAP.
1424 // We only do this if the previous is finishing, which should mean
1425 // it is on top of the one being resumed so hiding it quickly
1426 // is good. Otherwise, we want to do the normal route of allowing
1427 // the resumed activity to be shown so we can decide if the
1428 // previous should actually be hidden depending on whether the
1429 // new one is found to be full-screen or not.
1430 if (prev.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001431 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001432 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1433 + prev + ", waitingVisible="
1434 + (prev != null ? prev.waitingVisible : null)
1435 + ", nowVisible=" + next.nowVisible);
1436 } else {
1437 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1438 + prev + ", waitingVisible="
1439 + (prev != null ? prev.waitingVisible : null)
1440 + ", nowVisible=" + next.nowVisible);
1441 }
1442 }
1443 }
1444
Dianne Hackborne7f97212011-02-24 14:40:20 -08001445 // Launching this app's activity, make sure the app is no longer
1446 // considered stopped.
1447 try {
1448 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001449 next.packageName, false, next.userId); /* TODO: Verify if correct userid */
Dianne Hackborne7f97212011-02-24 14:40:20 -08001450 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001451 } catch (IllegalArgumentException e) {
1452 Slog.w(TAG, "Failed trying to unstop package "
1453 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001454 }
1455
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001456 // We are starting up the next activity, so tell the window manager
1457 // that the previous one will be hidden soon. This way it can know
1458 // to ignore it when computing the desired screen orientation.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001459 boolean noAnim = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001460 if (prev != null) {
1461 if (prev.finishing) {
1462 if (DEBUG_TRANSITION) Slog.v(TAG,
1463 "Prepare close transition: prev=" + prev);
1464 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001465 mService.mWindowManager.prepareAppTransition(
1466 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001467 } else {
1468 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1469 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001470 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001471 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001472 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1473 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001474 } else {
1475 if (DEBUG_TRANSITION) Slog.v(TAG,
1476 "Prepare open transition: prev=" + prev);
1477 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001478 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001479 mService.mWindowManager.prepareAppTransition(
1480 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001481 } else {
1482 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1483 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001484 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001485 }
1486 }
1487 if (false) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001488 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1489 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001490 }
1491 } else if (mHistory.size() > 1) {
1492 if (DEBUG_TRANSITION) Slog.v(TAG,
1493 "Prepare open transition: no previous");
1494 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001495 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001496 mService.mWindowManager.prepareAppTransition(
1497 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001498 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001499 mService.mWindowManager.prepareAppTransition(
1500 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001501 }
1502 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001503 if (!noAnim) {
1504 next.applyOptionsLocked();
1505 } else {
1506 next.clearOptionsLocked();
1507 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001508
1509 if (next.app != null && next.app.thread != null) {
1510 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1511
1512 // This activity is now becoming visible.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001513 mService.mWindowManager.setAppVisibility(next.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001514
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001515 // schedule launch ticks to collect information about slow apps.
1516 next.startLaunchTickingLocked();
1517
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001518 ActivityRecord lastResumedActivity = mResumedActivity;
1519 ActivityState lastState = next.state;
1520
1521 mService.updateCpuStats();
1522
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001523 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001524 next.state = ActivityState.RESUMED;
1525 mResumedActivity = next;
1526 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001527 if (mMainStack) {
1528 mService.addRecentTaskLocked(next.task);
1529 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001530 mService.updateLruProcessLocked(next.app, true, true);
1531 updateLRUListLocked(next);
1532
1533 // Have the window manager re-evaluate the orientation of
1534 // the screen based on the new activity order.
1535 boolean updated = false;
1536 if (mMainStack) {
1537 synchronized (mService) {
1538 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1539 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001540 next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001541 if (config != null) {
1542 next.frozenBeforeDestroy = true;
1543 }
Dianne Hackborn813075a62011-11-14 17:45:19 -08001544 updated = mService.updateConfigurationLocked(config, next, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001545 }
1546 }
1547 if (!updated) {
1548 // The configuration update wasn't able to keep the existing
1549 // instance of the activity, and instead started a new one.
1550 // We should be all done, but let's just make sure our activity
1551 // is still at the top and schedule another run if something
1552 // weird happened.
1553 ActivityRecord nextNext = topRunningActivityLocked(null);
1554 if (DEBUG_SWITCH) Slog.i(TAG,
1555 "Activity config changed during resume: " + next
1556 + ", new next: " + nextNext);
1557 if (nextNext != next) {
1558 // Do over!
1559 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1560 }
1561 if (mMainStack) {
1562 mService.setFocusedActivityLocked(next);
1563 }
1564 ensureActivitiesVisibleLocked(null, 0);
1565 mService.mWindowManager.executeAppTransition();
1566 mNoAnimActivities.clear();
1567 return true;
1568 }
1569
1570 try {
1571 // Deliver all pending results.
1572 ArrayList a = next.results;
1573 if (a != null) {
1574 final int N = a.size();
1575 if (!next.finishing && N > 0) {
1576 if (DEBUG_RESULTS) Slog.v(
1577 TAG, "Delivering results to " + next
1578 + ": " + a);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001579 next.app.thread.scheduleSendResult(next.appToken, a);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001580 }
1581 }
1582
1583 if (next.newIntents != null) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001584 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001585 }
1586
1587 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
1588 System.identityHashCode(next),
1589 next.task.taskId, next.shortComponentName);
1590
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001591 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001592 showAskCompatModeDialogLocked(next);
Dianne Hackborn905577f2011-09-07 18:31:28 -07001593 next.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001594 next.app.thread.scheduleResumeActivity(next.appToken,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001595 mService.isNextTransitionForward());
1596
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001597 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001598
1599 } catch (Exception e) {
1600 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001601 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1602 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001603 next.state = lastState;
1604 mResumedActivity = lastResumedActivity;
1605 Slog.i(TAG, "Restarting because process died: " + next);
1606 if (!next.hasBeenLaunched) {
1607 next.hasBeenLaunched = true;
1608 } else {
1609 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1610 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001611 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001612 mService.compatibilityInfoForPackageLocked(
1613 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001614 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001615 next.labelRes, next.icon, next.windowFlags,
1616 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001617 }
1618 }
1619 startSpecificActivityLocked(next, true, false);
1620 return true;
1621 }
1622
1623 // From this point on, if something goes wrong there is no way
1624 // to recover the activity.
1625 try {
1626 next.visible = true;
1627 completeResumeLocked(next);
1628 } catch (Exception e) {
1629 // If any exception gets thrown, toss away this
1630 // activity and try the next one.
1631 Slog.w(TAG, "Exception thrown during resume of " + next, e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001632 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001633 "resume-exception");
1634 return true;
1635 }
1636
1637 // Didn't need to use the icicle, and it is now out of date.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001638 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Resumed activity; didn't need icicle of: " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001639 next.icicle = null;
1640 next.haveState = false;
1641 next.stopped = false;
1642
1643 } else {
1644 // Whoops, need to restart this activity!
1645 if (!next.hasBeenLaunched) {
1646 next.hasBeenLaunched = true;
1647 } else {
1648 if (SHOW_APP_STARTING_PREVIEW) {
1649 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001650 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001651 mService.compatibilityInfoForPackageLocked(
1652 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001653 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001654 next.labelRes, next.icon, next.windowFlags,
1655 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001656 }
1657 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1658 }
1659 startSpecificActivityLocked(next, true, true);
1660 }
1661
1662 return true;
1663 }
1664
1665 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001666 boolean doResume, boolean keepCurTransition, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001667 final int NH = mHistory.size();
1668
1669 int addPos = -1;
1670
1671 if (!newTask) {
1672 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001673 boolean startIt = true;
1674 for (int i = NH-1; i >= 0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001675 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001676 if (p.finishing) {
1677 continue;
1678 }
1679 if (p.task == r.task) {
1680 // Here it is! Now, if this is not yet visible to the
1681 // user, then just add it without starting; it will
1682 // get started when the user navigates back to it.
1683 addPos = i+1;
1684 if (!startIt) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001685 if (DEBUG_ADD_REMOVE) {
1686 RuntimeException here = new RuntimeException("here");
1687 here.fillInStackTrace();
1688 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos,
1689 here);
1690 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001691 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001692 r.putInHistory();
Dianne Hackbornbe707852011-11-11 14:32:10 -08001693 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001694 r.info.screenOrientation, r.fullscreen);
1695 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001696 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001697 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001698 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001699 return;
1700 }
1701 break;
1702 }
1703 if (p.fullscreen) {
1704 startIt = false;
1705 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001706 }
1707 }
1708
1709 // Place a new activity at top of stack, so it is next to interact
1710 // with the user.
1711 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001712 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001713 }
1714
1715 // If we are not placing the new activity frontmost, we do not want
1716 // to deliver the onUserLeaving callback to the actual frontmost
1717 // activity
1718 if (addPos < NH) {
1719 mUserLeaving = false;
1720 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1721 }
1722
1723 // Slot the activity into the history stack and proceed
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001724 if (DEBUG_ADD_REMOVE) {
1725 RuntimeException here = new RuntimeException("here");
1726 here.fillInStackTrace();
1727 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos, here);
1728 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001729 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001730 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001731 r.frontOfTask = newTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001732 if (NH > 0) {
1733 // We want to show the starting preview window if we are
1734 // switching to a new task, or the next activity's process is
1735 // not currently running.
1736 boolean showStartingIcon = newTask;
1737 ProcessRecord proc = r.app;
1738 if (proc == null) {
1739 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1740 }
1741 if (proc == null || proc.thread == null) {
1742 showStartingIcon = true;
1743 }
1744 if (DEBUG_TRANSITION) Slog.v(TAG,
1745 "Prepare open transition: starting " + r);
1746 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001747 mService.mWindowManager.prepareAppTransition(
1748 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001749 mNoAnimActivities.add(r);
1750 } else if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
1751 mService.mWindowManager.prepareAppTransition(
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001752 WindowManagerPolicy.TRANSIT_TASK_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001753 mNoAnimActivities.remove(r);
1754 } else {
1755 mService.mWindowManager.prepareAppTransition(newTask
1756 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001757 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001758 mNoAnimActivities.remove(r);
1759 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001760 r.updateOptionsLocked(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001761 mService.mWindowManager.addAppToken(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001762 addPos, r.appToken, r.task.taskId, r.info.screenOrientation, r.fullscreen);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001763 boolean doShow = true;
1764 if (newTask) {
1765 // Even though this activity is starting fresh, we still need
1766 // to reset it to make sure we apply affinities to move any
1767 // existing activities from other tasks in to it.
1768 // If the caller has requested that the target task be
1769 // reset, then do so.
1770 if ((r.intent.getFlags()
1771 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1772 resetTaskIfNeededLocked(r, r);
1773 doShow = topRunningNonDelayedActivityLocked(null) == r;
1774 }
1775 }
1776 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1777 // Figure out if we are transitioning from another activity that is
1778 // "has the same starting icon" as the next one. This allows the
1779 // window manager to keep the previous window it had previously
1780 // created, if it still had one.
1781 ActivityRecord prev = mResumedActivity;
1782 if (prev != null) {
1783 // We don't want to reuse the previous starting preview if:
1784 // (1) The current activity is in a different task.
1785 if (prev.task != r.task) prev = null;
1786 // (2) The current activity is already displayed.
1787 else if (prev.nowVisible) prev = null;
1788 }
1789 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001790 r.appToken, r.packageName, r.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001791 mService.compatibilityInfoForPackageLocked(
1792 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001793 r.labelRes, r.icon, r.windowFlags,
1794 prev != null ? prev.appToken : null, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001795 }
1796 } else {
1797 // If this is the first activity, don't do any fancy animations,
1798 // because there is nothing for it to animate on top of.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001799 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001800 r.info.screenOrientation, r.fullscreen);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001801 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001802 }
1803 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001804 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001805 }
1806
1807 if (doResume) {
1808 resumeTopActivityLocked(null);
1809 }
1810 }
1811
Dianne Hackbornbe707852011-11-11 14:32:10 -08001812 final void validateAppTokensLocked() {
1813 mValidateAppTokens.clear();
1814 mValidateAppTokens.ensureCapacity(mHistory.size());
1815 for (int i=0; i<mHistory.size(); i++) {
1816 mValidateAppTokens.add(mHistory.get(i).appToken);
1817 }
1818 mService.mWindowManager.validateAppTokens(mValidateAppTokens);
1819 }
1820
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001821 /**
1822 * Perform a reset of the given task, if needed as part of launching it.
1823 * Returns the new HistoryRecord at the top of the task.
1824 */
1825 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1826 ActivityRecord newActivity) {
1827 boolean forceReset = (newActivity.info.flags
1828 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001829 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1830 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001831 if ((newActivity.info.flags
1832 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1833 forceReset = true;
1834 }
1835 }
1836
1837 final TaskRecord task = taskTop.task;
1838
1839 // We are going to move through the history list so that we can look
1840 // at each activity 'target' with 'below' either the interesting
1841 // activity immediately below it in the stack or null.
1842 ActivityRecord target = null;
1843 int targetI = 0;
1844 int taskTopI = -1;
1845 int replyChainEnd = -1;
1846 int lastReparentPos = -1;
1847 for (int i=mHistory.size()-1; i>=-1; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001848 ActivityRecord below = i >= 0 ? mHistory.get(i) : null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001849
1850 if (below != null && below.finishing) {
1851 continue;
1852 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001853 // Don't check any lower in the stack if we're crossing a user boundary.
1854 if (below != null && below.userId != taskTop.userId) {
1855 break;
1856 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001857 if (target == null) {
1858 target = below;
1859 targetI = i;
1860 // If we were in the middle of a reply chain before this
1861 // task, it doesn't appear like the root of the chain wants
1862 // anything interesting, so drop it.
1863 replyChainEnd = -1;
1864 continue;
1865 }
1866
1867 final int flags = target.info.flags;
1868
1869 final boolean finishOnTaskLaunch =
1870 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1871 final boolean allowTaskReparenting =
1872 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1873
1874 if (target.task == task) {
1875 // We are inside of the task being reset... we'll either
1876 // finish this activity, push it out for another task,
1877 // or leave it as-is. We only do this
1878 // for activities that are not the root of the task (since
1879 // if we finish the root, we may no longer have the task!).
1880 if (taskTopI < 0) {
1881 taskTopI = targetI;
1882 }
1883 if (below != null && below.task == task) {
1884 final boolean clearWhenTaskReset =
1885 (target.intent.getFlags()
1886 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
1887 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
1888 // If this activity is sending a reply to a previous
1889 // activity, we can't do anything with it now until
1890 // we reach the start of the reply chain.
1891 // XXX note that we are assuming the result is always
1892 // to the previous activity, which is almost always
1893 // the case but we really shouldn't count on.
1894 if (replyChainEnd < 0) {
1895 replyChainEnd = targetI;
1896 }
1897 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
1898 && target.taskAffinity != null
1899 && !target.taskAffinity.equals(task.affinity)) {
1900 // If this activity has an affinity for another
1901 // task, then we need to move it out of here. We will
1902 // move it as far out of the way as possible, to the
1903 // bottom of the activity stack. This also keeps it
1904 // correctly ordered with any activities we previously
1905 // moved.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001906 ActivityRecord p = mHistory.get(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001907 if (target.taskAffinity != null
1908 && target.taskAffinity.equals(p.task.affinity)) {
1909 // If the activity currently at the bottom has the
1910 // same task affinity as the one we are moving,
1911 // then merge it into the same task.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001912 target.setTask(p.task, p.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001913 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1914 + " out to bottom task " + p.task);
1915 } else {
1916 mService.mCurTask++;
1917 if (mService.mCurTask <= 0) {
1918 mService.mCurTask = 1;
1919 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001920 target.setTask(new TaskRecord(mService.mCurTask, target.info, null),
1921 null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001922 target.task.affinityIntent = target.intent;
1923 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1924 + " out to new task " + target.task);
1925 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001926 mService.mWindowManager.setAppGroupId(target.appToken, task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001927 if (replyChainEnd < 0) {
1928 replyChainEnd = targetI;
1929 }
1930 int dstPos = 0;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001931 ThumbnailHolder curThumbHolder = target.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001932 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001933 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001934 if (p.finishing) {
1935 continue;
1936 }
1937 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
1938 + " out to target's task " + target.task);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001939 p.setTask(target.task, curThumbHolder, false);
1940 curThumbHolder = p.thumbHolder;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001941 if (DEBUG_ADD_REMOVE) {
1942 RuntimeException here = new RuntimeException("here");
1943 here.fillInStackTrace();
1944 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
1945 + dstPos, here);
1946 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001947 mHistory.remove(srcPos);
1948 mHistory.add(dstPos, p);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001949 mService.mWindowManager.moveAppToken(dstPos, p.appToken);
1950 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001951 dstPos++;
1952 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001953 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001954 }
1955 i++;
1956 }
1957 if (taskTop == p) {
1958 taskTop = below;
1959 }
1960 if (taskTopI == replyChainEnd) {
1961 taskTopI = -1;
1962 }
1963 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001964 } else if (forceReset || finishOnTaskLaunch
1965 || clearWhenTaskReset) {
1966 // If the activity should just be removed -- either
1967 // because it asks for it, or the task should be
1968 // cleared -- then finish it and anything that is
1969 // part of its reply chain.
1970 if (clearWhenTaskReset) {
1971 // In this case, we want to finish this activity
1972 // and everything above it, so be sneaky and pretend
1973 // like these are all in the reply chain.
1974 replyChainEnd = targetI+1;
1975 while (replyChainEnd < mHistory.size() &&
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001976 (mHistory.get(
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001977 replyChainEnd)).task == task) {
1978 replyChainEnd++;
1979 }
1980 replyChainEnd--;
1981 } else if (replyChainEnd < 0) {
1982 replyChainEnd = targetI;
1983 }
1984 ActivityRecord p = null;
1985 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001986 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001987 if (p.finishing) {
1988 continue;
1989 }
1990 if (finishActivityLocked(p, srcPos,
1991 Activity.RESULT_CANCELED, null, "reset")) {
1992 replyChainEnd--;
1993 srcPos--;
1994 }
1995 }
1996 if (taskTop == p) {
1997 taskTop = below;
1998 }
1999 if (taskTopI == replyChainEnd) {
2000 taskTopI = -1;
2001 }
2002 replyChainEnd = -1;
2003 } else {
2004 // If we were in the middle of a chain, well the
2005 // activity that started it all doesn't want anything
2006 // special, so leave it all as-is.
2007 replyChainEnd = -1;
2008 }
2009 } else {
2010 // Reached the bottom of the task -- any reply chain
2011 // should be left as-is.
2012 replyChainEnd = -1;
2013 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002014
2015 } else if (target.resultTo != null && (below == null
2016 || below.task == target.task)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002017 // If this activity is sending a reply to a previous
2018 // activity, we can't do anything with it now until
2019 // we reach the start of the reply chain.
2020 // XXX note that we are assuming the result is always
2021 // to the previous activity, which is almost always
2022 // the case but we really shouldn't count on.
2023 if (replyChainEnd < 0) {
2024 replyChainEnd = targetI;
2025 }
2026
2027 } else if (taskTopI >= 0 && allowTaskReparenting
2028 && task.affinity != null
2029 && task.affinity.equals(target.taskAffinity)) {
2030 // We are inside of another task... if this activity has
2031 // an affinity for our task, then either remove it if we are
2032 // clearing or move it over to our task. Note that
2033 // we currently punt on the case where we are resetting a
2034 // task that is not at the top but who has activities above
2035 // with an affinity to it... this is really not a normal
2036 // case, and we will need to later pull that task to the front
2037 // and usually at that point we will do the reset and pick
2038 // up those remaining activities. (This only happens if
2039 // someone starts an activity in a new task from an activity
2040 // in a task that is not currently on top.)
2041 if (forceReset || finishOnTaskLaunch) {
2042 if (replyChainEnd < 0) {
2043 replyChainEnd = targetI;
2044 }
2045 ActivityRecord p = null;
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002046 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index "
2047 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002048 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002049 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002050 if (p.finishing) {
2051 continue;
2052 }
2053 if (finishActivityLocked(p, srcPos,
2054 Activity.RESULT_CANCELED, null, "reset")) {
2055 taskTopI--;
2056 lastReparentPos--;
2057 replyChainEnd--;
2058 srcPos--;
2059 }
2060 }
2061 replyChainEnd = -1;
2062 } else {
2063 if (replyChainEnd < 0) {
2064 replyChainEnd = targetI;
2065 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002066 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting task at index "
2067 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002068 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002069 ActivityRecord p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002070 if (p.finishing) {
2071 continue;
2072 }
2073 if (lastReparentPos < 0) {
2074 lastReparentPos = taskTopI;
2075 taskTop = p;
2076 } else {
2077 lastReparentPos--;
2078 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002079 if (DEBUG_ADD_REMOVE) {
2080 RuntimeException here = new RuntimeException("here");
2081 here.fillInStackTrace();
2082 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2083 + lastReparentPos, here);
2084 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002085 mHistory.remove(srcPos);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002086 p.setTask(task, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002087 mHistory.add(lastReparentPos, p);
2088 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002089 + " from " + srcPos + " to " + lastReparentPos
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002090 + " in to resetting task " + task);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002091 mService.mWindowManager.moveAppToken(lastReparentPos, p.appToken);
2092 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002093 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002094 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002095 }
2096 }
2097 replyChainEnd = -1;
2098
2099 // Now we've moved it in to place... but what if this is
2100 // a singleTop activity and we have put it on top of another
2101 // instance of the same activity? Then we drop the instance
2102 // below so it remains singleTop.
2103 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2104 for (int j=lastReparentPos-1; j>=0; j--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002105 ActivityRecord p = mHistory.get(j);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002106 if (p.finishing) {
2107 continue;
2108 }
2109 if (p.intent.getComponent().equals(target.intent.getComponent())) {
2110 if (finishActivityLocked(p, j,
2111 Activity.RESULT_CANCELED, null, "replace")) {
2112 taskTopI--;
2113 lastReparentPos--;
2114 }
2115 }
2116 }
2117 }
2118 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002119
2120 } else if (below != null && below.task != target.task) {
2121 // We hit the botton of a task; the reply chain can't
2122 // pass through it.
2123 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002124 }
2125
2126 target = below;
2127 targetI = i;
2128 }
2129
2130 return taskTop;
2131 }
2132
2133 /**
2134 * Perform clear operation as requested by
2135 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2136 * stack to the given task, then look for
2137 * an instance of that activity in the stack and, if found, finish all
2138 * activities on top of it and return the instance.
2139 *
2140 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002141 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002142 * or null if none was found.
2143 */
2144 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002145 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002146 int i = mHistory.size();
2147
2148 // First find the requested task.
2149 while (i > 0) {
2150 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002151 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002152 if (r.task.taskId == taskId) {
2153 i++;
2154 break;
2155 }
2156 }
2157
2158 // Now clear it.
2159 while (i > 0) {
2160 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002161 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002162 if (r.finishing) {
2163 continue;
2164 }
2165 if (r.task.taskId != taskId) {
2166 return null;
2167 }
2168 if (r.realActivity.equals(newR.realActivity)) {
2169 // Here it is! Now finish everything in front...
2170 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002171 while (i < (mHistory.size()-1)) {
2172 i++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002173 r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002174 if (r.task.taskId != taskId) {
2175 break;
2176 }
2177 if (r.finishing) {
2178 continue;
2179 }
2180 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2181 null, "clear")) {
2182 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002183 }
2184 }
2185
2186 // Finally, if this is a normal launch mode (that is, not
2187 // expecting onNewIntent()), then we will finish the current
2188 // instance of the activity so a new fresh one can be started.
2189 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2190 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
2191 if (!ret.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002192 int index = indexOfTokenLocked(ret.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002193 if (index >= 0) {
2194 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
2195 null, "clear");
2196 }
2197 return null;
2198 }
2199 }
2200
2201 return ret;
2202 }
2203 }
2204
2205 return null;
2206 }
2207
2208 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002209 * Completely remove all activities associated with an existing
2210 * task starting at a specified index.
2211 */
2212 private final void performClearTaskAtIndexLocked(int taskId, int i) {
Dianne Hackborneabd3282011-10-13 16:26:49 -07002213 while (i < mHistory.size()) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002214 ActivityRecord r = mHistory.get(i);
2215 if (r.task.taskId != taskId) {
2216 // Whoops hit the end.
2217 return;
2218 }
2219 if (r.finishing) {
2220 i++;
2221 continue;
2222 }
2223 if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2224 null, "clear")) {
2225 i++;
2226 }
2227 }
2228 }
2229
2230 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002231 * Completely remove all activities associated with an existing task.
2232 */
2233 private final void performClearTaskLocked(int taskId) {
2234 int i = mHistory.size();
2235
2236 // First find the requested task.
2237 while (i > 0) {
2238 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002239 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002240 if (r.task.taskId == taskId) {
2241 i++;
2242 break;
2243 }
2244 }
2245
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002246 // Now find the start and clear it.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002247 while (i > 0) {
2248 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002249 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002250 if (r.finishing) {
2251 continue;
2252 }
2253 if (r.task.taskId != taskId) {
2254 // We hit the bottom. Now finish it all...
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002255 performClearTaskAtIndexLocked(taskId, i+1);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002256 return;
2257 }
2258 }
2259 }
2260
2261 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002262 * Find the activity in the history stack within the given task. Returns
2263 * the index within the history at which it's found, or < 0 if not found.
2264 */
2265 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2266 int i = mHistory.size();
2267 while (i > 0) {
2268 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002269 ActivityRecord candidate = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002270 if (candidate.task.taskId != task) {
2271 break;
2272 }
2273 if (candidate.realActivity.equals(r.realActivity)) {
2274 return i;
2275 }
2276 }
2277
2278 return -1;
2279 }
2280
2281 /**
2282 * Reorder the history stack so that the activity at the given index is
2283 * brought to the front.
2284 */
2285 private final ActivityRecord moveActivityToFrontLocked(int where) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002286 ActivityRecord newTop = mHistory.remove(where);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002287 int top = mHistory.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002288 ActivityRecord oldTop = mHistory.get(top-1);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002289 if (DEBUG_ADD_REMOVE) {
2290 RuntimeException here = new RuntimeException("here");
2291 here.fillInStackTrace();
2292 Slog.i(TAG, "Removing and adding activity " + newTop + " to stack at "
2293 + top, here);
2294 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002295 mHistory.add(top, newTop);
2296 oldTop.frontOfTask = false;
2297 newTop.frontOfTask = true;
2298 return newTop;
2299 }
2300
2301 final int startActivityLocked(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002302 Intent intent, String resolvedType, ActivityInfo aInfo, IBinder resultTo,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002303 String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002304 int callingPid, int callingUid, int startFlags, Bundle options,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002305 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002306
Dianne Hackborna4972e92012-03-14 10:38:05 -07002307 int err = ActivityManager.START_SUCCESS;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002308
2309 ProcessRecord callerApp = null;
2310 if (caller != null) {
2311 callerApp = mService.getRecordForAppLocked(caller);
2312 if (callerApp != null) {
2313 callingPid = callerApp.pid;
2314 callingUid = callerApp.info.uid;
2315 } else {
2316 Slog.w(TAG, "Unable to find app for caller " + caller
2317 + " (pid=" + callingPid + ") when starting: "
2318 + intent.toString());
Dianne Hackborna4972e92012-03-14 10:38:05 -07002319 err = ActivityManager.START_PERMISSION_DENIED;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002320 }
2321 }
2322
Dianne Hackborna4972e92012-03-14 10:38:05 -07002323 if (err == ActivityManager.START_SUCCESS) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08002324 Slog.i(TAG, "START {" + intent.toShortString(true, true, true, false)
2325 + "} from pid " + (callerApp != null ? callerApp.pid : callingPid));
Dianne Hackbornefb58102010-10-14 16:47:34 -07002326 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002327
2328 ActivityRecord sourceRecord = null;
2329 ActivityRecord resultRecord = null;
2330 if (resultTo != null) {
2331 int index = indexOfTokenLocked(resultTo);
2332 if (DEBUG_RESULTS) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002333 TAG, "Will send result to " + resultTo + " (index " + index + ")");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002334 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002335 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002336 if (requestCode >= 0 && !sourceRecord.finishing) {
2337 resultRecord = sourceRecord;
2338 }
2339 }
2340 }
2341
2342 int launchFlags = intent.getFlags();
2343
2344 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2345 && sourceRecord != null) {
2346 // Transfer the result target from the source activity to the new
2347 // one being started, including any failures.
2348 if (requestCode >= 0) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002349 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002350 return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002351 }
2352 resultRecord = sourceRecord.resultTo;
2353 resultWho = sourceRecord.resultWho;
2354 requestCode = sourceRecord.requestCode;
2355 sourceRecord.resultTo = null;
2356 if (resultRecord != null) {
2357 resultRecord.removeResultsLocked(
2358 sourceRecord, resultWho, requestCode);
2359 }
2360 }
2361
Dianne Hackborna4972e92012-03-14 10:38:05 -07002362 if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002363 // We couldn't find a class that can handle the given Intent.
2364 // That's the end of that!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002365 err = ActivityManager.START_INTENT_NOT_RESOLVED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002366 }
2367
Dianne Hackborna4972e92012-03-14 10:38:05 -07002368 if (err == ActivityManager.START_SUCCESS && aInfo == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002369 // We couldn't find the specific class specified in the Intent.
2370 // Also the end of the line.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002371 err = ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002372 }
2373
Dianne Hackborna4972e92012-03-14 10:38:05 -07002374 if (err != ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002375 if (resultRecord != null) {
2376 sendActivityResultLocked(-1,
2377 resultRecord, resultWho, requestCode,
2378 Activity.RESULT_CANCELED, null);
2379 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002380 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002381 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002382 return err;
2383 }
2384
2385 final int perm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002386 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002387 if (perm != PackageManager.PERMISSION_GRANTED) {
2388 if (resultRecord != null) {
2389 sendActivityResultLocked(-1,
2390 resultRecord, resultWho, requestCode,
2391 Activity.RESULT_CANCELED, null);
2392 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002393 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002394 String msg;
2395 if (!aInfo.exported) {
2396 msg = "Permission Denial: starting " + intent.toString()
2397 + " from " + callerApp + " (pid=" + callingPid
2398 + ", uid=" + callingUid + ")"
2399 + " not exported from uid " + aInfo.applicationInfo.uid;
2400 } else {
2401 msg = "Permission Denial: starting " + intent.toString()
2402 + " from " + callerApp + " (pid=" + callingPid
2403 + ", uid=" + callingUid + ")"
2404 + " requires " + aInfo.permission;
2405 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002406 Slog.w(TAG, msg);
2407 throw new SecurityException(msg);
2408 }
2409
2410 if (mMainStack) {
2411 if (mService.mController != null) {
2412 boolean abort = false;
2413 try {
2414 // The Intent we give to the watcher has the extra data
2415 // stripped off, since it can contain private information.
2416 Intent watchIntent = intent.cloneFilter();
2417 abort = !mService.mController.activityStarting(watchIntent,
2418 aInfo.applicationInfo.packageName);
2419 } catch (RemoteException e) {
2420 mService.mController = null;
2421 }
2422
2423 if (abort) {
2424 if (resultRecord != null) {
2425 sendActivityResultLocked(-1,
2426 resultRecord, resultWho, requestCode,
2427 Activity.RESULT_CANCELED, null);
2428 }
2429 // We pretend to the caller that it was really started, but
2430 // they will just get a cancel result.
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002431 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002432 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002433 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002434 }
2435 }
2436 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002437
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002438 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2439 intent, resolvedType, aInfo, mService.mConfiguration,
2440 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002441 if (outActivity != null) {
2442 outActivity[0] = r;
2443 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002444
2445 if (mMainStack) {
2446 if (mResumedActivity == null
2447 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2448 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2449 PendingActivityLaunch pal = new PendingActivityLaunch();
2450 pal.r = r;
2451 pal.sourceRecord = sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002452 pal.startFlags = startFlags;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002453 mService.mPendingActivityLaunches.add(pal);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002454 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002455 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002456 return ActivityManager.START_SWITCHES_CANCELED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002457 }
2458 }
2459
2460 if (mService.mDidAppSwitch) {
2461 // This is the second allowed switch since we stopped switches,
2462 // so now just generally allow switches. Use case: user presses
2463 // home (switches disabled, switch to home, mDidAppSwitch now true);
2464 // user taps a home icon (coming from home so allowed, we hit here
2465 // and now allow anyone to switch again).
2466 mService.mAppSwitchesAllowedTime = 0;
2467 } else {
2468 mService.mDidAppSwitch = true;
2469 }
2470
2471 mService.doPendingActivityLaunchesLocked(false);
2472 }
2473
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002474 err = startActivityUncheckedLocked(r, sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002475 startFlags, true, options);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002476 if (mDismissKeyguardOnNextActivity && mPausingActivity == null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002477 // Someone asked to have the keyguard dismissed on the next
2478 // activity start, but we are not actually doing an activity
2479 // switch... just dismiss the keyguard now, because we
2480 // probably want to see whatever is behind it.
2481 mDismissKeyguardOnNextActivity = false;
2482 mService.mWindowManager.dismissKeyguard();
2483 }
2484 return err;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002485 }
2486
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002487 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2488 if ((launchFlags &
2489 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2490 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2491 // Caller wants to appear on home activity, so before starting
2492 // their own activity we will bring home to the front.
2493 moveHomeToFrontLocked();
2494 }
2495 }
2496
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002497 final int startActivityUncheckedLocked(ActivityRecord r,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002498 ActivityRecord sourceRecord, int startFlags, boolean doResume,
2499 Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002500 final Intent intent = r.intent;
2501 final int callingUid = r.launchedFromUid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002502 final int userId = r.userId;
2503
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002504 int launchFlags = intent.getFlags();
2505
2506 // We'll invoke onUserLeaving before onPause only if the launching
2507 // activity did not explicitly state that this is an automated launch.
2508 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2509 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2510 "startActivity() => mUserLeaving=" + mUserLeaving);
2511
2512 // If the caller has asked not to resume at this point, we make note
2513 // of this in the record so that we can skip it when trying to find
2514 // the top running activity.
2515 if (!doResume) {
2516 r.delayedResume = true;
2517 }
2518
2519 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2520 != 0 ? r : null;
2521
2522 // If the onlyIfNeeded flag is set, then we can do this if the activity
2523 // being launched is the same as the one making the call... or, as
2524 // a special case, if we do not know the caller then we count the
2525 // current top activity as the caller.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002526 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002527 ActivityRecord checkedCaller = sourceRecord;
2528 if (checkedCaller == null) {
2529 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2530 }
2531 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2532 // Caller is not the same as launcher, so always needed.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002533 startFlags &= ~ActivityManager.START_FLAG_ONLY_IF_NEEDED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002534 }
2535 }
2536
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002537 if (sourceRecord == null) {
2538 // This activity is not being started from another... in this
2539 // case we -always- start a new task.
2540 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2541 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2542 + intent);
2543 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2544 }
2545 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2546 // The original activity who is starting us is running as a single
2547 // instance... this new activity it is starting must go on its
2548 // own task.
2549 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2550 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2551 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2552 // The activity being started is a single instance... it always
2553 // gets launched into its own task.
2554 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2555 }
2556
2557 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2558 // For whatever reason this activity is being launched into a new
2559 // task... yet the caller has requested a result back. Well, that
2560 // is pretty messed up, so instead immediately send back a cancel
2561 // and let the new task continue launched as normal without a
2562 // dependency on its originator.
2563 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2564 sendActivityResultLocked(-1,
2565 r.resultTo, r.resultWho, r.requestCode,
2566 Activity.RESULT_CANCELED, null);
2567 r.resultTo = null;
2568 }
2569
2570 boolean addingToTask = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002571 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002572 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2573 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2574 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2575 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2576 // If bring to front is requested, and no result is requested, and
2577 // we can find a task that was started with this same
2578 // component, then instead of launching bring that one to the front.
2579 if (r.resultTo == null) {
2580 // See if there is a task to bring to the front. If this is
2581 // a SINGLE_INSTANCE activity, there can be one and only one
2582 // instance of it in the history, and it is always in its own
2583 // unique task, so we do a special search.
2584 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2585 ? findTaskLocked(intent, r.info)
2586 : findActivityLocked(intent, r.info);
2587 if (taskTop != null) {
2588 if (taskTop.task.intent == null) {
2589 // This task was started because of movement of
2590 // the activity based on affinity... now that we
2591 // are actually launching it, we can assign the
2592 // base intent.
2593 taskTop.task.setIntent(intent, r.info);
2594 }
2595 // If the target task is not in the front, then we need
2596 // to bring it to the front... except... well, with
2597 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2598 // to have the same behavior as if a new instance was
2599 // being started, which means not bringing it to the front
2600 // if the caller is not itself in the front.
2601 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002602 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002603 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2604 boolean callerAtFront = sourceRecord == null
2605 || curTop.task == sourceRecord.task;
2606 if (callerAtFront) {
2607 // We really do want to push this one into the
2608 // user's face, right now.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002609 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002610 moveTaskToFrontLocked(taskTop.task, r, options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002611 }
2612 }
2613 // If the caller has requested that the target task be
2614 // reset, then do so.
2615 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2616 taskTop = resetTaskIfNeededLocked(taskTop, r);
2617 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002618 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002619 // We don't need to start a new activity, and
2620 // the client said not to do anything if that
2621 // is the case, so this is it! And for paranoia, make
2622 // sure we have correctly resumed the top activity.
2623 if (doResume) {
2624 resumeTopActivityLocked(null);
2625 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002626 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002627 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002628 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002629 if ((launchFlags &
2630 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2631 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2632 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002633 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002634 // not be too hard...
2635 reuseTask = taskTop.task;
2636 performClearTaskLocked(taskTop.task.taskId);
2637 reuseTask.setIntent(r.intent, r.info);
2638 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002639 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2640 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2641 // In this situation we want to remove all activities
2642 // from the task up to the one being started. In most
2643 // cases this means we are resetting the task to its
2644 // initial state.
2645 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002646 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002647 if (top != null) {
2648 if (top.frontOfTask) {
2649 // Activity aliases may mean we use different
2650 // intents for the top activity, so make sure
2651 // the task now has the identity of the new
2652 // intent.
2653 top.task.setIntent(r.intent, r.info);
2654 }
2655 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002656 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002657 } else {
2658 // A special case: we need to
2659 // start the activity because it is not currently
2660 // running, and the caller has asked to clear the
2661 // current task to have this activity at the top.
2662 addingToTask = true;
2663 // Now pretend like this activity is being started
2664 // by the top of its task, so it is put in the
2665 // right place.
2666 sourceRecord = taskTop;
2667 }
2668 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2669 // In this case the top activity on the task is the
2670 // same as the one being launched, so we take that
2671 // as a request to bring the task to the foreground.
2672 // If the top activity in the task is the root
2673 // activity, deliver this new intent to it if it
2674 // desires.
2675 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2676 && taskTop.realActivity.equals(r.realActivity)) {
2677 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2678 if (taskTop.frontOfTask) {
2679 taskTop.task.setIntent(r.intent, r.info);
2680 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002681 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002682 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2683 // In this case we are launching the root activity
2684 // of the task, but with a different intent. We
2685 // should start a new instance on top.
2686 addingToTask = true;
2687 sourceRecord = taskTop;
2688 }
2689 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2690 // In this case an activity is being launched in to an
2691 // existing task, without resetting that task. This
2692 // is typically the situation of launching an activity
2693 // from a notification or shortcut. We want to place
2694 // the new activity on top of the current task.
2695 addingToTask = true;
2696 sourceRecord = taskTop;
2697 } else if (!taskTop.task.rootWasReset) {
2698 // In this case we are launching in to an existing task
2699 // that has not yet been started from its front door.
2700 // The current task has been brought to the front.
2701 // Ideally, we'd probably like to place this new task
2702 // at the bottom of its stack, but that's a little hard
2703 // to do with the current organization of the code so
2704 // for now we'll just drop it.
2705 taskTop.task.setIntent(r.intent, r.info);
2706 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002707 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002708 // We didn't do anything... but it was needed (a.k.a., client
2709 // don't use that intent!) And for paranoia, make
2710 // sure we have correctly resumed the top activity.
2711 if (doResume) {
2712 resumeTopActivityLocked(null);
2713 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002714 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002715 return ActivityManager.START_TASK_TO_FRONT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002716 }
2717 }
2718 }
2719 }
2720
2721 //String uri = r.intent.toURI();
2722 //Intent intent2 = new Intent(uri);
2723 //Slog.i(TAG, "Given intent: " + r.intent);
2724 //Slog.i(TAG, "URI is: " + uri);
2725 //Slog.i(TAG, "To intent: " + intent2);
2726
2727 if (r.packageName != null) {
2728 // If the activity being launched is the same as the one currently
2729 // at the top, then we need to check if it should only be launched
2730 // once.
2731 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2732 if (top != null && r.resultTo == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002733 if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002734 if (top.app != null && top.app.thread != null) {
2735 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2736 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2737 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2738 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2739 // For paranoia, make sure we have correctly
2740 // resumed the top activity.
2741 if (doResume) {
2742 resumeTopActivityLocked(null);
2743 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002744 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002745 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002746 // We don't need to start a new activity, and
2747 // the client said not to do anything if that
2748 // is the case, so this is it!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002749 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002750 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002751 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002752 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002753 }
2754 }
2755 }
2756 }
2757
2758 } else {
2759 if (r.resultTo != null) {
2760 sendActivityResultLocked(-1,
2761 r.resultTo, r.resultWho, r.requestCode,
2762 Activity.RESULT_CANCELED, null);
2763 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002764 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002765 return ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002766 }
2767
2768 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002769 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002770
2771 // Should this be considered a new task?
2772 if (r.resultTo == null && !addingToTask
2773 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002774 if (reuseTask == null) {
2775 // todo: should do better management of integers.
2776 mService.mCurTask++;
2777 if (mService.mCurTask <= 0) {
2778 mService.mCurTask = 1;
2779 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002780 r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002781 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2782 + " in new task " + r.task);
2783 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002784 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002785 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002786 newTask = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002787 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002788
2789 } else if (sourceRecord != null) {
2790 if (!addingToTask &&
2791 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2792 // In this case, we are adding the activity to an existing
2793 // task, but the caller has asked to clear that task if the
2794 // activity is already running.
2795 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002796 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002797 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002798 if (top != null) {
2799 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002800 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002801 // For paranoia, make sure we have correctly
2802 // resumed the top activity.
2803 if (doResume) {
2804 resumeTopActivityLocked(null);
2805 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002806 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002807 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002808 }
2809 } else if (!addingToTask &&
2810 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2811 // In this case, we are launching an activity in our own task
2812 // that may already be running somewhere in the history, and
2813 // we want to shuffle it to the front of the stack if so.
2814 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2815 if (where >= 0) {
2816 ActivityRecord top = moveActivityToFrontLocked(where);
2817 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002818 top.updateOptionsLocked(options);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002819 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002820 if (doResume) {
2821 resumeTopActivityLocked(null);
2822 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002823 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002824 }
2825 }
2826 // An existing activity is starting this new activity, so we want
2827 // to keep the new one in the same task as the one that is starting
2828 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002829 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002830 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2831 + " in existing task " + r.task);
2832
2833 } else {
2834 // This not being started from an existing activity, and not part
2835 // of a new task... just put it in the top task, though these days
2836 // this case should never happen.
2837 final int N = mHistory.size();
2838 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002839 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002840 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002841 ? prev.task
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002842 : new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002843 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2844 + " in new guessed " + r.task);
2845 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002846
Dianne Hackborn39792d22010-08-19 18:01:52 -07002847 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002848 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002849
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002850 if (newTask) {
2851 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
2852 }
2853 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002854 startActivityLocked(r, newTask, doResume, keepCurTransition, options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002855 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002856 }
2857
Dianne Hackborna4972e92012-03-14 10:38:05 -07002858 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002859 String profileFile, ParcelFileDescriptor profileFd, int userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002860 // Collect information about the target of the Intent.
2861 ActivityInfo aInfo;
2862 try {
2863 ResolveInfo rInfo =
2864 AppGlobals.getPackageManager().resolveIntent(
2865 intent, resolvedType,
2866 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07002867 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002868 aInfo = rInfo != null ? rInfo.activityInfo : null;
2869 } catch (RemoteException e) {
2870 aInfo = null;
2871 }
2872
2873 if (aInfo != null) {
2874 // Store the found target back into the intent, because now that
2875 // we have it we never want to do this again. For example, if the
2876 // user navigates back to this point in the history, we should
2877 // always restart the exact same activity.
2878 intent.setComponent(new ComponentName(
2879 aInfo.applicationInfo.packageName, aInfo.name));
2880
2881 // Don't debug things in the system process
Dianne Hackborna4972e92012-03-14 10:38:05 -07002882 if ((startFlags&ActivityManager.START_FLAG_DEBUG) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002883 if (!aInfo.processName.equals("system")) {
2884 mService.setDebugApp(aInfo.processName, true, false);
2885 }
2886 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002887
Dianne Hackborna4972e92012-03-14 10:38:05 -07002888 if ((startFlags&ActivityManager.START_FLAG_OPENGL_TRACES) != 0) {
Siva Velusamy92a8b222012-03-09 16:24:04 -08002889 if (!aInfo.processName.equals("system")) {
2890 mService.setOpenGlTraceApp(aInfo.applicationInfo, aInfo.processName);
2891 }
2892 }
2893
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002894 if (profileFile != null) {
2895 if (!aInfo.processName.equals("system")) {
2896 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002897 profileFile, profileFd,
2898 (startFlags&ActivityManager.START_FLAG_AUTO_STOP_PROFILER) != 0);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002899 }
2900 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002901 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002902 return aInfo;
2903 }
2904
2905 final int startActivityMayWait(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002906 Intent intent, String resolvedType, IBinder resultTo,
2907 String resultWho, int requestCode, int startFlags, String profileFile,
2908 ParcelFileDescriptor profileFd, WaitResult outResult, Configuration config,
2909 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002910 // Refuse possible leaked file descriptors
2911 if (intent != null && intent.hasFileDescriptors()) {
2912 throw new IllegalArgumentException("File descriptors passed in Intent");
2913 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002914 boolean componentSpecified = intent.getComponent() != null;
2915
2916 // Don't modify the client's object!
2917 intent = new Intent(intent);
2918
2919 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002920 ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002921 profileFile, profileFd, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002922 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002923
2924 synchronized (mService) {
2925 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002926 if (callingUid >= 0) {
2927 callingPid = -1;
2928 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002929 callingPid = Binder.getCallingPid();
2930 callingUid = Binder.getCallingUid();
2931 } else {
2932 callingPid = callingUid = -1;
2933 }
2934
2935 mConfigWillChange = config != null
2936 && mService.mConfiguration.diff(config) != 0;
2937 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2938 "Starting activity when config will change = " + mConfigWillChange);
2939
2940 final long origId = Binder.clearCallingIdentity();
2941
2942 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07002943 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002944 // This may be a heavy-weight process! Check to see if we already
2945 // have another, different heavy-weight process running.
2946 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
2947 if (mService.mHeavyWeightProcess != null &&
2948 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
2949 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
2950 int realCallingPid = callingPid;
2951 int realCallingUid = callingUid;
2952 if (caller != null) {
2953 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
2954 if (callerApp != null) {
2955 realCallingPid = callerApp.pid;
2956 realCallingUid = callerApp.info.uid;
2957 } else {
2958 Slog.w(TAG, "Unable to find app for caller " + caller
2959 + " (pid=" + realCallingPid + ") when starting: "
2960 + intent.toString());
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002961 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002962 return ActivityManager.START_PERMISSION_DENIED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002963 }
2964 }
2965
2966 IIntentSender target = mService.getIntentSenderLocked(
Dianne Hackborna4972e92012-03-14 10:38:05 -07002967 ActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002968 realCallingUid, null, null, 0, new Intent[] { intent },
2969 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002970 | PendingIntent.FLAG_ONE_SHOT, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002971
2972 Intent newIntent = new Intent();
2973 if (requestCode >= 0) {
2974 // Caller is requesting a result.
2975 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
2976 }
2977 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
2978 new IntentSender(target));
2979 if (mService.mHeavyWeightProcess.activities.size() > 0) {
2980 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
2981 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
2982 hist.packageName);
2983 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
2984 hist.task.taskId);
2985 }
2986 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
2987 aInfo.packageName);
2988 newIntent.setFlags(intent.getFlags());
2989 newIntent.setClassName("android",
2990 HeavyWeightSwitcherActivity.class.getName());
2991 intent = newIntent;
2992 resolvedType = null;
2993 caller = null;
2994 callingUid = Binder.getCallingUid();
2995 callingPid = Binder.getCallingPid();
2996 componentSpecified = true;
2997 try {
2998 ResolveInfo rInfo =
2999 AppGlobals.getPackageManager().resolveIntent(
3000 intent, null,
3001 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07003002 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003003 aInfo = rInfo != null ? rInfo.activityInfo : null;
Amith Yamasani742a6712011-05-04 14:49:28 -07003004 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003005 } catch (RemoteException e) {
3006 aInfo = null;
3007 }
3008 }
3009 }
3010 }
3011
3012 int res = startActivityLocked(caller, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003013 aInfo, resultTo, resultWho, requestCode, callingPid, callingUid,
3014 startFlags, options, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003015
3016 if (mConfigWillChange && mMainStack) {
3017 // If the caller also wants to switch to a new configuration,
3018 // do so now. This allows a clean switch, as we are waiting
3019 // for the current activity to pause (so we will not destroy
3020 // it), and have not yet started the next activity.
3021 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
3022 "updateConfiguration()");
3023 mConfigWillChange = false;
3024 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3025 "Updating to new configuration after starting activity.");
Dianne Hackborn813075a62011-11-14 17:45:19 -08003026 mService.updateConfigurationLocked(config, null, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003027 }
3028
3029 Binder.restoreCallingIdentity(origId);
3030
3031 if (outResult != null) {
3032 outResult.result = res;
Dianne Hackborna4972e92012-03-14 10:38:05 -07003033 if (res == ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003034 mWaitingActivityLaunched.add(outResult);
3035 do {
3036 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003037 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003038 } catch (InterruptedException e) {
3039 }
3040 } while (!outResult.timeout && outResult.who == null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003041 } else if (res == ActivityManager.START_TASK_TO_FRONT) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003042 ActivityRecord r = this.topRunningActivityLocked(null);
3043 if (r.nowVisible) {
3044 outResult.timeout = false;
3045 outResult.who = new ComponentName(r.info.packageName, r.info.name);
3046 outResult.totalTime = 0;
3047 outResult.thisTime = 0;
3048 } else {
3049 outResult.thisTime = SystemClock.uptimeMillis();
3050 mWaitingActivityVisible.add(outResult);
3051 do {
3052 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003053 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003054 } catch (InterruptedException e) {
3055 }
3056 } while (!outResult.timeout && outResult.who == null);
3057 }
3058 }
3059 }
3060
3061 return res;
3062 }
3063 }
3064
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003065 final int startActivities(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003066 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
3067 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003068 if (intents == null) {
3069 throw new NullPointerException("intents is null");
3070 }
3071 if (resolvedTypes == null) {
3072 throw new NullPointerException("resolvedTypes is null");
3073 }
3074 if (intents.length != resolvedTypes.length) {
3075 throw new IllegalArgumentException("intents are length different than resolvedTypes");
3076 }
3077
3078 ActivityRecord[] outActivity = new ActivityRecord[1];
3079
3080 int callingPid;
3081 if (callingUid >= 0) {
3082 callingPid = -1;
3083 } else if (caller == null) {
3084 callingPid = Binder.getCallingPid();
3085 callingUid = Binder.getCallingUid();
3086 } else {
3087 callingPid = callingUid = -1;
3088 }
3089 final long origId = Binder.clearCallingIdentity();
3090 try {
3091 synchronized (mService) {
3092
3093 for (int i=0; i<intents.length; i++) {
3094 Intent intent = intents[i];
3095 if (intent == null) {
3096 continue;
3097 }
3098
3099 // Refuse possible leaked file descriptors
3100 if (intent != null && intent.hasFileDescriptors()) {
3101 throw new IllegalArgumentException("File descriptors passed in Intent");
3102 }
3103
3104 boolean componentSpecified = intent.getComponent() != null;
3105
3106 // Don't modify the client's object!
3107 intent = new Intent(intent);
3108
3109 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003110 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i],
Amith Yamasani483f3b02012-03-13 16:08:00 -07003111 0, null, null, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07003112 // TODO: New, check if this is correct
3113 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003114
3115 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
3116 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
3117 throw new IllegalArgumentException(
3118 "FLAG_CANT_SAVE_STATE not supported here");
3119 }
3120
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003121 Bundle theseOptions;
3122 if (options != null && i == intents.length-1) {
3123 theseOptions = options;
3124 } else {
3125 theseOptions = null;
3126 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003127 int res = startActivityLocked(caller, intent, resolvedTypes[i],
Dianne Hackborna4972e92012-03-14 10:38:05 -07003128 aInfo, resultTo, null, -1, callingPid, callingUid,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003129 0, theseOptions, componentSpecified, outActivity);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003130 if (res < 0) {
3131 return res;
3132 }
3133
Dianne Hackbornbe707852011-11-11 14:32:10 -08003134 resultTo = outActivity[0] != null ? outActivity[0].appToken : null;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003135 }
3136 }
3137 } finally {
3138 Binder.restoreCallingIdentity(origId);
3139 }
3140
Dianne Hackborna4972e92012-03-14 10:38:05 -07003141 return ActivityManager.START_SUCCESS;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003142 }
3143
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003144 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
3145 long thisTime, long totalTime) {
3146 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
3147 WaitResult w = mWaitingActivityLaunched.get(i);
3148 w.timeout = timeout;
3149 if (r != null) {
3150 w.who = new ComponentName(r.info.packageName, r.info.name);
3151 }
3152 w.thisTime = thisTime;
3153 w.totalTime = totalTime;
3154 }
3155 mService.notifyAll();
3156 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003157
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003158 void reportActivityVisibleLocked(ActivityRecord r) {
3159 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
3160 WaitResult w = mWaitingActivityVisible.get(i);
3161 w.timeout = false;
3162 if (r != null) {
3163 w.who = new ComponentName(r.info.packageName, r.info.name);
3164 }
3165 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
3166 w.thisTime = w.totalTime;
3167 }
3168 mService.notifyAll();
Dianne Hackborn90c52de2011-09-23 12:57:44 -07003169
3170 if (mDismissKeyguardOnNextActivity) {
3171 mDismissKeyguardOnNextActivity = false;
3172 mService.mWindowManager.dismissKeyguard();
3173 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003174 }
3175
3176 void sendActivityResultLocked(int callingUid, ActivityRecord r,
3177 String resultWho, int requestCode, int resultCode, Intent data) {
3178
3179 if (callingUid > 0) {
3180 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003181 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003182 }
3183
3184 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3185 + " : who=" + resultWho + " req=" + requestCode
3186 + " res=" + resultCode + " data=" + data);
3187 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3188 try {
3189 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3190 list.add(new ResultInfo(resultWho, requestCode,
3191 resultCode, data));
Dianne Hackbornbe707852011-11-11 14:32:10 -08003192 r.app.thread.scheduleSendResult(r.appToken, list);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003193 return;
3194 } catch (Exception e) {
3195 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3196 }
3197 }
3198
3199 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3200 }
3201
3202 private final void stopActivityLocked(ActivityRecord r) {
3203 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3204 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3205 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3206 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003207 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003208 "no-history");
3209 }
3210 } else if (r.app != null && r.app.thread != null) {
3211 if (mMainStack) {
3212 if (mService.mFocusedActivity == r) {
3213 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3214 }
3215 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003216 r.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003217 try {
3218 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003219 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3220 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003221 r.state = ActivityState.STOPPING;
3222 if (DEBUG_VISBILITY) Slog.v(
3223 TAG, "Stopping visible=" + r.visible + " for " + r);
3224 if (!r.visible) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003225 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003226 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003227 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003228 if (mService.isSleeping()) {
3229 r.setSleeping(true);
3230 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003231 } catch (Exception e) {
3232 // Maybe just ignore exceptions here... if the process
3233 // has crashed, our death notification will clean things
3234 // up.
3235 Slog.w(TAG, "Exception thrown during pause", e);
3236 // Just in case, assume it to be stopped.
3237 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003238 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003239 r.state = ActivityState.STOPPED;
3240 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003241 destroyActivityLocked(r, true, false, "stop-except");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003242 }
3243 }
3244 }
3245 }
3246
3247 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3248 boolean remove) {
3249 int N = mStoppingActivities.size();
3250 if (N <= 0) return null;
3251
3252 ArrayList<ActivityRecord> stops = null;
3253
3254 final boolean nowVisible = mResumedActivity != null
3255 && mResumedActivity.nowVisible
3256 && !mResumedActivity.waitingVisible;
3257 for (int i=0; i<N; i++) {
3258 ActivityRecord s = mStoppingActivities.get(i);
3259 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3260 + nowVisible + " waitingVisible=" + s.waitingVisible
3261 + " finishing=" + s.finishing);
3262 if (s.waitingVisible && nowVisible) {
3263 mWaitingVisibleActivities.remove(s);
3264 s.waitingVisible = false;
3265 if (s.finishing) {
3266 // If this activity is finishing, it is sitting on top of
3267 // everyone else but we now know it is no longer needed...
3268 // so get rid of it. Otherwise, we need to go through the
3269 // normal flow and hide it once we determine that it is
3270 // hidden by the activities in front of it.
3271 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003272 mService.mWindowManager.setAppVisibility(s.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003273 }
3274 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003275 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003276 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3277 if (stops == null) {
3278 stops = new ArrayList<ActivityRecord>();
3279 }
3280 stops.add(s);
3281 mStoppingActivities.remove(i);
3282 N--;
3283 i--;
3284 }
3285 }
3286
3287 return stops;
3288 }
3289
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003290 final void scheduleIdleLocked() {
3291 Message msg = Message.obtain();
3292 msg.what = IDLE_NOW_MSG;
3293 mHandler.sendMessage(msg);
3294 }
3295
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003296 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003297 Configuration config) {
3298 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3299
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003300 ActivityRecord res = null;
3301
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003302 ArrayList<ActivityRecord> stops = null;
3303 ArrayList<ActivityRecord> finishes = null;
3304 ArrayList<ActivityRecord> thumbnails = null;
3305 int NS = 0;
3306 int NF = 0;
3307 int NT = 0;
3308 IApplicationThread sendThumbnail = null;
3309 boolean booting = false;
3310 boolean enableScreen = false;
3311
3312 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003313 ActivityRecord r = ActivityRecord.forToken(token);
3314 if (r != null) {
3315 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003316 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003317 }
3318
3319 // Get the activity record.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003320 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003321 if (index >= 0) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003322 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003323
3324 if (fromTimeout) {
3325 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3326 }
3327
3328 // This is a hack to semi-deal with a race condition
3329 // in the client where it can be constructed with a
3330 // newer configuration from when we asked it to launch.
3331 // We'll update with whatever configuration it now says
3332 // it used to launch.
3333 if (config != null) {
3334 r.configuration = config;
3335 }
3336
3337 // No longer need to keep the device awake.
3338 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3339 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3340 mLaunchingActivity.release();
3341 }
3342
3343 // We are now idle. If someone is waiting for a thumbnail from
3344 // us, we can now deliver.
3345 r.idle = true;
3346 mService.scheduleAppGcsLocked();
3347 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3348 sendThumbnail = r.app.thread;
3349 r.thumbnailNeeded = false;
3350 }
3351
3352 // If this activity is fullscreen, set up to hide those under it.
3353
3354 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3355 ensureActivitiesVisibleLocked(null, 0);
3356
3357 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3358 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003359 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003360 mService.mBooted = true;
3361 enableScreen = true;
3362 }
3363 }
3364
3365 } else if (fromTimeout) {
3366 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3367 }
3368
3369 // Atomically retrieve all of the other things to do.
3370 stops = processStoppingActivitiesLocked(true);
3371 NS = stops != null ? stops.size() : 0;
3372 if ((NF=mFinishingActivities.size()) > 0) {
3373 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3374 mFinishingActivities.clear();
3375 }
3376 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3377 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3378 mService.mCancelledThumbnails.clear();
3379 }
3380
3381 if (mMainStack) {
3382 booting = mService.mBooting;
3383 mService.mBooting = false;
3384 }
3385 }
3386
3387 int i;
3388
3389 // Send thumbnail if requested.
3390 if (sendThumbnail != null) {
3391 try {
3392 sendThumbnail.requestThumbnail(token);
3393 } catch (Exception e) {
3394 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3395 mService.sendPendingThumbnail(null, token, null, null, true);
3396 }
3397 }
3398
3399 // Stop any activities that are scheduled to do so but have been
3400 // waiting for the next one to start.
3401 for (i=0; i<NS; i++) {
3402 ActivityRecord r = (ActivityRecord)stops.get(i);
3403 synchronized (mService) {
3404 if (r.finishing) {
3405 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY);
3406 } else {
3407 stopActivityLocked(r);
3408 }
3409 }
3410 }
3411
3412 // Finish any activities that are scheduled to do so but have been
3413 // waiting for the next one to start.
3414 for (i=0; i<NF; i++) {
3415 ActivityRecord r = (ActivityRecord)finishes.get(i);
3416 synchronized (mService) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003417 destroyActivityLocked(r, true, false, "finish-idle");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003418 }
3419 }
3420
3421 // Report back to any thumbnail receivers.
3422 for (i=0; i<NT; i++) {
3423 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3424 mService.sendPendingThumbnail(r, null, null, null, true);
3425 }
3426
3427 if (booting) {
3428 mService.finishBooting();
3429 }
3430
3431 mService.trimApplications();
3432 //dump();
3433 //mWindowManager.dump();
3434
3435 if (enableScreen) {
3436 mService.enableScreenAfterBoot();
3437 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003438
3439 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003440 }
3441
3442 /**
3443 * @return Returns true if the activity is being finished, false if for
3444 * some reason it is being left as-is.
3445 */
3446 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
3447 Intent resultData, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003448 int index = indexOfTokenLocked(token);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003449 if (DEBUG_RESULTS) Slog.v(
3450 TAG, "Finishing activity @" + index + ": token=" + token
3451 + ", result=" + resultCode + ", data=" + resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003452 if (index < 0) {
3453 return false;
3454 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003455 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003456
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003457 finishActivityLocked(r, index, resultCode, resultData, reason);
3458 return true;
3459 }
3460
Dianne Hackborn5c607432012-02-28 14:44:19 -08003461 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
3462 // send the result
3463 ActivityRecord resultTo = r.resultTo;
3464 if (resultTo != null) {
3465 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3466 + " who=" + r.resultWho + " req=" + r.requestCode
3467 + " res=" + resultCode + " data=" + resultData);
3468 if (r.info.applicationInfo.uid > 0) {
3469 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3470 resultTo.packageName, resultData,
3471 resultTo.getUriPermissionsLocked());
3472 }
3473 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3474 resultData);
3475 r.resultTo = null;
3476 }
3477 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3478
3479 // Make sure this HistoryRecord is not holding on to other resources,
3480 // because clients have remote IPC references to this object so we
3481 // can't assume that will go away and want to avoid circular IPC refs.
3482 r.results = null;
3483 r.pendingResults = null;
3484 r.newIntents = null;
3485 r.icicle = null;
3486 }
3487
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003488 /**
3489 * @return Returns true if this activity has been removed from the history
3490 * list, or false if it is still in the list and will be removed later.
3491 */
3492 final boolean finishActivityLocked(ActivityRecord r, int index,
3493 int resultCode, Intent resultData, String reason) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003494 return finishActivityLocked(r, index, resultCode, resultData, reason, false);
3495 }
3496
3497 /**
3498 * @return Returns true if this activity has been removed from the history
3499 * list, or false if it is still in the list and will be removed later.
3500 */
3501 final boolean finishActivityLocked(ActivityRecord r, int index,
3502 int resultCode, Intent resultData, String reason, boolean immediate) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003503 if (r.finishing) {
3504 Slog.w(TAG, "Duplicate finish request for " + r);
3505 return false;
3506 }
3507
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003508 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003509 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3510 System.identityHashCode(r),
3511 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003512 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003513 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003514 if (next.task == r.task) {
3515 if (r.frontOfTask) {
3516 // The next activity is now the front of the task.
3517 next.frontOfTask = true;
3518 }
3519 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3520 // If the caller asked that this activity (and all above it)
3521 // be cleared when the task is reset, don't lose that information,
3522 // but propagate it up to the next activity.
3523 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3524 }
3525 }
3526 }
3527
3528 r.pauseKeyDispatchingLocked();
3529 if (mMainStack) {
3530 if (mService.mFocusedActivity == r) {
3531 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3532 }
3533 }
3534
Dianne Hackborn5c607432012-02-28 14:44:19 -08003535 finishActivityResultsLocked(r, resultCode, resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003536
3537 if (mService.mPendingThumbnails.size() > 0) {
3538 // There are clients waiting to receive thumbnails so, in case
3539 // this is an activity that someone is waiting for, add it
3540 // to the pending list so we can correctly update the clients.
3541 mService.mCancelledThumbnails.add(r);
3542 }
3543
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003544 if (immediate) {
3545 return finishCurrentActivityLocked(r, index,
3546 FINISH_IMMEDIATELY) == null;
3547 } else if (mResumedActivity == r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003548 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003549 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003550 if (DEBUG_TRANSITION) Slog.v(TAG,
3551 "Prepare close transition: finishing " + r);
3552 mService.mWindowManager.prepareAppTransition(endTask
3553 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003554 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003555
3556 // Tell window manager to prepare for this one to be removed.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003557 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003558
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003559 if (mPausingActivity == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003560 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3561 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3562 startPausingLocked(false, false);
3563 }
3564
3565 } else if (r.state != ActivityState.PAUSING) {
3566 // If the activity is PAUSING, we will complete the finish once
3567 // it is done pausing; else we can just directly finish it here.
3568 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3569 return finishCurrentActivityLocked(r, index,
3570 FINISH_AFTER_PAUSE) == null;
3571 } else {
3572 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3573 }
3574
3575 return false;
3576 }
3577
3578 private static final int FINISH_IMMEDIATELY = 0;
3579 private static final int FINISH_AFTER_PAUSE = 1;
3580 private static final int FINISH_AFTER_VISIBLE = 2;
3581
3582 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3583 int mode) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003584 final int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003585 if (index < 0) {
3586 return null;
3587 }
3588
3589 return finishCurrentActivityLocked(r, index, mode);
3590 }
3591
3592 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3593 int index, int mode) {
3594 // First things first: if this activity is currently visible,
3595 // and the resumed activity is not yet visible, then hold off on
3596 // finishing until the resumed one becomes visible.
3597 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3598 if (!mStoppingActivities.contains(r)) {
3599 mStoppingActivities.add(r);
3600 if (mStoppingActivities.size() > 3) {
3601 // If we already have a few activities waiting to stop,
3602 // then give up on things going idle and start clearing
3603 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003604 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003605 } else {
3606 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003607 }
3608 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003609 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3610 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003611 r.state = ActivityState.STOPPING;
3612 mService.updateOomAdjLocked();
3613 return r;
3614 }
3615
3616 // make sure the record is cleaned out of other places.
3617 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003618 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003619 mWaitingVisibleActivities.remove(r);
3620 if (mResumedActivity == r) {
3621 mResumedActivity = null;
3622 }
3623 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003624 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003625 r.state = ActivityState.FINISHING;
3626
3627 if (mode == FINISH_IMMEDIATELY
3628 || prevState == ActivityState.STOPPED
3629 || prevState == ActivityState.INITIALIZING) {
3630 // If this activity is already stopped, we can just finish
3631 // it right now.
Dianne Hackborn28695e02011-11-02 21:59:51 -07003632 return destroyActivityLocked(r, true, true, "finish-imm") ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003633 } else {
3634 // Need to go through the full pause cycle to get this
3635 // activity into the stopped state and then finish it.
3636 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3637 mFinishingActivities.add(r);
3638 resumeTopActivityLocked(null);
3639 }
3640 return r;
3641 }
3642
3643 /**
3644 * Perform the common clean-up of an activity record. This is called both
3645 * as part of destroyActivityLocked() (when destroying the client-side
3646 * representation) and cleaning things up as a result of its hosting
3647 * processing going away, in which case there is no remaining client-side
3648 * state to destroy so only the cleanup here is needed.
3649 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003650 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3651 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003652 if (mResumedActivity == r) {
3653 mResumedActivity = null;
3654 }
3655 if (mService.mFocusedActivity == r) {
3656 mService.mFocusedActivity = null;
3657 }
3658
3659 r.configDestroy = false;
3660 r.frozenBeforeDestroy = false;
3661
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003662 if (setState) {
3663 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3664 r.state = ActivityState.DESTROYED;
3665 }
3666
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003667 // Make sure this record is no longer in the pending finishes list.
3668 // This could happen, for example, if we are trimming activities
3669 // down to the max limit while they are still waiting to finish.
3670 mFinishingActivities.remove(r);
3671 mWaitingVisibleActivities.remove(r);
3672
3673 // Remove any pending results.
3674 if (r.finishing && r.pendingResults != null) {
3675 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3676 PendingIntentRecord rec = apr.get();
3677 if (rec != null) {
3678 mService.cancelIntentSenderLocked(rec, false);
3679 }
3680 }
3681 r.pendingResults = null;
3682 }
3683
3684 if (cleanServices) {
3685 cleanUpActivityServicesLocked(r);
3686 }
3687
3688 if (mService.mPendingThumbnails.size() > 0) {
3689 // There are clients waiting to receive thumbnails so, in case
3690 // this is an activity that someone is waiting for, add it
3691 // to the pending list so we can correctly update the clients.
3692 mService.mCancelledThumbnails.add(r);
3693 }
3694
3695 // Get rid of any pending idle timeouts.
3696 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
3697 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003698 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003699 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003700 }
3701
Dianne Hackborn5c607432012-02-28 14:44:19 -08003702 final void removeActivityFromHistoryLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003703 if (r.state != ActivityState.DESTROYED) {
Dianne Hackborn5c607432012-02-28 14:44:19 -08003704 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003705 r.makeFinishing();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003706 if (DEBUG_ADD_REMOVE) {
3707 RuntimeException here = new RuntimeException("here");
3708 here.fillInStackTrace();
3709 Slog.i(TAG, "Removing activity " + r + " from stack");
3710 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003711 mHistory.remove(r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003712 r.takeFromHistory();
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003713 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3714 + " (removed from history)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003715 r.state = ActivityState.DESTROYED;
Dianne Hackbornbe707852011-11-11 14:32:10 -08003716 mService.mWindowManager.removeAppToken(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003717 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003718 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003719 }
3720 cleanUpActivityServicesLocked(r);
3721 r.removeUriPermissionsLocked();
3722 }
3723 }
3724
3725 /**
3726 * Perform clean-up of service connections in an activity record.
3727 */
3728 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3729 // Throw away any services that have been bound by this activity.
3730 if (r.connections != null) {
3731 Iterator<ConnectionRecord> it = r.connections.iterator();
3732 while (it.hasNext()) {
3733 ConnectionRecord c = it.next();
3734 mService.removeConnectionLocked(c, null, r);
3735 }
3736 r.connections = null;
3737 }
3738 }
3739
Dianne Hackborn28695e02011-11-02 21:59:51 -07003740 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003741 for (int i=mHistory.size()-1; i>=0; i--) {
3742 ActivityRecord r = mHistory.get(i);
3743 if (owner != null && r.app != owner) {
3744 continue;
3745 }
3746 // We can destroy this one if we have its icicle saved and
3747 // it is not in the process of pausing/stopping/finishing.
3748 if (r.app != null && r.haveState && !r.visible && r.stopped && !r.finishing
3749 && r.state != ActivityState.DESTROYING
3750 && r.state != ActivityState.DESTROYED) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003751 destroyActivityLocked(r, true, oomAdj, "trim");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003752 }
3753 }
3754 }
3755
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003756 /**
3757 * Destroy the current CLIENT SIDE instance of an activity. This may be
3758 * called both when actually finishing an activity, or when performing
3759 * a configuration switch where we destroy the current client-side object
3760 * but then create a new client-side object for this same HistoryRecord.
3761 */
3762 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackborn28695e02011-11-02 21:59:51 -07003763 boolean removeFromApp, boolean oomAdj, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003764 if (DEBUG_SWITCH) Slog.v(
3765 TAG, "Removing activity: token=" + r
3766 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3767 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3768 System.identityHashCode(r),
Dianne Hackborn28695e02011-11-02 21:59:51 -07003769 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003770
3771 boolean removedFromHistory = false;
3772
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003773 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003774
3775 final boolean hadApp = r.app != null;
3776
3777 if (hadApp) {
3778 if (removeFromApp) {
3779 int idx = r.app.activities.indexOf(r);
3780 if (idx >= 0) {
3781 r.app.activities.remove(idx);
3782 }
3783 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
3784 mService.mHeavyWeightProcess = null;
3785 mService.mHandler.sendEmptyMessage(
3786 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
3787 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003788 if (r.app.activities.size() == 0) {
3789 // No longer have activities, so update location in
3790 // LRU list.
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003791 mService.updateLruProcessLocked(r.app, oomAdj, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003792 }
3793 }
3794
3795 boolean skipDestroy = false;
3796
3797 try {
3798 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003799 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003800 r.configChangeFlags);
3801 } catch (Exception e) {
3802 // We can just ignore exceptions here... if the process
3803 // has crashed, our death notification will clean things
3804 // up.
3805 //Slog.w(TAG, "Exception thrown during finish", e);
3806 if (r.finishing) {
3807 removeActivityFromHistoryLocked(r);
3808 removedFromHistory = true;
3809 skipDestroy = true;
3810 }
3811 }
3812
3813 r.app = null;
3814 r.nowVisible = false;
3815
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003816 // If the activity is finishing, we need to wait on removing it
3817 // from the list to give it a chance to do its cleanup. During
3818 // that time it may make calls back with its token so we need to
3819 // be able to find it on the list and so we don't want to remove
3820 // it from the list yet. Otherwise, we can just immediately put
3821 // it in the destroyed state since we are not removing it from the
3822 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003823 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003824 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
3825 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003826 r.state = ActivityState.DESTROYING;
3827 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
3828 msg.obj = r;
3829 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
3830 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003831 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3832 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003833 r.state = ActivityState.DESTROYED;
3834 }
3835 } else {
3836 // remove this record from the history.
3837 if (r.finishing) {
3838 removeActivityFromHistoryLocked(r);
3839 removedFromHistory = true;
3840 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003841 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3842 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003843 r.state = ActivityState.DESTROYED;
3844 }
3845 }
3846
3847 r.configChangeFlags = 0;
3848
3849 if (!mLRUActivities.remove(r) && hadApp) {
3850 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
3851 }
3852
3853 return removedFromHistory;
3854 }
3855
3856 final void activityDestroyed(IBinder token) {
3857 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003858 ActivityRecord r = ActivityRecord.forToken(token);
3859 if (r != null) {
3860 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
3861 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003862
Dianne Hackbornbe707852011-11-11 14:32:10 -08003863 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003864 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003865 if (r.state == ActivityState.DESTROYING) {
3866 final long origId = Binder.clearCallingIdentity();
3867 removeActivityFromHistoryLocked(r);
3868 Binder.restoreCallingIdentity(origId);
3869 }
3870 }
3871 }
3872 }
3873
3874 private static void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
3875 int i = list.size();
3876 if (localLOGV) Slog.v(
3877 TAG, "Removing app " + app + " from list " + list
3878 + " with " + i + " entries");
3879 while (i > 0) {
3880 i--;
3881 ActivityRecord r = (ActivityRecord)list.get(i);
3882 if (localLOGV) Slog.v(
3883 TAG, "Record #" + i + " " + r + ": app=" + r.app);
3884 if (r.app == app) {
3885 if (localLOGV) Slog.v(TAG, "Removing this entry!");
3886 list.remove(i);
3887 }
3888 }
3889 }
3890
3891 void removeHistoryRecordsForAppLocked(ProcessRecord app) {
3892 removeHistoryRecordsForAppLocked(mLRUActivities, app);
3893 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003894 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003895 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
3896 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
3897 }
3898
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003899 /**
3900 * Move the current home activity's task (if one exists) to the front
3901 * of the stack.
3902 */
3903 final void moveHomeToFrontLocked() {
3904 TaskRecord homeTask = null;
3905 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003906 ActivityRecord hr = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003907 if (hr.isHomeActivity) {
3908 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003909 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003910 }
3911 }
3912 if (homeTask != null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003913 moveTaskToFrontLocked(homeTask, null, null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003914 }
3915 }
3916
3917
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003918 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003919 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
3920
3921 final int task = tr.taskId;
3922 int top = mHistory.size()-1;
3923
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003924 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003925 // nothing to do!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003926 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003927 return;
3928 }
3929
Dianne Hackbornbe707852011-11-11 14:32:10 -08003930 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003931
3932 // Applying the affinities may have removed entries from the history,
3933 // so get the size again.
3934 top = mHistory.size()-1;
3935 int pos = top;
3936
3937 // Shift all activities with this task up to the top
3938 // of the stack, keeping them in the same internal order.
3939 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003940 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003941 if (localLOGV) Slog.v(
3942 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003943 if (r.task.taskId == task) {
3944 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003945 if (DEBUG_ADD_REMOVE) {
3946 RuntimeException here = new RuntimeException("here");
3947 here.fillInStackTrace();
3948 Slog.i(TAG, "Removing and adding activity " + r + " to stack at " + top, here);
3949 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003950 mHistory.remove(pos);
3951 mHistory.add(top, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003952 moved.add(0, r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003953 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003954 }
3955 pos--;
3956 }
3957
3958 if (DEBUG_TRANSITION) Slog.v(TAG,
3959 "Prepare to front transition: task=" + tr);
3960 if (reason != null &&
3961 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003962 mService.mWindowManager.prepareAppTransition(
3963 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003964 ActivityRecord r = topRunningActivityLocked(null);
3965 if (r != null) {
3966 mNoAnimActivities.add(r);
3967 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003968 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003969 } else {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003970 if (options != null) {
3971 ActivityRecord r = topRunningActivityLocked(null);
3972 if (r != null && r.state != ActivityState.RESUMED) {
3973 r.updateOptionsLocked(options);
3974 } else {
3975 ActivityOptions.abort(options);
3976 }
3977 }
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003978 mService.mWindowManager.prepareAppTransition(
3979 WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003980 }
3981
3982 mService.mWindowManager.moveAppTokensToTop(moved);
3983 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003984 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003985 }
3986
3987 finishTaskMoveLocked(task);
3988 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
3989 }
3990
3991 private final void finishTaskMoveLocked(int task) {
3992 resumeTopActivityLocked(null);
3993 }
3994
3995 /**
3996 * Worker method for rearranging history stack. Implements the function of moving all
3997 * activities for a specific task (gathering them if disjoint) into a single group at the
3998 * bottom of the stack.
3999 *
4000 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
4001 * to premeptively cancel the move.
4002 *
4003 * @param task The taskId to collect and move to the bottom.
4004 * @return Returns true if the move completed, false if not.
4005 */
4006 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
4007 Slog.i(TAG, "moveTaskToBack: " + task);
4008
4009 // If we have a watcher, preflight the move before committing to it. First check
4010 // for *other* available tasks, but if none are available, then try again allowing the
4011 // current task to be selected.
4012 if (mMainStack && mService.mController != null) {
4013 ActivityRecord next = topRunningActivityLocked(null, task);
4014 if (next == null) {
4015 next = topRunningActivityLocked(null, 0);
4016 }
4017 if (next != null) {
4018 // ask watcher if this is allowed
4019 boolean moveOK = true;
4020 try {
4021 moveOK = mService.mController.activityResuming(next.packageName);
4022 } catch (RemoteException e) {
4023 mService.mController = null;
4024 }
4025 if (!moveOK) {
4026 return false;
4027 }
4028 }
4029 }
4030
Dianne Hackbornbe707852011-11-11 14:32:10 -08004031 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004032
4033 if (DEBUG_TRANSITION) Slog.v(TAG,
4034 "Prepare to back transition: task=" + task);
4035
4036 final int N = mHistory.size();
4037 int bottom = 0;
4038 int pos = 0;
4039
4040 // Shift all activities with this task down to the bottom
4041 // of the stack, keeping them in the same internal order.
4042 while (pos < N) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004043 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004044 if (localLOGV) Slog.v(
4045 TAG, "At " + pos + " ckp " + r.task + ": " + r);
4046 if (r.task.taskId == task) {
4047 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004048 if (DEBUG_ADD_REMOVE) {
4049 RuntimeException here = new RuntimeException("here");
4050 here.fillInStackTrace();
4051 Slog.i(TAG, "Removing and adding activity " + r + " to stack at "
4052 + bottom, here);
4053 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004054 mHistory.remove(pos);
4055 mHistory.add(bottom, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004056 moved.add(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004057 bottom++;
4058 }
4059 pos++;
4060 }
4061
4062 if (reason != null &&
4063 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004064 mService.mWindowManager.prepareAppTransition(
4065 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004066 ActivityRecord r = topRunningActivityLocked(null);
4067 if (r != null) {
4068 mNoAnimActivities.add(r);
4069 }
4070 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004071 mService.mWindowManager.prepareAppTransition(
4072 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004073 }
4074 mService.mWindowManager.moveAppTokensToBottom(moved);
4075 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004076 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004077 }
4078
4079 finishTaskMoveLocked(task);
4080 return true;
4081 }
4082
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004083 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
4084 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4085 ActivityRecord resumed = mResumedActivity;
4086 if (resumed != null && resumed.thumbHolder == tr) {
4087 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
4088 } else {
4089 info.mainThumbnail = tr.lastThumbnail;
4090 }
4091 return info;
4092 }
4093
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004094 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex,
4095 boolean taskRequired) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004096 TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
4097 if (info.root == null) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004098 if (taskRequired) {
4099 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
4100 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004101 return null;
4102 }
4103
4104 if (subTaskIndex < 0) {
4105 // Just remove the entire task.
4106 performClearTaskAtIndexLocked(taskId, info.rootIndex);
4107 return info.root;
4108 }
4109
4110 if (subTaskIndex >= info.subtasks.size()) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004111 if (taskRequired) {
4112 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
4113 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004114 return null;
4115 }
4116
4117 // Remove all of this task's activies starting at the sub task.
4118 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
4119 performClearTaskAtIndexLocked(taskId, subtask.index);
4120 return subtask.activity;
4121 }
4122
4123 public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
4124 ActivityRecord resumed = mResumedActivity;
4125 final TaskAccessInfo thumbs = new TaskAccessInfo();
4126 // How many different sub-thumbnails?
4127 final int NA = mHistory.size();
4128 int j = 0;
4129 ThumbnailHolder holder = null;
4130 while (j < NA) {
4131 ActivityRecord ar = mHistory.get(j);
4132 if (!ar.finishing && ar.task.taskId == taskId) {
4133 holder = ar.thumbHolder;
4134 break;
4135 }
4136 j++;
4137 }
4138
4139 if (j >= NA) {
4140 return thumbs;
4141 }
4142
4143 thumbs.root = mHistory.get(j);
4144 thumbs.rootIndex = j;
4145
4146 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
4147 thumbs.subtasks = subtasks;
4148 ActivityRecord lastActivity = null;
4149 while (j < NA) {
4150 ActivityRecord ar = mHistory.get(j);
4151 j++;
4152 if (ar.finishing) {
4153 continue;
4154 }
4155 if (ar.task.taskId != taskId) {
4156 break;
4157 }
4158 lastActivity = ar;
4159 if (ar.thumbHolder != holder && holder != null) {
4160 thumbs.numSubThumbbails++;
4161 holder = ar.thumbHolder;
4162 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
4163 sub.thumbnail = holder.lastThumbnail;
4164 sub.activity = ar;
4165 sub.index = j-1;
4166 subtasks.add(sub);
4167 }
4168 }
4169 if (lastActivity != null && subtasks.size() > 0) {
4170 if (resumed == lastActivity) {
4171 TaskAccessInfo.SubTask sub = subtasks.get(subtasks.size()-1);
4172 sub.thumbnail = lastActivity.stack.screenshotActivities(lastActivity);
4173 }
4174 }
4175 if (thumbs.numSubThumbbails > 0) {
4176 thumbs.retriever = new IThumbnailRetriever.Stub() {
4177 public Bitmap getThumbnail(int index) {
4178 if (index < 0 || index >= thumbs.subtasks.size()) {
4179 return null;
4180 }
4181 return thumbs.subtasks.get(index).thumbnail;
4182 }
4183 };
4184 }
4185 return thumbs;
4186 }
4187
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004188 private final void logStartActivity(int tag, ActivityRecord r,
4189 TaskRecord task) {
4190 EventLog.writeEvent(tag,
4191 System.identityHashCode(r), task.taskId,
4192 r.shortComponentName, r.intent.getAction(),
4193 r.intent.getType(), r.intent.getDataString(),
4194 r.intent.getFlags());
4195 }
4196
4197 /**
4198 * Make sure the given activity matches the current configuration. Returns
4199 * false if the activity had to be destroyed. Returns true if the
4200 * configuration is the same, or the activity will remain running as-is
4201 * for whatever reason. Ensures the HistoryRecord is updated with the
4202 * correct configuration and all other bookkeeping is handled.
4203 */
4204 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
4205 int globalChanges) {
4206 if (mConfigWillChange) {
4207 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4208 "Skipping config check (will change): " + r);
4209 return true;
4210 }
4211
4212 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4213 "Ensuring correct configuration: " + r);
4214
4215 // Short circuit: if the two configurations are the exact same
4216 // object (the common case), then there is nothing to do.
4217 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004218 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004219 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4220 "Configuration unchanged in " + r);
4221 return true;
4222 }
4223
4224 // We don't worry about activities that are finishing.
4225 if (r.finishing) {
4226 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4227 "Configuration doesn't matter in finishing " + r);
4228 r.stopFreezingScreenLocked(false);
4229 return true;
4230 }
4231
4232 // Okay we now are going to make this activity have the new config.
4233 // But then we need to figure out how it needs to deal with that.
4234 Configuration oldConfig = r.configuration;
4235 r.configuration = newConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004236
4237 // Determine what has changed. May be nothing, if this is a config
4238 // that has come back from the app after going idle. In that case
4239 // we just want to leave the official config object now in the
4240 // activity and do nothing else.
4241 final int changes = oldConfig.diff(newConfig);
4242 if (changes == 0 && !r.forceNewConfig) {
4243 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4244 "Configuration no differences in " + r);
4245 return true;
4246 }
4247
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004248 // If the activity isn't currently running, just leave the new
4249 // configuration and it will pick that up next time it starts.
4250 if (r.app == null || r.app.thread == null) {
4251 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4252 "Configuration doesn't matter not running " + r);
4253 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004254 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004255 return true;
4256 }
4257
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004258 // Figure out how to handle the changes between the configurations.
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004259 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4260 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
4261 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07004262 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004263 + ", newConfig=" + newConfig);
4264 }
Dianne Hackborne6676352011-06-01 16:51:20 -07004265 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004266 // Aha, the activity isn't handling the change, so DIE DIE DIE.
4267 r.configChangeFlags |= changes;
4268 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004269 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004270 if (r.app == null || r.app.thread == null) {
4271 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4272 "Switch is destroying non-running " + r);
Dianne Hackborn28695e02011-11-02 21:59:51 -07004273 destroyActivityLocked(r, true, false, "config");
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004274 } else if (r.state == ActivityState.PAUSING) {
4275 // A little annoying: we are waiting for this activity to
4276 // finish pausing. Let's not do anything now, but just
4277 // flag that it needs to be restarted when done pausing.
4278 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4279 "Switch is skipping already pausing " + r);
4280 r.configDestroy = true;
4281 return true;
4282 } else if (r.state == ActivityState.RESUMED) {
4283 // Try to optimize this case: the configuration is changing
4284 // and we need to restart the top, resumed activity.
4285 // Instead of doing the normal handshaking, just say
4286 // "restart!".
4287 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4288 "Switch is restarting resumed " + r);
4289 relaunchActivityLocked(r, r.configChangeFlags, true);
4290 r.configChangeFlags = 0;
4291 } else {
4292 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4293 "Switch is restarting non-resumed " + r);
4294 relaunchActivityLocked(r, r.configChangeFlags, false);
4295 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004296 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004297
4298 // All done... tell the caller we weren't able to keep this
4299 // activity around.
4300 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004301 }
4302
4303 // Default case: the activity can handle this new configuration, so
4304 // hand it over. Note that we don't need to give it the new
4305 // configuration, since we always send configuration changes to all
4306 // process when they happen so it can just use whatever configuration
4307 // it last got.
4308 if (r.app != null && r.app.thread != null) {
4309 try {
4310 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004311 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004312 } catch (RemoteException e) {
4313 // If process died, whatever.
4314 }
4315 }
4316 r.stopFreezingScreenLocked(false);
4317
4318 return true;
4319 }
4320
4321 private final boolean relaunchActivityLocked(ActivityRecord r,
4322 int changes, boolean andResume) {
4323 List<ResultInfo> results = null;
4324 List<Intent> newIntents = null;
4325 if (andResume) {
4326 results = r.results;
4327 newIntents = r.newIntents;
4328 }
4329 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4330 + " with results=" + results + " newIntents=" + newIntents
4331 + " andResume=" + andResume);
4332 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
4333 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
4334 r.task.taskId, r.shortComponentName);
4335
4336 r.startFreezingScreenLocked(r.app, 0);
4337
4338 try {
4339 if (DEBUG_SWITCH) Slog.i(TAG, "Switch is restarting resumed " + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004340 r.forceNewConfig = false;
Dianne Hackbornbe707852011-11-11 14:32:10 -08004341 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004342 changes, !andResume, new Configuration(mService.mConfiguration));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004343 // Note: don't need to call pauseIfSleepingLocked() here, because
4344 // the caller will only pass in 'andResume' if this activity is
4345 // currently resumed, which implies we aren't sleeping.
4346 } catch (RemoteException e) {
4347 return false;
4348 }
4349
4350 if (andResume) {
4351 r.results = null;
4352 r.newIntents = null;
4353 if (mMainStack) {
4354 mService.reportResumedActivityLocked(r);
4355 }
4356 }
4357
4358 return true;
4359 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004360
4361 public void dismissKeyguardOnNextActivityLocked() {
4362 mDismissKeyguardOnNextActivity = true;
4363 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004364}