blob: 6596e1fd28fad050f2dfd51f1ed6ccbf99c76b73 [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 Hackborn162bc0e2012-04-09 14:06:16 -0700100 // How long we wait for the activity to tell us it has stopped before
101 // giving up. This is a good amount of time because we really need this
102 // from the application in order to get its saved state.
103 static final int STOP_TIMEOUT = 10*1000;
104
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800105 // How long we can hold the sleep wake lock before giving up.
106 static final int SLEEP_TIMEOUT = 5*1000;
107
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700108 // How long we can hold the launch wake lock before giving up.
109 static final int LAUNCH_TIMEOUT = 10*1000;
110
111 // How long we wait until giving up on an activity telling us it has
112 // finished destroying itself.
113 static final int DESTROY_TIMEOUT = 10*1000;
114
115 // How long until we reset a task when the user returns to it. Currently
Dianne Hackborn621e17d2010-11-22 15:59:56 -0800116 // disabled.
117 static final long ACTIVITY_INACTIVE_RESET_TIME = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700118
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700119 // How long between activity launches that we consider safe to not warn
120 // the user about an unexpected activity being launched on top.
121 static final long START_WARN_TIME = 5*1000;
122
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700123 // Set to false to disable the preview that is shown while a new activity
124 // is being started.
125 static final boolean SHOW_APP_STARTING_PREVIEW = true;
126
127 enum ActivityState {
128 INITIALIZING,
129 RESUMED,
130 PAUSING,
131 PAUSED,
132 STOPPING,
133 STOPPED,
134 FINISHING,
135 DESTROYING,
136 DESTROYED
137 }
138
139 final ActivityManagerService mService;
140 final boolean mMainStack;
141
142 final Context mContext;
143
144 /**
145 * The back history of all previous (and possibly still
146 * running) activities. It contains HistoryRecord objects.
147 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700148 final ArrayList<ActivityRecord> mHistory = new ArrayList<ActivityRecord>();
Dianne Hackbornbe707852011-11-11 14:32:10 -0800149
150 /**
151 * Used for validating app tokens with window manager.
152 */
153 final ArrayList<IBinder> mValidateAppTokens = new ArrayList<IBinder>();
154
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700155 /**
156 * List of running activities, sorted by recent usage.
157 * The first entry in the list is the least recently used.
158 * It contains HistoryRecord objects.
159 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700160 final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700161
162 /**
163 * List of activities that are waiting for a new activity
164 * to become visible before completing whatever operation they are
165 * supposed to do.
166 */
167 final ArrayList<ActivityRecord> mWaitingVisibleActivities
168 = new ArrayList<ActivityRecord>();
169
170 /**
171 * List of activities that are ready to be stopped, but waiting
172 * for the next activity to settle down before doing so. It contains
173 * HistoryRecord objects.
174 */
175 final ArrayList<ActivityRecord> mStoppingActivities
176 = new ArrayList<ActivityRecord>();
177
178 /**
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800179 * List of activities that are in the process of going to sleep.
180 */
181 final ArrayList<ActivityRecord> mGoingToSleepActivities
182 = new ArrayList<ActivityRecord>();
183
184 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700185 * Animations that for the current transition have requested not to
186 * be considered for the transition animation.
187 */
188 final ArrayList<ActivityRecord> mNoAnimActivities
189 = new ArrayList<ActivityRecord>();
190
191 /**
192 * List of activities that are ready to be finished, but waiting
193 * for the previous activity to settle down before doing so. It contains
194 * HistoryRecord objects.
195 */
196 final ArrayList<ActivityRecord> mFinishingActivities
197 = new ArrayList<ActivityRecord>();
198
199 /**
200 * List of people waiting to find out about the next launched activity.
201 */
202 final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched
203 = new ArrayList<IActivityManager.WaitResult>();
204
205 /**
206 * List of people waiting to find out about the next visible activity.
207 */
208 final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible
209 = new ArrayList<IActivityManager.WaitResult>();
210
211 /**
212 * Set when the system is going to sleep, until we have
213 * successfully paused the current activity and released our wake lock.
214 * At that point the system is allowed to actually sleep.
215 */
216 final PowerManager.WakeLock mGoingToSleep;
217
218 /**
219 * We don't want to allow the device to go to sleep while in the process
220 * of launching an activity. This is primarily to allow alarm intent
221 * receivers to launch an activity and get that to run before the device
222 * goes back to sleep.
223 */
224 final PowerManager.WakeLock mLaunchingActivity;
225
226 /**
227 * When we are in the process of pausing an activity, before starting the
228 * next one, this variable holds the activity that is currently being paused.
229 */
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800230 ActivityRecord mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700231
232 /**
233 * This is the last activity that we put into the paused state. This is
234 * used to determine if we need to do an activity transition while sleeping,
235 * when we normally hold the top activity paused.
236 */
237 ActivityRecord mLastPausedActivity = null;
238
239 /**
240 * Current activity that is resumed, or null if there is none.
241 */
242 ActivityRecord mResumedActivity = null;
243
244 /**
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700245 * This is the last activity that has been started. It is only used to
246 * identify when multiple activities are started at once so that the user
247 * can be warned they may not be in the activity they think they are.
248 */
249 ActivityRecord mLastStartedActivity = null;
250
251 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700252 * Set when we know we are going to be calling updateConfiguration()
253 * soon, so want to skip intermediate config checks.
254 */
255 boolean mConfigWillChange;
256
257 /**
258 * Set to indicate whether to issue an onUserLeaving callback when a
259 * newly launched activity is being brought in front of us.
260 */
261 boolean mUserLeaving = false;
262
263 long mInitialStartTime = 0;
264
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800265 /**
266 * Set when we have taken too long waiting to go to sleep.
267 */
268 boolean mSleepTimeout = false;
269
Dianne Hackborn90c52de2011-09-23 12:57:44 -0700270 /**
271 * Dismiss the keyguard after the next activity is displayed?
272 */
273 boolean mDismissKeyguardOnNextActivity = false;
274
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800275 int mThumbnailWidth = -1;
276 int mThumbnailHeight = -1;
277
Amith Yamasani742a6712011-05-04 14:49:28 -0700278 private int mCurrentUser;
279
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800280 static final int SLEEP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG;
281 static final int PAUSE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 1;
282 static final int IDLE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 2;
283 static final int IDLE_NOW_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 3;
284 static final int LAUNCH_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 4;
285 static final int DESTROY_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 5;
286 static final int RESUME_TOP_ACTIVITY_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 6;
Dianne Hackborn29ba7e62012-03-16 15:03:36 -0700287 static final int LAUNCH_TICK_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 7;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700288 static final int STOP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 8;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700289
290 final Handler mHandler = new Handler() {
291 //public Handler() {
292 // if (localLOGV) Slog.v(TAG, "Handler started!");
293 //}
294
295 public void handleMessage(Message msg) {
296 switch (msg.what) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800297 case SLEEP_TIMEOUT_MSG: {
Dianne Hackborn8e8d65f2011-08-11 19:36:18 -0700298 synchronized (mService) {
299 if (mService.isSleeping()) {
300 Slog.w(TAG, "Sleep timeout! Sleeping now.");
301 mSleepTimeout = true;
302 checkReadyForSleepLocked();
303 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800304 }
305 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700306 case PAUSE_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800307 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700308 // We don't at this point know if the activity is fullscreen,
309 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800310 Slog.w(TAG, "Activity pause timeout for " + r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700311 synchronized (mService) {
312 if (r.app != null) {
313 mService.logAppTooSlow(r.app, r.pauseTime,
314 "pausing " + r);
315 }
316 }
317
Dianne Hackbornbe707852011-11-11 14:32:10 -0800318 activityPaused(r != null ? r.appToken : null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700319 } break;
320 case IDLE_TIMEOUT_MSG: {
321 if (mService.mDidDexOpt) {
322 mService.mDidDexOpt = false;
323 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
324 nmsg.obj = msg.obj;
325 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
326 return;
327 }
328 // We don't at this point know if the activity is fullscreen,
329 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800330 ActivityRecord r = (ActivityRecord)msg.obj;
331 Slog.w(TAG, "Activity idle timeout for " + r);
332 activityIdleInternal(r != null ? r.appToken : null, true, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700333 } break;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700334 case LAUNCH_TICK_MSG: {
335 ActivityRecord r = (ActivityRecord)msg.obj;
336 synchronized (mService) {
337 if (r.continueLaunchTickingLocked()) {
338 mService.logAppTooSlow(r.app, r.launchTickTime,
339 "launching " + r);
340 }
341 }
342 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700343 case DESTROY_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800344 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700345 // We don't at this point know if the activity is fullscreen,
346 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800347 Slog.w(TAG, "Activity destroy timeout for " + r);
348 activityDestroyed(r != null ? r.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700349 } break;
350 case IDLE_NOW_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800351 ActivityRecord r = (ActivityRecord)msg.obj;
352 activityIdleInternal(r != null ? r.appToken : null, false, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700353 } break;
354 case LAUNCH_TIMEOUT_MSG: {
355 if (mService.mDidDexOpt) {
356 mService.mDidDexOpt = false;
357 Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
358 mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
359 return;
360 }
361 synchronized (mService) {
362 if (mLaunchingActivity.isHeld()) {
363 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
364 mLaunchingActivity.release();
365 }
366 }
367 } break;
368 case RESUME_TOP_ACTIVITY_MSG: {
369 synchronized (mService) {
370 resumeTopActivityLocked(null);
371 }
372 } break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700373 case STOP_TIMEOUT_MSG: {
374 ActivityRecord r = (ActivityRecord)msg.obj;
375 // We don't at this point know if the activity is fullscreen,
376 // so we need to be conservative and assume it isn't.
377 Slog.w(TAG, "Activity stop timeout for " + r);
378 synchronized (mService) {
379 if (r.isInHistory()) {
380 activityStoppedLocked(r, null, null, null);
381 }
382 }
383 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700384 }
385 }
386 };
387
388 ActivityStack(ActivityManagerService service, Context context, boolean mainStack) {
389 mService = service;
390 mContext = context;
391 mMainStack = mainStack;
392 PowerManager pm =
393 (PowerManager)context.getSystemService(Context.POWER_SERVICE);
394 mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
395 mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
396 mLaunchingActivity.setReferenceCounted(false);
397 }
398
399 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700400 // TODO: Don't look for any tasks from other users
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700401 int i = mHistory.size()-1;
402 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700403 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700404 if (!r.finishing && r != notTop) {
405 return r;
406 }
407 i--;
408 }
409 return null;
410 }
411
412 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700413 // TODO: Don't look for any tasks from other users
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700414 int i = mHistory.size()-1;
415 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700416 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700417 if (!r.finishing && !r.delayedResume && r != notTop) {
418 return r;
419 }
420 i--;
421 }
422 return null;
423 }
424
425 /**
426 * This is a simplified version of topRunningActivityLocked that provides a number of
427 * optional skip-over modes. It is intended for use with the ActivityController hook only.
428 *
429 * @param token If non-null, any history records matching this token will be skipped.
430 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
431 *
432 * @return Returns the HistoryRecord of the next activity on the stack.
433 */
434 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700435 // TODO: Don't look for any tasks from other users
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700436 int i = mHistory.size()-1;
437 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700438 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700439 // Note: the taskId check depends on real taskId fields being non-zero
Dianne Hackbornbe707852011-11-11 14:32:10 -0800440 if (!r.finishing && (token != r.appToken) && (taskId != r.task.taskId)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700441 return r;
442 }
443 i--;
444 }
445 return null;
446 }
447
448 final int indexOfTokenLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800449 return mHistory.indexOf(ActivityRecord.forToken(token));
450 }
451
452 final int indexOfActivityLocked(ActivityRecord r) {
453 return mHistory.indexOf(r);
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700454 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700455
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700456 final ActivityRecord isInStackLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800457 ActivityRecord r = ActivityRecord.forToken(token);
458 if (mHistory.contains(r)) {
459 return r;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700460 }
461 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700462 }
463
464 private final boolean updateLRUListLocked(ActivityRecord r) {
465 final boolean hadit = mLRUActivities.remove(r);
466 mLRUActivities.add(r);
467 return hadit;
468 }
469
470 /**
471 * Returns the top activity in any existing task matching the given
472 * Intent. Returns null if no such task is found.
473 */
474 private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
475 ComponentName cls = intent.getComponent();
476 if (info.targetActivity != null) {
477 cls = new ComponentName(info.packageName, info.targetActivity);
478 }
479
480 TaskRecord cp = null;
481
Amith Yamasani742a6712011-05-04 14:49:28 -0700482 final int userId = UserId.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700483 final int N = mHistory.size();
484 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700485 ActivityRecord r = mHistory.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -0700486 if (!r.finishing && r.task != cp && r.userId == userId
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700487 && r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
488 cp = r.task;
489 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
490 // + "/aff=" + r.task.affinity + " to new cls="
491 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
492 if (r.task.affinity != null) {
493 if (r.task.affinity.equals(info.taskAffinity)) {
494 //Slog.i(TAG, "Found matching affinity!");
495 return r;
496 }
497 } else if (r.task.intent != null
498 && r.task.intent.getComponent().equals(cls)) {
499 //Slog.i(TAG, "Found matching class!");
500 //dump();
501 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
502 return r;
503 } else if (r.task.affinityIntent != null
504 && r.task.affinityIntent.getComponent().equals(cls)) {
505 //Slog.i(TAG, "Found matching class!");
506 //dump();
507 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
508 return r;
509 }
510 }
511 }
512
513 return null;
514 }
515
516 /**
517 * Returns the first activity (starting from the top of the stack) that
518 * is the same as the given activity. Returns null if no such activity
519 * is found.
520 */
521 private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
522 ComponentName cls = intent.getComponent();
523 if (info.targetActivity != null) {
524 cls = new ComponentName(info.packageName, info.targetActivity);
525 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700526 final int userId = UserId.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700527
528 final int N = mHistory.size();
529 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700530 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700531 if (!r.finishing) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700532 if (r.intent.getComponent().equals(cls) && r.userId == userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700533 //Slog.i(TAG, "Found matching class!");
534 //dump();
535 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
536 return r;
537 }
538 }
539 }
540
541 return null;
542 }
543
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700544 final void showAskCompatModeDialogLocked(ActivityRecord r) {
545 Message msg = Message.obtain();
546 msg.what = ActivityManagerService.SHOW_COMPAT_MODE_DIALOG_MSG;
547 msg.obj = r.task.askedCompatMode ? null : r;
548 mService.mHandler.sendMessage(msg);
549 }
550
Amith Yamasani742a6712011-05-04 14:49:28 -0700551 /*
552 * Move the activities around in the stack to bring a user to the foreground.
553 * @return whether there are any activities for the specified user.
554 */
555 final boolean switchUser(int userId) {
556 synchronized (mService) {
557 mCurrentUser = userId;
558
559 // Only one activity? Nothing to do...
560 if (mHistory.size() < 2)
561 return false;
562
563 boolean haveActivities = false;
564 // Check if the top activity is from the new user.
565 ActivityRecord top = mHistory.get(mHistory.size() - 1);
566 if (top.userId == userId) return true;
567 // Otherwise, move the user's activities to the top.
568 int N = mHistory.size();
569 int i = 0;
570 while (i < N) {
571 ActivityRecord r = mHistory.get(i);
572 if (r.userId == userId) {
573 ActivityRecord moveToTop = mHistory.remove(i);
574 mHistory.add(moveToTop);
575 // No need to check the top one now
576 N--;
577 haveActivities = true;
578 } else {
579 i++;
580 }
581 }
582 // Transition from the old top to the new top
583 resumeTopActivityLocked(top);
584 return haveActivities;
585 }
586 }
587
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700588 final boolean realStartActivityLocked(ActivityRecord r,
589 ProcessRecord app, boolean andResume, boolean checkConfig)
590 throws RemoteException {
591
592 r.startFreezingScreenLocked(app, 0);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800593 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700594
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700595 // schedule launch ticks to collect information about slow apps.
596 r.startLaunchTickingLocked();
597
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700598 // Have the window manager re-evaluate the orientation of
599 // the screen based on the new activity order. Note that
600 // as a result of this, it can call back into the activity
601 // manager with a new orientation. We don't care about that,
602 // because the activity is not currently running so we are
603 // just restarting it anyway.
604 if (checkConfig) {
605 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
606 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -0800607 r.mayFreezeScreenLocked(app) ? r.appToken : null);
Dianne Hackborn813075a62011-11-14 17:45:19 -0800608 mService.updateConfigurationLocked(config, r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700609 }
610
611 r.app = app;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700612 app.waitingToKill = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700613
614 if (localLOGV) Slog.v(TAG, "Launching: " + r);
615
616 int idx = app.activities.indexOf(r);
617 if (idx < 0) {
618 app.activities.add(r);
619 }
620 mService.updateLruProcessLocked(app, true, true);
621
622 try {
623 if (app.thread == null) {
624 throw new RemoteException();
625 }
626 List<ResultInfo> results = null;
627 List<Intent> newIntents = null;
628 if (andResume) {
629 results = r.results;
630 newIntents = r.newIntents;
631 }
632 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
633 + " icicle=" + r.icicle
634 + " with results=" + results + " newIntents=" + newIntents
635 + " andResume=" + andResume);
636 if (andResume) {
637 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
638 System.identityHashCode(r),
639 r.task.taskId, r.shortComponentName);
640 }
641 if (r.isHomeActivity) {
642 mService.mHomeProcess = app;
643 }
644 mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800645 r.sleeping = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400646 r.forceNewConfig = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700647 showAskCompatModeDialogLocked(r);
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700648 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700649 String profileFile = null;
650 ParcelFileDescriptor profileFd = null;
651 boolean profileAutoStop = false;
652 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
653 if (mService.mProfileProc == null || mService.mProfileProc == app) {
654 mService.mProfileProc = app;
655 profileFile = mService.mProfileFile;
656 profileFd = mService.mProfileFd;
657 profileAutoStop = mService.mAutoStopProfiler;
658 }
659 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -0700660 app.hasShownUi = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700661 app.pendingUiClean = true;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700662 if (profileFd != null) {
663 try {
664 profileFd = profileFd.dup();
665 } catch (IOException e) {
666 profileFd = null;
667 }
668 }
Dianne Hackbornbe707852011-11-11 14:32:10 -0800669 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
Dianne Hackborn813075a62011-11-14 17:45:19 -0800670 System.identityHashCode(r), r.info,
671 new Configuration(mService.mConfiguration),
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700672 r.compat, r.icicle, results, newIntents, !andResume,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700673 mService.isNextTransitionForward(), profileFile, profileFd,
674 profileAutoStop);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700675
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700676 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700677 // This may be a heavy-weight process! Note that the package
678 // manager will ensure that only activity can run in the main
679 // process of the .apk, which is the only thing that will be
680 // considered heavy-weight.
681 if (app.processName.equals(app.info.packageName)) {
682 if (mService.mHeavyWeightProcess != null
683 && mService.mHeavyWeightProcess != app) {
684 Log.w(TAG, "Starting new heavy weight process " + app
685 + " when already running "
686 + mService.mHeavyWeightProcess);
687 }
688 mService.mHeavyWeightProcess = app;
689 Message msg = mService.mHandler.obtainMessage(
690 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
691 msg.obj = r;
692 mService.mHandler.sendMessage(msg);
693 }
694 }
695
696 } catch (RemoteException e) {
697 if (r.launchFailed) {
698 // This is the second time we failed -- finish activity
699 // and give up.
700 Slog.e(TAG, "Second failure launching "
701 + r.intent.getComponent().flattenToShortString()
702 + ", giving up", e);
703 mService.appDiedLocked(app, app.pid, app.thread);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800704 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700705 "2nd-crash");
706 return false;
707 }
708
709 // This is the first time we failed -- restart process and
710 // retry.
711 app.activities.remove(r);
712 throw e;
713 }
714
715 r.launchFailed = false;
716 if (updateLRUListLocked(r)) {
717 Slog.w(TAG, "Activity " + r
718 + " being launched, but already in LRU list");
719 }
720
721 if (andResume) {
722 // As part of the process of launching, ActivityThread also performs
723 // a resume.
724 r.state = ActivityState.RESUMED;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700725 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
726 + " (starting new instance)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700727 r.stopped = false;
728 mResumedActivity = r;
729 r.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -0800730 if (mMainStack) {
731 mService.addRecentTaskLocked(r.task);
732 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700733 completeResumeLocked(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800734 checkReadyForSleepLocked();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700735 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Launch completed; removing icicle of " + r.icicle);
736 r.icicle = null;
737 r.haveState = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700738 } else {
739 // This activity is not starting in the resumed state... which
740 // should look like we asked it to pause+stop (but remain visible),
741 // and it has done so and reported back the current icicle and
742 // other state.
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700743 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
744 + " (starting in stopped state)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700745 r.state = ActivityState.STOPPED;
746 r.stopped = true;
747 }
748
749 // Launch the new version setup screen if needed. We do this -after-
750 // launching the initial activity (that is, home), so that it can have
751 // a chance to initialize itself while in the background, making the
752 // switch back to it faster and look better.
753 if (mMainStack) {
754 mService.startSetupActivityLocked();
755 }
756
757 return true;
758 }
759
760 private final void startSpecificActivityLocked(ActivityRecord r,
761 boolean andResume, boolean checkConfig) {
762 // Is this activity's application already running?
763 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
764 r.info.applicationInfo.uid);
765
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700766 if (r.launchTime == 0) {
767 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700768 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700769 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700770 }
771 } else if (mInitialStartTime == 0) {
772 mInitialStartTime = SystemClock.uptimeMillis();
773 }
774
775 if (app != null && app.thread != null) {
776 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700777 app.addPackage(r.info.packageName);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700778 realStartActivityLocked(r, app, andResume, checkConfig);
779 return;
780 } catch (RemoteException e) {
781 Slog.w(TAG, "Exception when starting activity "
782 + r.intent.getComponent().flattenToShortString(), e);
783 }
784
785 // If a dead object exception was thrown -- fall through to
786 // restart the application.
787 }
788
789 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800790 "activity", r.intent.getComponent(), false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700791 }
792
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800793 void stopIfSleepingLocked() {
794 if (mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700795 if (!mGoingToSleep.isHeld()) {
796 mGoingToSleep.acquire();
797 if (mLaunchingActivity.isHeld()) {
798 mLaunchingActivity.release();
799 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
800 }
801 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800802 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
803 Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
804 mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
805 checkReadyForSleepLocked();
806 }
807 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700808
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800809 void awakeFromSleepingLocked() {
810 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
811 mSleepTimeout = false;
812 if (mGoingToSleep.isHeld()) {
813 mGoingToSleep.release();
814 }
815 // Ensure activities are no longer sleeping.
816 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700817 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800818 r.setSleeping(false);
819 }
820 mGoingToSleepActivities.clear();
821 }
822
823 void activitySleptLocked(ActivityRecord r) {
824 mGoingToSleepActivities.remove(r);
825 checkReadyForSleepLocked();
826 }
827
828 void checkReadyForSleepLocked() {
829 if (!mService.isSleeping()) {
830 // Do not care.
831 return;
832 }
833
834 if (!mSleepTimeout) {
835 if (mResumedActivity != null) {
836 // Still have something resumed; can't sleep until it is paused.
837 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700838 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
839 startPausingLocked(false, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800840 return;
841 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800842 if (mPausingActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800843 // Still waiting for something to pause; can't sleep yet.
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800844 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800845 return;
846 }
847
848 if (mStoppingActivities.size() > 0) {
849 // Still need to tell some activities to stop; can't sleep yet.
850 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
851 + mStoppingActivities.size() + " activities");
Dianne Hackborn80a7ac12011-09-22 18:32:52 -0700852 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800853 return;
854 }
855
856 ensureActivitiesVisibleLocked(null, 0);
857
858 // Make sure any stopped but visible activities are now sleeping.
859 // This ensures that the activity's onStop() is called.
860 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700861 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800862 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
863 r.setSleeping(true);
864 }
865 }
866
867 if (mGoingToSleepActivities.size() > 0) {
868 // Still need to tell some activities to sleep; can't sleep yet.
869 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
870 + mGoingToSleepActivities.size() + " activities");
871 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700872 }
873 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800874
875 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
876
877 if (mGoingToSleep.isHeld()) {
878 mGoingToSleep.release();
879 }
880 if (mService.mShuttingDown) {
881 mService.notifyAll();
882 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700883 }
884
Dianne Hackbornd2835932010-12-13 16:28:46 -0800885 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -0800886 if (who.noDisplay) {
887 return null;
888 }
889
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800890 Resources res = mService.mContext.getResources();
891 int w = mThumbnailWidth;
892 int h = mThumbnailHeight;
893 if (w < 0) {
894 mThumbnailWidth = w =
895 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
896 mThumbnailHeight = h =
897 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
898 }
899
900 if (w > 0) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800901 return mService.mWindowManager.screenshotApplications(who.appToken, w, h);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800902 }
903 return null;
904 }
905
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700906 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800907 if (mPausingActivity != null) {
908 RuntimeException e = new RuntimeException();
909 Slog.e(TAG, "Trying to pause when pause is already pending for "
910 + mPausingActivity, e);
911 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700912 ActivityRecord prev = mResumedActivity;
913 if (prev == null) {
914 RuntimeException e = new RuntimeException();
915 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
916 resumeTopActivityLocked(null);
917 return;
918 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700919 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
920 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700921 mResumedActivity = null;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800922 mPausingActivity = prev;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700923 mLastPausedActivity = prev;
924 prev.state = ActivityState.PAUSING;
925 prev.task.touchActiveTime();
Dianne Hackbornf26fd992011-04-08 18:14:09 -0700926 prev.updateThumbnail(screenshotActivities(prev), null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700927
928 mService.updateCpuStats();
929
930 if (prev.app != null && prev.app.thread != null) {
931 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
932 try {
933 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
934 System.identityHashCode(prev),
935 prev.shortComponentName);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800936 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
937 userLeaving, prev.configChangeFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700938 if (mMainStack) {
939 mService.updateUsageStats(prev, false);
940 }
941 } catch (Exception e) {
942 // Ignore exception, if process died other code will cleanup.
943 Slog.w(TAG, "Exception thrown during pause", e);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800944 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700945 mLastPausedActivity = null;
946 }
947 } else {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800948 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700949 mLastPausedActivity = null;
950 }
951
952 // If we are not going to sleep, we want to ensure the device is
953 // awake until the next activity is started.
954 if (!mService.mSleeping && !mService.mShuttingDown) {
955 mLaunchingActivity.acquire();
956 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
957 // To be safe, don't allow the wake lock to be held for too long.
958 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
959 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
960 }
961 }
962
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800963
964 if (mPausingActivity != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700965 // Have the window manager pause its key dispatching until the new
966 // activity has started. If we're pausing the activity just because
967 // the screen is being turned off and the UI is sleeping, don't interrupt
968 // key dispatch; the same activity will pick it up again on wakeup.
969 if (!uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800970 prev.pauseKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700971 } else {
972 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
973 }
974
975 // Schedule a pause timeout in case the app doesn't respond.
976 // We don't give it much time because this directly impacts the
977 // responsiveness seen by the user.
978 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
979 msg.obj = prev;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700980 prev.pauseTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700981 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
982 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
983 } else {
984 // This activity failed to schedule the
985 // pause, so just treat it as being paused now.
986 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800987 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700988 }
989 }
990
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800991 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700992 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800993 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700994
995 ActivityRecord r = null;
996
997 synchronized (mService) {
998 int index = indexOfTokenLocked(token);
999 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001000 r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001001 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001002 if (mPausingActivity == r) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001003 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
1004 + (timeout ? " (due to timeout)" : " (pause complete)"));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001005 r.state = ActivityState.PAUSED;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001006 completePauseLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001007 } else {
1008 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
1009 System.identityHashCode(r), r.shortComponentName,
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001010 mPausingActivity != null
1011 ? mPausingActivity.shortComponentName : "(none)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001012 }
1013 }
1014 }
1015 }
1016
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001017 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
1018 CharSequence description) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001019 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Saving icicle of " + r + ": " + icicle);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001020 if (icicle != null) {
1021 // If icicle is null, this is happening due to a timeout, so we
1022 // haven't really saved the state.
1023 r.icicle = icicle;
1024 r.haveState = true;
1025 r.updateThumbnail(thumbnail, description);
1026 }
1027 if (!r.stopped) {
1028 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
1029 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1030 r.stopped = true;
1031 r.state = ActivityState.STOPPED;
1032 if (!r.finishing) {
1033 if (r.configDestroy) {
1034 destroyActivityLocked(r, true, false, "stop-config");
1035 resumeTopActivityLocked(null);
1036 } else {
1037 // Now that this process has stopped, we may want to consider
1038 // it to be the previous app to try to keep around in case
1039 // the user wants to return to it.
1040 ProcessRecord fgApp = null;
1041 if (mResumedActivity != null) {
1042 fgApp = mResumedActivity.app;
1043 } else if (mPausingActivity != null) {
1044 fgApp = mPausingActivity.app;
1045 }
1046 if (r.app != null && fgApp != null && r.app != fgApp
1047 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
1048 && r.app != mService.mHomeProcess) {
1049 mService.mPreviousProcess = r.app;
1050 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
1051 }
Dianne Hackborn50685602011-12-01 12:23:37 -08001052 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001053 }
1054 }
1055 }
1056
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001057 private final void completePauseLocked() {
1058 ActivityRecord prev = mPausingActivity;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001059 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
1060
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001061 if (prev != null) {
1062 if (prev.finishing) {
1063 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
1064 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE);
1065 } else if (prev.app != null) {
1066 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
1067 if (prev.waitingVisible) {
1068 prev.waitingVisible = false;
1069 mWaitingVisibleActivities.remove(prev);
1070 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
1071 TAG, "Complete pause, no longer waiting: " + prev);
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001072 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001073 if (prev.configDestroy) {
1074 // The previous is being paused because the configuration
1075 // is changing, which means it is actually stopping...
1076 // To juggle the fact that we are also starting a new
1077 // instance right now, we need to first completely stop
1078 // the current instance before starting the new one.
1079 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
1080 destroyActivityLocked(prev, true, false, "pause-config");
1081 } else {
1082 mStoppingActivities.add(prev);
1083 if (mStoppingActivities.size() > 3) {
1084 // If we already have a few activities waiting to stop,
1085 // then give up on things going idle and start clearing
1086 // them out.
1087 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
1088 scheduleIdleLocked();
1089 } else {
1090 checkReadyForSleepLocked();
1091 }
1092 }
1093 } else {
1094 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
1095 prev = null;
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001096 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001097 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001098 }
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001099
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001100 if (!mService.isSleeping()) {
1101 resumeTopActivityLocked(prev);
1102 } else {
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001103 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001104 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001105
1106 if (prev != null) {
1107 prev.resumeKeyDispatchingLocked();
1108 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001109
1110 if (prev.app != null && prev.cpuTimeAtResume > 0
1111 && mService.mBatteryStatsService.isOnBattery()) {
1112 long diff = 0;
1113 synchronized (mService.mProcessStatsThread) {
1114 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
1115 - prev.cpuTimeAtResume;
1116 }
1117 if (diff > 0) {
1118 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
1119 synchronized (bsi) {
1120 BatteryStatsImpl.Uid.Proc ps =
1121 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
1122 prev.info.packageName);
1123 if (ps != null) {
1124 ps.addForegroundTimeLocked(diff);
1125 }
1126 }
1127 }
1128 }
1129 prev.cpuTimeAtResume = 0; // reset it
1130 }
1131
1132 /**
1133 * Once we know that we have asked an application to put an activity in
1134 * the resumed state (either by launching it or explicitly telling it),
1135 * this function updates the rest of our state to match that fact.
1136 */
1137 private final void completeResumeLocked(ActivityRecord next) {
1138 next.idle = false;
1139 next.results = null;
1140 next.newIntents = null;
1141
1142 // schedule an idle timeout in case the app doesn't do it for us.
1143 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1144 msg.obj = next;
1145 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
1146
1147 if (false) {
1148 // The activity was never told to pause, so just keep
1149 // things going as-is. To maintain our own state,
1150 // we need to emulate it coming back and saying it is
1151 // idle.
1152 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
1153 msg.obj = next;
1154 mHandler.sendMessage(msg);
1155 }
1156
1157 if (mMainStack) {
1158 mService.reportResumedActivityLocked(next);
1159 }
1160
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001161 next.clearThumbnail();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001162 if (mMainStack) {
1163 mService.setFocusedActivityLocked(next);
1164 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001165 next.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001166 ensureActivitiesVisibleLocked(null, 0);
1167 mService.mWindowManager.executeAppTransition();
1168 mNoAnimActivities.clear();
1169
1170 // Mark the point when the activity is resuming
1171 // TODO: To be more accurate, the mark should be before the onCreate,
1172 // not after the onResume. But for subsequent starts, onResume is fine.
1173 if (next.app != null) {
1174 synchronized (mService.mProcessStatsThread) {
1175 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1176 }
1177 } else {
1178 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1179 }
1180 }
1181
1182 /**
1183 * Make sure that all activities that need to be visible (that is, they
1184 * currently can be seen by the user) actually are.
1185 */
1186 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1187 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1188 if (DEBUG_VISBILITY) Slog.v(
1189 TAG, "ensureActivitiesVisible behind " + top
1190 + " configChanges=0x" + Integer.toHexString(configChanges));
1191
1192 // If the top activity is not fullscreen, then we need to
1193 // make sure any activities under it are now visible.
1194 final int count = mHistory.size();
1195 int i = count-1;
1196 while (mHistory.get(i) != top) {
1197 i--;
1198 }
1199 ActivityRecord r;
1200 boolean behindFullscreen = false;
1201 for (; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001202 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001203 if (DEBUG_VISBILITY) Slog.v(
1204 TAG, "Make visible? " + r + " finishing=" + r.finishing
1205 + " state=" + r.state);
1206 if (r.finishing) {
1207 continue;
1208 }
1209
1210 final boolean doThisProcess = onlyThisProcess == null
1211 || onlyThisProcess.equals(r.processName);
1212
1213 // First: if this is not the current activity being started, make
1214 // sure it matches the current configuration.
1215 if (r != starting && doThisProcess) {
1216 ensureActivityConfigurationLocked(r, 0);
1217 }
1218
1219 if (r.app == null || r.app.thread == null) {
1220 if (onlyThisProcess == null
1221 || onlyThisProcess.equals(r.processName)) {
1222 // This activity needs to be visible, but isn't even
1223 // running... get it started, but don't resume it
1224 // at this point.
1225 if (DEBUG_VISBILITY) Slog.v(
1226 TAG, "Start and freeze screen for " + r);
1227 if (r != starting) {
1228 r.startFreezingScreenLocked(r.app, configChanges);
1229 }
1230 if (!r.visible) {
1231 if (DEBUG_VISBILITY) Slog.v(
1232 TAG, "Starting and making visible: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001233 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001234 }
1235 if (r != starting) {
1236 startSpecificActivityLocked(r, false, false);
1237 }
1238 }
1239
1240 } else if (r.visible) {
1241 // If this activity is already visible, then there is nothing
1242 // else to do here.
1243 if (DEBUG_VISBILITY) Slog.v(
1244 TAG, "Skipping: already visible at " + r);
1245 r.stopFreezingScreenLocked(false);
1246
1247 } else if (onlyThisProcess == null) {
1248 // This activity is not currently visible, but is running.
1249 // Tell it to become visible.
1250 r.visible = true;
1251 if (r.state != ActivityState.RESUMED && r != starting) {
1252 // If this activity is paused, tell it
1253 // to now show its window.
1254 if (DEBUG_VISBILITY) Slog.v(
1255 TAG, "Making visible and scheduling visibility: " + r);
1256 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001257 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001258 r.sleeping = false;
Dianne Hackborn905577f2011-09-07 18:31:28 -07001259 r.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001260 r.app.thread.scheduleWindowVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001261 r.stopFreezingScreenLocked(false);
1262 } catch (Exception e) {
1263 // Just skip on any failure; we'll make it
1264 // visible when it next restarts.
1265 Slog.w(TAG, "Exception thrown making visibile: "
1266 + r.intent.getComponent(), e);
1267 }
1268 }
1269 }
1270
1271 // Aggregate current change flags.
1272 configChanges |= r.configChangeFlags;
1273
1274 if (r.fullscreen) {
1275 // At this point, nothing else needs to be shown
1276 if (DEBUG_VISBILITY) Slog.v(
1277 TAG, "Stopping: fullscreen at " + r);
1278 behindFullscreen = true;
1279 i--;
1280 break;
1281 }
1282 }
1283
1284 // Now for any activities that aren't visible to the user, make
1285 // sure they no longer are keeping the screen frozen.
1286 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001287 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001288 if (DEBUG_VISBILITY) Slog.v(
1289 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1290 + " state=" + r.state
1291 + " behindFullscreen=" + behindFullscreen);
1292 if (!r.finishing) {
1293 if (behindFullscreen) {
1294 if (r.visible) {
1295 if (DEBUG_VISBILITY) Slog.v(
1296 TAG, "Making invisible: " + r);
1297 r.visible = false;
1298 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001299 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001300 if ((r.state == ActivityState.STOPPING
1301 || r.state == ActivityState.STOPPED)
1302 && r.app != null && r.app.thread != null) {
1303 if (DEBUG_VISBILITY) Slog.v(
1304 TAG, "Scheduling invisibility: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001305 r.app.thread.scheduleWindowVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001306 }
1307 } catch (Exception e) {
1308 // Just skip on any failure; we'll make it
1309 // visible when it next restarts.
1310 Slog.w(TAG, "Exception thrown making hidden: "
1311 + r.intent.getComponent(), e);
1312 }
1313 } else {
1314 if (DEBUG_VISBILITY) Slog.v(
1315 TAG, "Already invisible: " + r);
1316 }
1317 } else if (r.fullscreen) {
1318 if (DEBUG_VISBILITY) Slog.v(
1319 TAG, "Now behindFullscreen: " + r);
1320 behindFullscreen = true;
1321 }
1322 }
1323 i--;
1324 }
1325 }
1326
1327 /**
1328 * Version of ensureActivitiesVisible that can easily be called anywhere.
1329 */
1330 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1331 int configChanges) {
1332 ActivityRecord r = topRunningActivityLocked(null);
1333 if (r != null) {
1334 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1335 }
1336 }
1337
1338 /**
1339 * Ensure that the top activity in the stack is resumed.
1340 *
1341 * @param prev The previously resumed activity, for when in the process
1342 * of pausing; can be null to call from elsewhere.
1343 *
1344 * @return Returns true if something is being resumed, or false if
1345 * nothing happened.
1346 */
1347 final boolean resumeTopActivityLocked(ActivityRecord prev) {
1348 // Find the first activity that is not finishing.
1349 ActivityRecord next = topRunningActivityLocked(null);
1350
1351 // Remember how we'll process this pause/resume situation, and ensure
1352 // that the state is reset however we wind up proceeding.
1353 final boolean userLeaving = mUserLeaving;
1354 mUserLeaving = false;
1355
1356 if (next == null) {
1357 // There are no more activities! Let's just start up the
1358 // Launcher...
1359 if (mMainStack) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001360 return mService.startHomeActivityLocked(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001361 }
1362 }
1363
1364 next.delayedResume = false;
1365
1366 // If the top activity is the resumed one, nothing to do.
1367 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1368 // Make sure we have executed any pending transitions, since there
1369 // should be nothing left to do at this point.
1370 mService.mWindowManager.executeAppTransition();
1371 mNoAnimActivities.clear();
1372 return false;
1373 }
1374
1375 // If we are sleeping, and there is no resumed activity, and the top
1376 // activity is paused, well that is the state we want.
1377 if ((mService.mSleeping || mService.mShuttingDown)
1378 && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
1379 // Make sure we have executed any pending transitions, since there
1380 // should be nothing left to do at this point.
1381 mService.mWindowManager.executeAppTransition();
1382 mNoAnimActivities.clear();
1383 return false;
1384 }
1385
1386 // The activity may be waiting for stop, but that is no longer
1387 // appropriate for it.
1388 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001389 mGoingToSleepActivities.remove(next);
1390 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001391 mWaitingVisibleActivities.remove(next);
1392
1393 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1394
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001395 // If we are currently pausing an activity, then don't do anything
1396 // until that is done.
1397 if (mPausingActivity != null) {
1398 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
1399 return false;
1400 }
1401
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001402 // Okay we are now going to start a switch, to 'next'. We may first
1403 // have to pause the current activity, but this is an important point
1404 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001405 // XXX "App Redirected" dialog is getting too many false positives
1406 // at this point, so turn off for now.
1407 if (false) {
1408 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1409 long now = SystemClock.uptimeMillis();
1410 final boolean inTime = mLastStartedActivity.startTime != 0
1411 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1412 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1413 final int nextUid = next.info.applicationInfo.uid;
1414 if (inTime && lastUid != nextUid
1415 && lastUid != next.launchedFromUid
1416 && mService.checkPermission(
1417 android.Manifest.permission.STOP_APP_SWITCHES,
1418 -1, next.launchedFromUid)
1419 != PackageManager.PERMISSION_GRANTED) {
1420 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1421 } else {
1422 next.startTime = now;
1423 mLastStartedActivity = next;
1424 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001425 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001426 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001427 mLastStartedActivity = next;
1428 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001429 }
1430
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001431 // We need to start pausing the current activity so the top one
1432 // can be resumed...
1433 if (mResumedActivity != null) {
1434 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
1435 startPausingLocked(userLeaving, false);
1436 return true;
1437 }
1438
1439 if (prev != null && prev != next) {
1440 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1441 prev.waitingVisible = true;
1442 mWaitingVisibleActivities.add(prev);
1443 if (DEBUG_SWITCH) Slog.v(
1444 TAG, "Resuming top, waiting visible to hide: " + prev);
1445 } else {
1446 // The next activity is already visible, so hide the previous
1447 // activity's windows right now so we can show the new one ASAP.
1448 // We only do this if the previous is finishing, which should mean
1449 // it is on top of the one being resumed so hiding it quickly
1450 // is good. Otherwise, we want to do the normal route of allowing
1451 // the resumed activity to be shown so we can decide if the
1452 // previous should actually be hidden depending on whether the
1453 // new one is found to be full-screen or not.
1454 if (prev.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001455 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001456 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1457 + prev + ", waitingVisible="
1458 + (prev != null ? prev.waitingVisible : null)
1459 + ", nowVisible=" + next.nowVisible);
1460 } else {
1461 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1462 + prev + ", waitingVisible="
1463 + (prev != null ? prev.waitingVisible : null)
1464 + ", nowVisible=" + next.nowVisible);
1465 }
1466 }
1467 }
1468
Dianne Hackborne7f97212011-02-24 14:40:20 -08001469 // Launching this app's activity, make sure the app is no longer
1470 // considered stopped.
1471 try {
1472 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001473 next.packageName, false, next.userId); /* TODO: Verify if correct userid */
Dianne Hackborne7f97212011-02-24 14:40:20 -08001474 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001475 } catch (IllegalArgumentException e) {
1476 Slog.w(TAG, "Failed trying to unstop package "
1477 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001478 }
1479
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001480 // We are starting up the next activity, so tell the window manager
1481 // that the previous one will be hidden soon. This way it can know
1482 // to ignore it when computing the desired screen orientation.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001483 boolean noAnim = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001484 if (prev != null) {
1485 if (prev.finishing) {
1486 if (DEBUG_TRANSITION) Slog.v(TAG,
1487 "Prepare close transition: prev=" + prev);
1488 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001489 mService.mWindowManager.prepareAppTransition(
1490 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001491 } else {
1492 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1493 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001494 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001495 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001496 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1497 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001498 } else {
1499 if (DEBUG_TRANSITION) Slog.v(TAG,
1500 "Prepare open transition: prev=" + prev);
1501 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001502 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001503 mService.mWindowManager.prepareAppTransition(
1504 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001505 } else {
1506 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1507 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001508 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001509 }
1510 }
1511 if (false) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001512 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1513 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001514 }
1515 } else if (mHistory.size() > 1) {
1516 if (DEBUG_TRANSITION) Slog.v(TAG,
1517 "Prepare open transition: no previous");
1518 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001519 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001520 mService.mWindowManager.prepareAppTransition(
1521 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001522 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001523 mService.mWindowManager.prepareAppTransition(
1524 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001525 }
1526 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001527 if (!noAnim) {
1528 next.applyOptionsLocked();
1529 } else {
1530 next.clearOptionsLocked();
1531 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001532
1533 if (next.app != null && next.app.thread != null) {
1534 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1535
1536 // This activity is now becoming visible.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001537 mService.mWindowManager.setAppVisibility(next.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001538
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001539 // schedule launch ticks to collect information about slow apps.
1540 next.startLaunchTickingLocked();
1541
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001542 ActivityRecord lastResumedActivity = mResumedActivity;
1543 ActivityState lastState = next.state;
1544
1545 mService.updateCpuStats();
1546
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001547 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001548 next.state = ActivityState.RESUMED;
1549 mResumedActivity = next;
1550 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001551 if (mMainStack) {
1552 mService.addRecentTaskLocked(next.task);
1553 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001554 mService.updateLruProcessLocked(next.app, true, true);
1555 updateLRUListLocked(next);
1556
1557 // Have the window manager re-evaluate the orientation of
1558 // the screen based on the new activity order.
1559 boolean updated = false;
1560 if (mMainStack) {
1561 synchronized (mService) {
1562 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1563 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001564 next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001565 if (config != null) {
1566 next.frozenBeforeDestroy = true;
1567 }
Dianne Hackborn813075a62011-11-14 17:45:19 -08001568 updated = mService.updateConfigurationLocked(config, next, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001569 }
1570 }
1571 if (!updated) {
1572 // The configuration update wasn't able to keep the existing
1573 // instance of the activity, and instead started a new one.
1574 // We should be all done, but let's just make sure our activity
1575 // is still at the top and schedule another run if something
1576 // weird happened.
1577 ActivityRecord nextNext = topRunningActivityLocked(null);
1578 if (DEBUG_SWITCH) Slog.i(TAG,
1579 "Activity config changed during resume: " + next
1580 + ", new next: " + nextNext);
1581 if (nextNext != next) {
1582 // Do over!
1583 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1584 }
1585 if (mMainStack) {
1586 mService.setFocusedActivityLocked(next);
1587 }
1588 ensureActivitiesVisibleLocked(null, 0);
1589 mService.mWindowManager.executeAppTransition();
1590 mNoAnimActivities.clear();
1591 return true;
1592 }
1593
1594 try {
1595 // Deliver all pending results.
1596 ArrayList a = next.results;
1597 if (a != null) {
1598 final int N = a.size();
1599 if (!next.finishing && N > 0) {
1600 if (DEBUG_RESULTS) Slog.v(
1601 TAG, "Delivering results to " + next
1602 + ": " + a);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001603 next.app.thread.scheduleSendResult(next.appToken, a);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001604 }
1605 }
1606
1607 if (next.newIntents != null) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001608 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001609 }
1610
1611 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
1612 System.identityHashCode(next),
1613 next.task.taskId, next.shortComponentName);
1614
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001615 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001616 showAskCompatModeDialogLocked(next);
Dianne Hackborn905577f2011-09-07 18:31:28 -07001617 next.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001618 next.app.thread.scheduleResumeActivity(next.appToken,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001619 mService.isNextTransitionForward());
1620
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001621 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001622
1623 } catch (Exception e) {
1624 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001625 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1626 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001627 next.state = lastState;
1628 mResumedActivity = lastResumedActivity;
1629 Slog.i(TAG, "Restarting because process died: " + next);
1630 if (!next.hasBeenLaunched) {
1631 next.hasBeenLaunched = true;
1632 } else {
1633 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1634 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001635 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001636 mService.compatibilityInfoForPackageLocked(
1637 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001638 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001639 next.labelRes, next.icon, next.windowFlags,
1640 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001641 }
1642 }
1643 startSpecificActivityLocked(next, true, false);
1644 return true;
1645 }
1646
1647 // From this point on, if something goes wrong there is no way
1648 // to recover the activity.
1649 try {
1650 next.visible = true;
1651 completeResumeLocked(next);
1652 } catch (Exception e) {
1653 // If any exception gets thrown, toss away this
1654 // activity and try the next one.
1655 Slog.w(TAG, "Exception thrown during resume of " + next, e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001656 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001657 "resume-exception");
1658 return true;
1659 }
1660
1661 // Didn't need to use the icicle, and it is now out of date.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001662 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Resumed activity; didn't need icicle of: " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001663 next.icicle = null;
1664 next.haveState = false;
1665 next.stopped = false;
1666
1667 } else {
1668 // Whoops, need to restart this activity!
1669 if (!next.hasBeenLaunched) {
1670 next.hasBeenLaunched = true;
1671 } else {
1672 if (SHOW_APP_STARTING_PREVIEW) {
1673 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001674 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001675 mService.compatibilityInfoForPackageLocked(
1676 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001677 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001678 next.labelRes, next.icon, next.windowFlags,
1679 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001680 }
1681 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1682 }
1683 startSpecificActivityLocked(next, true, true);
1684 }
1685
1686 return true;
1687 }
1688
1689 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001690 boolean doResume, boolean keepCurTransition, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001691 final int NH = mHistory.size();
1692
1693 int addPos = -1;
1694
1695 if (!newTask) {
1696 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001697 boolean startIt = true;
1698 for (int i = NH-1; i >= 0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001699 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001700 if (p.finishing) {
1701 continue;
1702 }
1703 if (p.task == r.task) {
1704 // Here it is! Now, if this is not yet visible to the
1705 // user, then just add it without starting; it will
1706 // get started when the user navigates back to it.
1707 addPos = i+1;
1708 if (!startIt) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001709 if (DEBUG_ADD_REMOVE) {
1710 RuntimeException here = new RuntimeException("here");
1711 here.fillInStackTrace();
1712 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos,
1713 here);
1714 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001715 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001716 r.putInHistory();
Dianne Hackbornbe707852011-11-11 14:32:10 -08001717 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001718 r.info.screenOrientation, r.fullscreen);
1719 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001720 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001721 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001722 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001723 return;
1724 }
1725 break;
1726 }
1727 if (p.fullscreen) {
1728 startIt = false;
1729 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001730 }
1731 }
1732
1733 // Place a new activity at top of stack, so it is next to interact
1734 // with the user.
1735 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001736 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001737 }
1738
1739 // If we are not placing the new activity frontmost, we do not want
1740 // to deliver the onUserLeaving callback to the actual frontmost
1741 // activity
1742 if (addPos < NH) {
1743 mUserLeaving = false;
1744 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1745 }
1746
1747 // Slot the activity into the history stack and proceed
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001748 if (DEBUG_ADD_REMOVE) {
1749 RuntimeException here = new RuntimeException("here");
1750 here.fillInStackTrace();
1751 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos, here);
1752 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001753 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001754 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001755 r.frontOfTask = newTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001756 if (NH > 0) {
1757 // We want to show the starting preview window if we are
1758 // switching to a new task, or the next activity's process is
1759 // not currently running.
1760 boolean showStartingIcon = newTask;
1761 ProcessRecord proc = r.app;
1762 if (proc == null) {
1763 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1764 }
1765 if (proc == null || proc.thread == null) {
1766 showStartingIcon = true;
1767 }
1768 if (DEBUG_TRANSITION) Slog.v(TAG,
1769 "Prepare open transition: starting " + r);
1770 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001771 mService.mWindowManager.prepareAppTransition(
1772 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001773 mNoAnimActivities.add(r);
1774 } else if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
1775 mService.mWindowManager.prepareAppTransition(
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001776 WindowManagerPolicy.TRANSIT_TASK_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001777 mNoAnimActivities.remove(r);
1778 } else {
1779 mService.mWindowManager.prepareAppTransition(newTask
1780 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001781 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001782 mNoAnimActivities.remove(r);
1783 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001784 r.updateOptionsLocked(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001785 mService.mWindowManager.addAppToken(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001786 addPos, r.appToken, r.task.taskId, r.info.screenOrientation, r.fullscreen);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001787 boolean doShow = true;
1788 if (newTask) {
1789 // Even though this activity is starting fresh, we still need
1790 // to reset it to make sure we apply affinities to move any
1791 // existing activities from other tasks in to it.
1792 // If the caller has requested that the target task be
1793 // reset, then do so.
1794 if ((r.intent.getFlags()
1795 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1796 resetTaskIfNeededLocked(r, r);
1797 doShow = topRunningNonDelayedActivityLocked(null) == r;
1798 }
1799 }
1800 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1801 // Figure out if we are transitioning from another activity that is
1802 // "has the same starting icon" as the next one. This allows the
1803 // window manager to keep the previous window it had previously
1804 // created, if it still had one.
1805 ActivityRecord prev = mResumedActivity;
1806 if (prev != null) {
1807 // We don't want to reuse the previous starting preview if:
1808 // (1) The current activity is in a different task.
1809 if (prev.task != r.task) prev = null;
1810 // (2) The current activity is already displayed.
1811 else if (prev.nowVisible) prev = null;
1812 }
1813 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001814 r.appToken, r.packageName, r.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001815 mService.compatibilityInfoForPackageLocked(
1816 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001817 r.labelRes, r.icon, r.windowFlags,
1818 prev != null ? prev.appToken : null, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001819 }
1820 } else {
1821 // If this is the first activity, don't do any fancy animations,
1822 // because there is nothing for it to animate on top of.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001823 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001824 r.info.screenOrientation, r.fullscreen);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001825 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001826 }
1827 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001828 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001829 }
1830
1831 if (doResume) {
1832 resumeTopActivityLocked(null);
1833 }
1834 }
1835
Dianne Hackbornbe707852011-11-11 14:32:10 -08001836 final void validateAppTokensLocked() {
1837 mValidateAppTokens.clear();
1838 mValidateAppTokens.ensureCapacity(mHistory.size());
1839 for (int i=0; i<mHistory.size(); i++) {
1840 mValidateAppTokens.add(mHistory.get(i).appToken);
1841 }
1842 mService.mWindowManager.validateAppTokens(mValidateAppTokens);
1843 }
1844
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001845 /**
1846 * Perform a reset of the given task, if needed as part of launching it.
1847 * Returns the new HistoryRecord at the top of the task.
1848 */
1849 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1850 ActivityRecord newActivity) {
1851 boolean forceReset = (newActivity.info.flags
1852 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001853 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1854 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001855 if ((newActivity.info.flags
1856 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1857 forceReset = true;
1858 }
1859 }
1860
1861 final TaskRecord task = taskTop.task;
1862
1863 // We are going to move through the history list so that we can look
1864 // at each activity 'target' with 'below' either the interesting
1865 // activity immediately below it in the stack or null.
1866 ActivityRecord target = null;
1867 int targetI = 0;
1868 int taskTopI = -1;
1869 int replyChainEnd = -1;
1870 int lastReparentPos = -1;
1871 for (int i=mHistory.size()-1; i>=-1; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001872 ActivityRecord below = i >= 0 ? mHistory.get(i) : null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001873
1874 if (below != null && below.finishing) {
1875 continue;
1876 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001877 // Don't check any lower in the stack if we're crossing a user boundary.
1878 if (below != null && below.userId != taskTop.userId) {
1879 break;
1880 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001881 if (target == null) {
1882 target = below;
1883 targetI = i;
1884 // If we were in the middle of a reply chain before this
1885 // task, it doesn't appear like the root of the chain wants
1886 // anything interesting, so drop it.
1887 replyChainEnd = -1;
1888 continue;
1889 }
1890
1891 final int flags = target.info.flags;
1892
1893 final boolean finishOnTaskLaunch =
1894 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1895 final boolean allowTaskReparenting =
1896 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1897
1898 if (target.task == task) {
1899 // We are inside of the task being reset... we'll either
1900 // finish this activity, push it out for another task,
1901 // or leave it as-is. We only do this
1902 // for activities that are not the root of the task (since
1903 // if we finish the root, we may no longer have the task!).
1904 if (taskTopI < 0) {
1905 taskTopI = targetI;
1906 }
1907 if (below != null && below.task == task) {
1908 final boolean clearWhenTaskReset =
1909 (target.intent.getFlags()
1910 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
1911 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
1912 // If this activity is sending a reply to a previous
1913 // activity, we can't do anything with it now until
1914 // we reach the start of the reply chain.
1915 // XXX note that we are assuming the result is always
1916 // to the previous activity, which is almost always
1917 // the case but we really shouldn't count on.
1918 if (replyChainEnd < 0) {
1919 replyChainEnd = targetI;
1920 }
1921 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
1922 && target.taskAffinity != null
1923 && !target.taskAffinity.equals(task.affinity)) {
1924 // If this activity has an affinity for another
1925 // task, then we need to move it out of here. We will
1926 // move it as far out of the way as possible, to the
1927 // bottom of the activity stack. This also keeps it
1928 // correctly ordered with any activities we previously
1929 // moved.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001930 ActivityRecord p = mHistory.get(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001931 if (target.taskAffinity != null
1932 && target.taskAffinity.equals(p.task.affinity)) {
1933 // If the activity currently at the bottom has the
1934 // same task affinity as the one we are moving,
1935 // then merge it into the same task.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001936 target.setTask(p.task, p.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001937 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1938 + " out to bottom task " + p.task);
1939 } else {
1940 mService.mCurTask++;
1941 if (mService.mCurTask <= 0) {
1942 mService.mCurTask = 1;
1943 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001944 target.setTask(new TaskRecord(mService.mCurTask, target.info, null),
1945 null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001946 target.task.affinityIntent = target.intent;
1947 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1948 + " out to new task " + target.task);
1949 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001950 mService.mWindowManager.setAppGroupId(target.appToken, task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001951 if (replyChainEnd < 0) {
1952 replyChainEnd = targetI;
1953 }
1954 int dstPos = 0;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001955 ThumbnailHolder curThumbHolder = target.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001956 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001957 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001958 if (p.finishing) {
1959 continue;
1960 }
1961 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
1962 + " out to target's task " + target.task);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001963 p.setTask(target.task, curThumbHolder, false);
1964 curThumbHolder = p.thumbHolder;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001965 if (DEBUG_ADD_REMOVE) {
1966 RuntimeException here = new RuntimeException("here");
1967 here.fillInStackTrace();
1968 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
1969 + dstPos, here);
1970 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001971 mHistory.remove(srcPos);
1972 mHistory.add(dstPos, p);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001973 mService.mWindowManager.moveAppToken(dstPos, p.appToken);
1974 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001975 dstPos++;
1976 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001977 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001978 }
1979 i++;
1980 }
1981 if (taskTop == p) {
1982 taskTop = below;
1983 }
1984 if (taskTopI == replyChainEnd) {
1985 taskTopI = -1;
1986 }
1987 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001988 } else if (forceReset || finishOnTaskLaunch
1989 || clearWhenTaskReset) {
1990 // If the activity should just be removed -- either
1991 // because it asks for it, or the task should be
1992 // cleared -- then finish it and anything that is
1993 // part of its reply chain.
1994 if (clearWhenTaskReset) {
1995 // In this case, we want to finish this activity
1996 // and everything above it, so be sneaky and pretend
1997 // like these are all in the reply chain.
1998 replyChainEnd = targetI+1;
1999 while (replyChainEnd < mHistory.size() &&
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002000 (mHistory.get(
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002001 replyChainEnd)).task == task) {
2002 replyChainEnd++;
2003 }
2004 replyChainEnd--;
2005 } else if (replyChainEnd < 0) {
2006 replyChainEnd = targetI;
2007 }
2008 ActivityRecord p = null;
2009 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002010 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002011 if (p.finishing) {
2012 continue;
2013 }
2014 if (finishActivityLocked(p, srcPos,
2015 Activity.RESULT_CANCELED, null, "reset")) {
2016 replyChainEnd--;
2017 srcPos--;
2018 }
2019 }
2020 if (taskTop == p) {
2021 taskTop = below;
2022 }
2023 if (taskTopI == replyChainEnd) {
2024 taskTopI = -1;
2025 }
2026 replyChainEnd = -1;
2027 } else {
2028 // If we were in the middle of a chain, well the
2029 // activity that started it all doesn't want anything
2030 // special, so leave it all as-is.
2031 replyChainEnd = -1;
2032 }
2033 } else {
2034 // Reached the bottom of the task -- any reply chain
2035 // should be left as-is.
2036 replyChainEnd = -1;
2037 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002038
2039 } else if (target.resultTo != null && (below == null
2040 || below.task == target.task)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002041 // If this activity is sending a reply to a previous
2042 // activity, we can't do anything with it now until
2043 // we reach the start of the reply chain.
2044 // XXX note that we are assuming the result is always
2045 // to the previous activity, which is almost always
2046 // the case but we really shouldn't count on.
2047 if (replyChainEnd < 0) {
2048 replyChainEnd = targetI;
2049 }
2050
2051 } else if (taskTopI >= 0 && allowTaskReparenting
2052 && task.affinity != null
2053 && task.affinity.equals(target.taskAffinity)) {
2054 // We are inside of another task... if this activity has
2055 // an affinity for our task, then either remove it if we are
2056 // clearing or move it over to our task. Note that
2057 // we currently punt on the case where we are resetting a
2058 // task that is not at the top but who has activities above
2059 // with an affinity to it... this is really not a normal
2060 // case, and we will need to later pull that task to the front
2061 // and usually at that point we will do the reset and pick
2062 // up those remaining activities. (This only happens if
2063 // someone starts an activity in a new task from an activity
2064 // in a task that is not currently on top.)
2065 if (forceReset || finishOnTaskLaunch) {
2066 if (replyChainEnd < 0) {
2067 replyChainEnd = targetI;
2068 }
2069 ActivityRecord p = null;
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002070 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index "
2071 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002072 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002073 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002074 if (p.finishing) {
2075 continue;
2076 }
2077 if (finishActivityLocked(p, srcPos,
2078 Activity.RESULT_CANCELED, null, "reset")) {
2079 taskTopI--;
2080 lastReparentPos--;
2081 replyChainEnd--;
2082 srcPos--;
2083 }
2084 }
2085 replyChainEnd = -1;
2086 } else {
2087 if (replyChainEnd < 0) {
2088 replyChainEnd = targetI;
2089 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002090 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting task at index "
2091 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002092 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002093 ActivityRecord p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002094 if (p.finishing) {
2095 continue;
2096 }
2097 if (lastReparentPos < 0) {
2098 lastReparentPos = taskTopI;
2099 taskTop = p;
2100 } else {
2101 lastReparentPos--;
2102 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002103 if (DEBUG_ADD_REMOVE) {
2104 RuntimeException here = new RuntimeException("here");
2105 here.fillInStackTrace();
2106 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2107 + lastReparentPos, here);
2108 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002109 mHistory.remove(srcPos);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002110 p.setTask(task, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002111 mHistory.add(lastReparentPos, p);
2112 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002113 + " from " + srcPos + " to " + lastReparentPos
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002114 + " in to resetting task " + task);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002115 mService.mWindowManager.moveAppToken(lastReparentPos, p.appToken);
2116 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002117 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002118 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002119 }
2120 }
2121 replyChainEnd = -1;
2122
2123 // Now we've moved it in to place... but what if this is
2124 // a singleTop activity and we have put it on top of another
2125 // instance of the same activity? Then we drop the instance
2126 // below so it remains singleTop.
2127 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2128 for (int j=lastReparentPos-1; j>=0; j--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002129 ActivityRecord p = mHistory.get(j);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002130 if (p.finishing) {
2131 continue;
2132 }
2133 if (p.intent.getComponent().equals(target.intent.getComponent())) {
2134 if (finishActivityLocked(p, j,
2135 Activity.RESULT_CANCELED, null, "replace")) {
2136 taskTopI--;
2137 lastReparentPos--;
2138 }
2139 }
2140 }
2141 }
2142 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002143
2144 } else if (below != null && below.task != target.task) {
2145 // We hit the botton of a task; the reply chain can't
2146 // pass through it.
2147 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002148 }
2149
2150 target = below;
2151 targetI = i;
2152 }
2153
2154 return taskTop;
2155 }
2156
2157 /**
2158 * Perform clear operation as requested by
2159 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2160 * stack to the given task, then look for
2161 * an instance of that activity in the stack and, if found, finish all
2162 * activities on top of it and return the instance.
2163 *
2164 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002165 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002166 * or null if none was found.
2167 */
2168 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002169 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002170 int i = mHistory.size();
2171
2172 // First find the requested task.
2173 while (i > 0) {
2174 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002175 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002176 if (r.task.taskId == taskId) {
2177 i++;
2178 break;
2179 }
2180 }
2181
2182 // Now clear it.
2183 while (i > 0) {
2184 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002185 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002186 if (r.finishing) {
2187 continue;
2188 }
2189 if (r.task.taskId != taskId) {
2190 return null;
2191 }
2192 if (r.realActivity.equals(newR.realActivity)) {
2193 // Here it is! Now finish everything in front...
2194 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002195 while (i < (mHistory.size()-1)) {
2196 i++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002197 r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002198 if (r.task.taskId != taskId) {
2199 break;
2200 }
2201 if (r.finishing) {
2202 continue;
2203 }
2204 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2205 null, "clear")) {
2206 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002207 }
2208 }
2209
2210 // Finally, if this is a normal launch mode (that is, not
2211 // expecting onNewIntent()), then we will finish the current
2212 // instance of the activity so a new fresh one can be started.
2213 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2214 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
2215 if (!ret.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002216 int index = indexOfTokenLocked(ret.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002217 if (index >= 0) {
2218 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
2219 null, "clear");
2220 }
2221 return null;
2222 }
2223 }
2224
2225 return ret;
2226 }
2227 }
2228
2229 return null;
2230 }
2231
2232 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002233 * Completely remove all activities associated with an existing
2234 * task starting at a specified index.
2235 */
2236 private final void performClearTaskAtIndexLocked(int taskId, int i) {
Dianne Hackborneabd3282011-10-13 16:26:49 -07002237 while (i < mHistory.size()) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002238 ActivityRecord r = mHistory.get(i);
2239 if (r.task.taskId != taskId) {
2240 // Whoops hit the end.
2241 return;
2242 }
2243 if (r.finishing) {
2244 i++;
2245 continue;
2246 }
2247 if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2248 null, "clear")) {
2249 i++;
2250 }
2251 }
2252 }
2253
2254 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002255 * Completely remove all activities associated with an existing task.
2256 */
2257 private final void performClearTaskLocked(int taskId) {
2258 int i = mHistory.size();
2259
2260 // First find the requested task.
2261 while (i > 0) {
2262 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002263 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002264 if (r.task.taskId == taskId) {
2265 i++;
2266 break;
2267 }
2268 }
2269
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002270 // Now find the start and clear it.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002271 while (i > 0) {
2272 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002273 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002274 if (r.finishing) {
2275 continue;
2276 }
2277 if (r.task.taskId != taskId) {
2278 // We hit the bottom. Now finish it all...
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002279 performClearTaskAtIndexLocked(taskId, i+1);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002280 return;
2281 }
2282 }
2283 }
2284
2285 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002286 * Find the activity in the history stack within the given task. Returns
2287 * the index within the history at which it's found, or < 0 if not found.
2288 */
2289 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2290 int i = mHistory.size();
2291 while (i > 0) {
2292 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002293 ActivityRecord candidate = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002294 if (candidate.task.taskId != task) {
2295 break;
2296 }
2297 if (candidate.realActivity.equals(r.realActivity)) {
2298 return i;
2299 }
2300 }
2301
2302 return -1;
2303 }
2304
2305 /**
2306 * Reorder the history stack so that the activity at the given index is
2307 * brought to the front.
2308 */
2309 private final ActivityRecord moveActivityToFrontLocked(int where) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002310 ActivityRecord newTop = mHistory.remove(where);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002311 int top = mHistory.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002312 ActivityRecord oldTop = mHistory.get(top-1);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002313 if (DEBUG_ADD_REMOVE) {
2314 RuntimeException here = new RuntimeException("here");
2315 here.fillInStackTrace();
2316 Slog.i(TAG, "Removing and adding activity " + newTop + " to stack at "
2317 + top, here);
2318 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002319 mHistory.add(top, newTop);
2320 oldTop.frontOfTask = false;
2321 newTop.frontOfTask = true;
2322 return newTop;
2323 }
2324
2325 final int startActivityLocked(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002326 Intent intent, String resolvedType, ActivityInfo aInfo, IBinder resultTo,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002327 String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002328 int callingPid, int callingUid, int startFlags, Bundle options,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002329 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002330
Dianne Hackborna4972e92012-03-14 10:38:05 -07002331 int err = ActivityManager.START_SUCCESS;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002332
2333 ProcessRecord callerApp = null;
2334 if (caller != null) {
2335 callerApp = mService.getRecordForAppLocked(caller);
2336 if (callerApp != null) {
2337 callingPid = callerApp.pid;
2338 callingUid = callerApp.info.uid;
2339 } else {
2340 Slog.w(TAG, "Unable to find app for caller " + caller
2341 + " (pid=" + callingPid + ") when starting: "
2342 + intent.toString());
Dianne Hackborna4972e92012-03-14 10:38:05 -07002343 err = ActivityManager.START_PERMISSION_DENIED;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002344 }
2345 }
2346
Dianne Hackborna4972e92012-03-14 10:38:05 -07002347 if (err == ActivityManager.START_SUCCESS) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08002348 Slog.i(TAG, "START {" + intent.toShortString(true, true, true, false)
2349 + "} from pid " + (callerApp != null ? callerApp.pid : callingPid));
Dianne Hackbornefb58102010-10-14 16:47:34 -07002350 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002351
2352 ActivityRecord sourceRecord = null;
2353 ActivityRecord resultRecord = null;
2354 if (resultTo != null) {
2355 int index = indexOfTokenLocked(resultTo);
2356 if (DEBUG_RESULTS) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002357 TAG, "Will send result to " + resultTo + " (index " + index + ")");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002358 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002359 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002360 if (requestCode >= 0 && !sourceRecord.finishing) {
2361 resultRecord = sourceRecord;
2362 }
2363 }
2364 }
2365
2366 int launchFlags = intent.getFlags();
2367
2368 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2369 && sourceRecord != null) {
2370 // Transfer the result target from the source activity to the new
2371 // one being started, including any failures.
2372 if (requestCode >= 0) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002373 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002374 return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002375 }
2376 resultRecord = sourceRecord.resultTo;
2377 resultWho = sourceRecord.resultWho;
2378 requestCode = sourceRecord.requestCode;
2379 sourceRecord.resultTo = null;
2380 if (resultRecord != null) {
2381 resultRecord.removeResultsLocked(
2382 sourceRecord, resultWho, requestCode);
2383 }
2384 }
2385
Dianne Hackborna4972e92012-03-14 10:38:05 -07002386 if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002387 // We couldn't find a class that can handle the given Intent.
2388 // That's the end of that!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002389 err = ActivityManager.START_INTENT_NOT_RESOLVED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002390 }
2391
Dianne Hackborna4972e92012-03-14 10:38:05 -07002392 if (err == ActivityManager.START_SUCCESS && aInfo == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002393 // We couldn't find the specific class specified in the Intent.
2394 // Also the end of the line.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002395 err = ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002396 }
2397
Dianne Hackborna4972e92012-03-14 10:38:05 -07002398 if (err != ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002399 if (resultRecord != null) {
2400 sendActivityResultLocked(-1,
2401 resultRecord, resultWho, requestCode,
2402 Activity.RESULT_CANCELED, null);
2403 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002404 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002405 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002406 return err;
2407 }
2408
2409 final int perm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002410 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002411 if (perm != PackageManager.PERMISSION_GRANTED) {
2412 if (resultRecord != null) {
2413 sendActivityResultLocked(-1,
2414 resultRecord, resultWho, requestCode,
2415 Activity.RESULT_CANCELED, null);
2416 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002417 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002418 String msg;
2419 if (!aInfo.exported) {
2420 msg = "Permission Denial: starting " + intent.toString()
2421 + " from " + callerApp + " (pid=" + callingPid
2422 + ", uid=" + callingUid + ")"
2423 + " not exported from uid " + aInfo.applicationInfo.uid;
2424 } else {
2425 msg = "Permission Denial: starting " + intent.toString()
2426 + " from " + callerApp + " (pid=" + callingPid
2427 + ", uid=" + callingUid + ")"
2428 + " requires " + aInfo.permission;
2429 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002430 Slog.w(TAG, msg);
2431 throw new SecurityException(msg);
2432 }
2433
2434 if (mMainStack) {
2435 if (mService.mController != null) {
2436 boolean abort = false;
2437 try {
2438 // The Intent we give to the watcher has the extra data
2439 // stripped off, since it can contain private information.
2440 Intent watchIntent = intent.cloneFilter();
2441 abort = !mService.mController.activityStarting(watchIntent,
2442 aInfo.applicationInfo.packageName);
2443 } catch (RemoteException e) {
2444 mService.mController = null;
2445 }
2446
2447 if (abort) {
2448 if (resultRecord != null) {
2449 sendActivityResultLocked(-1,
2450 resultRecord, resultWho, requestCode,
2451 Activity.RESULT_CANCELED, null);
2452 }
2453 // We pretend to the caller that it was really started, but
2454 // they will just get a cancel result.
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002455 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002456 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002457 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002458 }
2459 }
2460 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002461
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002462 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2463 intent, resolvedType, aInfo, mService.mConfiguration,
2464 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002465 if (outActivity != null) {
2466 outActivity[0] = r;
2467 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002468
2469 if (mMainStack) {
2470 if (mResumedActivity == null
2471 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2472 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2473 PendingActivityLaunch pal = new PendingActivityLaunch();
2474 pal.r = r;
2475 pal.sourceRecord = sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002476 pal.startFlags = startFlags;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002477 mService.mPendingActivityLaunches.add(pal);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002478 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002479 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002480 return ActivityManager.START_SWITCHES_CANCELED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002481 }
2482 }
2483
2484 if (mService.mDidAppSwitch) {
2485 // This is the second allowed switch since we stopped switches,
2486 // so now just generally allow switches. Use case: user presses
2487 // home (switches disabled, switch to home, mDidAppSwitch now true);
2488 // user taps a home icon (coming from home so allowed, we hit here
2489 // and now allow anyone to switch again).
2490 mService.mAppSwitchesAllowedTime = 0;
2491 } else {
2492 mService.mDidAppSwitch = true;
2493 }
2494
2495 mService.doPendingActivityLaunchesLocked(false);
2496 }
2497
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002498 err = startActivityUncheckedLocked(r, sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002499 startFlags, true, options);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002500 if (mDismissKeyguardOnNextActivity && mPausingActivity == null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002501 // Someone asked to have the keyguard dismissed on the next
2502 // activity start, but we are not actually doing an activity
2503 // switch... just dismiss the keyguard now, because we
2504 // probably want to see whatever is behind it.
2505 mDismissKeyguardOnNextActivity = false;
2506 mService.mWindowManager.dismissKeyguard();
2507 }
2508 return err;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002509 }
2510
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002511 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2512 if ((launchFlags &
2513 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2514 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2515 // Caller wants to appear on home activity, so before starting
2516 // their own activity we will bring home to the front.
2517 moveHomeToFrontLocked();
2518 }
2519 }
2520
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002521 final int startActivityUncheckedLocked(ActivityRecord r,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002522 ActivityRecord sourceRecord, int startFlags, boolean doResume,
2523 Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002524 final Intent intent = r.intent;
2525 final int callingUid = r.launchedFromUid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002526 final int userId = r.userId;
2527
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002528 int launchFlags = intent.getFlags();
2529
2530 // We'll invoke onUserLeaving before onPause only if the launching
2531 // activity did not explicitly state that this is an automated launch.
2532 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2533 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2534 "startActivity() => mUserLeaving=" + mUserLeaving);
2535
2536 // If the caller has asked not to resume at this point, we make note
2537 // of this in the record so that we can skip it when trying to find
2538 // the top running activity.
2539 if (!doResume) {
2540 r.delayedResume = true;
2541 }
2542
2543 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2544 != 0 ? r : null;
2545
2546 // If the onlyIfNeeded flag is set, then we can do this if the activity
2547 // being launched is the same as the one making the call... or, as
2548 // a special case, if we do not know the caller then we count the
2549 // current top activity as the caller.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002550 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002551 ActivityRecord checkedCaller = sourceRecord;
2552 if (checkedCaller == null) {
2553 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2554 }
2555 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2556 // Caller is not the same as launcher, so always needed.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002557 startFlags &= ~ActivityManager.START_FLAG_ONLY_IF_NEEDED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002558 }
2559 }
2560
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002561 if (sourceRecord == null) {
2562 // This activity is not being started from another... in this
2563 // case we -always- start a new task.
2564 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2565 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2566 + intent);
2567 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2568 }
2569 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2570 // The original activity who is starting us is running as a single
2571 // instance... this new activity it is starting must go on its
2572 // own task.
2573 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2574 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2575 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2576 // The activity being started is a single instance... it always
2577 // gets launched into its own task.
2578 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2579 }
2580
2581 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2582 // For whatever reason this activity is being launched into a new
2583 // task... yet the caller has requested a result back. Well, that
2584 // is pretty messed up, so instead immediately send back a cancel
2585 // and let the new task continue launched as normal without a
2586 // dependency on its originator.
2587 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2588 sendActivityResultLocked(-1,
2589 r.resultTo, r.resultWho, r.requestCode,
2590 Activity.RESULT_CANCELED, null);
2591 r.resultTo = null;
2592 }
2593
2594 boolean addingToTask = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002595 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002596 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2597 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2598 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2599 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2600 // If bring to front is requested, and no result is requested, and
2601 // we can find a task that was started with this same
2602 // component, then instead of launching bring that one to the front.
2603 if (r.resultTo == null) {
2604 // See if there is a task to bring to the front. If this is
2605 // a SINGLE_INSTANCE activity, there can be one and only one
2606 // instance of it in the history, and it is always in its own
2607 // unique task, so we do a special search.
2608 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2609 ? findTaskLocked(intent, r.info)
2610 : findActivityLocked(intent, r.info);
2611 if (taskTop != null) {
2612 if (taskTop.task.intent == null) {
2613 // This task was started because of movement of
2614 // the activity based on affinity... now that we
2615 // are actually launching it, we can assign the
2616 // base intent.
2617 taskTop.task.setIntent(intent, r.info);
2618 }
2619 // If the target task is not in the front, then we need
2620 // to bring it to the front... except... well, with
2621 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2622 // to have the same behavior as if a new instance was
2623 // being started, which means not bringing it to the front
2624 // if the caller is not itself in the front.
2625 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002626 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002627 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2628 boolean callerAtFront = sourceRecord == null
2629 || curTop.task == sourceRecord.task;
2630 if (callerAtFront) {
2631 // We really do want to push this one into the
2632 // user's face, right now.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002633 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002634 moveTaskToFrontLocked(taskTop.task, r, options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002635 }
2636 }
2637 // If the caller has requested that the target task be
2638 // reset, then do so.
2639 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2640 taskTop = resetTaskIfNeededLocked(taskTop, r);
2641 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002642 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002643 // We don't need to start a new activity, and
2644 // the client said not to do anything if that
2645 // is the case, so this is it! And for paranoia, make
2646 // sure we have correctly resumed the top activity.
2647 if (doResume) {
2648 resumeTopActivityLocked(null);
2649 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002650 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002651 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002652 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002653 if ((launchFlags &
2654 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2655 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2656 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002657 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002658 // not be too hard...
2659 reuseTask = taskTop.task;
2660 performClearTaskLocked(taskTop.task.taskId);
2661 reuseTask.setIntent(r.intent, r.info);
2662 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002663 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2664 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2665 // In this situation we want to remove all activities
2666 // from the task up to the one being started. In most
2667 // cases this means we are resetting the task to its
2668 // initial state.
2669 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002670 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002671 if (top != null) {
2672 if (top.frontOfTask) {
2673 // Activity aliases may mean we use different
2674 // intents for the top activity, so make sure
2675 // the task now has the identity of the new
2676 // intent.
2677 top.task.setIntent(r.intent, r.info);
2678 }
2679 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002680 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002681 } else {
2682 // A special case: we need to
2683 // start the activity because it is not currently
2684 // running, and the caller has asked to clear the
2685 // current task to have this activity at the top.
2686 addingToTask = true;
2687 // Now pretend like this activity is being started
2688 // by the top of its task, so it is put in the
2689 // right place.
2690 sourceRecord = taskTop;
2691 }
2692 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2693 // In this case the top activity on the task is the
2694 // same as the one being launched, so we take that
2695 // as a request to bring the task to the foreground.
2696 // If the top activity in the task is the root
2697 // activity, deliver this new intent to it if it
2698 // desires.
2699 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2700 && taskTop.realActivity.equals(r.realActivity)) {
2701 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2702 if (taskTop.frontOfTask) {
2703 taskTop.task.setIntent(r.intent, r.info);
2704 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002705 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002706 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2707 // In this case we are launching the root activity
2708 // of the task, but with a different intent. We
2709 // should start a new instance on top.
2710 addingToTask = true;
2711 sourceRecord = taskTop;
2712 }
2713 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2714 // In this case an activity is being launched in to an
2715 // existing task, without resetting that task. This
2716 // is typically the situation of launching an activity
2717 // from a notification or shortcut. We want to place
2718 // the new activity on top of the current task.
2719 addingToTask = true;
2720 sourceRecord = taskTop;
2721 } else if (!taskTop.task.rootWasReset) {
2722 // In this case we are launching in to an existing task
2723 // that has not yet been started from its front door.
2724 // The current task has been brought to the front.
2725 // Ideally, we'd probably like to place this new task
2726 // at the bottom of its stack, but that's a little hard
2727 // to do with the current organization of the code so
2728 // for now we'll just drop it.
2729 taskTop.task.setIntent(r.intent, r.info);
2730 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002731 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002732 // We didn't do anything... but it was needed (a.k.a., client
2733 // don't use that intent!) And for paranoia, make
2734 // sure we have correctly resumed the top activity.
2735 if (doResume) {
2736 resumeTopActivityLocked(null);
2737 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002738 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002739 return ActivityManager.START_TASK_TO_FRONT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002740 }
2741 }
2742 }
2743 }
2744
2745 //String uri = r.intent.toURI();
2746 //Intent intent2 = new Intent(uri);
2747 //Slog.i(TAG, "Given intent: " + r.intent);
2748 //Slog.i(TAG, "URI is: " + uri);
2749 //Slog.i(TAG, "To intent: " + intent2);
2750
2751 if (r.packageName != null) {
2752 // If the activity being launched is the same as the one currently
2753 // at the top, then we need to check if it should only be launched
2754 // once.
2755 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2756 if (top != null && r.resultTo == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002757 if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002758 if (top.app != null && top.app.thread != null) {
2759 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2760 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2761 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2762 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2763 // For paranoia, make sure we have correctly
2764 // resumed the top activity.
2765 if (doResume) {
2766 resumeTopActivityLocked(null);
2767 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002768 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002769 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002770 // We don't need to start a new activity, and
2771 // the client said not to do anything if that
2772 // is the case, so this is it!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002773 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002774 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002775 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002776 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002777 }
2778 }
2779 }
2780 }
2781
2782 } else {
2783 if (r.resultTo != null) {
2784 sendActivityResultLocked(-1,
2785 r.resultTo, r.resultWho, r.requestCode,
2786 Activity.RESULT_CANCELED, null);
2787 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002788 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002789 return ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002790 }
2791
2792 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002793 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002794
2795 // Should this be considered a new task?
2796 if (r.resultTo == null && !addingToTask
2797 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002798 if (reuseTask == null) {
2799 // todo: should do better management of integers.
2800 mService.mCurTask++;
2801 if (mService.mCurTask <= 0) {
2802 mService.mCurTask = 1;
2803 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002804 r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002805 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2806 + " in new task " + r.task);
2807 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002808 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002809 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002810 newTask = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002811 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002812
2813 } else if (sourceRecord != null) {
2814 if (!addingToTask &&
2815 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2816 // In this case, we are adding the activity to an existing
2817 // task, but the caller has asked to clear that task if the
2818 // activity is already running.
2819 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002820 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002821 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002822 if (top != null) {
2823 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002824 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002825 // For paranoia, make sure we have correctly
2826 // resumed the top activity.
2827 if (doResume) {
2828 resumeTopActivityLocked(null);
2829 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002830 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002831 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002832 }
2833 } else if (!addingToTask &&
2834 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2835 // In this case, we are launching an activity in our own task
2836 // that may already be running somewhere in the history, and
2837 // we want to shuffle it to the front of the stack if so.
2838 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2839 if (where >= 0) {
2840 ActivityRecord top = moveActivityToFrontLocked(where);
2841 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002842 top.updateOptionsLocked(options);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002843 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002844 if (doResume) {
2845 resumeTopActivityLocked(null);
2846 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002847 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002848 }
2849 }
2850 // An existing activity is starting this new activity, so we want
2851 // to keep the new one in the same task as the one that is starting
2852 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002853 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002854 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2855 + " in existing task " + r.task);
2856
2857 } else {
2858 // This not being started from an existing activity, and not part
2859 // of a new task... just put it in the top task, though these days
2860 // this case should never happen.
2861 final int N = mHistory.size();
2862 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002863 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002864 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002865 ? prev.task
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002866 : new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002867 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2868 + " in new guessed " + r.task);
2869 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002870
Dianne Hackborn39792d22010-08-19 18:01:52 -07002871 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002872 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002873
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002874 if (newTask) {
2875 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
2876 }
2877 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002878 startActivityLocked(r, newTask, doResume, keepCurTransition, options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002879 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002880 }
2881
Dianne Hackborna4972e92012-03-14 10:38:05 -07002882 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002883 String profileFile, ParcelFileDescriptor profileFd, int userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002884 // Collect information about the target of the Intent.
2885 ActivityInfo aInfo;
2886 try {
2887 ResolveInfo rInfo =
2888 AppGlobals.getPackageManager().resolveIntent(
2889 intent, resolvedType,
2890 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07002891 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002892 aInfo = rInfo != null ? rInfo.activityInfo : null;
2893 } catch (RemoteException e) {
2894 aInfo = null;
2895 }
2896
2897 if (aInfo != null) {
2898 // Store the found target back into the intent, because now that
2899 // we have it we never want to do this again. For example, if the
2900 // user navigates back to this point in the history, we should
2901 // always restart the exact same activity.
2902 intent.setComponent(new ComponentName(
2903 aInfo.applicationInfo.packageName, aInfo.name));
2904
2905 // Don't debug things in the system process
Dianne Hackborna4972e92012-03-14 10:38:05 -07002906 if ((startFlags&ActivityManager.START_FLAG_DEBUG) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002907 if (!aInfo.processName.equals("system")) {
2908 mService.setDebugApp(aInfo.processName, true, false);
2909 }
2910 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002911
Dianne Hackborna4972e92012-03-14 10:38:05 -07002912 if ((startFlags&ActivityManager.START_FLAG_OPENGL_TRACES) != 0) {
Siva Velusamy92a8b222012-03-09 16:24:04 -08002913 if (!aInfo.processName.equals("system")) {
2914 mService.setOpenGlTraceApp(aInfo.applicationInfo, aInfo.processName);
2915 }
2916 }
2917
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002918 if (profileFile != null) {
2919 if (!aInfo.processName.equals("system")) {
2920 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002921 profileFile, profileFd,
2922 (startFlags&ActivityManager.START_FLAG_AUTO_STOP_PROFILER) != 0);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002923 }
2924 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002925 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002926 return aInfo;
2927 }
2928
2929 final int startActivityMayWait(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002930 Intent intent, String resolvedType, IBinder resultTo,
2931 String resultWho, int requestCode, int startFlags, String profileFile,
2932 ParcelFileDescriptor profileFd, WaitResult outResult, Configuration config,
2933 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002934 // Refuse possible leaked file descriptors
2935 if (intent != null && intent.hasFileDescriptors()) {
2936 throw new IllegalArgumentException("File descriptors passed in Intent");
2937 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002938 boolean componentSpecified = intent.getComponent() != null;
2939
2940 // Don't modify the client's object!
2941 intent = new Intent(intent);
2942
2943 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002944 ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002945 profileFile, profileFd, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002946 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002947
2948 synchronized (mService) {
2949 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002950 if (callingUid >= 0) {
2951 callingPid = -1;
2952 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002953 callingPid = Binder.getCallingPid();
2954 callingUid = Binder.getCallingUid();
2955 } else {
2956 callingPid = callingUid = -1;
2957 }
2958
2959 mConfigWillChange = config != null
2960 && mService.mConfiguration.diff(config) != 0;
2961 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2962 "Starting activity when config will change = " + mConfigWillChange);
2963
2964 final long origId = Binder.clearCallingIdentity();
2965
2966 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07002967 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002968 // This may be a heavy-weight process! Check to see if we already
2969 // have another, different heavy-weight process running.
2970 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
2971 if (mService.mHeavyWeightProcess != null &&
2972 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
2973 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
2974 int realCallingPid = callingPid;
2975 int realCallingUid = callingUid;
2976 if (caller != null) {
2977 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
2978 if (callerApp != null) {
2979 realCallingPid = callerApp.pid;
2980 realCallingUid = callerApp.info.uid;
2981 } else {
2982 Slog.w(TAG, "Unable to find app for caller " + caller
2983 + " (pid=" + realCallingPid + ") when starting: "
2984 + intent.toString());
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002985 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002986 return ActivityManager.START_PERMISSION_DENIED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002987 }
2988 }
2989
2990 IIntentSender target = mService.getIntentSenderLocked(
Dianne Hackborna4972e92012-03-14 10:38:05 -07002991 ActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002992 realCallingUid, null, null, 0, new Intent[] { intent },
2993 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002994 | PendingIntent.FLAG_ONE_SHOT, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002995
2996 Intent newIntent = new Intent();
2997 if (requestCode >= 0) {
2998 // Caller is requesting a result.
2999 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
3000 }
3001 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
3002 new IntentSender(target));
3003 if (mService.mHeavyWeightProcess.activities.size() > 0) {
3004 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
3005 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
3006 hist.packageName);
3007 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
3008 hist.task.taskId);
3009 }
3010 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
3011 aInfo.packageName);
3012 newIntent.setFlags(intent.getFlags());
3013 newIntent.setClassName("android",
3014 HeavyWeightSwitcherActivity.class.getName());
3015 intent = newIntent;
3016 resolvedType = null;
3017 caller = null;
3018 callingUid = Binder.getCallingUid();
3019 callingPid = Binder.getCallingPid();
3020 componentSpecified = true;
3021 try {
3022 ResolveInfo rInfo =
3023 AppGlobals.getPackageManager().resolveIntent(
3024 intent, null,
3025 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07003026 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003027 aInfo = rInfo != null ? rInfo.activityInfo : null;
Amith Yamasani742a6712011-05-04 14:49:28 -07003028 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003029 } catch (RemoteException e) {
3030 aInfo = null;
3031 }
3032 }
3033 }
3034 }
3035
3036 int res = startActivityLocked(caller, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003037 aInfo, resultTo, resultWho, requestCode, callingPid, callingUid,
3038 startFlags, options, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003039
3040 if (mConfigWillChange && mMainStack) {
3041 // If the caller also wants to switch to a new configuration,
3042 // do so now. This allows a clean switch, as we are waiting
3043 // for the current activity to pause (so we will not destroy
3044 // it), and have not yet started the next activity.
3045 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
3046 "updateConfiguration()");
3047 mConfigWillChange = false;
3048 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3049 "Updating to new configuration after starting activity.");
Dianne Hackborn813075a62011-11-14 17:45:19 -08003050 mService.updateConfigurationLocked(config, null, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003051 }
3052
3053 Binder.restoreCallingIdentity(origId);
3054
3055 if (outResult != null) {
3056 outResult.result = res;
Dianne Hackborna4972e92012-03-14 10:38:05 -07003057 if (res == ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003058 mWaitingActivityLaunched.add(outResult);
3059 do {
3060 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003061 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003062 } catch (InterruptedException e) {
3063 }
3064 } while (!outResult.timeout && outResult.who == null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003065 } else if (res == ActivityManager.START_TASK_TO_FRONT) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003066 ActivityRecord r = this.topRunningActivityLocked(null);
3067 if (r.nowVisible) {
3068 outResult.timeout = false;
3069 outResult.who = new ComponentName(r.info.packageName, r.info.name);
3070 outResult.totalTime = 0;
3071 outResult.thisTime = 0;
3072 } else {
3073 outResult.thisTime = SystemClock.uptimeMillis();
3074 mWaitingActivityVisible.add(outResult);
3075 do {
3076 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003077 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003078 } catch (InterruptedException e) {
3079 }
3080 } while (!outResult.timeout && outResult.who == null);
3081 }
3082 }
3083 }
3084
3085 return res;
3086 }
3087 }
3088
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003089 final int startActivities(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003090 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
3091 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003092 if (intents == null) {
3093 throw new NullPointerException("intents is null");
3094 }
3095 if (resolvedTypes == null) {
3096 throw new NullPointerException("resolvedTypes is null");
3097 }
3098 if (intents.length != resolvedTypes.length) {
3099 throw new IllegalArgumentException("intents are length different than resolvedTypes");
3100 }
3101
3102 ActivityRecord[] outActivity = new ActivityRecord[1];
3103
3104 int callingPid;
3105 if (callingUid >= 0) {
3106 callingPid = -1;
3107 } else if (caller == null) {
3108 callingPid = Binder.getCallingPid();
3109 callingUid = Binder.getCallingUid();
3110 } else {
3111 callingPid = callingUid = -1;
3112 }
3113 final long origId = Binder.clearCallingIdentity();
3114 try {
3115 synchronized (mService) {
3116
3117 for (int i=0; i<intents.length; i++) {
3118 Intent intent = intents[i];
3119 if (intent == null) {
3120 continue;
3121 }
3122
3123 // Refuse possible leaked file descriptors
3124 if (intent != null && intent.hasFileDescriptors()) {
3125 throw new IllegalArgumentException("File descriptors passed in Intent");
3126 }
3127
3128 boolean componentSpecified = intent.getComponent() != null;
3129
3130 // Don't modify the client's object!
3131 intent = new Intent(intent);
3132
3133 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003134 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i],
Amith Yamasani483f3b02012-03-13 16:08:00 -07003135 0, null, null, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07003136 // TODO: New, check if this is correct
3137 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003138
3139 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
3140 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
3141 throw new IllegalArgumentException(
3142 "FLAG_CANT_SAVE_STATE not supported here");
3143 }
3144
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003145 Bundle theseOptions;
3146 if (options != null && i == intents.length-1) {
3147 theseOptions = options;
3148 } else {
3149 theseOptions = null;
3150 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003151 int res = startActivityLocked(caller, intent, resolvedTypes[i],
Dianne Hackborna4972e92012-03-14 10:38:05 -07003152 aInfo, resultTo, null, -1, callingPid, callingUid,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003153 0, theseOptions, componentSpecified, outActivity);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003154 if (res < 0) {
3155 return res;
3156 }
3157
Dianne Hackbornbe707852011-11-11 14:32:10 -08003158 resultTo = outActivity[0] != null ? outActivity[0].appToken : null;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003159 }
3160 }
3161 } finally {
3162 Binder.restoreCallingIdentity(origId);
3163 }
3164
Dianne Hackborna4972e92012-03-14 10:38:05 -07003165 return ActivityManager.START_SUCCESS;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003166 }
3167
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003168 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
3169 long thisTime, long totalTime) {
3170 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
3171 WaitResult w = mWaitingActivityLaunched.get(i);
3172 w.timeout = timeout;
3173 if (r != null) {
3174 w.who = new ComponentName(r.info.packageName, r.info.name);
3175 }
3176 w.thisTime = thisTime;
3177 w.totalTime = totalTime;
3178 }
3179 mService.notifyAll();
3180 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003181
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003182 void reportActivityVisibleLocked(ActivityRecord r) {
3183 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
3184 WaitResult w = mWaitingActivityVisible.get(i);
3185 w.timeout = false;
3186 if (r != null) {
3187 w.who = new ComponentName(r.info.packageName, r.info.name);
3188 }
3189 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
3190 w.thisTime = w.totalTime;
3191 }
3192 mService.notifyAll();
Dianne Hackborn90c52de2011-09-23 12:57:44 -07003193
3194 if (mDismissKeyguardOnNextActivity) {
3195 mDismissKeyguardOnNextActivity = false;
3196 mService.mWindowManager.dismissKeyguard();
3197 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003198 }
3199
3200 void sendActivityResultLocked(int callingUid, ActivityRecord r,
3201 String resultWho, int requestCode, int resultCode, Intent data) {
3202
3203 if (callingUid > 0) {
3204 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003205 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003206 }
3207
3208 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3209 + " : who=" + resultWho + " req=" + requestCode
3210 + " res=" + resultCode + " data=" + data);
3211 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3212 try {
3213 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3214 list.add(new ResultInfo(resultWho, requestCode,
3215 resultCode, data));
Dianne Hackbornbe707852011-11-11 14:32:10 -08003216 r.app.thread.scheduleSendResult(r.appToken, list);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003217 return;
3218 } catch (Exception e) {
3219 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3220 }
3221 }
3222
3223 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3224 }
3225
3226 private final void stopActivityLocked(ActivityRecord r) {
3227 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3228 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3229 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3230 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003231 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003232 "no-history");
3233 }
3234 } else if (r.app != null && r.app.thread != null) {
3235 if (mMainStack) {
3236 if (mService.mFocusedActivity == r) {
3237 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3238 }
3239 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003240 r.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003241 try {
3242 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003243 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3244 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003245 r.state = ActivityState.STOPPING;
3246 if (DEBUG_VISBILITY) Slog.v(
3247 TAG, "Stopping visible=" + r.visible + " for " + r);
3248 if (!r.visible) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003249 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003250 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003251 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003252 if (mService.isSleeping()) {
3253 r.setSleeping(true);
3254 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003255 Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG);
3256 msg.obj = r;
3257 mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003258 } catch (Exception e) {
3259 // Maybe just ignore exceptions here... if the process
3260 // has crashed, our death notification will clean things
3261 // up.
3262 Slog.w(TAG, "Exception thrown during pause", e);
3263 // Just in case, assume it to be stopped.
3264 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003265 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003266 r.state = ActivityState.STOPPED;
3267 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003268 destroyActivityLocked(r, true, false, "stop-except");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003269 }
3270 }
3271 }
3272 }
3273
3274 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3275 boolean remove) {
3276 int N = mStoppingActivities.size();
3277 if (N <= 0) return null;
3278
3279 ArrayList<ActivityRecord> stops = null;
3280
3281 final boolean nowVisible = mResumedActivity != null
3282 && mResumedActivity.nowVisible
3283 && !mResumedActivity.waitingVisible;
3284 for (int i=0; i<N; i++) {
3285 ActivityRecord s = mStoppingActivities.get(i);
3286 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3287 + nowVisible + " waitingVisible=" + s.waitingVisible
3288 + " finishing=" + s.finishing);
3289 if (s.waitingVisible && nowVisible) {
3290 mWaitingVisibleActivities.remove(s);
3291 s.waitingVisible = false;
3292 if (s.finishing) {
3293 // If this activity is finishing, it is sitting on top of
3294 // everyone else but we now know it is no longer needed...
3295 // so get rid of it. Otherwise, we need to go through the
3296 // normal flow and hide it once we determine that it is
3297 // hidden by the activities in front of it.
3298 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003299 mService.mWindowManager.setAppVisibility(s.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003300 }
3301 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003302 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003303 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3304 if (stops == null) {
3305 stops = new ArrayList<ActivityRecord>();
3306 }
3307 stops.add(s);
3308 mStoppingActivities.remove(i);
3309 N--;
3310 i--;
3311 }
3312 }
3313
3314 return stops;
3315 }
3316
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003317 final void scheduleIdleLocked() {
3318 Message msg = Message.obtain();
3319 msg.what = IDLE_NOW_MSG;
3320 mHandler.sendMessage(msg);
3321 }
3322
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003323 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003324 Configuration config) {
3325 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3326
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003327 ActivityRecord res = null;
3328
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003329 ArrayList<ActivityRecord> stops = null;
3330 ArrayList<ActivityRecord> finishes = null;
3331 ArrayList<ActivityRecord> thumbnails = null;
3332 int NS = 0;
3333 int NF = 0;
3334 int NT = 0;
3335 IApplicationThread sendThumbnail = null;
3336 boolean booting = false;
3337 boolean enableScreen = false;
3338
3339 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003340 ActivityRecord r = ActivityRecord.forToken(token);
3341 if (r != null) {
3342 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003343 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003344 }
3345
3346 // Get the activity record.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003347 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003348 if (index >= 0) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003349 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003350
3351 if (fromTimeout) {
3352 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3353 }
3354
3355 // This is a hack to semi-deal with a race condition
3356 // in the client where it can be constructed with a
3357 // newer configuration from when we asked it to launch.
3358 // We'll update with whatever configuration it now says
3359 // it used to launch.
3360 if (config != null) {
3361 r.configuration = config;
3362 }
3363
3364 // No longer need to keep the device awake.
3365 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3366 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3367 mLaunchingActivity.release();
3368 }
3369
3370 // We are now idle. If someone is waiting for a thumbnail from
3371 // us, we can now deliver.
3372 r.idle = true;
3373 mService.scheduleAppGcsLocked();
3374 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3375 sendThumbnail = r.app.thread;
3376 r.thumbnailNeeded = false;
3377 }
3378
3379 // If this activity is fullscreen, set up to hide those under it.
3380
3381 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3382 ensureActivitiesVisibleLocked(null, 0);
3383
3384 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3385 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003386 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003387 mService.mBooted = true;
3388 enableScreen = true;
3389 }
3390 }
3391
3392 } else if (fromTimeout) {
3393 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3394 }
3395
3396 // Atomically retrieve all of the other things to do.
3397 stops = processStoppingActivitiesLocked(true);
3398 NS = stops != null ? stops.size() : 0;
3399 if ((NF=mFinishingActivities.size()) > 0) {
3400 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3401 mFinishingActivities.clear();
3402 }
3403 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3404 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3405 mService.mCancelledThumbnails.clear();
3406 }
3407
3408 if (mMainStack) {
3409 booting = mService.mBooting;
3410 mService.mBooting = false;
3411 }
3412 }
3413
3414 int i;
3415
3416 // Send thumbnail if requested.
3417 if (sendThumbnail != null) {
3418 try {
3419 sendThumbnail.requestThumbnail(token);
3420 } catch (Exception e) {
3421 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3422 mService.sendPendingThumbnail(null, token, null, null, true);
3423 }
3424 }
3425
3426 // Stop any activities that are scheduled to do so but have been
3427 // waiting for the next one to start.
3428 for (i=0; i<NS; i++) {
3429 ActivityRecord r = (ActivityRecord)stops.get(i);
3430 synchronized (mService) {
3431 if (r.finishing) {
3432 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY);
3433 } else {
3434 stopActivityLocked(r);
3435 }
3436 }
3437 }
3438
3439 // Finish any activities that are scheduled to do so but have been
3440 // waiting for the next one to start.
3441 for (i=0; i<NF; i++) {
3442 ActivityRecord r = (ActivityRecord)finishes.get(i);
3443 synchronized (mService) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003444 destroyActivityLocked(r, true, false, "finish-idle");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003445 }
3446 }
3447
3448 // Report back to any thumbnail receivers.
3449 for (i=0; i<NT; i++) {
3450 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3451 mService.sendPendingThumbnail(r, null, null, null, true);
3452 }
3453
3454 if (booting) {
3455 mService.finishBooting();
3456 }
3457
3458 mService.trimApplications();
3459 //dump();
3460 //mWindowManager.dump();
3461
3462 if (enableScreen) {
3463 mService.enableScreenAfterBoot();
3464 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003465
3466 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003467 }
3468
3469 /**
3470 * @return Returns true if the activity is being finished, false if for
3471 * some reason it is being left as-is.
3472 */
3473 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
3474 Intent resultData, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003475 int index = indexOfTokenLocked(token);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003476 if (DEBUG_RESULTS) Slog.v(
3477 TAG, "Finishing activity @" + index + ": token=" + token
3478 + ", result=" + resultCode + ", data=" + resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003479 if (index < 0) {
3480 return false;
3481 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003482 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003483
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003484 finishActivityLocked(r, index, resultCode, resultData, reason);
3485 return true;
3486 }
3487
Dianne Hackborn5c607432012-02-28 14:44:19 -08003488 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
3489 // send the result
3490 ActivityRecord resultTo = r.resultTo;
3491 if (resultTo != null) {
3492 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3493 + " who=" + r.resultWho + " req=" + r.requestCode
3494 + " res=" + resultCode + " data=" + resultData);
3495 if (r.info.applicationInfo.uid > 0) {
3496 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3497 resultTo.packageName, resultData,
3498 resultTo.getUriPermissionsLocked());
3499 }
3500 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3501 resultData);
3502 r.resultTo = null;
3503 }
3504 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3505
3506 // Make sure this HistoryRecord is not holding on to other resources,
3507 // because clients have remote IPC references to this object so we
3508 // can't assume that will go away and want to avoid circular IPC refs.
3509 r.results = null;
3510 r.pendingResults = null;
3511 r.newIntents = null;
3512 r.icicle = null;
3513 }
3514
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003515 /**
3516 * @return Returns true if this activity has been removed from the history
3517 * list, or false if it is still in the list and will be removed later.
3518 */
3519 final boolean finishActivityLocked(ActivityRecord r, int index,
3520 int resultCode, Intent resultData, String reason) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003521 return finishActivityLocked(r, index, resultCode, resultData, reason, false);
3522 }
3523
3524 /**
3525 * @return Returns true if this activity has been removed from the history
3526 * list, or false if it is still in the list and will be removed later.
3527 */
3528 final boolean finishActivityLocked(ActivityRecord r, int index,
3529 int resultCode, Intent resultData, String reason, boolean immediate) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003530 if (r.finishing) {
3531 Slog.w(TAG, "Duplicate finish request for " + r);
3532 return false;
3533 }
3534
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003535 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003536 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3537 System.identityHashCode(r),
3538 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003539 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003540 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003541 if (next.task == r.task) {
3542 if (r.frontOfTask) {
3543 // The next activity is now the front of the task.
3544 next.frontOfTask = true;
3545 }
3546 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3547 // If the caller asked that this activity (and all above it)
3548 // be cleared when the task is reset, don't lose that information,
3549 // but propagate it up to the next activity.
3550 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3551 }
3552 }
3553 }
3554
3555 r.pauseKeyDispatchingLocked();
3556 if (mMainStack) {
3557 if (mService.mFocusedActivity == r) {
3558 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3559 }
3560 }
3561
Dianne Hackborn5c607432012-02-28 14:44:19 -08003562 finishActivityResultsLocked(r, resultCode, resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003563
3564 if (mService.mPendingThumbnails.size() > 0) {
3565 // There are clients waiting to receive thumbnails so, in case
3566 // this is an activity that someone is waiting for, add it
3567 // to the pending list so we can correctly update the clients.
3568 mService.mCancelledThumbnails.add(r);
3569 }
3570
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003571 if (immediate) {
3572 return finishCurrentActivityLocked(r, index,
3573 FINISH_IMMEDIATELY) == null;
3574 } else if (mResumedActivity == r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003575 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003576 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003577 if (DEBUG_TRANSITION) Slog.v(TAG,
3578 "Prepare close transition: finishing " + r);
3579 mService.mWindowManager.prepareAppTransition(endTask
3580 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003581 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003582
3583 // Tell window manager to prepare for this one to be removed.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003584 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003585
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003586 if (mPausingActivity == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003587 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3588 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3589 startPausingLocked(false, false);
3590 }
3591
3592 } else if (r.state != ActivityState.PAUSING) {
3593 // If the activity is PAUSING, we will complete the finish once
3594 // it is done pausing; else we can just directly finish it here.
3595 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3596 return finishCurrentActivityLocked(r, index,
3597 FINISH_AFTER_PAUSE) == null;
3598 } else {
3599 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3600 }
3601
3602 return false;
3603 }
3604
3605 private static final int FINISH_IMMEDIATELY = 0;
3606 private static final int FINISH_AFTER_PAUSE = 1;
3607 private static final int FINISH_AFTER_VISIBLE = 2;
3608
3609 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3610 int mode) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003611 final int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003612 if (index < 0) {
3613 return null;
3614 }
3615
3616 return finishCurrentActivityLocked(r, index, mode);
3617 }
3618
3619 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3620 int index, int mode) {
3621 // First things first: if this activity is currently visible,
3622 // and the resumed activity is not yet visible, then hold off on
3623 // finishing until the resumed one becomes visible.
3624 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3625 if (!mStoppingActivities.contains(r)) {
3626 mStoppingActivities.add(r);
3627 if (mStoppingActivities.size() > 3) {
3628 // If we already have a few activities waiting to stop,
3629 // then give up on things going idle and start clearing
3630 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003631 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003632 } else {
3633 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003634 }
3635 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003636 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3637 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003638 r.state = ActivityState.STOPPING;
3639 mService.updateOomAdjLocked();
3640 return r;
3641 }
3642
3643 // make sure the record is cleaned out of other places.
3644 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003645 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003646 mWaitingVisibleActivities.remove(r);
3647 if (mResumedActivity == r) {
3648 mResumedActivity = null;
3649 }
3650 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003651 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003652 r.state = ActivityState.FINISHING;
3653
3654 if (mode == FINISH_IMMEDIATELY
3655 || prevState == ActivityState.STOPPED
3656 || prevState == ActivityState.INITIALIZING) {
3657 // If this activity is already stopped, we can just finish
3658 // it right now.
Dianne Hackborn28695e02011-11-02 21:59:51 -07003659 return destroyActivityLocked(r, true, true, "finish-imm") ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003660 } else {
3661 // Need to go through the full pause cycle to get this
3662 // activity into the stopped state and then finish it.
3663 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3664 mFinishingActivities.add(r);
3665 resumeTopActivityLocked(null);
3666 }
3667 return r;
3668 }
3669
3670 /**
3671 * Perform the common clean-up of an activity record. This is called both
3672 * as part of destroyActivityLocked() (when destroying the client-side
3673 * representation) and cleaning things up as a result of its hosting
3674 * processing going away, in which case there is no remaining client-side
3675 * state to destroy so only the cleanup here is needed.
3676 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003677 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3678 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003679 if (mResumedActivity == r) {
3680 mResumedActivity = null;
3681 }
3682 if (mService.mFocusedActivity == r) {
3683 mService.mFocusedActivity = null;
3684 }
3685
3686 r.configDestroy = false;
3687 r.frozenBeforeDestroy = false;
3688
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003689 if (setState) {
3690 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3691 r.state = ActivityState.DESTROYED;
3692 }
3693
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003694 // Make sure this record is no longer in the pending finishes list.
3695 // This could happen, for example, if we are trimming activities
3696 // down to the max limit while they are still waiting to finish.
3697 mFinishingActivities.remove(r);
3698 mWaitingVisibleActivities.remove(r);
3699
3700 // Remove any pending results.
3701 if (r.finishing && r.pendingResults != null) {
3702 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3703 PendingIntentRecord rec = apr.get();
3704 if (rec != null) {
3705 mService.cancelIntentSenderLocked(rec, false);
3706 }
3707 }
3708 r.pendingResults = null;
3709 }
3710
3711 if (cleanServices) {
3712 cleanUpActivityServicesLocked(r);
3713 }
3714
3715 if (mService.mPendingThumbnails.size() > 0) {
3716 // There are clients waiting to receive thumbnails so, in case
3717 // this is an activity that someone is waiting for, add it
3718 // to the pending list so we can correctly update the clients.
3719 mService.mCancelledThumbnails.add(r);
3720 }
3721
3722 // Get rid of any pending idle timeouts.
3723 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003724 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003725 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003726 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003727 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003728 }
3729
Dianne Hackborn5c607432012-02-28 14:44:19 -08003730 final void removeActivityFromHistoryLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003731 if (r.state != ActivityState.DESTROYED) {
Dianne Hackborn5c607432012-02-28 14:44:19 -08003732 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003733 r.makeFinishing();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003734 if (DEBUG_ADD_REMOVE) {
3735 RuntimeException here = new RuntimeException("here");
3736 here.fillInStackTrace();
3737 Slog.i(TAG, "Removing activity " + r + " from stack");
3738 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003739 mHistory.remove(r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003740 r.takeFromHistory();
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003741 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3742 + " (removed from history)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003743 r.state = ActivityState.DESTROYED;
Dianne Hackbornbe707852011-11-11 14:32:10 -08003744 mService.mWindowManager.removeAppToken(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003745 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003746 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003747 }
3748 cleanUpActivityServicesLocked(r);
3749 r.removeUriPermissionsLocked();
3750 }
3751 }
3752
3753 /**
3754 * Perform clean-up of service connections in an activity record.
3755 */
3756 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3757 // Throw away any services that have been bound by this activity.
3758 if (r.connections != null) {
3759 Iterator<ConnectionRecord> it = r.connections.iterator();
3760 while (it.hasNext()) {
3761 ConnectionRecord c = it.next();
3762 mService.removeConnectionLocked(c, null, r);
3763 }
3764 r.connections = null;
3765 }
3766 }
3767
Dianne Hackborn28695e02011-11-02 21:59:51 -07003768 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003769 for (int i=mHistory.size()-1; i>=0; i--) {
3770 ActivityRecord r = mHistory.get(i);
3771 if (owner != null && r.app != owner) {
3772 continue;
3773 }
3774 // We can destroy this one if we have its icicle saved and
3775 // it is not in the process of pausing/stopping/finishing.
3776 if (r.app != null && r.haveState && !r.visible && r.stopped && !r.finishing
3777 && r.state != ActivityState.DESTROYING
3778 && r.state != ActivityState.DESTROYED) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003779 destroyActivityLocked(r, true, oomAdj, "trim");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003780 }
3781 }
3782 }
3783
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003784 /**
3785 * Destroy the current CLIENT SIDE instance of an activity. This may be
3786 * called both when actually finishing an activity, or when performing
3787 * a configuration switch where we destroy the current client-side object
3788 * but then create a new client-side object for this same HistoryRecord.
3789 */
3790 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackborn28695e02011-11-02 21:59:51 -07003791 boolean removeFromApp, boolean oomAdj, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003792 if (DEBUG_SWITCH) Slog.v(
3793 TAG, "Removing activity: token=" + r
3794 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3795 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3796 System.identityHashCode(r),
Dianne Hackborn28695e02011-11-02 21:59:51 -07003797 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003798
3799 boolean removedFromHistory = false;
3800
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003801 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003802
3803 final boolean hadApp = r.app != null;
3804
3805 if (hadApp) {
3806 if (removeFromApp) {
3807 int idx = r.app.activities.indexOf(r);
3808 if (idx >= 0) {
3809 r.app.activities.remove(idx);
3810 }
3811 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
3812 mService.mHeavyWeightProcess = null;
3813 mService.mHandler.sendEmptyMessage(
3814 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
3815 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003816 if (r.app.activities.size() == 0) {
3817 // No longer have activities, so update location in
3818 // LRU list.
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003819 mService.updateLruProcessLocked(r.app, oomAdj, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003820 }
3821 }
3822
3823 boolean skipDestroy = false;
3824
3825 try {
3826 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003827 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003828 r.configChangeFlags);
3829 } catch (Exception e) {
3830 // We can just ignore exceptions here... if the process
3831 // has crashed, our death notification will clean things
3832 // up.
3833 //Slog.w(TAG, "Exception thrown during finish", e);
3834 if (r.finishing) {
3835 removeActivityFromHistoryLocked(r);
3836 removedFromHistory = true;
3837 skipDestroy = true;
3838 }
3839 }
3840
3841 r.app = null;
3842 r.nowVisible = false;
3843
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003844 // If the activity is finishing, we need to wait on removing it
3845 // from the list to give it a chance to do its cleanup. During
3846 // that time it may make calls back with its token so we need to
3847 // be able to find it on the list and so we don't want to remove
3848 // it from the list yet. Otherwise, we can just immediately put
3849 // it in the destroyed state since we are not removing it from the
3850 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003851 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003852 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
3853 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003854 r.state = ActivityState.DESTROYING;
3855 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
3856 msg.obj = r;
3857 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
3858 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003859 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3860 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003861 r.state = ActivityState.DESTROYED;
3862 }
3863 } else {
3864 // remove this record from the history.
3865 if (r.finishing) {
3866 removeActivityFromHistoryLocked(r);
3867 removedFromHistory = true;
3868 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003869 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3870 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003871 r.state = ActivityState.DESTROYED;
3872 }
3873 }
3874
3875 r.configChangeFlags = 0;
3876
3877 if (!mLRUActivities.remove(r) && hadApp) {
3878 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
3879 }
3880
3881 return removedFromHistory;
3882 }
3883
3884 final void activityDestroyed(IBinder token) {
3885 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003886 ActivityRecord r = ActivityRecord.forToken(token);
3887 if (r != null) {
3888 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
3889 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003890
Dianne Hackbornbe707852011-11-11 14:32:10 -08003891 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003892 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003893 if (r.state == ActivityState.DESTROYING) {
3894 final long origId = Binder.clearCallingIdentity();
3895 removeActivityFromHistoryLocked(r);
3896 Binder.restoreCallingIdentity(origId);
3897 }
3898 }
3899 }
3900 }
3901
3902 private static void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
3903 int i = list.size();
3904 if (localLOGV) Slog.v(
3905 TAG, "Removing app " + app + " from list " + list
3906 + " with " + i + " entries");
3907 while (i > 0) {
3908 i--;
3909 ActivityRecord r = (ActivityRecord)list.get(i);
3910 if (localLOGV) Slog.v(
3911 TAG, "Record #" + i + " " + r + ": app=" + r.app);
3912 if (r.app == app) {
3913 if (localLOGV) Slog.v(TAG, "Removing this entry!");
3914 list.remove(i);
3915 }
3916 }
3917 }
3918
3919 void removeHistoryRecordsForAppLocked(ProcessRecord app) {
3920 removeHistoryRecordsForAppLocked(mLRUActivities, app);
3921 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003922 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003923 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
3924 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
3925 }
3926
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003927 /**
3928 * Move the current home activity's task (if one exists) to the front
3929 * of the stack.
3930 */
3931 final void moveHomeToFrontLocked() {
3932 TaskRecord homeTask = null;
3933 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003934 ActivityRecord hr = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003935 if (hr.isHomeActivity) {
3936 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003937 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003938 }
3939 }
3940 if (homeTask != null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003941 moveTaskToFrontLocked(homeTask, null, null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003942 }
3943 }
3944
3945
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003946 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003947 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
3948
3949 final int task = tr.taskId;
3950 int top = mHistory.size()-1;
3951
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003952 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003953 // nothing to do!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003954 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003955 return;
3956 }
3957
Dianne Hackbornbe707852011-11-11 14:32:10 -08003958 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003959
3960 // Applying the affinities may have removed entries from the history,
3961 // so get the size again.
3962 top = mHistory.size()-1;
3963 int pos = top;
3964
3965 // Shift all activities with this task up to the top
3966 // of the stack, keeping them in the same internal order.
3967 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003968 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003969 if (localLOGV) Slog.v(
3970 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003971 if (r.task.taskId == task) {
3972 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003973 if (DEBUG_ADD_REMOVE) {
3974 RuntimeException here = new RuntimeException("here");
3975 here.fillInStackTrace();
3976 Slog.i(TAG, "Removing and adding activity " + r + " to stack at " + top, here);
3977 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003978 mHistory.remove(pos);
3979 mHistory.add(top, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003980 moved.add(0, r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003981 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003982 }
3983 pos--;
3984 }
3985
3986 if (DEBUG_TRANSITION) Slog.v(TAG,
3987 "Prepare to front transition: task=" + tr);
3988 if (reason != null &&
3989 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003990 mService.mWindowManager.prepareAppTransition(
3991 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003992 ActivityRecord r = topRunningActivityLocked(null);
3993 if (r != null) {
3994 mNoAnimActivities.add(r);
3995 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003996 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003997 } else {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003998 if (options != null) {
3999 ActivityRecord r = topRunningActivityLocked(null);
4000 if (r != null && r.state != ActivityState.RESUMED) {
4001 r.updateOptionsLocked(options);
4002 } else {
4003 ActivityOptions.abort(options);
4004 }
4005 }
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004006 mService.mWindowManager.prepareAppTransition(
4007 WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004008 }
4009
4010 mService.mWindowManager.moveAppTokensToTop(moved);
4011 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004012 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004013 }
4014
4015 finishTaskMoveLocked(task);
4016 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
4017 }
4018
4019 private final void finishTaskMoveLocked(int task) {
4020 resumeTopActivityLocked(null);
4021 }
4022
4023 /**
4024 * Worker method for rearranging history stack. Implements the function of moving all
4025 * activities for a specific task (gathering them if disjoint) into a single group at the
4026 * bottom of the stack.
4027 *
4028 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
4029 * to premeptively cancel the move.
4030 *
4031 * @param task The taskId to collect and move to the bottom.
4032 * @return Returns true if the move completed, false if not.
4033 */
4034 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
4035 Slog.i(TAG, "moveTaskToBack: " + task);
4036
4037 // If we have a watcher, preflight the move before committing to it. First check
4038 // for *other* available tasks, but if none are available, then try again allowing the
4039 // current task to be selected.
4040 if (mMainStack && mService.mController != null) {
4041 ActivityRecord next = topRunningActivityLocked(null, task);
4042 if (next == null) {
4043 next = topRunningActivityLocked(null, 0);
4044 }
4045 if (next != null) {
4046 // ask watcher if this is allowed
4047 boolean moveOK = true;
4048 try {
4049 moveOK = mService.mController.activityResuming(next.packageName);
4050 } catch (RemoteException e) {
4051 mService.mController = null;
4052 }
4053 if (!moveOK) {
4054 return false;
4055 }
4056 }
4057 }
4058
Dianne Hackbornbe707852011-11-11 14:32:10 -08004059 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004060
4061 if (DEBUG_TRANSITION) Slog.v(TAG,
4062 "Prepare to back transition: task=" + task);
4063
4064 final int N = mHistory.size();
4065 int bottom = 0;
4066 int pos = 0;
4067
4068 // Shift all activities with this task down to the bottom
4069 // of the stack, keeping them in the same internal order.
4070 while (pos < N) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004071 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004072 if (localLOGV) Slog.v(
4073 TAG, "At " + pos + " ckp " + r.task + ": " + r);
4074 if (r.task.taskId == task) {
4075 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004076 if (DEBUG_ADD_REMOVE) {
4077 RuntimeException here = new RuntimeException("here");
4078 here.fillInStackTrace();
4079 Slog.i(TAG, "Removing and adding activity " + r + " to stack at "
4080 + bottom, here);
4081 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004082 mHistory.remove(pos);
4083 mHistory.add(bottom, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004084 moved.add(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004085 bottom++;
4086 }
4087 pos++;
4088 }
4089
4090 if (reason != null &&
4091 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004092 mService.mWindowManager.prepareAppTransition(
4093 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004094 ActivityRecord r = topRunningActivityLocked(null);
4095 if (r != null) {
4096 mNoAnimActivities.add(r);
4097 }
4098 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004099 mService.mWindowManager.prepareAppTransition(
4100 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004101 }
4102 mService.mWindowManager.moveAppTokensToBottom(moved);
4103 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004104 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004105 }
4106
4107 finishTaskMoveLocked(task);
4108 return true;
4109 }
4110
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004111 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
4112 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4113 ActivityRecord resumed = mResumedActivity;
4114 if (resumed != null && resumed.thumbHolder == tr) {
4115 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
4116 } else {
4117 info.mainThumbnail = tr.lastThumbnail;
4118 }
4119 return info;
4120 }
4121
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004122 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex,
4123 boolean taskRequired) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004124 TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
4125 if (info.root == null) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004126 if (taskRequired) {
4127 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
4128 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004129 return null;
4130 }
4131
4132 if (subTaskIndex < 0) {
4133 // Just remove the entire task.
4134 performClearTaskAtIndexLocked(taskId, info.rootIndex);
4135 return info.root;
4136 }
4137
4138 if (subTaskIndex >= info.subtasks.size()) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004139 if (taskRequired) {
4140 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
4141 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004142 return null;
4143 }
4144
4145 // Remove all of this task's activies starting at the sub task.
4146 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
4147 performClearTaskAtIndexLocked(taskId, subtask.index);
4148 return subtask.activity;
4149 }
4150
4151 public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
4152 ActivityRecord resumed = mResumedActivity;
4153 final TaskAccessInfo thumbs = new TaskAccessInfo();
4154 // How many different sub-thumbnails?
4155 final int NA = mHistory.size();
4156 int j = 0;
4157 ThumbnailHolder holder = null;
4158 while (j < NA) {
4159 ActivityRecord ar = mHistory.get(j);
4160 if (!ar.finishing && ar.task.taskId == taskId) {
4161 holder = ar.thumbHolder;
4162 break;
4163 }
4164 j++;
4165 }
4166
4167 if (j >= NA) {
4168 return thumbs;
4169 }
4170
4171 thumbs.root = mHistory.get(j);
4172 thumbs.rootIndex = j;
4173
4174 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
4175 thumbs.subtasks = subtasks;
4176 ActivityRecord lastActivity = null;
4177 while (j < NA) {
4178 ActivityRecord ar = mHistory.get(j);
4179 j++;
4180 if (ar.finishing) {
4181 continue;
4182 }
4183 if (ar.task.taskId != taskId) {
4184 break;
4185 }
4186 lastActivity = ar;
4187 if (ar.thumbHolder != holder && holder != null) {
4188 thumbs.numSubThumbbails++;
4189 holder = ar.thumbHolder;
4190 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
4191 sub.thumbnail = holder.lastThumbnail;
4192 sub.activity = ar;
4193 sub.index = j-1;
4194 subtasks.add(sub);
4195 }
4196 }
4197 if (lastActivity != null && subtasks.size() > 0) {
4198 if (resumed == lastActivity) {
4199 TaskAccessInfo.SubTask sub = subtasks.get(subtasks.size()-1);
4200 sub.thumbnail = lastActivity.stack.screenshotActivities(lastActivity);
4201 }
4202 }
4203 if (thumbs.numSubThumbbails > 0) {
4204 thumbs.retriever = new IThumbnailRetriever.Stub() {
4205 public Bitmap getThumbnail(int index) {
4206 if (index < 0 || index >= thumbs.subtasks.size()) {
4207 return null;
4208 }
4209 return thumbs.subtasks.get(index).thumbnail;
4210 }
4211 };
4212 }
4213 return thumbs;
4214 }
4215
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004216 private final void logStartActivity(int tag, ActivityRecord r,
4217 TaskRecord task) {
4218 EventLog.writeEvent(tag,
4219 System.identityHashCode(r), task.taskId,
4220 r.shortComponentName, r.intent.getAction(),
4221 r.intent.getType(), r.intent.getDataString(),
4222 r.intent.getFlags());
4223 }
4224
4225 /**
4226 * Make sure the given activity matches the current configuration. Returns
4227 * false if the activity had to be destroyed. Returns true if the
4228 * configuration is the same, or the activity will remain running as-is
4229 * for whatever reason. Ensures the HistoryRecord is updated with the
4230 * correct configuration and all other bookkeeping is handled.
4231 */
4232 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
4233 int globalChanges) {
4234 if (mConfigWillChange) {
4235 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4236 "Skipping config check (will change): " + r);
4237 return true;
4238 }
4239
4240 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4241 "Ensuring correct configuration: " + r);
4242
4243 // Short circuit: if the two configurations are the exact same
4244 // object (the common case), then there is nothing to do.
4245 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004246 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004247 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4248 "Configuration unchanged in " + r);
4249 return true;
4250 }
4251
4252 // We don't worry about activities that are finishing.
4253 if (r.finishing) {
4254 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4255 "Configuration doesn't matter in finishing " + r);
4256 r.stopFreezingScreenLocked(false);
4257 return true;
4258 }
4259
4260 // Okay we now are going to make this activity have the new config.
4261 // But then we need to figure out how it needs to deal with that.
4262 Configuration oldConfig = r.configuration;
4263 r.configuration = newConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004264
4265 // Determine what has changed. May be nothing, if this is a config
4266 // that has come back from the app after going idle. In that case
4267 // we just want to leave the official config object now in the
4268 // activity and do nothing else.
4269 final int changes = oldConfig.diff(newConfig);
4270 if (changes == 0 && !r.forceNewConfig) {
4271 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4272 "Configuration no differences in " + r);
4273 return true;
4274 }
4275
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004276 // If the activity isn't currently running, just leave the new
4277 // configuration and it will pick that up next time it starts.
4278 if (r.app == null || r.app.thread == null) {
4279 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4280 "Configuration doesn't matter not running " + r);
4281 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004282 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004283 return true;
4284 }
4285
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004286 // Figure out how to handle the changes between the configurations.
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004287 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4288 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
4289 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07004290 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004291 + ", newConfig=" + newConfig);
4292 }
Dianne Hackborne6676352011-06-01 16:51:20 -07004293 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004294 // Aha, the activity isn't handling the change, so DIE DIE DIE.
4295 r.configChangeFlags |= changes;
4296 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004297 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004298 if (r.app == null || r.app.thread == null) {
4299 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4300 "Switch is destroying non-running " + r);
Dianne Hackborn28695e02011-11-02 21:59:51 -07004301 destroyActivityLocked(r, true, false, "config");
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004302 } else if (r.state == ActivityState.PAUSING) {
4303 // A little annoying: we are waiting for this activity to
4304 // finish pausing. Let's not do anything now, but just
4305 // flag that it needs to be restarted when done pausing.
4306 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4307 "Switch is skipping already pausing " + r);
4308 r.configDestroy = true;
4309 return true;
4310 } else if (r.state == ActivityState.RESUMED) {
4311 // Try to optimize this case: the configuration is changing
4312 // and we need to restart the top, resumed activity.
4313 // Instead of doing the normal handshaking, just say
4314 // "restart!".
4315 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4316 "Switch is restarting resumed " + r);
4317 relaunchActivityLocked(r, r.configChangeFlags, true);
4318 r.configChangeFlags = 0;
4319 } else {
4320 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4321 "Switch is restarting non-resumed " + r);
4322 relaunchActivityLocked(r, r.configChangeFlags, false);
4323 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004324 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004325
4326 // All done... tell the caller we weren't able to keep this
4327 // activity around.
4328 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004329 }
4330
4331 // Default case: the activity can handle this new configuration, so
4332 // hand it over. Note that we don't need to give it the new
4333 // configuration, since we always send configuration changes to all
4334 // process when they happen so it can just use whatever configuration
4335 // it last got.
4336 if (r.app != null && r.app.thread != null) {
4337 try {
4338 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004339 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004340 } catch (RemoteException e) {
4341 // If process died, whatever.
4342 }
4343 }
4344 r.stopFreezingScreenLocked(false);
4345
4346 return true;
4347 }
4348
4349 private final boolean relaunchActivityLocked(ActivityRecord r,
4350 int changes, boolean andResume) {
4351 List<ResultInfo> results = null;
4352 List<Intent> newIntents = null;
4353 if (andResume) {
4354 results = r.results;
4355 newIntents = r.newIntents;
4356 }
4357 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4358 + " with results=" + results + " newIntents=" + newIntents
4359 + " andResume=" + andResume);
4360 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
4361 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
4362 r.task.taskId, r.shortComponentName);
4363
4364 r.startFreezingScreenLocked(r.app, 0);
4365
4366 try {
4367 if (DEBUG_SWITCH) Slog.i(TAG, "Switch is restarting resumed " + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004368 r.forceNewConfig = false;
Dianne Hackbornbe707852011-11-11 14:32:10 -08004369 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004370 changes, !andResume, new Configuration(mService.mConfiguration));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004371 // Note: don't need to call pauseIfSleepingLocked() here, because
4372 // the caller will only pass in 'andResume' if this activity is
4373 // currently resumed, which implies we aren't sleeping.
4374 } catch (RemoteException e) {
4375 return false;
4376 }
4377
4378 if (andResume) {
4379 r.results = null;
4380 r.newIntents = null;
4381 if (mMainStack) {
4382 mService.reportResumedActivityLocked(r);
4383 }
4384 }
4385
4386 return true;
4387 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004388
4389 public void dismissKeyguardOnNextActivityLocked() {
4390 mDismissKeyguardOnNextActivity = true;
4391 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004392}