blob: ad13c41b47030e6dd8c8086add22a5aaceec57ba [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) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07002348 final int userId = aInfo != null ? UserId.getUserId(aInfo.applicationInfo.uid) : 0;
Dianne Hackborn21c241e2012-03-08 13:57:23 -08002349 Slog.i(TAG, "START {" + intent.toShortString(true, true, true, false)
Amith Yamasania4a54e22012-04-16 15:44:19 -07002350 + " u=" + userId + "} from pid " + (callerApp != null ? callerApp.pid : callingPid));
Dianne Hackbornefb58102010-10-14 16:47:34 -07002351 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002352
2353 ActivityRecord sourceRecord = null;
2354 ActivityRecord resultRecord = null;
2355 if (resultTo != null) {
2356 int index = indexOfTokenLocked(resultTo);
2357 if (DEBUG_RESULTS) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002358 TAG, "Will send result to " + resultTo + " (index " + index + ")");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002359 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002360 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002361 if (requestCode >= 0 && !sourceRecord.finishing) {
2362 resultRecord = sourceRecord;
2363 }
2364 }
2365 }
2366
2367 int launchFlags = intent.getFlags();
2368
2369 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2370 && sourceRecord != null) {
2371 // Transfer the result target from the source activity to the new
2372 // one being started, including any failures.
2373 if (requestCode >= 0) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002374 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002375 return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002376 }
2377 resultRecord = sourceRecord.resultTo;
2378 resultWho = sourceRecord.resultWho;
2379 requestCode = sourceRecord.requestCode;
2380 sourceRecord.resultTo = null;
2381 if (resultRecord != null) {
2382 resultRecord.removeResultsLocked(
2383 sourceRecord, resultWho, requestCode);
2384 }
2385 }
2386
Dianne Hackborna4972e92012-03-14 10:38:05 -07002387 if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002388 // We couldn't find a class that can handle the given Intent.
2389 // That's the end of that!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002390 err = ActivityManager.START_INTENT_NOT_RESOLVED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002391 }
2392
Dianne Hackborna4972e92012-03-14 10:38:05 -07002393 if (err == ActivityManager.START_SUCCESS && aInfo == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002394 // We couldn't find the specific class specified in the Intent.
2395 // Also the end of the line.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002396 err = ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002397 }
2398
Dianne Hackborna4972e92012-03-14 10:38:05 -07002399 if (err != ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002400 if (resultRecord != null) {
2401 sendActivityResultLocked(-1,
2402 resultRecord, resultWho, requestCode,
2403 Activity.RESULT_CANCELED, null);
2404 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002405 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002406 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002407 return err;
2408 }
2409
2410 final int perm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002411 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002412 if (perm != PackageManager.PERMISSION_GRANTED) {
2413 if (resultRecord != null) {
2414 sendActivityResultLocked(-1,
2415 resultRecord, resultWho, requestCode,
2416 Activity.RESULT_CANCELED, null);
2417 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002418 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002419 String msg;
2420 if (!aInfo.exported) {
2421 msg = "Permission Denial: starting " + intent.toString()
2422 + " from " + callerApp + " (pid=" + callingPid
2423 + ", uid=" + callingUid + ")"
2424 + " not exported from uid " + aInfo.applicationInfo.uid;
2425 } else {
2426 msg = "Permission Denial: starting " + intent.toString()
2427 + " from " + callerApp + " (pid=" + callingPid
2428 + ", uid=" + callingUid + ")"
2429 + " requires " + aInfo.permission;
2430 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002431 Slog.w(TAG, msg);
2432 throw new SecurityException(msg);
2433 }
2434
2435 if (mMainStack) {
2436 if (mService.mController != null) {
2437 boolean abort = false;
2438 try {
2439 // The Intent we give to the watcher has the extra data
2440 // stripped off, since it can contain private information.
2441 Intent watchIntent = intent.cloneFilter();
2442 abort = !mService.mController.activityStarting(watchIntent,
2443 aInfo.applicationInfo.packageName);
2444 } catch (RemoteException e) {
2445 mService.mController = null;
2446 }
2447
2448 if (abort) {
2449 if (resultRecord != null) {
2450 sendActivityResultLocked(-1,
2451 resultRecord, resultWho, requestCode,
2452 Activity.RESULT_CANCELED, null);
2453 }
2454 // We pretend to the caller that it was really started, but
2455 // they will just get a cancel result.
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002456 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002457 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002458 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002459 }
2460 }
2461 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002462
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002463 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2464 intent, resolvedType, aInfo, mService.mConfiguration,
2465 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002466 if (outActivity != null) {
2467 outActivity[0] = r;
2468 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002469
2470 if (mMainStack) {
2471 if (mResumedActivity == null
2472 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2473 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2474 PendingActivityLaunch pal = new PendingActivityLaunch();
2475 pal.r = r;
2476 pal.sourceRecord = sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002477 pal.startFlags = startFlags;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002478 mService.mPendingActivityLaunches.add(pal);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002479 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002480 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002481 return ActivityManager.START_SWITCHES_CANCELED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002482 }
2483 }
2484
2485 if (mService.mDidAppSwitch) {
2486 // This is the second allowed switch since we stopped switches,
2487 // so now just generally allow switches. Use case: user presses
2488 // home (switches disabled, switch to home, mDidAppSwitch now true);
2489 // user taps a home icon (coming from home so allowed, we hit here
2490 // and now allow anyone to switch again).
2491 mService.mAppSwitchesAllowedTime = 0;
2492 } else {
2493 mService.mDidAppSwitch = true;
2494 }
2495
2496 mService.doPendingActivityLaunchesLocked(false);
2497 }
2498
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002499 err = startActivityUncheckedLocked(r, sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002500 startFlags, true, options);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002501 if (mDismissKeyguardOnNextActivity && mPausingActivity == null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002502 // Someone asked to have the keyguard dismissed on the next
2503 // activity start, but we are not actually doing an activity
2504 // switch... just dismiss the keyguard now, because we
2505 // probably want to see whatever is behind it.
2506 mDismissKeyguardOnNextActivity = false;
2507 mService.mWindowManager.dismissKeyguard();
2508 }
2509 return err;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002510 }
2511
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002512 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2513 if ((launchFlags &
2514 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2515 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2516 // Caller wants to appear on home activity, so before starting
2517 // their own activity we will bring home to the front.
2518 moveHomeToFrontLocked();
2519 }
2520 }
2521
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002522 final int startActivityUncheckedLocked(ActivityRecord r,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002523 ActivityRecord sourceRecord, int startFlags, boolean doResume,
2524 Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002525 final Intent intent = r.intent;
2526 final int callingUid = r.launchedFromUid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002527 final int userId = r.userId;
2528
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002529 int launchFlags = intent.getFlags();
2530
2531 // We'll invoke onUserLeaving before onPause only if the launching
2532 // activity did not explicitly state that this is an automated launch.
2533 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2534 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2535 "startActivity() => mUserLeaving=" + mUserLeaving);
2536
2537 // If the caller has asked not to resume at this point, we make note
2538 // of this in the record so that we can skip it when trying to find
2539 // the top running activity.
2540 if (!doResume) {
2541 r.delayedResume = true;
2542 }
2543
2544 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2545 != 0 ? r : null;
2546
2547 // If the onlyIfNeeded flag is set, then we can do this if the activity
2548 // being launched is the same as the one making the call... or, as
2549 // a special case, if we do not know the caller then we count the
2550 // current top activity as the caller.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002551 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002552 ActivityRecord checkedCaller = sourceRecord;
2553 if (checkedCaller == null) {
2554 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2555 }
2556 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2557 // Caller is not the same as launcher, so always needed.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002558 startFlags &= ~ActivityManager.START_FLAG_ONLY_IF_NEEDED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002559 }
2560 }
2561
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002562 if (sourceRecord == null) {
2563 // This activity is not being started from another... in this
2564 // case we -always- start a new task.
2565 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2566 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2567 + intent);
2568 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2569 }
2570 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2571 // The original activity who is starting us is running as a single
2572 // instance... this new activity it is starting must go on its
2573 // own task.
2574 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2575 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2576 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2577 // The activity being started is a single instance... it always
2578 // gets launched into its own task.
2579 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2580 }
2581
2582 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2583 // For whatever reason this activity is being launched into a new
2584 // task... yet the caller has requested a result back. Well, that
2585 // is pretty messed up, so instead immediately send back a cancel
2586 // and let the new task continue launched as normal without a
2587 // dependency on its originator.
2588 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2589 sendActivityResultLocked(-1,
2590 r.resultTo, r.resultWho, r.requestCode,
2591 Activity.RESULT_CANCELED, null);
2592 r.resultTo = null;
2593 }
2594
2595 boolean addingToTask = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002596 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002597 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2598 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2599 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2600 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2601 // If bring to front is requested, and no result is requested, and
2602 // we can find a task that was started with this same
2603 // component, then instead of launching bring that one to the front.
2604 if (r.resultTo == null) {
2605 // See if there is a task to bring to the front. If this is
2606 // a SINGLE_INSTANCE activity, there can be one and only one
2607 // instance of it in the history, and it is always in its own
2608 // unique task, so we do a special search.
2609 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2610 ? findTaskLocked(intent, r.info)
2611 : findActivityLocked(intent, r.info);
2612 if (taskTop != null) {
2613 if (taskTop.task.intent == null) {
2614 // This task was started because of movement of
2615 // the activity based on affinity... now that we
2616 // are actually launching it, we can assign the
2617 // base intent.
2618 taskTop.task.setIntent(intent, r.info);
2619 }
2620 // If the target task is not in the front, then we need
2621 // to bring it to the front... except... well, with
2622 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2623 // to have the same behavior as if a new instance was
2624 // being started, which means not bringing it to the front
2625 // if the caller is not itself in the front.
2626 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002627 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002628 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2629 boolean callerAtFront = sourceRecord == null
2630 || curTop.task == sourceRecord.task;
2631 if (callerAtFront) {
2632 // We really do want to push this one into the
2633 // user's face, right now.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002634 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002635 moveTaskToFrontLocked(taskTop.task, r, options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002636 }
2637 }
2638 // If the caller has requested that the target task be
2639 // reset, then do so.
2640 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2641 taskTop = resetTaskIfNeededLocked(taskTop, r);
2642 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002643 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002644 // We don't need to start a new activity, and
2645 // the client said not to do anything if that
2646 // is the case, so this is it! And for paranoia, make
2647 // sure we have correctly resumed the top activity.
2648 if (doResume) {
2649 resumeTopActivityLocked(null);
2650 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002651 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002652 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002653 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002654 if ((launchFlags &
2655 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2656 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2657 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002658 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002659 // not be too hard...
2660 reuseTask = taskTop.task;
2661 performClearTaskLocked(taskTop.task.taskId);
2662 reuseTask.setIntent(r.intent, r.info);
2663 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002664 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2665 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2666 // In this situation we want to remove all activities
2667 // from the task up to the one being started. In most
2668 // cases this means we are resetting the task to its
2669 // initial state.
2670 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002671 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002672 if (top != null) {
2673 if (top.frontOfTask) {
2674 // Activity aliases may mean we use different
2675 // intents for the top activity, so make sure
2676 // the task now has the identity of the new
2677 // intent.
2678 top.task.setIntent(r.intent, r.info);
2679 }
2680 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002681 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002682 } else {
2683 // A special case: we need to
2684 // start the activity because it is not currently
2685 // running, and the caller has asked to clear the
2686 // current task to have this activity at the top.
2687 addingToTask = true;
2688 // Now pretend like this activity is being started
2689 // by the top of its task, so it is put in the
2690 // right place.
2691 sourceRecord = taskTop;
2692 }
2693 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2694 // In this case the top activity on the task is the
2695 // same as the one being launched, so we take that
2696 // as a request to bring the task to the foreground.
2697 // If the top activity in the task is the root
2698 // activity, deliver this new intent to it if it
2699 // desires.
2700 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2701 && taskTop.realActivity.equals(r.realActivity)) {
2702 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2703 if (taskTop.frontOfTask) {
2704 taskTop.task.setIntent(r.intent, r.info);
2705 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002706 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002707 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2708 // In this case we are launching the root activity
2709 // of the task, but with a different intent. We
2710 // should start a new instance on top.
2711 addingToTask = true;
2712 sourceRecord = taskTop;
2713 }
2714 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2715 // In this case an activity is being launched in to an
2716 // existing task, without resetting that task. This
2717 // is typically the situation of launching an activity
2718 // from a notification or shortcut. We want to place
2719 // the new activity on top of the current task.
2720 addingToTask = true;
2721 sourceRecord = taskTop;
2722 } else if (!taskTop.task.rootWasReset) {
2723 // In this case we are launching in to an existing task
2724 // that has not yet been started from its front door.
2725 // The current task has been brought to the front.
2726 // Ideally, we'd probably like to place this new task
2727 // at the bottom of its stack, but that's a little hard
2728 // to do with the current organization of the code so
2729 // for now we'll just drop it.
2730 taskTop.task.setIntent(r.intent, r.info);
2731 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002732 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002733 // We didn't do anything... but it was needed (a.k.a., client
2734 // don't use that intent!) And for paranoia, make
2735 // sure we have correctly resumed the top activity.
2736 if (doResume) {
2737 resumeTopActivityLocked(null);
2738 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002739 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002740 return ActivityManager.START_TASK_TO_FRONT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002741 }
2742 }
2743 }
2744 }
2745
2746 //String uri = r.intent.toURI();
2747 //Intent intent2 = new Intent(uri);
2748 //Slog.i(TAG, "Given intent: " + r.intent);
2749 //Slog.i(TAG, "URI is: " + uri);
2750 //Slog.i(TAG, "To intent: " + intent2);
2751
2752 if (r.packageName != null) {
2753 // If the activity being launched is the same as the one currently
2754 // at the top, then we need to check if it should only be launched
2755 // once.
2756 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2757 if (top != null && r.resultTo == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002758 if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002759 if (top.app != null && top.app.thread != null) {
2760 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2761 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2762 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2763 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2764 // For paranoia, make sure we have correctly
2765 // resumed the top activity.
2766 if (doResume) {
2767 resumeTopActivityLocked(null);
2768 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002769 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002770 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002771 // We don't need to start a new activity, and
2772 // the client said not to do anything if that
2773 // is the case, so this is it!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002774 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002775 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002776 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002777 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002778 }
2779 }
2780 }
2781 }
2782
2783 } else {
2784 if (r.resultTo != null) {
2785 sendActivityResultLocked(-1,
2786 r.resultTo, r.resultWho, r.requestCode,
2787 Activity.RESULT_CANCELED, null);
2788 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002789 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002790 return ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002791 }
2792
2793 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002794 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002795
2796 // Should this be considered a new task?
2797 if (r.resultTo == null && !addingToTask
2798 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002799 if (reuseTask == null) {
2800 // todo: should do better management of integers.
2801 mService.mCurTask++;
2802 if (mService.mCurTask <= 0) {
2803 mService.mCurTask = 1;
2804 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002805 r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002806 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2807 + " in new task " + r.task);
2808 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002809 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002810 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002811 newTask = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002812 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002813
2814 } else if (sourceRecord != null) {
2815 if (!addingToTask &&
2816 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2817 // In this case, we are adding the activity to an existing
2818 // task, but the caller has asked to clear that task if the
2819 // activity is already running.
2820 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002821 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002822 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002823 if (top != null) {
2824 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002825 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002826 // For paranoia, make sure we have correctly
2827 // resumed the top activity.
2828 if (doResume) {
2829 resumeTopActivityLocked(null);
2830 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002831 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002832 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002833 }
2834 } else if (!addingToTask &&
2835 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2836 // In this case, we are launching an activity in our own task
2837 // that may already be running somewhere in the history, and
2838 // we want to shuffle it to the front of the stack if so.
2839 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2840 if (where >= 0) {
2841 ActivityRecord top = moveActivityToFrontLocked(where);
2842 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002843 top.updateOptionsLocked(options);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002844 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002845 if (doResume) {
2846 resumeTopActivityLocked(null);
2847 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002848 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002849 }
2850 }
2851 // An existing activity is starting this new activity, so we want
2852 // to keep the new one in the same task as the one that is starting
2853 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002854 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002855 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2856 + " in existing task " + r.task);
2857
2858 } else {
2859 // This not being started from an existing activity, and not part
2860 // of a new task... just put it in the top task, though these days
2861 // this case should never happen.
2862 final int N = mHistory.size();
2863 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002864 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002865 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002866 ? prev.task
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002867 : new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002868 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2869 + " in new guessed " + r.task);
2870 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002871
Dianne Hackborn39792d22010-08-19 18:01:52 -07002872 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002873 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002874
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002875 if (newTask) {
2876 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
2877 }
2878 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002879 startActivityLocked(r, newTask, doResume, keepCurTransition, options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002880 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002881 }
2882
Dianne Hackborna4972e92012-03-14 10:38:05 -07002883 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002884 String profileFile, ParcelFileDescriptor profileFd, int userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002885 // Collect information about the target of the Intent.
2886 ActivityInfo aInfo;
2887 try {
2888 ResolveInfo rInfo =
2889 AppGlobals.getPackageManager().resolveIntent(
2890 intent, resolvedType,
2891 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07002892 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002893 aInfo = rInfo != null ? rInfo.activityInfo : null;
2894 } catch (RemoteException e) {
2895 aInfo = null;
2896 }
2897
2898 if (aInfo != null) {
2899 // Store the found target back into the intent, because now that
2900 // we have it we never want to do this again. For example, if the
2901 // user navigates back to this point in the history, we should
2902 // always restart the exact same activity.
2903 intent.setComponent(new ComponentName(
2904 aInfo.applicationInfo.packageName, aInfo.name));
2905
2906 // Don't debug things in the system process
Dianne Hackborna4972e92012-03-14 10:38:05 -07002907 if ((startFlags&ActivityManager.START_FLAG_DEBUG) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002908 if (!aInfo.processName.equals("system")) {
2909 mService.setDebugApp(aInfo.processName, true, false);
2910 }
2911 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002912
Dianne Hackborna4972e92012-03-14 10:38:05 -07002913 if ((startFlags&ActivityManager.START_FLAG_OPENGL_TRACES) != 0) {
Siva Velusamy92a8b222012-03-09 16:24:04 -08002914 if (!aInfo.processName.equals("system")) {
2915 mService.setOpenGlTraceApp(aInfo.applicationInfo, aInfo.processName);
2916 }
2917 }
2918
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002919 if (profileFile != null) {
2920 if (!aInfo.processName.equals("system")) {
2921 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002922 profileFile, profileFd,
2923 (startFlags&ActivityManager.START_FLAG_AUTO_STOP_PROFILER) != 0);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002924 }
2925 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002926 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002927 return aInfo;
2928 }
2929
2930 final int startActivityMayWait(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002931 Intent intent, String resolvedType, IBinder resultTo,
2932 String resultWho, int requestCode, int startFlags, String profileFile,
2933 ParcelFileDescriptor profileFd, WaitResult outResult, Configuration config,
2934 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002935 // Refuse possible leaked file descriptors
2936 if (intent != null && intent.hasFileDescriptors()) {
2937 throw new IllegalArgumentException("File descriptors passed in Intent");
2938 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002939 boolean componentSpecified = intent.getComponent() != null;
2940
2941 // Don't modify the client's object!
2942 intent = new Intent(intent);
2943
2944 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002945 ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002946 profileFile, profileFd, userId);
Amith Yamasani95a6a962012-04-18 09:54:43 -07002947 if (aInfo != null && mService.isSingleton(aInfo.processName, aInfo.applicationInfo)) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07002948 userId = 0;
2949 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002950 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002951
2952 synchronized (mService) {
2953 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002954 if (callingUid >= 0) {
2955 callingPid = -1;
2956 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002957 callingPid = Binder.getCallingPid();
2958 callingUid = Binder.getCallingUid();
2959 } else {
2960 callingPid = callingUid = -1;
2961 }
2962
2963 mConfigWillChange = config != null
2964 && mService.mConfiguration.diff(config) != 0;
2965 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2966 "Starting activity when config will change = " + mConfigWillChange);
2967
2968 final long origId = Binder.clearCallingIdentity();
2969
2970 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07002971 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002972 // This may be a heavy-weight process! Check to see if we already
2973 // have another, different heavy-weight process running.
2974 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
2975 if (mService.mHeavyWeightProcess != null &&
2976 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
2977 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
2978 int realCallingPid = callingPid;
2979 int realCallingUid = callingUid;
2980 if (caller != null) {
2981 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
2982 if (callerApp != null) {
2983 realCallingPid = callerApp.pid;
2984 realCallingUid = callerApp.info.uid;
2985 } else {
2986 Slog.w(TAG, "Unable to find app for caller " + caller
2987 + " (pid=" + realCallingPid + ") when starting: "
2988 + intent.toString());
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002989 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002990 return ActivityManager.START_PERMISSION_DENIED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002991 }
2992 }
2993
2994 IIntentSender target = mService.getIntentSenderLocked(
Dianne Hackborna4972e92012-03-14 10:38:05 -07002995 ActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002996 realCallingUid, null, null, 0, new Intent[] { intent },
2997 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002998 | PendingIntent.FLAG_ONE_SHOT, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002999
3000 Intent newIntent = new Intent();
3001 if (requestCode >= 0) {
3002 // Caller is requesting a result.
3003 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
3004 }
3005 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
3006 new IntentSender(target));
3007 if (mService.mHeavyWeightProcess.activities.size() > 0) {
3008 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
3009 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
3010 hist.packageName);
3011 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
3012 hist.task.taskId);
3013 }
3014 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
3015 aInfo.packageName);
3016 newIntent.setFlags(intent.getFlags());
3017 newIntent.setClassName("android",
3018 HeavyWeightSwitcherActivity.class.getName());
3019 intent = newIntent;
3020 resolvedType = null;
3021 caller = null;
3022 callingUid = Binder.getCallingUid();
3023 callingPid = Binder.getCallingPid();
3024 componentSpecified = true;
3025 try {
3026 ResolveInfo rInfo =
3027 AppGlobals.getPackageManager().resolveIntent(
3028 intent, null,
3029 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07003030 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003031 aInfo = rInfo != null ? rInfo.activityInfo : null;
Amith Yamasani742a6712011-05-04 14:49:28 -07003032 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003033 } catch (RemoteException e) {
3034 aInfo = null;
3035 }
3036 }
3037 }
3038 }
3039
3040 int res = startActivityLocked(caller, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003041 aInfo, resultTo, resultWho, requestCode, callingPid, callingUid,
3042 startFlags, options, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003043
3044 if (mConfigWillChange && mMainStack) {
3045 // If the caller also wants to switch to a new configuration,
3046 // do so now. This allows a clean switch, as we are waiting
3047 // for the current activity to pause (so we will not destroy
3048 // it), and have not yet started the next activity.
3049 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
3050 "updateConfiguration()");
3051 mConfigWillChange = false;
3052 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3053 "Updating to new configuration after starting activity.");
Dianne Hackborn813075a62011-11-14 17:45:19 -08003054 mService.updateConfigurationLocked(config, null, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003055 }
3056
3057 Binder.restoreCallingIdentity(origId);
3058
3059 if (outResult != null) {
3060 outResult.result = res;
Dianne Hackborna4972e92012-03-14 10:38:05 -07003061 if (res == ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003062 mWaitingActivityLaunched.add(outResult);
3063 do {
3064 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003065 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003066 } catch (InterruptedException e) {
3067 }
3068 } while (!outResult.timeout && outResult.who == null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003069 } else if (res == ActivityManager.START_TASK_TO_FRONT) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003070 ActivityRecord r = this.topRunningActivityLocked(null);
3071 if (r.nowVisible) {
3072 outResult.timeout = false;
3073 outResult.who = new ComponentName(r.info.packageName, r.info.name);
3074 outResult.totalTime = 0;
3075 outResult.thisTime = 0;
3076 } else {
3077 outResult.thisTime = SystemClock.uptimeMillis();
3078 mWaitingActivityVisible.add(outResult);
3079 do {
3080 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003081 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003082 } catch (InterruptedException e) {
3083 }
3084 } while (!outResult.timeout && outResult.who == null);
3085 }
3086 }
3087 }
3088
3089 return res;
3090 }
3091 }
3092
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003093 final int startActivities(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003094 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
3095 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003096 if (intents == null) {
3097 throw new NullPointerException("intents is null");
3098 }
3099 if (resolvedTypes == null) {
3100 throw new NullPointerException("resolvedTypes is null");
3101 }
3102 if (intents.length != resolvedTypes.length) {
3103 throw new IllegalArgumentException("intents are length different than resolvedTypes");
3104 }
3105
3106 ActivityRecord[] outActivity = new ActivityRecord[1];
3107
3108 int callingPid;
3109 if (callingUid >= 0) {
3110 callingPid = -1;
3111 } else if (caller == null) {
3112 callingPid = Binder.getCallingPid();
3113 callingUid = Binder.getCallingUid();
3114 } else {
3115 callingPid = callingUid = -1;
3116 }
3117 final long origId = Binder.clearCallingIdentity();
3118 try {
3119 synchronized (mService) {
3120
3121 for (int i=0; i<intents.length; i++) {
3122 Intent intent = intents[i];
3123 if (intent == null) {
3124 continue;
3125 }
3126
3127 // Refuse possible leaked file descriptors
3128 if (intent != null && intent.hasFileDescriptors()) {
3129 throw new IllegalArgumentException("File descriptors passed in Intent");
3130 }
3131
3132 boolean componentSpecified = intent.getComponent() != null;
3133
3134 // Don't modify the client's object!
3135 intent = new Intent(intent);
3136
3137 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003138 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i],
Amith Yamasani483f3b02012-03-13 16:08:00 -07003139 0, null, null, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07003140 // TODO: New, check if this is correct
3141 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003142
3143 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
3144 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
3145 throw new IllegalArgumentException(
3146 "FLAG_CANT_SAVE_STATE not supported here");
3147 }
3148
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003149 Bundle theseOptions;
3150 if (options != null && i == intents.length-1) {
3151 theseOptions = options;
3152 } else {
3153 theseOptions = null;
3154 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003155 int res = startActivityLocked(caller, intent, resolvedTypes[i],
Dianne Hackborna4972e92012-03-14 10:38:05 -07003156 aInfo, resultTo, null, -1, callingPid, callingUid,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003157 0, theseOptions, componentSpecified, outActivity);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003158 if (res < 0) {
3159 return res;
3160 }
3161
Dianne Hackbornbe707852011-11-11 14:32:10 -08003162 resultTo = outActivity[0] != null ? outActivity[0].appToken : null;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003163 }
3164 }
3165 } finally {
3166 Binder.restoreCallingIdentity(origId);
3167 }
3168
Dianne Hackborna4972e92012-03-14 10:38:05 -07003169 return ActivityManager.START_SUCCESS;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003170 }
3171
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003172 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
3173 long thisTime, long totalTime) {
3174 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
3175 WaitResult w = mWaitingActivityLaunched.get(i);
3176 w.timeout = timeout;
3177 if (r != null) {
3178 w.who = new ComponentName(r.info.packageName, r.info.name);
3179 }
3180 w.thisTime = thisTime;
3181 w.totalTime = totalTime;
3182 }
3183 mService.notifyAll();
3184 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003185
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003186 void reportActivityVisibleLocked(ActivityRecord r) {
3187 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
3188 WaitResult w = mWaitingActivityVisible.get(i);
3189 w.timeout = false;
3190 if (r != null) {
3191 w.who = new ComponentName(r.info.packageName, r.info.name);
3192 }
3193 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
3194 w.thisTime = w.totalTime;
3195 }
3196 mService.notifyAll();
Dianne Hackborn90c52de2011-09-23 12:57:44 -07003197
3198 if (mDismissKeyguardOnNextActivity) {
3199 mDismissKeyguardOnNextActivity = false;
3200 mService.mWindowManager.dismissKeyguard();
3201 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003202 }
3203
3204 void sendActivityResultLocked(int callingUid, ActivityRecord r,
3205 String resultWho, int requestCode, int resultCode, Intent data) {
3206
3207 if (callingUid > 0) {
3208 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003209 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003210 }
3211
3212 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3213 + " : who=" + resultWho + " req=" + requestCode
3214 + " res=" + resultCode + " data=" + data);
3215 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3216 try {
3217 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3218 list.add(new ResultInfo(resultWho, requestCode,
3219 resultCode, data));
Dianne Hackbornbe707852011-11-11 14:32:10 -08003220 r.app.thread.scheduleSendResult(r.appToken, list);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003221 return;
3222 } catch (Exception e) {
3223 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3224 }
3225 }
3226
3227 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3228 }
3229
3230 private final void stopActivityLocked(ActivityRecord r) {
3231 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3232 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3233 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3234 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003235 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003236 "no-history");
3237 }
3238 } else if (r.app != null && r.app.thread != null) {
3239 if (mMainStack) {
3240 if (mService.mFocusedActivity == r) {
3241 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3242 }
3243 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003244 r.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003245 try {
3246 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003247 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3248 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003249 r.state = ActivityState.STOPPING;
3250 if (DEBUG_VISBILITY) Slog.v(
3251 TAG, "Stopping visible=" + r.visible + " for " + r);
3252 if (!r.visible) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003253 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003254 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003255 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003256 if (mService.isSleeping()) {
3257 r.setSleeping(true);
3258 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003259 Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG);
3260 msg.obj = r;
3261 mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003262 } catch (Exception e) {
3263 // Maybe just ignore exceptions here... if the process
3264 // has crashed, our death notification will clean things
3265 // up.
3266 Slog.w(TAG, "Exception thrown during pause", e);
3267 // Just in case, assume it to be stopped.
3268 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003269 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003270 r.state = ActivityState.STOPPED;
3271 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003272 destroyActivityLocked(r, true, false, "stop-except");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003273 }
3274 }
3275 }
3276 }
3277
3278 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3279 boolean remove) {
3280 int N = mStoppingActivities.size();
3281 if (N <= 0) return null;
3282
3283 ArrayList<ActivityRecord> stops = null;
3284
3285 final boolean nowVisible = mResumedActivity != null
3286 && mResumedActivity.nowVisible
3287 && !mResumedActivity.waitingVisible;
3288 for (int i=0; i<N; i++) {
3289 ActivityRecord s = mStoppingActivities.get(i);
3290 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3291 + nowVisible + " waitingVisible=" + s.waitingVisible
3292 + " finishing=" + s.finishing);
3293 if (s.waitingVisible && nowVisible) {
3294 mWaitingVisibleActivities.remove(s);
3295 s.waitingVisible = false;
3296 if (s.finishing) {
3297 // If this activity is finishing, it is sitting on top of
3298 // everyone else but we now know it is no longer needed...
3299 // so get rid of it. Otherwise, we need to go through the
3300 // normal flow and hide it once we determine that it is
3301 // hidden by the activities in front of it.
3302 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003303 mService.mWindowManager.setAppVisibility(s.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003304 }
3305 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003306 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003307 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3308 if (stops == null) {
3309 stops = new ArrayList<ActivityRecord>();
3310 }
3311 stops.add(s);
3312 mStoppingActivities.remove(i);
3313 N--;
3314 i--;
3315 }
3316 }
3317
3318 return stops;
3319 }
3320
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003321 final void scheduleIdleLocked() {
3322 Message msg = Message.obtain();
3323 msg.what = IDLE_NOW_MSG;
3324 mHandler.sendMessage(msg);
3325 }
3326
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003327 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003328 Configuration config) {
3329 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3330
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003331 ActivityRecord res = null;
3332
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003333 ArrayList<ActivityRecord> stops = null;
3334 ArrayList<ActivityRecord> finishes = null;
3335 ArrayList<ActivityRecord> thumbnails = null;
3336 int NS = 0;
3337 int NF = 0;
3338 int NT = 0;
3339 IApplicationThread sendThumbnail = null;
3340 boolean booting = false;
3341 boolean enableScreen = false;
3342
3343 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003344 ActivityRecord r = ActivityRecord.forToken(token);
3345 if (r != null) {
3346 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003347 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003348 }
3349
3350 // Get the activity record.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003351 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003352 if (index >= 0) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003353 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003354
3355 if (fromTimeout) {
3356 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3357 }
3358
3359 // This is a hack to semi-deal with a race condition
3360 // in the client where it can be constructed with a
3361 // newer configuration from when we asked it to launch.
3362 // We'll update with whatever configuration it now says
3363 // it used to launch.
3364 if (config != null) {
3365 r.configuration = config;
3366 }
3367
3368 // No longer need to keep the device awake.
3369 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3370 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3371 mLaunchingActivity.release();
3372 }
3373
3374 // We are now idle. If someone is waiting for a thumbnail from
3375 // us, we can now deliver.
3376 r.idle = true;
3377 mService.scheduleAppGcsLocked();
3378 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3379 sendThumbnail = r.app.thread;
3380 r.thumbnailNeeded = false;
3381 }
3382
3383 // If this activity is fullscreen, set up to hide those under it.
3384
3385 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3386 ensureActivitiesVisibleLocked(null, 0);
3387
3388 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3389 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003390 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003391 mService.mBooted = true;
3392 enableScreen = true;
3393 }
3394 }
3395
3396 } else if (fromTimeout) {
3397 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3398 }
3399
3400 // Atomically retrieve all of the other things to do.
3401 stops = processStoppingActivitiesLocked(true);
3402 NS = stops != null ? stops.size() : 0;
3403 if ((NF=mFinishingActivities.size()) > 0) {
3404 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3405 mFinishingActivities.clear();
3406 }
3407 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3408 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3409 mService.mCancelledThumbnails.clear();
3410 }
3411
3412 if (mMainStack) {
3413 booting = mService.mBooting;
3414 mService.mBooting = false;
3415 }
3416 }
3417
3418 int i;
3419
3420 // Send thumbnail if requested.
3421 if (sendThumbnail != null) {
3422 try {
3423 sendThumbnail.requestThumbnail(token);
3424 } catch (Exception e) {
3425 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3426 mService.sendPendingThumbnail(null, token, null, null, true);
3427 }
3428 }
3429
3430 // Stop any activities that are scheduled to do so but have been
3431 // waiting for the next one to start.
3432 for (i=0; i<NS; i++) {
3433 ActivityRecord r = (ActivityRecord)stops.get(i);
3434 synchronized (mService) {
3435 if (r.finishing) {
3436 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY);
3437 } else {
3438 stopActivityLocked(r);
3439 }
3440 }
3441 }
3442
3443 // Finish any activities that are scheduled to do so but have been
3444 // waiting for the next one to start.
3445 for (i=0; i<NF; i++) {
3446 ActivityRecord r = (ActivityRecord)finishes.get(i);
3447 synchronized (mService) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003448 destroyActivityLocked(r, true, false, "finish-idle");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003449 }
3450 }
3451
3452 // Report back to any thumbnail receivers.
3453 for (i=0; i<NT; i++) {
3454 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3455 mService.sendPendingThumbnail(r, null, null, null, true);
3456 }
3457
3458 if (booting) {
3459 mService.finishBooting();
3460 }
3461
3462 mService.trimApplications();
3463 //dump();
3464 //mWindowManager.dump();
3465
3466 if (enableScreen) {
3467 mService.enableScreenAfterBoot();
3468 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003469
3470 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003471 }
3472
3473 /**
3474 * @return Returns true if the activity is being finished, false if for
3475 * some reason it is being left as-is.
3476 */
3477 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
3478 Intent resultData, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003479 int index = indexOfTokenLocked(token);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003480 if (DEBUG_RESULTS) Slog.v(
3481 TAG, "Finishing activity @" + index + ": token=" + token
3482 + ", result=" + resultCode + ", data=" + resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003483 if (index < 0) {
3484 return false;
3485 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003486 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003487
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003488 finishActivityLocked(r, index, resultCode, resultData, reason);
3489 return true;
3490 }
3491
Dianne Hackborn5c607432012-02-28 14:44:19 -08003492 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
3493 // send the result
3494 ActivityRecord resultTo = r.resultTo;
3495 if (resultTo != null) {
3496 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3497 + " who=" + r.resultWho + " req=" + r.requestCode
3498 + " res=" + resultCode + " data=" + resultData);
3499 if (r.info.applicationInfo.uid > 0) {
3500 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3501 resultTo.packageName, resultData,
3502 resultTo.getUriPermissionsLocked());
3503 }
3504 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3505 resultData);
3506 r.resultTo = null;
3507 }
3508 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3509
3510 // Make sure this HistoryRecord is not holding on to other resources,
3511 // because clients have remote IPC references to this object so we
3512 // can't assume that will go away and want to avoid circular IPC refs.
3513 r.results = null;
3514 r.pendingResults = null;
3515 r.newIntents = null;
3516 r.icicle = null;
3517 }
3518
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003519 /**
3520 * @return Returns true if this activity has been removed from the history
3521 * list, or false if it is still in the list and will be removed later.
3522 */
3523 final boolean finishActivityLocked(ActivityRecord r, int index,
3524 int resultCode, Intent resultData, String reason) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003525 return finishActivityLocked(r, index, resultCode, resultData, reason, false);
3526 }
3527
3528 /**
3529 * @return Returns true if this activity has been removed from the history
3530 * list, or false if it is still in the list and will be removed later.
3531 */
3532 final boolean finishActivityLocked(ActivityRecord r, int index,
3533 int resultCode, Intent resultData, String reason, boolean immediate) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003534 if (r.finishing) {
3535 Slog.w(TAG, "Duplicate finish request for " + r);
3536 return false;
3537 }
3538
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003539 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003540 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3541 System.identityHashCode(r),
3542 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003543 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003544 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003545 if (next.task == r.task) {
3546 if (r.frontOfTask) {
3547 // The next activity is now the front of the task.
3548 next.frontOfTask = true;
3549 }
3550 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3551 // If the caller asked that this activity (and all above it)
3552 // be cleared when the task is reset, don't lose that information,
3553 // but propagate it up to the next activity.
3554 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3555 }
3556 }
3557 }
3558
3559 r.pauseKeyDispatchingLocked();
3560 if (mMainStack) {
3561 if (mService.mFocusedActivity == r) {
3562 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3563 }
3564 }
3565
Dianne Hackborn5c607432012-02-28 14:44:19 -08003566 finishActivityResultsLocked(r, resultCode, resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003567
3568 if (mService.mPendingThumbnails.size() > 0) {
3569 // There are clients waiting to receive thumbnails so, in case
3570 // this is an activity that someone is waiting for, add it
3571 // to the pending list so we can correctly update the clients.
3572 mService.mCancelledThumbnails.add(r);
3573 }
3574
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003575 if (immediate) {
3576 return finishCurrentActivityLocked(r, index,
3577 FINISH_IMMEDIATELY) == null;
3578 } else if (mResumedActivity == r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003579 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003580 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003581 if (DEBUG_TRANSITION) Slog.v(TAG,
3582 "Prepare close transition: finishing " + r);
3583 mService.mWindowManager.prepareAppTransition(endTask
3584 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003585 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003586
3587 // Tell window manager to prepare for this one to be removed.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003588 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003589
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003590 if (mPausingActivity == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003591 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3592 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3593 startPausingLocked(false, false);
3594 }
3595
3596 } else if (r.state != ActivityState.PAUSING) {
3597 // If the activity is PAUSING, we will complete the finish once
3598 // it is done pausing; else we can just directly finish it here.
3599 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3600 return finishCurrentActivityLocked(r, index,
3601 FINISH_AFTER_PAUSE) == null;
3602 } else {
3603 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3604 }
3605
3606 return false;
3607 }
3608
3609 private static final int FINISH_IMMEDIATELY = 0;
3610 private static final int FINISH_AFTER_PAUSE = 1;
3611 private static final int FINISH_AFTER_VISIBLE = 2;
3612
3613 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3614 int mode) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003615 final int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003616 if (index < 0) {
3617 return null;
3618 }
3619
3620 return finishCurrentActivityLocked(r, index, mode);
3621 }
3622
3623 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3624 int index, int mode) {
3625 // First things first: if this activity is currently visible,
3626 // and the resumed activity is not yet visible, then hold off on
3627 // finishing until the resumed one becomes visible.
3628 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3629 if (!mStoppingActivities.contains(r)) {
3630 mStoppingActivities.add(r);
3631 if (mStoppingActivities.size() > 3) {
3632 // If we already have a few activities waiting to stop,
3633 // then give up on things going idle and start clearing
3634 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003635 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003636 } else {
3637 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003638 }
3639 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003640 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3641 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003642 r.state = ActivityState.STOPPING;
3643 mService.updateOomAdjLocked();
3644 return r;
3645 }
3646
3647 // make sure the record is cleaned out of other places.
3648 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003649 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003650 mWaitingVisibleActivities.remove(r);
3651 if (mResumedActivity == r) {
3652 mResumedActivity = null;
3653 }
3654 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003655 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003656 r.state = ActivityState.FINISHING;
3657
3658 if (mode == FINISH_IMMEDIATELY
3659 || prevState == ActivityState.STOPPED
3660 || prevState == ActivityState.INITIALIZING) {
3661 // If this activity is already stopped, we can just finish
3662 // it right now.
Dianne Hackborn28695e02011-11-02 21:59:51 -07003663 return destroyActivityLocked(r, true, true, "finish-imm") ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003664 } else {
3665 // Need to go through the full pause cycle to get this
3666 // activity into the stopped state and then finish it.
3667 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3668 mFinishingActivities.add(r);
3669 resumeTopActivityLocked(null);
3670 }
3671 return r;
3672 }
3673
3674 /**
3675 * Perform the common clean-up of an activity record. This is called both
3676 * as part of destroyActivityLocked() (when destroying the client-side
3677 * representation) and cleaning things up as a result of its hosting
3678 * processing going away, in which case there is no remaining client-side
3679 * state to destroy so only the cleanup here is needed.
3680 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003681 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3682 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003683 if (mResumedActivity == r) {
3684 mResumedActivity = null;
3685 }
3686 if (mService.mFocusedActivity == r) {
3687 mService.mFocusedActivity = null;
3688 }
3689
3690 r.configDestroy = false;
3691 r.frozenBeforeDestroy = false;
3692
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003693 if (setState) {
3694 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3695 r.state = ActivityState.DESTROYED;
3696 }
3697
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003698 // Make sure this record is no longer in the pending finishes list.
3699 // This could happen, for example, if we are trimming activities
3700 // down to the max limit while they are still waiting to finish.
3701 mFinishingActivities.remove(r);
3702 mWaitingVisibleActivities.remove(r);
3703
3704 // Remove any pending results.
3705 if (r.finishing && r.pendingResults != null) {
3706 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3707 PendingIntentRecord rec = apr.get();
3708 if (rec != null) {
3709 mService.cancelIntentSenderLocked(rec, false);
3710 }
3711 }
3712 r.pendingResults = null;
3713 }
3714
3715 if (cleanServices) {
3716 cleanUpActivityServicesLocked(r);
3717 }
3718
3719 if (mService.mPendingThumbnails.size() > 0) {
3720 // There are clients waiting to receive thumbnails so, in case
3721 // this is an activity that someone is waiting for, add it
3722 // to the pending list so we can correctly update the clients.
3723 mService.mCancelledThumbnails.add(r);
3724 }
3725
3726 // Get rid of any pending idle timeouts.
3727 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003728 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003729 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003730 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003731 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003732 }
3733
Dianne Hackborn5c607432012-02-28 14:44:19 -08003734 final void removeActivityFromHistoryLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003735 if (r.state != ActivityState.DESTROYED) {
Dianne Hackborn5c607432012-02-28 14:44:19 -08003736 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003737 r.makeFinishing();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003738 if (DEBUG_ADD_REMOVE) {
3739 RuntimeException here = new RuntimeException("here");
3740 here.fillInStackTrace();
3741 Slog.i(TAG, "Removing activity " + r + " from stack");
3742 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003743 mHistory.remove(r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003744 r.takeFromHistory();
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003745 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3746 + " (removed from history)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003747 r.state = ActivityState.DESTROYED;
Dianne Hackbornbe707852011-11-11 14:32:10 -08003748 mService.mWindowManager.removeAppToken(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003749 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003750 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003751 }
3752 cleanUpActivityServicesLocked(r);
3753 r.removeUriPermissionsLocked();
3754 }
3755 }
3756
3757 /**
3758 * Perform clean-up of service connections in an activity record.
3759 */
3760 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3761 // Throw away any services that have been bound by this activity.
3762 if (r.connections != null) {
3763 Iterator<ConnectionRecord> it = r.connections.iterator();
3764 while (it.hasNext()) {
3765 ConnectionRecord c = it.next();
3766 mService.removeConnectionLocked(c, null, r);
3767 }
3768 r.connections = null;
3769 }
3770 }
3771
Dianne Hackborn28695e02011-11-02 21:59:51 -07003772 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003773 for (int i=mHistory.size()-1; i>=0; i--) {
3774 ActivityRecord r = mHistory.get(i);
3775 if (owner != null && r.app != owner) {
3776 continue;
3777 }
3778 // We can destroy this one if we have its icicle saved and
3779 // it is not in the process of pausing/stopping/finishing.
3780 if (r.app != null && r.haveState && !r.visible && r.stopped && !r.finishing
3781 && r.state != ActivityState.DESTROYING
3782 && r.state != ActivityState.DESTROYED) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003783 destroyActivityLocked(r, true, oomAdj, "trim");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003784 }
3785 }
3786 }
3787
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003788 /**
3789 * Destroy the current CLIENT SIDE instance of an activity. This may be
3790 * called both when actually finishing an activity, or when performing
3791 * a configuration switch where we destroy the current client-side object
3792 * but then create a new client-side object for this same HistoryRecord.
3793 */
3794 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackborn28695e02011-11-02 21:59:51 -07003795 boolean removeFromApp, boolean oomAdj, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003796 if (DEBUG_SWITCH) Slog.v(
3797 TAG, "Removing activity: token=" + r
3798 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3799 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3800 System.identityHashCode(r),
Dianne Hackborn28695e02011-11-02 21:59:51 -07003801 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003802
3803 boolean removedFromHistory = false;
3804
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003805 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003806
3807 final boolean hadApp = r.app != null;
3808
3809 if (hadApp) {
3810 if (removeFromApp) {
3811 int idx = r.app.activities.indexOf(r);
3812 if (idx >= 0) {
3813 r.app.activities.remove(idx);
3814 }
3815 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
3816 mService.mHeavyWeightProcess = null;
3817 mService.mHandler.sendEmptyMessage(
3818 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
3819 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003820 if (r.app.activities.size() == 0) {
3821 // No longer have activities, so update location in
3822 // LRU list.
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003823 mService.updateLruProcessLocked(r.app, oomAdj, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003824 }
3825 }
3826
3827 boolean skipDestroy = false;
3828
3829 try {
3830 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003831 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003832 r.configChangeFlags);
3833 } catch (Exception e) {
3834 // We can just ignore exceptions here... if the process
3835 // has crashed, our death notification will clean things
3836 // up.
3837 //Slog.w(TAG, "Exception thrown during finish", e);
3838 if (r.finishing) {
3839 removeActivityFromHistoryLocked(r);
3840 removedFromHistory = true;
3841 skipDestroy = true;
3842 }
3843 }
3844
3845 r.app = null;
3846 r.nowVisible = false;
3847
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003848 // If the activity is finishing, we need to wait on removing it
3849 // from the list to give it a chance to do its cleanup. During
3850 // that time it may make calls back with its token so we need to
3851 // be able to find it on the list and so we don't want to remove
3852 // it from the list yet. Otherwise, we can just immediately put
3853 // it in the destroyed state since we are not removing it from the
3854 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003855 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003856 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
3857 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003858 r.state = ActivityState.DESTROYING;
3859 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
3860 msg.obj = r;
3861 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
3862 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003863 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3864 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003865 r.state = ActivityState.DESTROYED;
3866 }
3867 } else {
3868 // remove this record from the history.
3869 if (r.finishing) {
3870 removeActivityFromHistoryLocked(r);
3871 removedFromHistory = true;
3872 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003873 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3874 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003875 r.state = ActivityState.DESTROYED;
3876 }
3877 }
3878
3879 r.configChangeFlags = 0;
3880
3881 if (!mLRUActivities.remove(r) && hadApp) {
3882 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
3883 }
3884
3885 return removedFromHistory;
3886 }
3887
3888 final void activityDestroyed(IBinder token) {
3889 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003890 ActivityRecord r = ActivityRecord.forToken(token);
3891 if (r != null) {
3892 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
3893 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003894
Dianne Hackbornbe707852011-11-11 14:32:10 -08003895 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003896 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003897 if (r.state == ActivityState.DESTROYING) {
3898 final long origId = Binder.clearCallingIdentity();
3899 removeActivityFromHistoryLocked(r);
3900 Binder.restoreCallingIdentity(origId);
3901 }
3902 }
3903 }
3904 }
3905
3906 private static void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
3907 int i = list.size();
3908 if (localLOGV) Slog.v(
3909 TAG, "Removing app " + app + " from list " + list
3910 + " with " + i + " entries");
3911 while (i > 0) {
3912 i--;
3913 ActivityRecord r = (ActivityRecord)list.get(i);
3914 if (localLOGV) Slog.v(
3915 TAG, "Record #" + i + " " + r + ": app=" + r.app);
3916 if (r.app == app) {
3917 if (localLOGV) Slog.v(TAG, "Removing this entry!");
3918 list.remove(i);
3919 }
3920 }
3921 }
3922
3923 void removeHistoryRecordsForAppLocked(ProcessRecord app) {
3924 removeHistoryRecordsForAppLocked(mLRUActivities, app);
3925 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003926 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003927 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
3928 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
3929 }
3930
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003931 /**
3932 * Move the current home activity's task (if one exists) to the front
3933 * of the stack.
3934 */
3935 final void moveHomeToFrontLocked() {
3936 TaskRecord homeTask = null;
3937 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003938 ActivityRecord hr = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003939 if (hr.isHomeActivity) {
3940 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003941 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003942 }
3943 }
3944 if (homeTask != null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003945 moveTaskToFrontLocked(homeTask, null, null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003946 }
3947 }
3948
Dianne Hackborn7f58b952012-04-18 12:59:29 -07003949 final void updateTransitLocked(int transit, Bundle options) {
3950 if (options != null) {
3951 ActivityRecord r = topRunningActivityLocked(null);
3952 if (r != null && r.state != ActivityState.RESUMED) {
3953 r.updateOptionsLocked(options);
3954 } else {
3955 ActivityOptions.abort(options);
3956 }
3957 }
3958 mService.mWindowManager.prepareAppTransition(transit, false);
3959 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003960
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003961 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003962 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
3963
3964 final int task = tr.taskId;
3965 int top = mHistory.size()-1;
3966
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003967 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003968 // nothing to do!
Dianne Hackborn7f58b952012-04-18 12:59:29 -07003969 if (reason != null &&
3970 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
3971 ActivityOptions.abort(options);
3972 } else {
3973 updateTransitLocked(WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, options);
3974 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003975 return;
3976 }
3977
Dianne Hackbornbe707852011-11-11 14:32:10 -08003978 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003979
3980 // Applying the affinities may have removed entries from the history,
3981 // so get the size again.
3982 top = mHistory.size()-1;
3983 int pos = top;
3984
3985 // Shift all activities with this task up to the top
3986 // of the stack, keeping them in the same internal order.
3987 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003988 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003989 if (localLOGV) Slog.v(
3990 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003991 if (r.task.taskId == task) {
3992 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003993 if (DEBUG_ADD_REMOVE) {
3994 RuntimeException here = new RuntimeException("here");
3995 here.fillInStackTrace();
3996 Slog.i(TAG, "Removing and adding activity " + r + " to stack at " + top, here);
3997 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003998 mHistory.remove(pos);
3999 mHistory.add(top, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004000 moved.add(0, r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004001 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004002 }
4003 pos--;
4004 }
4005
4006 if (DEBUG_TRANSITION) Slog.v(TAG,
4007 "Prepare to front transition: task=" + tr);
4008 if (reason != null &&
4009 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004010 mService.mWindowManager.prepareAppTransition(
4011 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004012 ActivityRecord r = topRunningActivityLocked(null);
4013 if (r != null) {
4014 mNoAnimActivities.add(r);
4015 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004016 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004017 } else {
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004018 updateTransitLocked(WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004019 }
4020
4021 mService.mWindowManager.moveAppTokensToTop(moved);
4022 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004023 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004024 }
4025
4026 finishTaskMoveLocked(task);
4027 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
4028 }
4029
4030 private final void finishTaskMoveLocked(int task) {
4031 resumeTopActivityLocked(null);
4032 }
4033
4034 /**
4035 * Worker method for rearranging history stack. Implements the function of moving all
4036 * activities for a specific task (gathering them if disjoint) into a single group at the
4037 * bottom of the stack.
4038 *
4039 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
4040 * to premeptively cancel the move.
4041 *
4042 * @param task The taskId to collect and move to the bottom.
4043 * @return Returns true if the move completed, false if not.
4044 */
4045 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
4046 Slog.i(TAG, "moveTaskToBack: " + task);
4047
4048 // If we have a watcher, preflight the move before committing to it. First check
4049 // for *other* available tasks, but if none are available, then try again allowing the
4050 // current task to be selected.
4051 if (mMainStack && mService.mController != null) {
4052 ActivityRecord next = topRunningActivityLocked(null, task);
4053 if (next == null) {
4054 next = topRunningActivityLocked(null, 0);
4055 }
4056 if (next != null) {
4057 // ask watcher if this is allowed
4058 boolean moveOK = true;
4059 try {
4060 moveOK = mService.mController.activityResuming(next.packageName);
4061 } catch (RemoteException e) {
4062 mService.mController = null;
4063 }
4064 if (!moveOK) {
4065 return false;
4066 }
4067 }
4068 }
4069
Dianne Hackbornbe707852011-11-11 14:32:10 -08004070 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004071
4072 if (DEBUG_TRANSITION) Slog.v(TAG,
4073 "Prepare to back transition: task=" + task);
4074
4075 final int N = mHistory.size();
4076 int bottom = 0;
4077 int pos = 0;
4078
4079 // Shift all activities with this task down to the bottom
4080 // of the stack, keeping them in the same internal order.
4081 while (pos < N) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004082 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004083 if (localLOGV) Slog.v(
4084 TAG, "At " + pos + " ckp " + r.task + ": " + r);
4085 if (r.task.taskId == task) {
4086 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004087 if (DEBUG_ADD_REMOVE) {
4088 RuntimeException here = new RuntimeException("here");
4089 here.fillInStackTrace();
4090 Slog.i(TAG, "Removing and adding activity " + r + " to stack at "
4091 + bottom, here);
4092 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004093 mHistory.remove(pos);
4094 mHistory.add(bottom, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004095 moved.add(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004096 bottom++;
4097 }
4098 pos++;
4099 }
4100
4101 if (reason != null &&
4102 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004103 mService.mWindowManager.prepareAppTransition(
4104 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004105 ActivityRecord r = topRunningActivityLocked(null);
4106 if (r != null) {
4107 mNoAnimActivities.add(r);
4108 }
4109 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004110 mService.mWindowManager.prepareAppTransition(
4111 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004112 }
4113 mService.mWindowManager.moveAppTokensToBottom(moved);
4114 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004115 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004116 }
4117
4118 finishTaskMoveLocked(task);
4119 return true;
4120 }
4121
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004122 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
4123 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4124 ActivityRecord resumed = mResumedActivity;
4125 if (resumed != null && resumed.thumbHolder == tr) {
4126 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
4127 } else {
4128 info.mainThumbnail = tr.lastThumbnail;
4129 }
4130 return info;
4131 }
4132
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004133 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex,
4134 boolean taskRequired) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004135 TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
4136 if (info.root == null) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004137 if (taskRequired) {
4138 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
4139 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004140 return null;
4141 }
4142
4143 if (subTaskIndex < 0) {
4144 // Just remove the entire task.
4145 performClearTaskAtIndexLocked(taskId, info.rootIndex);
4146 return info.root;
4147 }
4148
4149 if (subTaskIndex >= info.subtasks.size()) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004150 if (taskRequired) {
4151 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
4152 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004153 return null;
4154 }
4155
4156 // Remove all of this task's activies starting at the sub task.
4157 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
4158 performClearTaskAtIndexLocked(taskId, subtask.index);
4159 return subtask.activity;
4160 }
4161
4162 public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
4163 ActivityRecord resumed = mResumedActivity;
4164 final TaskAccessInfo thumbs = new TaskAccessInfo();
4165 // How many different sub-thumbnails?
4166 final int NA = mHistory.size();
4167 int j = 0;
4168 ThumbnailHolder holder = null;
4169 while (j < NA) {
4170 ActivityRecord ar = mHistory.get(j);
4171 if (!ar.finishing && ar.task.taskId == taskId) {
4172 holder = ar.thumbHolder;
4173 break;
4174 }
4175 j++;
4176 }
4177
4178 if (j >= NA) {
4179 return thumbs;
4180 }
4181
4182 thumbs.root = mHistory.get(j);
4183 thumbs.rootIndex = j;
4184
4185 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
4186 thumbs.subtasks = subtasks;
4187 ActivityRecord lastActivity = null;
4188 while (j < NA) {
4189 ActivityRecord ar = mHistory.get(j);
4190 j++;
4191 if (ar.finishing) {
4192 continue;
4193 }
4194 if (ar.task.taskId != taskId) {
4195 break;
4196 }
4197 lastActivity = ar;
4198 if (ar.thumbHolder != holder && holder != null) {
4199 thumbs.numSubThumbbails++;
4200 holder = ar.thumbHolder;
4201 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
4202 sub.thumbnail = holder.lastThumbnail;
4203 sub.activity = ar;
4204 sub.index = j-1;
4205 subtasks.add(sub);
4206 }
4207 }
4208 if (lastActivity != null && subtasks.size() > 0) {
4209 if (resumed == lastActivity) {
4210 TaskAccessInfo.SubTask sub = subtasks.get(subtasks.size()-1);
4211 sub.thumbnail = lastActivity.stack.screenshotActivities(lastActivity);
4212 }
4213 }
4214 if (thumbs.numSubThumbbails > 0) {
4215 thumbs.retriever = new IThumbnailRetriever.Stub() {
4216 public Bitmap getThumbnail(int index) {
4217 if (index < 0 || index >= thumbs.subtasks.size()) {
4218 return null;
4219 }
4220 return thumbs.subtasks.get(index).thumbnail;
4221 }
4222 };
4223 }
4224 return thumbs;
4225 }
4226
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004227 private final void logStartActivity(int tag, ActivityRecord r,
4228 TaskRecord task) {
4229 EventLog.writeEvent(tag,
4230 System.identityHashCode(r), task.taskId,
4231 r.shortComponentName, r.intent.getAction(),
4232 r.intent.getType(), r.intent.getDataString(),
4233 r.intent.getFlags());
4234 }
4235
4236 /**
4237 * Make sure the given activity matches the current configuration. Returns
4238 * false if the activity had to be destroyed. Returns true if the
4239 * configuration is the same, or the activity will remain running as-is
4240 * for whatever reason. Ensures the HistoryRecord is updated with the
4241 * correct configuration and all other bookkeeping is handled.
4242 */
4243 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
4244 int globalChanges) {
4245 if (mConfigWillChange) {
4246 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4247 "Skipping config check (will change): " + r);
4248 return true;
4249 }
4250
4251 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4252 "Ensuring correct configuration: " + r);
4253
4254 // Short circuit: if the two configurations are the exact same
4255 // object (the common case), then there is nothing to do.
4256 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004257 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004258 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4259 "Configuration unchanged in " + r);
4260 return true;
4261 }
4262
4263 // We don't worry about activities that are finishing.
4264 if (r.finishing) {
4265 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4266 "Configuration doesn't matter in finishing " + r);
4267 r.stopFreezingScreenLocked(false);
4268 return true;
4269 }
4270
4271 // Okay we now are going to make this activity have the new config.
4272 // But then we need to figure out how it needs to deal with that.
4273 Configuration oldConfig = r.configuration;
4274 r.configuration = newConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004275
4276 // Determine what has changed. May be nothing, if this is a config
4277 // that has come back from the app after going idle. In that case
4278 // we just want to leave the official config object now in the
4279 // activity and do nothing else.
4280 final int changes = oldConfig.diff(newConfig);
4281 if (changes == 0 && !r.forceNewConfig) {
4282 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4283 "Configuration no differences in " + r);
4284 return true;
4285 }
4286
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004287 // If the activity isn't currently running, just leave the new
4288 // configuration and it will pick that up next time it starts.
4289 if (r.app == null || r.app.thread == null) {
4290 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4291 "Configuration doesn't matter not running " + r);
4292 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004293 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004294 return true;
4295 }
4296
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004297 // Figure out how to handle the changes between the configurations.
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004298 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4299 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
4300 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07004301 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004302 + ", newConfig=" + newConfig);
4303 }
Dianne Hackborne6676352011-06-01 16:51:20 -07004304 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004305 // Aha, the activity isn't handling the change, so DIE DIE DIE.
4306 r.configChangeFlags |= changes;
4307 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004308 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004309 if (r.app == null || r.app.thread == null) {
4310 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4311 "Switch is destroying non-running " + r);
Dianne Hackborn28695e02011-11-02 21:59:51 -07004312 destroyActivityLocked(r, true, false, "config");
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004313 } else if (r.state == ActivityState.PAUSING) {
4314 // A little annoying: we are waiting for this activity to
4315 // finish pausing. Let's not do anything now, but just
4316 // flag that it needs to be restarted when done pausing.
4317 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4318 "Switch is skipping already pausing " + r);
4319 r.configDestroy = true;
4320 return true;
4321 } else if (r.state == ActivityState.RESUMED) {
4322 // Try to optimize this case: the configuration is changing
4323 // and we need to restart the top, resumed activity.
4324 // Instead of doing the normal handshaking, just say
4325 // "restart!".
4326 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4327 "Switch is restarting resumed " + r);
4328 relaunchActivityLocked(r, r.configChangeFlags, true);
4329 r.configChangeFlags = 0;
4330 } else {
4331 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4332 "Switch is restarting non-resumed " + r);
4333 relaunchActivityLocked(r, r.configChangeFlags, false);
4334 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004335 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004336
4337 // All done... tell the caller we weren't able to keep this
4338 // activity around.
4339 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004340 }
4341
4342 // Default case: the activity can handle this new configuration, so
4343 // hand it over. Note that we don't need to give it the new
4344 // configuration, since we always send configuration changes to all
4345 // process when they happen so it can just use whatever configuration
4346 // it last got.
4347 if (r.app != null && r.app.thread != null) {
4348 try {
4349 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004350 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004351 } catch (RemoteException e) {
4352 // If process died, whatever.
4353 }
4354 }
4355 r.stopFreezingScreenLocked(false);
4356
4357 return true;
4358 }
4359
4360 private final boolean relaunchActivityLocked(ActivityRecord r,
4361 int changes, boolean andResume) {
4362 List<ResultInfo> results = null;
4363 List<Intent> newIntents = null;
4364 if (andResume) {
4365 results = r.results;
4366 newIntents = r.newIntents;
4367 }
4368 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4369 + " with results=" + results + " newIntents=" + newIntents
4370 + " andResume=" + andResume);
4371 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
4372 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
4373 r.task.taskId, r.shortComponentName);
4374
4375 r.startFreezingScreenLocked(r.app, 0);
4376
4377 try {
4378 if (DEBUG_SWITCH) Slog.i(TAG, "Switch is restarting resumed " + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004379 r.forceNewConfig = false;
Dianne Hackbornbe707852011-11-11 14:32:10 -08004380 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004381 changes, !andResume, new Configuration(mService.mConfiguration));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004382 // Note: don't need to call pauseIfSleepingLocked() here, because
4383 // the caller will only pass in 'andResume' if this activity is
4384 // currently resumed, which implies we aren't sleeping.
4385 } catch (RemoteException e) {
4386 return false;
4387 }
4388
4389 if (andResume) {
4390 r.results = null;
4391 r.newIntents = null;
4392 if (mMainStack) {
4393 mService.reportResumedActivityLocked(r);
4394 }
4395 }
4396
4397 return true;
4398 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004399
4400 public void dismissKeyguardOnNextActivityLocked() {
4401 mDismissKeyguardOnNextActivity = true;
4402 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004403}