blob: e07aee6c91f190a50dcdef9fc496f61e8ce4f990 [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 Hackborn50dc3bc2010-06-25 10:05:59 -070025import android.app.AppGlobals;
26import android.app.IActivityManager;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070027import android.app.IThumbnailRetriever;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070028import static android.app.IActivityManager.START_CLASS_NOT_FOUND;
29import static android.app.IActivityManager.START_DELIVERED_TO_TOP;
30import static android.app.IActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
31import static android.app.IActivityManager.START_INTENT_NOT_RESOLVED;
32import static android.app.IActivityManager.START_PERMISSION_DENIED;
33import static android.app.IActivityManager.START_RETURN_INTENT_TO_CALLER;
34import static android.app.IActivityManager.START_SUCCESS;
35import static android.app.IActivityManager.START_SWITCHES_CANCELED;
36import static android.app.IActivityManager.START_TASK_TO_FRONT;
37import android.app.IApplicationThread;
38import android.app.PendingIntent;
39import android.app.ResultInfo;
40import android.app.IActivityManager.WaitResult;
41import android.content.ComponentName;
42import android.content.Context;
43import android.content.IIntentSender;
44import android.content.Intent;
45import android.content.IntentSender;
46import android.content.pm.ActivityInfo;
47import android.content.pm.ApplicationInfo;
48import android.content.pm.PackageManager;
49import android.content.pm.ResolveInfo;
50import android.content.res.Configuration;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -080051import android.content.res.Resources;
52import android.graphics.Bitmap;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070053import android.net.Uri;
54import android.os.Binder;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070055import android.os.Bundle;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070056import android.os.Handler;
57import android.os.IBinder;
58import android.os.Message;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070059import android.os.ParcelFileDescriptor;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070060import android.os.PowerManager;
61import android.os.RemoteException;
62import android.os.SystemClock;
Amith Yamasani742a6712011-05-04 14:49:28 -070063import android.os.UserId;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070064import android.util.EventLog;
65import android.util.Log;
66import android.util.Slog;
67import android.view.WindowManagerPolicy;
68
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070069import java.io.IOException;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070070import java.lang.ref.WeakReference;
71import java.util.ArrayList;
72import java.util.Iterator;
73import java.util.List;
74
75/**
76 * State and management of a single stack of activities.
77 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070078final class ActivityStack {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070079 static final String TAG = ActivityManagerService.TAG;
Dianne Hackbornb961cd22011-06-21 12:13:37 -070080 static final boolean localLOGV = ActivityManagerService.localLOGV;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070081 static final boolean DEBUG_SWITCH = ActivityManagerService.DEBUG_SWITCH;
82 static final boolean DEBUG_PAUSE = ActivityManagerService.DEBUG_PAUSE;
83 static final boolean DEBUG_VISBILITY = ActivityManagerService.DEBUG_VISBILITY;
84 static final boolean DEBUG_USER_LEAVING = ActivityManagerService.DEBUG_USER_LEAVING;
85 static final boolean DEBUG_TRANSITION = ActivityManagerService.DEBUG_TRANSITION;
86 static final boolean DEBUG_RESULTS = ActivityManagerService.DEBUG_RESULTS;
87 static final boolean DEBUG_CONFIGURATION = ActivityManagerService.DEBUG_CONFIGURATION;
88 static final boolean DEBUG_TASKS = ActivityManagerService.DEBUG_TASKS;
89
Dianne Hackbornce86ba82011-07-13 19:33:41 -070090 static final boolean DEBUG_STATES = false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070091 static final boolean DEBUG_ADD_REMOVE = false;
92 static final boolean DEBUG_SAVED_STATE = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070093
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070094 static final boolean VALIDATE_TOKENS = ActivityManagerService.VALIDATE_TOKENS;
95
96 // How long we wait until giving up on the last activity telling us it
97 // is idle.
98 static final int IDLE_TIMEOUT = 10*1000;
99
100 // How long we wait until giving up on the last activity to pause. This
101 // is short because it directly impacts the responsiveness of starting the
102 // next activity.
103 static final int PAUSE_TIMEOUT = 500;
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 Hackborn50dc3bc2010-06-25 10:05:59 -0700287
288 final Handler mHandler = new Handler() {
289 //public Handler() {
290 // if (localLOGV) Slog.v(TAG, "Handler started!");
291 //}
292
293 public void handleMessage(Message msg) {
294 switch (msg.what) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800295 case SLEEP_TIMEOUT_MSG: {
Dianne Hackborn8e8d65f2011-08-11 19:36:18 -0700296 synchronized (mService) {
297 if (mService.isSleeping()) {
298 Slog.w(TAG, "Sleep timeout! Sleeping now.");
299 mSleepTimeout = true;
300 checkReadyForSleepLocked();
301 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800302 }
303 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700304 case PAUSE_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800305 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700306 // We don't at this point know if the activity is fullscreen,
307 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800308 Slog.w(TAG, "Activity pause timeout for " + r);
309 activityPaused(r != null ? r.appToken : null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700310 } break;
311 case IDLE_TIMEOUT_MSG: {
312 if (mService.mDidDexOpt) {
313 mService.mDidDexOpt = false;
314 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
315 nmsg.obj = msg.obj;
316 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
317 return;
318 }
319 // We don't at this point know if the activity is fullscreen,
320 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800321 ActivityRecord r = (ActivityRecord)msg.obj;
322 Slog.w(TAG, "Activity idle timeout for " + r);
323 activityIdleInternal(r != null ? r.appToken : null, true, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700324 } break;
325 case DESTROY_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800326 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700327 // We don't at this point know if the activity is fullscreen,
328 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800329 Slog.w(TAG, "Activity destroy timeout for " + r);
330 activityDestroyed(r != null ? r.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700331 } break;
332 case IDLE_NOW_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800333 ActivityRecord r = (ActivityRecord)msg.obj;
334 activityIdleInternal(r != null ? r.appToken : null, false, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700335 } break;
336 case LAUNCH_TIMEOUT_MSG: {
337 if (mService.mDidDexOpt) {
338 mService.mDidDexOpt = false;
339 Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
340 mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
341 return;
342 }
343 synchronized (mService) {
344 if (mLaunchingActivity.isHeld()) {
345 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
346 mLaunchingActivity.release();
347 }
348 }
349 } break;
350 case RESUME_TOP_ACTIVITY_MSG: {
351 synchronized (mService) {
352 resumeTopActivityLocked(null);
353 }
354 } break;
355 }
356 }
357 };
358
359 ActivityStack(ActivityManagerService service, Context context, boolean mainStack) {
360 mService = service;
361 mContext = context;
362 mMainStack = mainStack;
363 PowerManager pm =
364 (PowerManager)context.getSystemService(Context.POWER_SERVICE);
365 mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
366 mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
367 mLaunchingActivity.setReferenceCounted(false);
368 }
369
370 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700371 // TODO: Don't look for any tasks from other users
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700372 int i = mHistory.size()-1;
373 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700374 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700375 if (!r.finishing && r != notTop) {
376 return r;
377 }
378 i--;
379 }
380 return null;
381 }
382
383 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700384 // TODO: Don't look for any tasks from other users
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700385 int i = mHistory.size()-1;
386 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700387 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700388 if (!r.finishing && !r.delayedResume && r != notTop) {
389 return r;
390 }
391 i--;
392 }
393 return null;
394 }
395
396 /**
397 * This is a simplified version of topRunningActivityLocked that provides a number of
398 * optional skip-over modes. It is intended for use with the ActivityController hook only.
399 *
400 * @param token If non-null, any history records matching this token will be skipped.
401 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
402 *
403 * @return Returns the HistoryRecord of the next activity on the stack.
404 */
405 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700406 // TODO: Don't look for any tasks from other users
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700407 int i = mHistory.size()-1;
408 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700409 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700410 // Note: the taskId check depends on real taskId fields being non-zero
Dianne Hackbornbe707852011-11-11 14:32:10 -0800411 if (!r.finishing && (token != r.appToken) && (taskId != r.task.taskId)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700412 return r;
413 }
414 i--;
415 }
416 return null;
417 }
418
419 final int indexOfTokenLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800420 return mHistory.indexOf(ActivityRecord.forToken(token));
421 }
422
423 final int indexOfActivityLocked(ActivityRecord r) {
424 return mHistory.indexOf(r);
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700425 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700426
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700427 final ActivityRecord isInStackLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800428 ActivityRecord r = ActivityRecord.forToken(token);
429 if (mHistory.contains(r)) {
430 return r;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700431 }
432 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700433 }
434
435 private final boolean updateLRUListLocked(ActivityRecord r) {
436 final boolean hadit = mLRUActivities.remove(r);
437 mLRUActivities.add(r);
438 return hadit;
439 }
440
441 /**
442 * Returns the top activity in any existing task matching the given
443 * Intent. Returns null if no such task is found.
444 */
445 private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
446 ComponentName cls = intent.getComponent();
447 if (info.targetActivity != null) {
448 cls = new ComponentName(info.packageName, info.targetActivity);
449 }
450
451 TaskRecord cp = null;
452
Amith Yamasani742a6712011-05-04 14:49:28 -0700453 final int userId = UserId.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700454 final int N = mHistory.size();
455 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700456 ActivityRecord r = mHistory.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -0700457 if (!r.finishing && r.task != cp && r.userId == userId
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700458 && r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
459 cp = r.task;
460 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
461 // + "/aff=" + r.task.affinity + " to new cls="
462 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
463 if (r.task.affinity != null) {
464 if (r.task.affinity.equals(info.taskAffinity)) {
465 //Slog.i(TAG, "Found matching affinity!");
466 return r;
467 }
468 } else if (r.task.intent != null
469 && r.task.intent.getComponent().equals(cls)) {
470 //Slog.i(TAG, "Found matching class!");
471 //dump();
472 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
473 return r;
474 } else if (r.task.affinityIntent != null
475 && r.task.affinityIntent.getComponent().equals(cls)) {
476 //Slog.i(TAG, "Found matching class!");
477 //dump();
478 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
479 return r;
480 }
481 }
482 }
483
484 return null;
485 }
486
487 /**
488 * Returns the first activity (starting from the top of the stack) that
489 * is the same as the given activity. Returns null if no such activity
490 * is found.
491 */
492 private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
493 ComponentName cls = intent.getComponent();
494 if (info.targetActivity != null) {
495 cls = new ComponentName(info.packageName, info.targetActivity);
496 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700497 final int userId = UserId.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700498
499 final int N = mHistory.size();
500 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700501 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700502 if (!r.finishing) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700503 if (r.intent.getComponent().equals(cls) && r.userId == userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700504 //Slog.i(TAG, "Found matching class!");
505 //dump();
506 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
507 return r;
508 }
509 }
510 }
511
512 return null;
513 }
514
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700515 final void showAskCompatModeDialogLocked(ActivityRecord r) {
516 Message msg = Message.obtain();
517 msg.what = ActivityManagerService.SHOW_COMPAT_MODE_DIALOG_MSG;
518 msg.obj = r.task.askedCompatMode ? null : r;
519 mService.mHandler.sendMessage(msg);
520 }
521
Amith Yamasani742a6712011-05-04 14:49:28 -0700522 /*
523 * Move the activities around in the stack to bring a user to the foreground.
524 * @return whether there are any activities for the specified user.
525 */
526 final boolean switchUser(int userId) {
527 synchronized (mService) {
528 mCurrentUser = userId;
529
530 // Only one activity? Nothing to do...
531 if (mHistory.size() < 2)
532 return false;
533
534 boolean haveActivities = false;
535 // Check if the top activity is from the new user.
536 ActivityRecord top = mHistory.get(mHistory.size() - 1);
537 if (top.userId == userId) return true;
538 // Otherwise, move the user's activities to the top.
539 int N = mHistory.size();
540 int i = 0;
541 while (i < N) {
542 ActivityRecord r = mHistory.get(i);
543 if (r.userId == userId) {
544 ActivityRecord moveToTop = mHistory.remove(i);
545 mHistory.add(moveToTop);
546 // No need to check the top one now
547 N--;
548 haveActivities = true;
549 } else {
550 i++;
551 }
552 }
553 // Transition from the old top to the new top
554 resumeTopActivityLocked(top);
555 return haveActivities;
556 }
557 }
558
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700559 final boolean realStartActivityLocked(ActivityRecord r,
560 ProcessRecord app, boolean andResume, boolean checkConfig)
561 throws RemoteException {
562
563 r.startFreezingScreenLocked(app, 0);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800564 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700565
566 // Have the window manager re-evaluate the orientation of
567 // the screen based on the new activity order. Note that
568 // as a result of this, it can call back into the activity
569 // manager with a new orientation. We don't care about that,
570 // because the activity is not currently running so we are
571 // just restarting it anyway.
572 if (checkConfig) {
573 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
574 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -0800575 r.mayFreezeScreenLocked(app) ? r.appToken : null);
Dianne Hackborn813075a62011-11-14 17:45:19 -0800576 mService.updateConfigurationLocked(config, r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700577 }
578
579 r.app = app;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700580 app.waitingToKill = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700581
582 if (localLOGV) Slog.v(TAG, "Launching: " + r);
583
584 int idx = app.activities.indexOf(r);
585 if (idx < 0) {
586 app.activities.add(r);
587 }
588 mService.updateLruProcessLocked(app, true, true);
589
590 try {
591 if (app.thread == null) {
592 throw new RemoteException();
593 }
594 List<ResultInfo> results = null;
595 List<Intent> newIntents = null;
596 if (andResume) {
597 results = r.results;
598 newIntents = r.newIntents;
599 }
600 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
601 + " icicle=" + r.icicle
602 + " with results=" + results + " newIntents=" + newIntents
603 + " andResume=" + andResume);
604 if (andResume) {
605 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
606 System.identityHashCode(r),
607 r.task.taskId, r.shortComponentName);
608 }
609 if (r.isHomeActivity) {
610 mService.mHomeProcess = app;
611 }
612 mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800613 r.sleeping = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400614 r.forceNewConfig = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700615 showAskCompatModeDialogLocked(r);
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700616 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700617 String profileFile = null;
618 ParcelFileDescriptor profileFd = null;
619 boolean profileAutoStop = false;
620 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
621 if (mService.mProfileProc == null || mService.mProfileProc == app) {
622 mService.mProfileProc = app;
623 profileFile = mService.mProfileFile;
624 profileFd = mService.mProfileFd;
625 profileAutoStop = mService.mAutoStopProfiler;
626 }
627 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -0700628 app.hasShownUi = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700629 app.pendingUiClean = true;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700630 if (profileFd != null) {
631 try {
632 profileFd = profileFd.dup();
633 } catch (IOException e) {
634 profileFd = null;
635 }
636 }
Dianne Hackbornbe707852011-11-11 14:32:10 -0800637 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
Dianne Hackborn813075a62011-11-14 17:45:19 -0800638 System.identityHashCode(r), r.info,
639 new Configuration(mService.mConfiguration),
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700640 r.compat, r.icicle, results, newIntents, !andResume,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700641 mService.isNextTransitionForward(), profileFile, profileFd,
642 profileAutoStop);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700643
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700644 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700645 // This may be a heavy-weight process! Note that the package
646 // manager will ensure that only activity can run in the main
647 // process of the .apk, which is the only thing that will be
648 // considered heavy-weight.
649 if (app.processName.equals(app.info.packageName)) {
650 if (mService.mHeavyWeightProcess != null
651 && mService.mHeavyWeightProcess != app) {
652 Log.w(TAG, "Starting new heavy weight process " + app
653 + " when already running "
654 + mService.mHeavyWeightProcess);
655 }
656 mService.mHeavyWeightProcess = app;
657 Message msg = mService.mHandler.obtainMessage(
658 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
659 msg.obj = r;
660 mService.mHandler.sendMessage(msg);
661 }
662 }
663
664 } catch (RemoteException e) {
665 if (r.launchFailed) {
666 // This is the second time we failed -- finish activity
667 // and give up.
668 Slog.e(TAG, "Second failure launching "
669 + r.intent.getComponent().flattenToShortString()
670 + ", giving up", e);
671 mService.appDiedLocked(app, app.pid, app.thread);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800672 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700673 "2nd-crash");
674 return false;
675 }
676
677 // This is the first time we failed -- restart process and
678 // retry.
679 app.activities.remove(r);
680 throw e;
681 }
682
683 r.launchFailed = false;
684 if (updateLRUListLocked(r)) {
685 Slog.w(TAG, "Activity " + r
686 + " being launched, but already in LRU list");
687 }
688
689 if (andResume) {
690 // As part of the process of launching, ActivityThread also performs
691 // a resume.
692 r.state = ActivityState.RESUMED;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700693 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
694 + " (starting new instance)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700695 r.stopped = false;
696 mResumedActivity = r;
697 r.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -0800698 if (mMainStack) {
699 mService.addRecentTaskLocked(r.task);
700 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700701 completeResumeLocked(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800702 checkReadyForSleepLocked();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700703 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Launch completed; removing icicle of " + r.icicle);
704 r.icicle = null;
705 r.haveState = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700706 } else {
707 // This activity is not starting in the resumed state... which
708 // should look like we asked it to pause+stop (but remain visible),
709 // and it has done so and reported back the current icicle and
710 // other state.
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700711 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
712 + " (starting in stopped state)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700713 r.state = ActivityState.STOPPED;
714 r.stopped = true;
715 }
716
717 // Launch the new version setup screen if needed. We do this -after-
718 // launching the initial activity (that is, home), so that it can have
719 // a chance to initialize itself while in the background, making the
720 // switch back to it faster and look better.
721 if (mMainStack) {
722 mService.startSetupActivityLocked();
723 }
724
725 return true;
726 }
727
728 private final void startSpecificActivityLocked(ActivityRecord r,
729 boolean andResume, boolean checkConfig) {
730 // Is this activity's application already running?
731 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
732 r.info.applicationInfo.uid);
733
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700734 if (r.launchTime == 0) {
735 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700736 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700737 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700738 }
739 } else if (mInitialStartTime == 0) {
740 mInitialStartTime = SystemClock.uptimeMillis();
741 }
742
743 if (app != null && app.thread != null) {
744 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700745 app.addPackage(r.info.packageName);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700746 realStartActivityLocked(r, app, andResume, checkConfig);
747 return;
748 } catch (RemoteException e) {
749 Slog.w(TAG, "Exception when starting activity "
750 + r.intent.getComponent().flattenToShortString(), e);
751 }
752
753 // If a dead object exception was thrown -- fall through to
754 // restart the application.
755 }
756
757 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800758 "activity", r.intent.getComponent(), false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700759 }
760
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800761 void stopIfSleepingLocked() {
762 if (mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700763 if (!mGoingToSleep.isHeld()) {
764 mGoingToSleep.acquire();
765 if (mLaunchingActivity.isHeld()) {
766 mLaunchingActivity.release();
767 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
768 }
769 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800770 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
771 Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
772 mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
773 checkReadyForSleepLocked();
774 }
775 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700776
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800777 void awakeFromSleepingLocked() {
778 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
779 mSleepTimeout = false;
780 if (mGoingToSleep.isHeld()) {
781 mGoingToSleep.release();
782 }
783 // Ensure activities are no longer sleeping.
784 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700785 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800786 r.setSleeping(false);
787 }
788 mGoingToSleepActivities.clear();
789 }
790
791 void activitySleptLocked(ActivityRecord r) {
792 mGoingToSleepActivities.remove(r);
793 checkReadyForSleepLocked();
794 }
795
796 void checkReadyForSleepLocked() {
797 if (!mService.isSleeping()) {
798 // Do not care.
799 return;
800 }
801
802 if (!mSleepTimeout) {
803 if (mResumedActivity != null) {
804 // Still have something resumed; can't sleep until it is paused.
805 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700806 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
807 startPausingLocked(false, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800808 return;
809 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800810 if (mPausingActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800811 // Still waiting for something to pause; can't sleep yet.
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800812 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800813 return;
814 }
815
816 if (mStoppingActivities.size() > 0) {
817 // Still need to tell some activities to stop; can't sleep yet.
818 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
819 + mStoppingActivities.size() + " activities");
Dianne Hackborn80a7ac12011-09-22 18:32:52 -0700820 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800821 return;
822 }
823
824 ensureActivitiesVisibleLocked(null, 0);
825
826 // Make sure any stopped but visible activities are now sleeping.
827 // This ensures that the activity's onStop() is called.
828 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700829 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800830 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
831 r.setSleeping(true);
832 }
833 }
834
835 if (mGoingToSleepActivities.size() > 0) {
836 // Still need to tell some activities to sleep; can't sleep yet.
837 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
838 + mGoingToSleepActivities.size() + " activities");
839 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700840 }
841 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800842
843 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
844
845 if (mGoingToSleep.isHeld()) {
846 mGoingToSleep.release();
847 }
848 if (mService.mShuttingDown) {
849 mService.notifyAll();
850 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700851 }
852
Dianne Hackbornd2835932010-12-13 16:28:46 -0800853 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -0800854 if (who.noDisplay) {
855 return null;
856 }
857
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800858 Resources res = mService.mContext.getResources();
859 int w = mThumbnailWidth;
860 int h = mThumbnailHeight;
861 if (w < 0) {
862 mThumbnailWidth = w =
863 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
864 mThumbnailHeight = h =
865 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
866 }
867
868 if (w > 0) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800869 return mService.mWindowManager.screenshotApplications(who.appToken, w, h);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800870 }
871 return null;
872 }
873
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700874 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800875 if (mPausingActivity != null) {
876 RuntimeException e = new RuntimeException();
877 Slog.e(TAG, "Trying to pause when pause is already pending for "
878 + mPausingActivity, e);
879 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700880 ActivityRecord prev = mResumedActivity;
881 if (prev == null) {
882 RuntimeException e = new RuntimeException();
883 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
884 resumeTopActivityLocked(null);
885 return;
886 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700887 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
888 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700889 mResumedActivity = null;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800890 mPausingActivity = prev;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700891 mLastPausedActivity = prev;
892 prev.state = ActivityState.PAUSING;
893 prev.task.touchActiveTime();
Dianne Hackbornf26fd992011-04-08 18:14:09 -0700894 prev.updateThumbnail(screenshotActivities(prev), null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700895
896 mService.updateCpuStats();
897
898 if (prev.app != null && prev.app.thread != null) {
899 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
900 try {
901 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
902 System.identityHashCode(prev),
903 prev.shortComponentName);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800904 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
905 userLeaving, prev.configChangeFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700906 if (mMainStack) {
907 mService.updateUsageStats(prev, false);
908 }
909 } catch (Exception e) {
910 // Ignore exception, if process died other code will cleanup.
911 Slog.w(TAG, "Exception thrown during pause", e);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800912 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700913 mLastPausedActivity = null;
914 }
915 } else {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800916 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700917 mLastPausedActivity = null;
918 }
919
920 // If we are not going to sleep, we want to ensure the device is
921 // awake until the next activity is started.
922 if (!mService.mSleeping && !mService.mShuttingDown) {
923 mLaunchingActivity.acquire();
924 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
925 // To be safe, don't allow the wake lock to be held for too long.
926 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
927 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
928 }
929 }
930
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800931
932 if (mPausingActivity != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700933 // Have the window manager pause its key dispatching until the new
934 // activity has started. If we're pausing the activity just because
935 // the screen is being turned off and the UI is sleeping, don't interrupt
936 // key dispatch; the same activity will pick it up again on wakeup.
937 if (!uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800938 prev.pauseKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700939 } else {
940 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
941 }
942
943 // Schedule a pause timeout in case the app doesn't respond.
944 // We don't give it much time because this directly impacts the
945 // responsiveness seen by the user.
946 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
947 msg.obj = prev;
948 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
949 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
950 } else {
951 // This activity failed to schedule the
952 // pause, so just treat it as being paused now.
953 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800954 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700955 }
956 }
957
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800958 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700959 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800960 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700961
962 ActivityRecord r = null;
963
964 synchronized (mService) {
965 int index = indexOfTokenLocked(token);
966 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700967 r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700968 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800969 if (mPausingActivity == r) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700970 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
971 + (timeout ? " (due to timeout)" : " (pause complete)"));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700972 r.state = ActivityState.PAUSED;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800973 completePauseLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700974 } else {
975 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
976 System.identityHashCode(r), r.shortComponentName,
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800977 mPausingActivity != null
978 ? mPausingActivity.shortComponentName : "(none)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700979 }
980 }
981 }
982 }
983
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700984 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
985 CharSequence description) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700986 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Saving icicle of " + r + ": " + icicle);
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700987 r.icicle = icicle;
988 r.haveState = true;
989 r.updateThumbnail(thumbnail, description);
990 r.stopped = true;
991 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
992 r.state = ActivityState.STOPPED;
993 if (!r.finishing) {
994 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -0700995 destroyActivityLocked(r, true, false, "stop-config");
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700996 resumeTopActivityLocked(null);
Dianne Hackborn50685602011-12-01 12:23:37 -0800997 } else {
998 // Now that this process has stopped, we may want to consider
999 // it to be the previous app to try to keep around in case
1000 // the user wants to return to it.
1001 ProcessRecord fgApp = null;
1002 if (mResumedActivity != null) {
1003 fgApp = mResumedActivity.app;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001004 } else if (mPausingActivity != null) {
1005 fgApp = mPausingActivity.app;
Dianne Hackborn50685602011-12-01 12:23:37 -08001006 }
1007 if (r.app != null && fgApp != null && r.app != fgApp
1008 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
1009 && r.app != mService.mHomeProcess) {
1010 mService.mPreviousProcess = r.app;
1011 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
1012 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001013 }
1014 }
1015 }
1016
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001017 private final void completePauseLocked() {
1018 ActivityRecord prev = mPausingActivity;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001019 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
1020
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001021 if (prev != null) {
1022 if (prev.finishing) {
1023 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
1024 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE);
1025 } else if (prev.app != null) {
1026 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
1027 if (prev.waitingVisible) {
1028 prev.waitingVisible = false;
1029 mWaitingVisibleActivities.remove(prev);
1030 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
1031 TAG, "Complete pause, no longer waiting: " + prev);
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001032 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001033 if (prev.configDestroy) {
1034 // The previous is being paused because the configuration
1035 // is changing, which means it is actually stopping...
1036 // To juggle the fact that we are also starting a new
1037 // instance right now, we need to first completely stop
1038 // the current instance before starting the new one.
1039 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
1040 destroyActivityLocked(prev, true, false, "pause-config");
1041 } else {
1042 mStoppingActivities.add(prev);
1043 if (mStoppingActivities.size() > 3) {
1044 // If we already have a few activities waiting to stop,
1045 // then give up on things going idle and start clearing
1046 // them out.
1047 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
1048 scheduleIdleLocked();
1049 } else {
1050 checkReadyForSleepLocked();
1051 }
1052 }
1053 } else {
1054 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
1055 prev = null;
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001056 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001057 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001058 }
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001059
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001060 if (!mService.isSleeping()) {
1061 resumeTopActivityLocked(prev);
1062 } else {
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001063 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001064 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001065
1066 if (prev != null) {
1067 prev.resumeKeyDispatchingLocked();
1068 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001069
1070 if (prev.app != null && prev.cpuTimeAtResume > 0
1071 && mService.mBatteryStatsService.isOnBattery()) {
1072 long diff = 0;
1073 synchronized (mService.mProcessStatsThread) {
1074 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
1075 - prev.cpuTimeAtResume;
1076 }
1077 if (diff > 0) {
1078 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
1079 synchronized (bsi) {
1080 BatteryStatsImpl.Uid.Proc ps =
1081 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
1082 prev.info.packageName);
1083 if (ps != null) {
1084 ps.addForegroundTimeLocked(diff);
1085 }
1086 }
1087 }
1088 }
1089 prev.cpuTimeAtResume = 0; // reset it
1090 }
1091
1092 /**
1093 * Once we know that we have asked an application to put an activity in
1094 * the resumed state (either by launching it or explicitly telling it),
1095 * this function updates the rest of our state to match that fact.
1096 */
1097 private final void completeResumeLocked(ActivityRecord next) {
1098 next.idle = false;
1099 next.results = null;
1100 next.newIntents = null;
1101
1102 // schedule an idle timeout in case the app doesn't do it for us.
1103 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1104 msg.obj = next;
1105 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
1106
1107 if (false) {
1108 // The activity was never told to pause, so just keep
1109 // things going as-is. To maintain our own state,
1110 // we need to emulate it coming back and saying it is
1111 // idle.
1112 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
1113 msg.obj = next;
1114 mHandler.sendMessage(msg);
1115 }
1116
1117 if (mMainStack) {
1118 mService.reportResumedActivityLocked(next);
1119 }
1120
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001121 next.clearThumbnail();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001122 if (mMainStack) {
1123 mService.setFocusedActivityLocked(next);
1124 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001125 next.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001126 ensureActivitiesVisibleLocked(null, 0);
1127 mService.mWindowManager.executeAppTransition();
1128 mNoAnimActivities.clear();
1129
1130 // Mark the point when the activity is resuming
1131 // TODO: To be more accurate, the mark should be before the onCreate,
1132 // not after the onResume. But for subsequent starts, onResume is fine.
1133 if (next.app != null) {
1134 synchronized (mService.mProcessStatsThread) {
1135 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1136 }
1137 } else {
1138 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1139 }
1140 }
1141
1142 /**
1143 * Make sure that all activities that need to be visible (that is, they
1144 * currently can be seen by the user) actually are.
1145 */
1146 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1147 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1148 if (DEBUG_VISBILITY) Slog.v(
1149 TAG, "ensureActivitiesVisible behind " + top
1150 + " configChanges=0x" + Integer.toHexString(configChanges));
1151
1152 // If the top activity is not fullscreen, then we need to
1153 // make sure any activities under it are now visible.
1154 final int count = mHistory.size();
1155 int i = count-1;
1156 while (mHistory.get(i) != top) {
1157 i--;
1158 }
1159 ActivityRecord r;
1160 boolean behindFullscreen = false;
1161 for (; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001162 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001163 if (DEBUG_VISBILITY) Slog.v(
1164 TAG, "Make visible? " + r + " finishing=" + r.finishing
1165 + " state=" + r.state);
1166 if (r.finishing) {
1167 continue;
1168 }
1169
1170 final boolean doThisProcess = onlyThisProcess == null
1171 || onlyThisProcess.equals(r.processName);
1172
1173 // First: if this is not the current activity being started, make
1174 // sure it matches the current configuration.
1175 if (r != starting && doThisProcess) {
1176 ensureActivityConfigurationLocked(r, 0);
1177 }
1178
1179 if (r.app == null || r.app.thread == null) {
1180 if (onlyThisProcess == null
1181 || onlyThisProcess.equals(r.processName)) {
1182 // This activity needs to be visible, but isn't even
1183 // running... get it started, but don't resume it
1184 // at this point.
1185 if (DEBUG_VISBILITY) Slog.v(
1186 TAG, "Start and freeze screen for " + r);
1187 if (r != starting) {
1188 r.startFreezingScreenLocked(r.app, configChanges);
1189 }
1190 if (!r.visible) {
1191 if (DEBUG_VISBILITY) Slog.v(
1192 TAG, "Starting and making visible: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001193 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001194 }
1195 if (r != starting) {
1196 startSpecificActivityLocked(r, false, false);
1197 }
1198 }
1199
1200 } else if (r.visible) {
1201 // If this activity is already visible, then there is nothing
1202 // else to do here.
1203 if (DEBUG_VISBILITY) Slog.v(
1204 TAG, "Skipping: already visible at " + r);
1205 r.stopFreezingScreenLocked(false);
1206
1207 } else if (onlyThisProcess == null) {
1208 // This activity is not currently visible, but is running.
1209 // Tell it to become visible.
1210 r.visible = true;
1211 if (r.state != ActivityState.RESUMED && r != starting) {
1212 // If this activity is paused, tell it
1213 // to now show its window.
1214 if (DEBUG_VISBILITY) Slog.v(
1215 TAG, "Making visible and scheduling visibility: " + r);
1216 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001217 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001218 r.sleeping = false;
Dianne Hackborn905577f2011-09-07 18:31:28 -07001219 r.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001220 r.app.thread.scheduleWindowVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001221 r.stopFreezingScreenLocked(false);
1222 } catch (Exception e) {
1223 // Just skip on any failure; we'll make it
1224 // visible when it next restarts.
1225 Slog.w(TAG, "Exception thrown making visibile: "
1226 + r.intent.getComponent(), e);
1227 }
1228 }
1229 }
1230
1231 // Aggregate current change flags.
1232 configChanges |= r.configChangeFlags;
1233
1234 if (r.fullscreen) {
1235 // At this point, nothing else needs to be shown
1236 if (DEBUG_VISBILITY) Slog.v(
1237 TAG, "Stopping: fullscreen at " + r);
1238 behindFullscreen = true;
1239 i--;
1240 break;
1241 }
1242 }
1243
1244 // Now for any activities that aren't visible to the user, make
1245 // sure they no longer are keeping the screen frozen.
1246 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001247 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001248 if (DEBUG_VISBILITY) Slog.v(
1249 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1250 + " state=" + r.state
1251 + " behindFullscreen=" + behindFullscreen);
1252 if (!r.finishing) {
1253 if (behindFullscreen) {
1254 if (r.visible) {
1255 if (DEBUG_VISBILITY) Slog.v(
1256 TAG, "Making invisible: " + r);
1257 r.visible = false;
1258 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001259 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001260 if ((r.state == ActivityState.STOPPING
1261 || r.state == ActivityState.STOPPED)
1262 && r.app != null && r.app.thread != null) {
1263 if (DEBUG_VISBILITY) Slog.v(
1264 TAG, "Scheduling invisibility: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001265 r.app.thread.scheduleWindowVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001266 }
1267 } catch (Exception e) {
1268 // Just skip on any failure; we'll make it
1269 // visible when it next restarts.
1270 Slog.w(TAG, "Exception thrown making hidden: "
1271 + r.intent.getComponent(), e);
1272 }
1273 } else {
1274 if (DEBUG_VISBILITY) Slog.v(
1275 TAG, "Already invisible: " + r);
1276 }
1277 } else if (r.fullscreen) {
1278 if (DEBUG_VISBILITY) Slog.v(
1279 TAG, "Now behindFullscreen: " + r);
1280 behindFullscreen = true;
1281 }
1282 }
1283 i--;
1284 }
1285 }
1286
1287 /**
1288 * Version of ensureActivitiesVisible that can easily be called anywhere.
1289 */
1290 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1291 int configChanges) {
1292 ActivityRecord r = topRunningActivityLocked(null);
1293 if (r != null) {
1294 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1295 }
1296 }
1297
1298 /**
1299 * Ensure that the top activity in the stack is resumed.
1300 *
1301 * @param prev The previously resumed activity, for when in the process
1302 * of pausing; can be null to call from elsewhere.
1303 *
1304 * @return Returns true if something is being resumed, or false if
1305 * nothing happened.
1306 */
1307 final boolean resumeTopActivityLocked(ActivityRecord prev) {
1308 // Find the first activity that is not finishing.
1309 ActivityRecord next = topRunningActivityLocked(null);
1310
1311 // Remember how we'll process this pause/resume situation, and ensure
1312 // that the state is reset however we wind up proceeding.
1313 final boolean userLeaving = mUserLeaving;
1314 mUserLeaving = false;
1315
1316 if (next == null) {
1317 // There are no more activities! Let's just start up the
1318 // Launcher...
1319 if (mMainStack) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001320 return mService.startHomeActivityLocked(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001321 }
1322 }
1323
1324 next.delayedResume = false;
1325
1326 // If the top activity is the resumed one, nothing to do.
1327 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1328 // Make sure we have executed any pending transitions, since there
1329 // should be nothing left to do at this point.
1330 mService.mWindowManager.executeAppTransition();
1331 mNoAnimActivities.clear();
1332 return false;
1333 }
1334
1335 // If we are sleeping, and there is no resumed activity, and the top
1336 // activity is paused, well that is the state we want.
1337 if ((mService.mSleeping || mService.mShuttingDown)
1338 && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
1339 // Make sure we have executed any pending transitions, since there
1340 // should be nothing left to do at this point.
1341 mService.mWindowManager.executeAppTransition();
1342 mNoAnimActivities.clear();
1343 return false;
1344 }
1345
1346 // The activity may be waiting for stop, but that is no longer
1347 // appropriate for it.
1348 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001349 mGoingToSleepActivities.remove(next);
1350 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001351 mWaitingVisibleActivities.remove(next);
1352
1353 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1354
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001355 // If we are currently pausing an activity, then don't do anything
1356 // until that is done.
1357 if (mPausingActivity != null) {
1358 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
1359 return false;
1360 }
1361
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001362 // Okay we are now going to start a switch, to 'next'. We may first
1363 // have to pause the current activity, but this is an important point
1364 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001365 // XXX "App Redirected" dialog is getting too many false positives
1366 // at this point, so turn off for now.
1367 if (false) {
1368 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1369 long now = SystemClock.uptimeMillis();
1370 final boolean inTime = mLastStartedActivity.startTime != 0
1371 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1372 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1373 final int nextUid = next.info.applicationInfo.uid;
1374 if (inTime && lastUid != nextUid
1375 && lastUid != next.launchedFromUid
1376 && mService.checkPermission(
1377 android.Manifest.permission.STOP_APP_SWITCHES,
1378 -1, next.launchedFromUid)
1379 != PackageManager.PERMISSION_GRANTED) {
1380 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1381 } else {
1382 next.startTime = now;
1383 mLastStartedActivity = next;
1384 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001385 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001386 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001387 mLastStartedActivity = next;
1388 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001389 }
1390
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001391 // We need to start pausing the current activity so the top one
1392 // can be resumed...
1393 if (mResumedActivity != null) {
1394 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
1395 startPausingLocked(userLeaving, false);
1396 return true;
1397 }
1398
1399 if (prev != null && prev != next) {
1400 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1401 prev.waitingVisible = true;
1402 mWaitingVisibleActivities.add(prev);
1403 if (DEBUG_SWITCH) Slog.v(
1404 TAG, "Resuming top, waiting visible to hide: " + prev);
1405 } else {
1406 // The next activity is already visible, so hide the previous
1407 // activity's windows right now so we can show the new one ASAP.
1408 // We only do this if the previous is finishing, which should mean
1409 // it is on top of the one being resumed so hiding it quickly
1410 // is good. Otherwise, we want to do the normal route of allowing
1411 // the resumed activity to be shown so we can decide if the
1412 // previous should actually be hidden depending on whether the
1413 // new one is found to be full-screen or not.
1414 if (prev.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001415 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001416 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1417 + prev + ", waitingVisible="
1418 + (prev != null ? prev.waitingVisible : null)
1419 + ", nowVisible=" + next.nowVisible);
1420 } else {
1421 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1422 + prev + ", waitingVisible="
1423 + (prev != null ? prev.waitingVisible : null)
1424 + ", nowVisible=" + next.nowVisible);
1425 }
1426 }
1427 }
1428
Dianne Hackborne7f97212011-02-24 14:40:20 -08001429 // Launching this app's activity, make sure the app is no longer
1430 // considered stopped.
1431 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07001432 // TODO: Apply to the correct userId
Dianne Hackborne7f97212011-02-24 14:40:20 -08001433 AppGlobals.getPackageManager().setPackageStoppedState(
1434 next.packageName, false);
1435 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001436 } catch (IllegalArgumentException e) {
1437 Slog.w(TAG, "Failed trying to unstop package "
1438 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001439 }
1440
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001441 // We are starting up the next activity, so tell the window manager
1442 // that the previous one will be hidden soon. This way it can know
1443 // to ignore it when computing the desired screen orientation.
1444 if (prev != null) {
1445 if (prev.finishing) {
1446 if (DEBUG_TRANSITION) Slog.v(TAG,
1447 "Prepare close transition: prev=" + prev);
1448 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001449 mService.mWindowManager.prepareAppTransition(
1450 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001451 } else {
1452 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1453 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001454 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001455 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001456 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1457 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001458 } else {
1459 if (DEBUG_TRANSITION) Slog.v(TAG,
1460 "Prepare open transition: prev=" + prev);
1461 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001462 mService.mWindowManager.prepareAppTransition(
1463 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001464 } else {
1465 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1466 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001467 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001468 }
1469 }
1470 if (false) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001471 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1472 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001473 }
1474 } else if (mHistory.size() > 1) {
1475 if (DEBUG_TRANSITION) Slog.v(TAG,
1476 "Prepare open transition: no previous");
1477 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001478 mService.mWindowManager.prepareAppTransition(
1479 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001480 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001481 mService.mWindowManager.prepareAppTransition(
1482 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001483 }
1484 }
1485
1486 if (next.app != null && next.app.thread != null) {
1487 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1488
1489 // This activity is now becoming visible.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001490 mService.mWindowManager.setAppVisibility(next.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001491
1492 ActivityRecord lastResumedActivity = mResumedActivity;
1493 ActivityState lastState = next.state;
1494
1495 mService.updateCpuStats();
1496
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001497 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001498 next.state = ActivityState.RESUMED;
1499 mResumedActivity = next;
1500 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001501 if (mMainStack) {
1502 mService.addRecentTaskLocked(next.task);
1503 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001504 mService.updateLruProcessLocked(next.app, true, true);
1505 updateLRUListLocked(next);
1506
1507 // Have the window manager re-evaluate the orientation of
1508 // the screen based on the new activity order.
1509 boolean updated = false;
1510 if (mMainStack) {
1511 synchronized (mService) {
1512 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1513 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001514 next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001515 if (config != null) {
1516 next.frozenBeforeDestroy = true;
1517 }
Dianne Hackborn813075a62011-11-14 17:45:19 -08001518 updated = mService.updateConfigurationLocked(config, next, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001519 }
1520 }
1521 if (!updated) {
1522 // The configuration update wasn't able to keep the existing
1523 // instance of the activity, and instead started a new one.
1524 // We should be all done, but let's just make sure our activity
1525 // is still at the top and schedule another run if something
1526 // weird happened.
1527 ActivityRecord nextNext = topRunningActivityLocked(null);
1528 if (DEBUG_SWITCH) Slog.i(TAG,
1529 "Activity config changed during resume: " + next
1530 + ", new next: " + nextNext);
1531 if (nextNext != next) {
1532 // Do over!
1533 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1534 }
1535 if (mMainStack) {
1536 mService.setFocusedActivityLocked(next);
1537 }
1538 ensureActivitiesVisibleLocked(null, 0);
1539 mService.mWindowManager.executeAppTransition();
1540 mNoAnimActivities.clear();
1541 return true;
1542 }
1543
1544 try {
1545 // Deliver all pending results.
1546 ArrayList a = next.results;
1547 if (a != null) {
1548 final int N = a.size();
1549 if (!next.finishing && N > 0) {
1550 if (DEBUG_RESULTS) Slog.v(
1551 TAG, "Delivering results to " + next
1552 + ": " + a);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001553 next.app.thread.scheduleSendResult(next.appToken, a);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001554 }
1555 }
1556
1557 if (next.newIntents != null) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001558 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001559 }
1560
1561 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
1562 System.identityHashCode(next),
1563 next.task.taskId, next.shortComponentName);
1564
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001565 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001566 showAskCompatModeDialogLocked(next);
Dianne Hackborn905577f2011-09-07 18:31:28 -07001567 next.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001568 next.app.thread.scheduleResumeActivity(next.appToken,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001569 mService.isNextTransitionForward());
1570
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001571 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001572
1573 } catch (Exception e) {
1574 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001575 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1576 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001577 next.state = lastState;
1578 mResumedActivity = lastResumedActivity;
1579 Slog.i(TAG, "Restarting because process died: " + next);
1580 if (!next.hasBeenLaunched) {
1581 next.hasBeenLaunched = true;
1582 } else {
1583 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1584 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001585 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001586 mService.compatibilityInfoForPackageLocked(
1587 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001588 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001589 next.labelRes, next.icon, next.windowFlags,
1590 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001591 }
1592 }
1593 startSpecificActivityLocked(next, true, false);
1594 return true;
1595 }
1596
1597 // From this point on, if something goes wrong there is no way
1598 // to recover the activity.
1599 try {
1600 next.visible = true;
1601 completeResumeLocked(next);
1602 } catch (Exception e) {
1603 // If any exception gets thrown, toss away this
1604 // activity and try the next one.
1605 Slog.w(TAG, "Exception thrown during resume of " + next, e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001606 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001607 "resume-exception");
1608 return true;
1609 }
1610
1611 // Didn't need to use the icicle, and it is now out of date.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001612 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Resumed activity; didn't need icicle of: " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001613 next.icicle = null;
1614 next.haveState = false;
1615 next.stopped = false;
1616
1617 } else {
1618 // Whoops, need to restart this activity!
1619 if (!next.hasBeenLaunched) {
1620 next.hasBeenLaunched = true;
1621 } else {
1622 if (SHOW_APP_STARTING_PREVIEW) {
1623 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001624 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001625 mService.compatibilityInfoForPackageLocked(
1626 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001627 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001628 next.labelRes, next.icon, next.windowFlags,
1629 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001630 }
1631 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1632 }
1633 startSpecificActivityLocked(next, true, true);
1634 }
1635
1636 return true;
1637 }
1638
1639 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001640 boolean doResume, boolean keepCurTransition) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001641 final int NH = mHistory.size();
1642
1643 int addPos = -1;
1644
1645 if (!newTask) {
1646 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001647 boolean startIt = true;
1648 for (int i = NH-1; i >= 0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001649 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001650 if (p.finishing) {
1651 continue;
1652 }
1653 if (p.task == r.task) {
1654 // Here it is! Now, if this is not yet visible to the
1655 // user, then just add it without starting; it will
1656 // get started when the user navigates back to it.
1657 addPos = i+1;
1658 if (!startIt) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001659 if (DEBUG_ADD_REMOVE) {
1660 RuntimeException here = new RuntimeException("here");
1661 here.fillInStackTrace();
1662 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos,
1663 here);
1664 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001665 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001666 r.putInHistory();
Dianne Hackbornbe707852011-11-11 14:32:10 -08001667 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001668 r.info.screenOrientation, r.fullscreen);
1669 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001670 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001671 }
1672 return;
1673 }
1674 break;
1675 }
1676 if (p.fullscreen) {
1677 startIt = false;
1678 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001679 }
1680 }
1681
1682 // Place a new activity at top of stack, so it is next to interact
1683 // with the user.
1684 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001685 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001686 }
1687
1688 // If we are not placing the new activity frontmost, we do not want
1689 // to deliver the onUserLeaving callback to the actual frontmost
1690 // activity
1691 if (addPos < NH) {
1692 mUserLeaving = false;
1693 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1694 }
1695
1696 // Slot the activity into the history stack and proceed
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001697 if (DEBUG_ADD_REMOVE) {
1698 RuntimeException here = new RuntimeException("here");
1699 here.fillInStackTrace();
1700 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos, here);
1701 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001702 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001703 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001704 r.frontOfTask = newTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001705 if (NH > 0) {
1706 // We want to show the starting preview window if we are
1707 // switching to a new task, or the next activity's process is
1708 // not currently running.
1709 boolean showStartingIcon = newTask;
1710 ProcessRecord proc = r.app;
1711 if (proc == null) {
1712 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1713 }
1714 if (proc == null || proc.thread == null) {
1715 showStartingIcon = true;
1716 }
1717 if (DEBUG_TRANSITION) Slog.v(TAG,
1718 "Prepare open transition: starting " + r);
1719 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001720 mService.mWindowManager.prepareAppTransition(
1721 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001722 mNoAnimActivities.add(r);
1723 } else if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
1724 mService.mWindowManager.prepareAppTransition(
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001725 WindowManagerPolicy.TRANSIT_TASK_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001726 mNoAnimActivities.remove(r);
1727 } else {
1728 mService.mWindowManager.prepareAppTransition(newTask
1729 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001730 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001731 mNoAnimActivities.remove(r);
1732 }
1733 mService.mWindowManager.addAppToken(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001734 addPos, r.appToken, r.task.taskId, r.info.screenOrientation, r.fullscreen);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001735 boolean doShow = true;
1736 if (newTask) {
1737 // Even though this activity is starting fresh, we still need
1738 // to reset it to make sure we apply affinities to move any
1739 // existing activities from other tasks in to it.
1740 // If the caller has requested that the target task be
1741 // reset, then do so.
1742 if ((r.intent.getFlags()
1743 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1744 resetTaskIfNeededLocked(r, r);
1745 doShow = topRunningNonDelayedActivityLocked(null) == r;
1746 }
1747 }
1748 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1749 // Figure out if we are transitioning from another activity that is
1750 // "has the same starting icon" as the next one. This allows the
1751 // window manager to keep the previous window it had previously
1752 // created, if it still had one.
1753 ActivityRecord prev = mResumedActivity;
1754 if (prev != null) {
1755 // We don't want to reuse the previous starting preview if:
1756 // (1) The current activity is in a different task.
1757 if (prev.task != r.task) prev = null;
1758 // (2) The current activity is already displayed.
1759 else if (prev.nowVisible) prev = null;
1760 }
1761 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001762 r.appToken, r.packageName, r.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001763 mService.compatibilityInfoForPackageLocked(
1764 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001765 r.labelRes, r.icon, r.windowFlags,
1766 prev != null ? prev.appToken : null, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001767 }
1768 } else {
1769 // If this is the first activity, don't do any fancy animations,
1770 // because there is nothing for it to animate on top of.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001771 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001772 r.info.screenOrientation, r.fullscreen);
1773 }
1774 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001775 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001776 }
1777
1778 if (doResume) {
1779 resumeTopActivityLocked(null);
1780 }
1781 }
1782
Dianne Hackbornbe707852011-11-11 14:32:10 -08001783 final void validateAppTokensLocked() {
1784 mValidateAppTokens.clear();
1785 mValidateAppTokens.ensureCapacity(mHistory.size());
1786 for (int i=0; i<mHistory.size(); i++) {
1787 mValidateAppTokens.add(mHistory.get(i).appToken);
1788 }
1789 mService.mWindowManager.validateAppTokens(mValidateAppTokens);
1790 }
1791
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001792 /**
1793 * Perform a reset of the given task, if needed as part of launching it.
1794 * Returns the new HistoryRecord at the top of the task.
1795 */
1796 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1797 ActivityRecord newActivity) {
1798 boolean forceReset = (newActivity.info.flags
1799 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001800 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1801 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001802 if ((newActivity.info.flags
1803 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1804 forceReset = true;
1805 }
1806 }
1807
1808 final TaskRecord task = taskTop.task;
1809
1810 // We are going to move through the history list so that we can look
1811 // at each activity 'target' with 'below' either the interesting
1812 // activity immediately below it in the stack or null.
1813 ActivityRecord target = null;
1814 int targetI = 0;
1815 int taskTopI = -1;
1816 int replyChainEnd = -1;
1817 int lastReparentPos = -1;
1818 for (int i=mHistory.size()-1; i>=-1; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001819 ActivityRecord below = i >= 0 ? mHistory.get(i) : null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001820
1821 if (below != null && below.finishing) {
1822 continue;
1823 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001824 // Don't check any lower in the stack if we're crossing a user boundary.
1825 if (below != null && below.userId != taskTop.userId) {
1826 break;
1827 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001828 if (target == null) {
1829 target = below;
1830 targetI = i;
1831 // If we were in the middle of a reply chain before this
1832 // task, it doesn't appear like the root of the chain wants
1833 // anything interesting, so drop it.
1834 replyChainEnd = -1;
1835 continue;
1836 }
1837
1838 final int flags = target.info.flags;
1839
1840 final boolean finishOnTaskLaunch =
1841 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1842 final boolean allowTaskReparenting =
1843 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1844
1845 if (target.task == task) {
1846 // We are inside of the task being reset... we'll either
1847 // finish this activity, push it out for another task,
1848 // or leave it as-is. We only do this
1849 // for activities that are not the root of the task (since
1850 // if we finish the root, we may no longer have the task!).
1851 if (taskTopI < 0) {
1852 taskTopI = targetI;
1853 }
1854 if (below != null && below.task == task) {
1855 final boolean clearWhenTaskReset =
1856 (target.intent.getFlags()
1857 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
1858 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
1859 // If this activity is sending a reply to a previous
1860 // activity, we can't do anything with it now until
1861 // we reach the start of the reply chain.
1862 // XXX note that we are assuming the result is always
1863 // to the previous activity, which is almost always
1864 // the case but we really shouldn't count on.
1865 if (replyChainEnd < 0) {
1866 replyChainEnd = targetI;
1867 }
1868 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
1869 && target.taskAffinity != null
1870 && !target.taskAffinity.equals(task.affinity)) {
1871 // If this activity has an affinity for another
1872 // task, then we need to move it out of here. We will
1873 // move it as far out of the way as possible, to the
1874 // bottom of the activity stack. This also keeps it
1875 // correctly ordered with any activities we previously
1876 // moved.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001877 ActivityRecord p = mHistory.get(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001878 if (target.taskAffinity != null
1879 && target.taskAffinity.equals(p.task.affinity)) {
1880 // If the activity currently at the bottom has the
1881 // same task affinity as the one we are moving,
1882 // then merge it into the same task.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001883 target.setTask(p.task, p.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001884 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1885 + " out to bottom task " + p.task);
1886 } else {
1887 mService.mCurTask++;
1888 if (mService.mCurTask <= 0) {
1889 mService.mCurTask = 1;
1890 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001891 target.setTask(new TaskRecord(mService.mCurTask, target.info, null),
1892 null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001893 target.task.affinityIntent = target.intent;
1894 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1895 + " out to new task " + target.task);
1896 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001897 mService.mWindowManager.setAppGroupId(target.appToken, task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001898 if (replyChainEnd < 0) {
1899 replyChainEnd = targetI;
1900 }
1901 int dstPos = 0;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001902 ThumbnailHolder curThumbHolder = target.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001903 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001904 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001905 if (p.finishing) {
1906 continue;
1907 }
1908 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
1909 + " out to target's task " + target.task);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001910 p.setTask(target.task, curThumbHolder, false);
1911 curThumbHolder = p.thumbHolder;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001912 if (DEBUG_ADD_REMOVE) {
1913 RuntimeException here = new RuntimeException("here");
1914 here.fillInStackTrace();
1915 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
1916 + dstPos, here);
1917 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001918 mHistory.remove(srcPos);
1919 mHistory.add(dstPos, p);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001920 mService.mWindowManager.moveAppToken(dstPos, p.appToken);
1921 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001922 dstPos++;
1923 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001924 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001925 }
1926 i++;
1927 }
1928 if (taskTop == p) {
1929 taskTop = below;
1930 }
1931 if (taskTopI == replyChainEnd) {
1932 taskTopI = -1;
1933 }
1934 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001935 } else if (forceReset || finishOnTaskLaunch
1936 || clearWhenTaskReset) {
1937 // If the activity should just be removed -- either
1938 // because it asks for it, or the task should be
1939 // cleared -- then finish it and anything that is
1940 // part of its reply chain.
1941 if (clearWhenTaskReset) {
1942 // In this case, we want to finish this activity
1943 // and everything above it, so be sneaky and pretend
1944 // like these are all in the reply chain.
1945 replyChainEnd = targetI+1;
1946 while (replyChainEnd < mHistory.size() &&
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001947 (mHistory.get(
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001948 replyChainEnd)).task == task) {
1949 replyChainEnd++;
1950 }
1951 replyChainEnd--;
1952 } else if (replyChainEnd < 0) {
1953 replyChainEnd = targetI;
1954 }
1955 ActivityRecord p = null;
1956 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 (finishActivityLocked(p, srcPos,
1962 Activity.RESULT_CANCELED, null, "reset")) {
1963 replyChainEnd--;
1964 srcPos--;
1965 }
1966 }
1967 if (taskTop == p) {
1968 taskTop = below;
1969 }
1970 if (taskTopI == replyChainEnd) {
1971 taskTopI = -1;
1972 }
1973 replyChainEnd = -1;
1974 } else {
1975 // If we were in the middle of a chain, well the
1976 // activity that started it all doesn't want anything
1977 // special, so leave it all as-is.
1978 replyChainEnd = -1;
1979 }
1980 } else {
1981 // Reached the bottom of the task -- any reply chain
1982 // should be left as-is.
1983 replyChainEnd = -1;
1984 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08001985
1986 } else if (target.resultTo != null && (below == null
1987 || below.task == target.task)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001988 // If this activity is sending a reply to a previous
1989 // activity, we can't do anything with it now until
1990 // we reach the start of the reply chain.
1991 // XXX note that we are assuming the result is always
1992 // to the previous activity, which is almost always
1993 // the case but we really shouldn't count on.
1994 if (replyChainEnd < 0) {
1995 replyChainEnd = targetI;
1996 }
1997
1998 } else if (taskTopI >= 0 && allowTaskReparenting
1999 && task.affinity != null
2000 && task.affinity.equals(target.taskAffinity)) {
2001 // We are inside of another task... if this activity has
2002 // an affinity for our task, then either remove it if we are
2003 // clearing or move it over to our task. Note that
2004 // we currently punt on the case where we are resetting a
2005 // task that is not at the top but who has activities above
2006 // with an affinity to it... this is really not a normal
2007 // case, and we will need to later pull that task to the front
2008 // and usually at that point we will do the reset and pick
2009 // up those remaining activities. (This only happens if
2010 // someone starts an activity in a new task from an activity
2011 // in a task that is not currently on top.)
2012 if (forceReset || finishOnTaskLaunch) {
2013 if (replyChainEnd < 0) {
2014 replyChainEnd = targetI;
2015 }
2016 ActivityRecord p = null;
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002017 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index "
2018 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002019 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002020 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002021 if (p.finishing) {
2022 continue;
2023 }
2024 if (finishActivityLocked(p, srcPos,
2025 Activity.RESULT_CANCELED, null, "reset")) {
2026 taskTopI--;
2027 lastReparentPos--;
2028 replyChainEnd--;
2029 srcPos--;
2030 }
2031 }
2032 replyChainEnd = -1;
2033 } else {
2034 if (replyChainEnd < 0) {
2035 replyChainEnd = targetI;
2036 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002037 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting task at index "
2038 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002039 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002040 ActivityRecord p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002041 if (p.finishing) {
2042 continue;
2043 }
2044 if (lastReparentPos < 0) {
2045 lastReparentPos = taskTopI;
2046 taskTop = p;
2047 } else {
2048 lastReparentPos--;
2049 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002050 if (DEBUG_ADD_REMOVE) {
2051 RuntimeException here = new RuntimeException("here");
2052 here.fillInStackTrace();
2053 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2054 + lastReparentPos, here);
2055 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002056 mHistory.remove(srcPos);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002057 p.setTask(task, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002058 mHistory.add(lastReparentPos, p);
2059 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002060 + " from " + srcPos + " to " + lastReparentPos
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002061 + " in to resetting task " + task);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002062 mService.mWindowManager.moveAppToken(lastReparentPos, p.appToken);
2063 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002064 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002065 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002066 }
2067 }
2068 replyChainEnd = -1;
2069
2070 // Now we've moved it in to place... but what if this is
2071 // a singleTop activity and we have put it on top of another
2072 // instance of the same activity? Then we drop the instance
2073 // below so it remains singleTop.
2074 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2075 for (int j=lastReparentPos-1; j>=0; j--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002076 ActivityRecord p = mHistory.get(j);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002077 if (p.finishing) {
2078 continue;
2079 }
2080 if (p.intent.getComponent().equals(target.intent.getComponent())) {
2081 if (finishActivityLocked(p, j,
2082 Activity.RESULT_CANCELED, null, "replace")) {
2083 taskTopI--;
2084 lastReparentPos--;
2085 }
2086 }
2087 }
2088 }
2089 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002090
2091 } else if (below != null && below.task != target.task) {
2092 // We hit the botton of a task; the reply chain can't
2093 // pass through it.
2094 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002095 }
2096
2097 target = below;
2098 targetI = i;
2099 }
2100
2101 return taskTop;
2102 }
2103
2104 /**
2105 * Perform clear operation as requested by
2106 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2107 * stack to the given task, then look for
2108 * an instance of that activity in the stack and, if found, finish all
2109 * activities on top of it and return the instance.
2110 *
2111 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002112 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002113 * or null if none was found.
2114 */
2115 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002116 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002117 int i = mHistory.size();
2118
2119 // First find the requested task.
2120 while (i > 0) {
2121 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002122 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002123 if (r.task.taskId == taskId) {
2124 i++;
2125 break;
2126 }
2127 }
2128
2129 // Now clear it.
2130 while (i > 0) {
2131 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002132 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002133 if (r.finishing) {
2134 continue;
2135 }
2136 if (r.task.taskId != taskId) {
2137 return null;
2138 }
2139 if (r.realActivity.equals(newR.realActivity)) {
2140 // Here it is! Now finish everything in front...
2141 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002142 while (i < (mHistory.size()-1)) {
2143 i++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002144 r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002145 if (r.task.taskId != taskId) {
2146 break;
2147 }
2148 if (r.finishing) {
2149 continue;
2150 }
2151 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2152 null, "clear")) {
2153 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002154 }
2155 }
2156
2157 // Finally, if this is a normal launch mode (that is, not
2158 // expecting onNewIntent()), then we will finish the current
2159 // instance of the activity so a new fresh one can be started.
2160 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2161 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
2162 if (!ret.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002163 int index = indexOfTokenLocked(ret.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002164 if (index >= 0) {
2165 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
2166 null, "clear");
2167 }
2168 return null;
2169 }
2170 }
2171
2172 return ret;
2173 }
2174 }
2175
2176 return null;
2177 }
2178
2179 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002180 * Completely remove all activities associated with an existing
2181 * task starting at a specified index.
2182 */
2183 private final void performClearTaskAtIndexLocked(int taskId, int i) {
Dianne Hackborneabd3282011-10-13 16:26:49 -07002184 while (i < mHistory.size()) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002185 ActivityRecord r = mHistory.get(i);
2186 if (r.task.taskId != taskId) {
2187 // Whoops hit the end.
2188 return;
2189 }
2190 if (r.finishing) {
2191 i++;
2192 continue;
2193 }
2194 if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2195 null, "clear")) {
2196 i++;
2197 }
2198 }
2199 }
2200
2201 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002202 * Completely remove all activities associated with an existing task.
2203 */
2204 private final void performClearTaskLocked(int taskId) {
2205 int i = mHistory.size();
2206
2207 // First find the requested task.
2208 while (i > 0) {
2209 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002210 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002211 if (r.task.taskId == taskId) {
2212 i++;
2213 break;
2214 }
2215 }
2216
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002217 // Now find the start and clear it.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002218 while (i > 0) {
2219 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002220 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002221 if (r.finishing) {
2222 continue;
2223 }
2224 if (r.task.taskId != taskId) {
2225 // We hit the bottom. Now finish it all...
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002226 performClearTaskAtIndexLocked(taskId, i+1);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002227 return;
2228 }
2229 }
2230 }
2231
2232 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002233 * Find the activity in the history stack within the given task. Returns
2234 * the index within the history at which it's found, or < 0 if not found.
2235 */
2236 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2237 int i = mHistory.size();
2238 while (i > 0) {
2239 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002240 ActivityRecord candidate = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002241 if (candidate.task.taskId != task) {
2242 break;
2243 }
2244 if (candidate.realActivity.equals(r.realActivity)) {
2245 return i;
2246 }
2247 }
2248
2249 return -1;
2250 }
2251
2252 /**
2253 * Reorder the history stack so that the activity at the given index is
2254 * brought to the front.
2255 */
2256 private final ActivityRecord moveActivityToFrontLocked(int where) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002257 ActivityRecord newTop = mHistory.remove(where);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002258 int top = mHistory.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002259 ActivityRecord oldTop = mHistory.get(top-1);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002260 if (DEBUG_ADD_REMOVE) {
2261 RuntimeException here = new RuntimeException("here");
2262 here.fillInStackTrace();
2263 Slog.i(TAG, "Removing and adding activity " + newTop + " to stack at "
2264 + top, here);
2265 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002266 mHistory.add(top, newTop);
2267 oldTop.frontOfTask = false;
2268 newTop.frontOfTask = true;
2269 return newTop;
2270 }
2271
2272 final int startActivityLocked(IApplicationThread caller,
2273 Intent intent, String resolvedType,
2274 Uri[] grantedUriPermissions,
2275 int grantedMode, ActivityInfo aInfo, IBinder resultTo,
2276 String resultWho, int requestCode,
2277 int callingPid, int callingUid, boolean onlyIfNeeded,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002278 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002279
2280 int err = START_SUCCESS;
2281
2282 ProcessRecord callerApp = null;
2283 if (caller != null) {
2284 callerApp = mService.getRecordForAppLocked(caller);
2285 if (callerApp != null) {
2286 callingPid = callerApp.pid;
2287 callingUid = callerApp.info.uid;
2288 } else {
2289 Slog.w(TAG, "Unable to find app for caller " + caller
2290 + " (pid=" + callingPid + ") when starting: "
2291 + intent.toString());
2292 err = START_PERMISSION_DENIED;
2293 }
2294 }
2295
2296 if (err == START_SUCCESS) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002297 Slog.i(TAG, "START {" + intent.toShortString(true, true, true) + "} from pid "
Dianne Hackbornefb58102010-10-14 16:47:34 -07002298 + (callerApp != null ? callerApp.pid : callingPid));
2299 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002300
2301 ActivityRecord sourceRecord = null;
2302 ActivityRecord resultRecord = null;
2303 if (resultTo != null) {
2304 int index = indexOfTokenLocked(resultTo);
2305 if (DEBUG_RESULTS) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002306 TAG, "Will send result to " + resultTo + " (index " + index + ")");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002307 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002308 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002309 if (requestCode >= 0 && !sourceRecord.finishing) {
2310 resultRecord = sourceRecord;
2311 }
2312 }
2313 }
2314
2315 int launchFlags = intent.getFlags();
2316
2317 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2318 && sourceRecord != null) {
2319 // Transfer the result target from the source activity to the new
2320 // one being started, including any failures.
2321 if (requestCode >= 0) {
2322 return START_FORWARD_AND_REQUEST_CONFLICT;
2323 }
2324 resultRecord = sourceRecord.resultTo;
2325 resultWho = sourceRecord.resultWho;
2326 requestCode = sourceRecord.requestCode;
2327 sourceRecord.resultTo = null;
2328 if (resultRecord != null) {
2329 resultRecord.removeResultsLocked(
2330 sourceRecord, resultWho, requestCode);
2331 }
2332 }
2333
Dianne Hackbornefb58102010-10-14 16:47:34 -07002334 if (err == START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002335 // We couldn't find a class that can handle the given Intent.
2336 // That's the end of that!
2337 err = START_INTENT_NOT_RESOLVED;
2338 }
2339
2340 if (err == START_SUCCESS && aInfo == null) {
2341 // We couldn't find the specific class specified in the Intent.
2342 // Also the end of the line.
2343 err = START_CLASS_NOT_FOUND;
2344 }
2345
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002346 if (err != START_SUCCESS) {
2347 if (resultRecord != null) {
2348 sendActivityResultLocked(-1,
2349 resultRecord, resultWho, requestCode,
2350 Activity.RESULT_CANCELED, null);
2351 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002352 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002353 return err;
2354 }
2355
2356 final int perm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002357 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002358 if (perm != PackageManager.PERMISSION_GRANTED) {
2359 if (resultRecord != null) {
2360 sendActivityResultLocked(-1,
2361 resultRecord, resultWho, requestCode,
2362 Activity.RESULT_CANCELED, null);
2363 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002364 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002365 String msg;
2366 if (!aInfo.exported) {
2367 msg = "Permission Denial: starting " + intent.toString()
2368 + " from " + callerApp + " (pid=" + callingPid
2369 + ", uid=" + callingUid + ")"
2370 + " not exported from uid " + aInfo.applicationInfo.uid;
2371 } else {
2372 msg = "Permission Denial: starting " + intent.toString()
2373 + " from " + callerApp + " (pid=" + callingPid
2374 + ", uid=" + callingUid + ")"
2375 + " requires " + aInfo.permission;
2376 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002377 Slog.w(TAG, msg);
2378 throw new SecurityException(msg);
2379 }
2380
2381 if (mMainStack) {
2382 if (mService.mController != null) {
2383 boolean abort = false;
2384 try {
2385 // The Intent we give to the watcher has the extra data
2386 // stripped off, since it can contain private information.
2387 Intent watchIntent = intent.cloneFilter();
2388 abort = !mService.mController.activityStarting(watchIntent,
2389 aInfo.applicationInfo.packageName);
2390 } catch (RemoteException e) {
2391 mService.mController = null;
2392 }
2393
2394 if (abort) {
2395 if (resultRecord != null) {
2396 sendActivityResultLocked(-1,
2397 resultRecord, resultWho, requestCode,
2398 Activity.RESULT_CANCELED, null);
2399 }
2400 // We pretend to the caller that it was really started, but
2401 // they will just get a cancel result.
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002402 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002403 return START_SUCCESS;
2404 }
2405 }
2406 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002407
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002408 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2409 intent, resolvedType, aInfo, mService.mConfiguration,
2410 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002411 if (outActivity != null) {
2412 outActivity[0] = r;
2413 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002414
2415 if (mMainStack) {
2416 if (mResumedActivity == null
2417 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2418 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2419 PendingActivityLaunch pal = new PendingActivityLaunch();
2420 pal.r = r;
2421 pal.sourceRecord = sourceRecord;
2422 pal.grantedUriPermissions = grantedUriPermissions;
2423 pal.grantedMode = grantedMode;
2424 pal.onlyIfNeeded = onlyIfNeeded;
2425 mService.mPendingActivityLaunches.add(pal);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002426 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002427 return START_SWITCHES_CANCELED;
2428 }
2429 }
2430
2431 if (mService.mDidAppSwitch) {
2432 // This is the second allowed switch since we stopped switches,
2433 // so now just generally allow switches. Use case: user presses
2434 // home (switches disabled, switch to home, mDidAppSwitch now true);
2435 // user taps a home icon (coming from home so allowed, we hit here
2436 // and now allow anyone to switch again).
2437 mService.mAppSwitchesAllowedTime = 0;
2438 } else {
2439 mService.mDidAppSwitch = true;
2440 }
2441
2442 mService.doPendingActivityLaunchesLocked(false);
2443 }
2444
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002445 err = startActivityUncheckedLocked(r, sourceRecord,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002446 grantedUriPermissions, grantedMode, onlyIfNeeded, true);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002447 if (mDismissKeyguardOnNextActivity && mPausingActivity == null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002448 // Someone asked to have the keyguard dismissed on the next
2449 // activity start, but we are not actually doing an activity
2450 // switch... just dismiss the keyguard now, because we
2451 // probably want to see whatever is behind it.
2452 mDismissKeyguardOnNextActivity = false;
2453 mService.mWindowManager.dismissKeyguard();
2454 }
2455 return err;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002456 }
2457
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002458 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2459 if ((launchFlags &
2460 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2461 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2462 // Caller wants to appear on home activity, so before starting
2463 // their own activity we will bring home to the front.
2464 moveHomeToFrontLocked();
2465 }
2466 }
2467
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002468 final int startActivityUncheckedLocked(ActivityRecord r,
2469 ActivityRecord sourceRecord, Uri[] grantedUriPermissions,
2470 int grantedMode, boolean onlyIfNeeded, boolean doResume) {
2471 final Intent intent = r.intent;
2472 final int callingUid = r.launchedFromUid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002473 final int userId = r.userId;
2474
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002475 int launchFlags = intent.getFlags();
2476
2477 // We'll invoke onUserLeaving before onPause only if the launching
2478 // activity did not explicitly state that this is an automated launch.
2479 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2480 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2481 "startActivity() => mUserLeaving=" + mUserLeaving);
2482
2483 // If the caller has asked not to resume at this point, we make note
2484 // of this in the record so that we can skip it when trying to find
2485 // the top running activity.
2486 if (!doResume) {
2487 r.delayedResume = true;
2488 }
2489
2490 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2491 != 0 ? r : null;
2492
2493 // If the onlyIfNeeded flag is set, then we can do this if the activity
2494 // being launched is the same as the one making the call... or, as
2495 // a special case, if we do not know the caller then we count the
2496 // current top activity as the caller.
2497 if (onlyIfNeeded) {
2498 ActivityRecord checkedCaller = sourceRecord;
2499 if (checkedCaller == null) {
2500 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2501 }
2502 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2503 // Caller is not the same as launcher, so always needed.
2504 onlyIfNeeded = false;
2505 }
2506 }
2507
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002508 if (sourceRecord == null) {
2509 // This activity is not being started from another... in this
2510 // case we -always- start a new task.
2511 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2512 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2513 + intent);
2514 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2515 }
2516 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2517 // The original activity who is starting us is running as a single
2518 // instance... this new activity it is starting must go on its
2519 // own task.
2520 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2521 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2522 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2523 // The activity being started is a single instance... it always
2524 // gets launched into its own task.
2525 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2526 }
2527
2528 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2529 // For whatever reason this activity is being launched into a new
2530 // task... yet the caller has requested a result back. Well, that
2531 // is pretty messed up, so instead immediately send back a cancel
2532 // and let the new task continue launched as normal without a
2533 // dependency on its originator.
2534 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2535 sendActivityResultLocked(-1,
2536 r.resultTo, r.resultWho, r.requestCode,
2537 Activity.RESULT_CANCELED, null);
2538 r.resultTo = null;
2539 }
2540
2541 boolean addingToTask = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002542 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002543 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2544 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2545 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2546 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2547 // If bring to front is requested, and no result is requested, and
2548 // we can find a task that was started with this same
2549 // component, then instead of launching bring that one to the front.
2550 if (r.resultTo == null) {
2551 // See if there is a task to bring to the front. If this is
2552 // a SINGLE_INSTANCE activity, there can be one and only one
2553 // instance of it in the history, and it is always in its own
2554 // unique task, so we do a special search.
2555 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2556 ? findTaskLocked(intent, r.info)
2557 : findActivityLocked(intent, r.info);
2558 if (taskTop != null) {
2559 if (taskTop.task.intent == null) {
2560 // This task was started because of movement of
2561 // the activity based on affinity... now that we
2562 // are actually launching it, we can assign the
2563 // base intent.
2564 taskTop.task.setIntent(intent, r.info);
2565 }
2566 // If the target task is not in the front, then we need
2567 // to bring it to the front... except... well, with
2568 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2569 // to have the same behavior as if a new instance was
2570 // being started, which means not bringing it to the front
2571 // if the caller is not itself in the front.
2572 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002573 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002574 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2575 boolean callerAtFront = sourceRecord == null
2576 || curTop.task == sourceRecord.task;
2577 if (callerAtFront) {
2578 // We really do want to push this one into the
2579 // user's face, right now.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002580 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002581 moveTaskToFrontLocked(taskTop.task, r);
2582 }
2583 }
2584 // If the caller has requested that the target task be
2585 // reset, then do so.
2586 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2587 taskTop = resetTaskIfNeededLocked(taskTop, r);
2588 }
2589 if (onlyIfNeeded) {
2590 // We don't need to start a new activity, and
2591 // the client said not to do anything if that
2592 // is the case, so this is it! And for paranoia, make
2593 // sure we have correctly resumed the top activity.
2594 if (doResume) {
2595 resumeTopActivityLocked(null);
2596 }
2597 return START_RETURN_INTENT_TO_CALLER;
2598 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002599 if ((launchFlags &
2600 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2601 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2602 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002603 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002604 // not be too hard...
2605 reuseTask = taskTop.task;
2606 performClearTaskLocked(taskTop.task.taskId);
2607 reuseTask.setIntent(r.intent, r.info);
2608 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002609 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2610 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2611 // In this situation we want to remove all activities
2612 // from the task up to the one being started. In most
2613 // cases this means we are resetting the task to its
2614 // initial state.
2615 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002616 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002617 if (top != null) {
2618 if (top.frontOfTask) {
2619 // Activity aliases may mean we use different
2620 // intents for the top activity, so make sure
2621 // the task now has the identity of the new
2622 // intent.
2623 top.task.setIntent(r.intent, r.info);
2624 }
2625 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002626 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002627 } else {
2628 // A special case: we need to
2629 // start the activity because it is not currently
2630 // running, and the caller has asked to clear the
2631 // current task to have this activity at the top.
2632 addingToTask = true;
2633 // Now pretend like this activity is being started
2634 // by the top of its task, so it is put in the
2635 // right place.
2636 sourceRecord = taskTop;
2637 }
2638 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2639 // In this case the top activity on the task is the
2640 // same as the one being launched, so we take that
2641 // as a request to bring the task to the foreground.
2642 // If the top activity in the task is the root
2643 // activity, deliver this new intent to it if it
2644 // desires.
2645 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2646 && taskTop.realActivity.equals(r.realActivity)) {
2647 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2648 if (taskTop.frontOfTask) {
2649 taskTop.task.setIntent(r.intent, r.info);
2650 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002651 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002652 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2653 // In this case we are launching the root activity
2654 // of the task, but with a different intent. We
2655 // should start a new instance on top.
2656 addingToTask = true;
2657 sourceRecord = taskTop;
2658 }
2659 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2660 // In this case an activity is being launched in to an
2661 // existing task, without resetting that task. This
2662 // is typically the situation of launching an activity
2663 // from a notification or shortcut. We want to place
2664 // the new activity on top of the current task.
2665 addingToTask = true;
2666 sourceRecord = taskTop;
2667 } else if (!taskTop.task.rootWasReset) {
2668 // In this case we are launching in to an existing task
2669 // that has not yet been started from its front door.
2670 // The current task has been brought to the front.
2671 // Ideally, we'd probably like to place this new task
2672 // at the bottom of its stack, but that's a little hard
2673 // to do with the current organization of the code so
2674 // for now we'll just drop it.
2675 taskTop.task.setIntent(r.intent, r.info);
2676 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002677 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002678 // We didn't do anything... but it was needed (a.k.a., client
2679 // don't use that intent!) And for paranoia, make
2680 // sure we have correctly resumed the top activity.
2681 if (doResume) {
2682 resumeTopActivityLocked(null);
2683 }
2684 return START_TASK_TO_FRONT;
2685 }
2686 }
2687 }
2688 }
2689
2690 //String uri = r.intent.toURI();
2691 //Intent intent2 = new Intent(uri);
2692 //Slog.i(TAG, "Given intent: " + r.intent);
2693 //Slog.i(TAG, "URI is: " + uri);
2694 //Slog.i(TAG, "To intent: " + intent2);
2695
2696 if (r.packageName != null) {
2697 // If the activity being launched is the same as the one currently
2698 // at the top, then we need to check if it should only be launched
2699 // once.
2700 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2701 if (top != null && r.resultTo == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002702 if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002703 if (top.app != null && top.app.thread != null) {
2704 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2705 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2706 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2707 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2708 // For paranoia, make sure we have correctly
2709 // resumed the top activity.
2710 if (doResume) {
2711 resumeTopActivityLocked(null);
2712 }
2713 if (onlyIfNeeded) {
2714 // We don't need to start a new activity, and
2715 // the client said not to do anything if that
2716 // is the case, so this is it!
2717 return START_RETURN_INTENT_TO_CALLER;
2718 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002719 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002720 return START_DELIVERED_TO_TOP;
2721 }
2722 }
2723 }
2724 }
2725
2726 } else {
2727 if (r.resultTo != null) {
2728 sendActivityResultLocked(-1,
2729 r.resultTo, r.resultWho, r.requestCode,
2730 Activity.RESULT_CANCELED, null);
2731 }
2732 return START_CLASS_NOT_FOUND;
2733 }
2734
2735 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002736 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002737
2738 // Should this be considered a new task?
2739 if (r.resultTo == null && !addingToTask
2740 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002741 if (reuseTask == null) {
2742 // todo: should do better management of integers.
2743 mService.mCurTask++;
2744 if (mService.mCurTask <= 0) {
2745 mService.mCurTask = 1;
2746 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002747 r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002748 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2749 + " in new task " + r.task);
2750 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002751 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002752 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002753 newTask = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002754 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002755
2756 } else if (sourceRecord != null) {
2757 if (!addingToTask &&
2758 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2759 // In this case, we are adding the activity to an existing
2760 // task, but the caller has asked to clear that task if the
2761 // activity is already running.
2762 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002763 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002764 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002765 if (top != null) {
2766 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002767 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002768 // For paranoia, make sure we have correctly
2769 // resumed the top activity.
2770 if (doResume) {
2771 resumeTopActivityLocked(null);
2772 }
2773 return START_DELIVERED_TO_TOP;
2774 }
2775 } else if (!addingToTask &&
2776 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2777 // In this case, we are launching an activity in our own task
2778 // that may already be running somewhere in the history, and
2779 // we want to shuffle it to the front of the stack if so.
2780 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2781 if (where >= 0) {
2782 ActivityRecord top = moveActivityToFrontLocked(where);
2783 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002784 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002785 if (doResume) {
2786 resumeTopActivityLocked(null);
2787 }
2788 return START_DELIVERED_TO_TOP;
2789 }
2790 }
2791 // An existing activity is starting this new activity, so we want
2792 // to keep the new one in the same task as the one that is starting
2793 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002794 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002795 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2796 + " in existing task " + r.task);
2797
2798 } else {
2799 // This not being started from an existing activity, and not part
2800 // of a new task... just put it in the top task, though these days
2801 // this case should never happen.
2802 final int N = mHistory.size();
2803 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002804 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002805 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002806 ? prev.task
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002807 : new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002808 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2809 + " in new guessed " + r.task);
2810 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002811
2812 if (grantedUriPermissions != null && callingUid > 0) {
2813 for (int i=0; i<grantedUriPermissions.length; i++) {
2814 mService.grantUriPermissionLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002815 grantedUriPermissions[i], grantedMode, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002816 }
2817 }
2818
2819 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002820 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002821
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002822 if (newTask) {
2823 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
2824 }
2825 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002826 startActivityLocked(r, newTask, doResume, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002827 return START_SUCCESS;
2828 }
2829
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002830 ActivityInfo resolveActivity(Intent intent, String resolvedType, boolean debug,
2831 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002832 // Collect information about the target of the Intent.
2833 ActivityInfo aInfo;
2834 try {
2835 ResolveInfo rInfo =
2836 AppGlobals.getPackageManager().resolveIntent(
2837 intent, resolvedType,
2838 PackageManager.MATCH_DEFAULT_ONLY
2839 | ActivityManagerService.STOCK_PM_FLAGS);
2840 aInfo = rInfo != null ? rInfo.activityInfo : null;
2841 } catch (RemoteException e) {
2842 aInfo = null;
2843 }
2844
2845 if (aInfo != null) {
2846 // Store the found target back into the intent, because now that
2847 // we have it we never want to do this again. For example, if the
2848 // user navigates back to this point in the history, we should
2849 // always restart the exact same activity.
2850 intent.setComponent(new ComponentName(
2851 aInfo.applicationInfo.packageName, aInfo.name));
2852
2853 // Don't debug things in the system process
2854 if (debug) {
2855 if (!aInfo.processName.equals("system")) {
2856 mService.setDebugApp(aInfo.processName, true, false);
2857 }
2858 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002859
2860 if (profileFile != null) {
2861 if (!aInfo.processName.equals("system")) {
2862 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
2863 profileFile, profileFd, autoStopProfiler);
2864 }
2865 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002866 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002867 return aInfo;
2868 }
2869
2870 final int startActivityMayWait(IApplicationThread caller, int callingUid,
2871 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2872 int grantedMode, IBinder resultTo,
2873 String resultWho, int requestCode, boolean onlyIfNeeded,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002874 boolean debug, String profileFile, ParcelFileDescriptor profileFd,
Amith Yamasani742a6712011-05-04 14:49:28 -07002875 boolean autoStopProfiler,
2876 WaitResult outResult, Configuration config, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002877 // Refuse possible leaked file descriptors
2878 if (intent != null && intent.hasFileDescriptors()) {
2879 throw new IllegalArgumentException("File descriptors passed in Intent");
2880 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002881 boolean componentSpecified = intent.getComponent() != null;
2882
2883 // Don't modify the client's object!
2884 intent = new Intent(intent);
2885
2886 // Collect information about the target of the Intent.
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002887 ActivityInfo aInfo = resolveActivity(intent, resolvedType, debug,
2888 profileFile, profileFd, autoStopProfiler);
Amith Yamasani742a6712011-05-04 14:49:28 -07002889 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002890
2891 synchronized (mService) {
2892 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002893 if (callingUid >= 0) {
2894 callingPid = -1;
2895 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002896 callingPid = Binder.getCallingPid();
2897 callingUid = Binder.getCallingUid();
2898 } else {
2899 callingPid = callingUid = -1;
2900 }
2901
2902 mConfigWillChange = config != null
2903 && mService.mConfiguration.diff(config) != 0;
2904 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2905 "Starting activity when config will change = " + mConfigWillChange);
2906
2907 final long origId = Binder.clearCallingIdentity();
2908
2909 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07002910 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002911 // This may be a heavy-weight process! Check to see if we already
2912 // have another, different heavy-weight process running.
2913 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
2914 if (mService.mHeavyWeightProcess != null &&
2915 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
2916 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
2917 int realCallingPid = callingPid;
2918 int realCallingUid = callingUid;
2919 if (caller != null) {
2920 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
2921 if (callerApp != null) {
2922 realCallingPid = callerApp.pid;
2923 realCallingUid = callerApp.info.uid;
2924 } else {
2925 Slog.w(TAG, "Unable to find app for caller " + caller
2926 + " (pid=" + realCallingPid + ") when starting: "
2927 + intent.toString());
2928 return START_PERMISSION_DENIED;
2929 }
2930 }
2931
2932 IIntentSender target = mService.getIntentSenderLocked(
2933 IActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002934 realCallingUid, null, null, 0, new Intent[] { intent },
2935 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002936 | PendingIntent.FLAG_ONE_SHOT);
2937
2938 Intent newIntent = new Intent();
2939 if (requestCode >= 0) {
2940 // Caller is requesting a result.
2941 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
2942 }
2943 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
2944 new IntentSender(target));
2945 if (mService.mHeavyWeightProcess.activities.size() > 0) {
2946 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
2947 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
2948 hist.packageName);
2949 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
2950 hist.task.taskId);
2951 }
2952 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
2953 aInfo.packageName);
2954 newIntent.setFlags(intent.getFlags());
2955 newIntent.setClassName("android",
2956 HeavyWeightSwitcherActivity.class.getName());
2957 intent = newIntent;
2958 resolvedType = null;
2959 caller = null;
2960 callingUid = Binder.getCallingUid();
2961 callingPid = Binder.getCallingPid();
2962 componentSpecified = true;
2963 try {
2964 ResolveInfo rInfo =
2965 AppGlobals.getPackageManager().resolveIntent(
2966 intent, null,
2967 PackageManager.MATCH_DEFAULT_ONLY
2968 | ActivityManagerService.STOCK_PM_FLAGS);
2969 aInfo = rInfo != null ? rInfo.activityInfo : null;
Amith Yamasani742a6712011-05-04 14:49:28 -07002970 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002971 } catch (RemoteException e) {
2972 aInfo = null;
2973 }
2974 }
2975 }
2976 }
2977
2978 int res = startActivityLocked(caller, intent, resolvedType,
2979 grantedUriPermissions, grantedMode, aInfo,
2980 resultTo, resultWho, requestCode, callingPid, callingUid,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002981 onlyIfNeeded, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002982
2983 if (mConfigWillChange && mMainStack) {
2984 // If the caller also wants to switch to a new configuration,
2985 // do so now. This allows a clean switch, as we are waiting
2986 // for the current activity to pause (so we will not destroy
2987 // it), and have not yet started the next activity.
2988 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
2989 "updateConfiguration()");
2990 mConfigWillChange = false;
2991 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2992 "Updating to new configuration after starting activity.");
Dianne Hackborn813075a62011-11-14 17:45:19 -08002993 mService.updateConfigurationLocked(config, null, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002994 }
2995
2996 Binder.restoreCallingIdentity(origId);
2997
2998 if (outResult != null) {
2999 outResult.result = res;
3000 if (res == IActivityManager.START_SUCCESS) {
3001 mWaitingActivityLaunched.add(outResult);
3002 do {
3003 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003004 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003005 } catch (InterruptedException e) {
3006 }
3007 } while (!outResult.timeout && outResult.who == null);
3008 } else if (res == IActivityManager.START_TASK_TO_FRONT) {
3009 ActivityRecord r = this.topRunningActivityLocked(null);
3010 if (r.nowVisible) {
3011 outResult.timeout = false;
3012 outResult.who = new ComponentName(r.info.packageName, r.info.name);
3013 outResult.totalTime = 0;
3014 outResult.thisTime = 0;
3015 } else {
3016 outResult.thisTime = SystemClock.uptimeMillis();
3017 mWaitingActivityVisible.add(outResult);
3018 do {
3019 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003020 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003021 } catch (InterruptedException e) {
3022 }
3023 } while (!outResult.timeout && outResult.who == null);
3024 }
3025 }
3026 }
3027
3028 return res;
3029 }
3030 }
3031
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003032 final int startActivities(IApplicationThread caller, int callingUid,
Amith Yamasani742a6712011-05-04 14:49:28 -07003033 Intent[] intents,
3034 String[] resolvedTypes, IBinder resultTo, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003035 if (intents == null) {
3036 throw new NullPointerException("intents is null");
3037 }
3038 if (resolvedTypes == null) {
3039 throw new NullPointerException("resolvedTypes is null");
3040 }
3041 if (intents.length != resolvedTypes.length) {
3042 throw new IllegalArgumentException("intents are length different than resolvedTypes");
3043 }
3044
3045 ActivityRecord[] outActivity = new ActivityRecord[1];
3046
3047 int callingPid;
3048 if (callingUid >= 0) {
3049 callingPid = -1;
3050 } else if (caller == null) {
3051 callingPid = Binder.getCallingPid();
3052 callingUid = Binder.getCallingUid();
3053 } else {
3054 callingPid = callingUid = -1;
3055 }
3056 final long origId = Binder.clearCallingIdentity();
3057 try {
3058 synchronized (mService) {
3059
3060 for (int i=0; i<intents.length; i++) {
3061 Intent intent = intents[i];
3062 if (intent == null) {
3063 continue;
3064 }
3065
3066 // Refuse possible leaked file descriptors
3067 if (intent != null && intent.hasFileDescriptors()) {
3068 throw new IllegalArgumentException("File descriptors passed in Intent");
3069 }
3070
3071 boolean componentSpecified = intent.getComponent() != null;
3072
3073 // Don't modify the client's object!
3074 intent = new Intent(intent);
3075
3076 // Collect information about the target of the Intent.
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003077 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i], false,
3078 null, null, false);
Amith Yamasani742a6712011-05-04 14:49:28 -07003079 // TODO: New, check if this is correct
3080 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003081
3082 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
3083 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
3084 throw new IllegalArgumentException(
3085 "FLAG_CANT_SAVE_STATE not supported here");
3086 }
3087
3088 int res = startActivityLocked(caller, intent, resolvedTypes[i],
3089 null, 0, aInfo, resultTo, null, -1, callingPid, callingUid,
3090 false, componentSpecified, outActivity);
3091 if (res < 0) {
3092 return res;
3093 }
3094
Dianne Hackbornbe707852011-11-11 14:32:10 -08003095 resultTo = outActivity[0] != null ? outActivity[0].appToken : null;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003096 }
3097 }
3098 } finally {
3099 Binder.restoreCallingIdentity(origId);
3100 }
3101
3102 return IActivityManager.START_SUCCESS;
3103 }
3104
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003105 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
3106 long thisTime, long totalTime) {
3107 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
3108 WaitResult w = mWaitingActivityLaunched.get(i);
3109 w.timeout = timeout;
3110 if (r != null) {
3111 w.who = new ComponentName(r.info.packageName, r.info.name);
3112 }
3113 w.thisTime = thisTime;
3114 w.totalTime = totalTime;
3115 }
3116 mService.notifyAll();
3117 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003118
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003119 void reportActivityVisibleLocked(ActivityRecord r) {
3120 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
3121 WaitResult w = mWaitingActivityVisible.get(i);
3122 w.timeout = false;
3123 if (r != null) {
3124 w.who = new ComponentName(r.info.packageName, r.info.name);
3125 }
3126 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
3127 w.thisTime = w.totalTime;
3128 }
3129 mService.notifyAll();
Dianne Hackborn90c52de2011-09-23 12:57:44 -07003130
3131 if (mDismissKeyguardOnNextActivity) {
3132 mDismissKeyguardOnNextActivity = false;
3133 mService.mWindowManager.dismissKeyguard();
3134 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003135 }
3136
3137 void sendActivityResultLocked(int callingUid, ActivityRecord r,
3138 String resultWho, int requestCode, int resultCode, Intent data) {
3139
3140 if (callingUid > 0) {
3141 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003142 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003143 }
3144
3145 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3146 + " : who=" + resultWho + " req=" + requestCode
3147 + " res=" + resultCode + " data=" + data);
3148 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3149 try {
3150 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3151 list.add(new ResultInfo(resultWho, requestCode,
3152 resultCode, data));
Dianne Hackbornbe707852011-11-11 14:32:10 -08003153 r.app.thread.scheduleSendResult(r.appToken, list);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003154 return;
3155 } catch (Exception e) {
3156 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3157 }
3158 }
3159
3160 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3161 }
3162
3163 private final void stopActivityLocked(ActivityRecord r) {
3164 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3165 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3166 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3167 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003168 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003169 "no-history");
3170 }
3171 } else if (r.app != null && r.app.thread != null) {
3172 if (mMainStack) {
3173 if (mService.mFocusedActivity == r) {
3174 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3175 }
3176 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003177 r.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003178 try {
3179 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003180 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3181 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003182 r.state = ActivityState.STOPPING;
3183 if (DEBUG_VISBILITY) Slog.v(
3184 TAG, "Stopping visible=" + r.visible + " for " + r);
3185 if (!r.visible) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003186 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003187 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003188 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003189 if (mService.isSleeping()) {
3190 r.setSleeping(true);
3191 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003192 } catch (Exception e) {
3193 // Maybe just ignore exceptions here... if the process
3194 // has crashed, our death notification will clean things
3195 // up.
3196 Slog.w(TAG, "Exception thrown during pause", e);
3197 // Just in case, assume it to be stopped.
3198 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003199 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003200 r.state = ActivityState.STOPPED;
3201 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003202 destroyActivityLocked(r, true, false, "stop-except");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003203 }
3204 }
3205 }
3206 }
3207
3208 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3209 boolean remove) {
3210 int N = mStoppingActivities.size();
3211 if (N <= 0) return null;
3212
3213 ArrayList<ActivityRecord> stops = null;
3214
3215 final boolean nowVisible = mResumedActivity != null
3216 && mResumedActivity.nowVisible
3217 && !mResumedActivity.waitingVisible;
3218 for (int i=0; i<N; i++) {
3219 ActivityRecord s = mStoppingActivities.get(i);
3220 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3221 + nowVisible + " waitingVisible=" + s.waitingVisible
3222 + " finishing=" + s.finishing);
3223 if (s.waitingVisible && nowVisible) {
3224 mWaitingVisibleActivities.remove(s);
3225 s.waitingVisible = false;
3226 if (s.finishing) {
3227 // If this activity is finishing, it is sitting on top of
3228 // everyone else but we now know it is no longer needed...
3229 // so get rid of it. Otherwise, we need to go through the
3230 // normal flow and hide it once we determine that it is
3231 // hidden by the activities in front of it.
3232 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003233 mService.mWindowManager.setAppVisibility(s.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003234 }
3235 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003236 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003237 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3238 if (stops == null) {
3239 stops = new ArrayList<ActivityRecord>();
3240 }
3241 stops.add(s);
3242 mStoppingActivities.remove(i);
3243 N--;
3244 i--;
3245 }
3246 }
3247
3248 return stops;
3249 }
3250
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003251 final void scheduleIdleLocked() {
3252 Message msg = Message.obtain();
3253 msg.what = IDLE_NOW_MSG;
3254 mHandler.sendMessage(msg);
3255 }
3256
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003257 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003258 Configuration config) {
3259 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3260
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003261 ActivityRecord res = null;
3262
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003263 ArrayList<ActivityRecord> stops = null;
3264 ArrayList<ActivityRecord> finishes = null;
3265 ArrayList<ActivityRecord> thumbnails = null;
3266 int NS = 0;
3267 int NF = 0;
3268 int NT = 0;
3269 IApplicationThread sendThumbnail = null;
3270 boolean booting = false;
3271 boolean enableScreen = false;
3272
3273 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003274 ActivityRecord r = ActivityRecord.forToken(token);
3275 if (r != null) {
3276 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003277 }
3278
3279 // Get the activity record.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003280 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003281 if (index >= 0) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003282 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003283
3284 if (fromTimeout) {
3285 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3286 }
3287
3288 // This is a hack to semi-deal with a race condition
3289 // in the client where it can be constructed with a
3290 // newer configuration from when we asked it to launch.
3291 // We'll update with whatever configuration it now says
3292 // it used to launch.
3293 if (config != null) {
3294 r.configuration = config;
3295 }
3296
3297 // No longer need to keep the device awake.
3298 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3299 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3300 mLaunchingActivity.release();
3301 }
3302
3303 // We are now idle. If someone is waiting for a thumbnail from
3304 // us, we can now deliver.
3305 r.idle = true;
3306 mService.scheduleAppGcsLocked();
3307 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3308 sendThumbnail = r.app.thread;
3309 r.thumbnailNeeded = false;
3310 }
3311
3312 // If this activity is fullscreen, set up to hide those under it.
3313
3314 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3315 ensureActivitiesVisibleLocked(null, 0);
3316
3317 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3318 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003319 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003320 mService.mBooted = true;
3321 enableScreen = true;
3322 }
3323 }
3324
3325 } else if (fromTimeout) {
3326 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3327 }
3328
3329 // Atomically retrieve all of the other things to do.
3330 stops = processStoppingActivitiesLocked(true);
3331 NS = stops != null ? stops.size() : 0;
3332 if ((NF=mFinishingActivities.size()) > 0) {
3333 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3334 mFinishingActivities.clear();
3335 }
3336 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3337 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3338 mService.mCancelledThumbnails.clear();
3339 }
3340
3341 if (mMainStack) {
3342 booting = mService.mBooting;
3343 mService.mBooting = false;
3344 }
3345 }
3346
3347 int i;
3348
3349 // Send thumbnail if requested.
3350 if (sendThumbnail != null) {
3351 try {
3352 sendThumbnail.requestThumbnail(token);
3353 } catch (Exception e) {
3354 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3355 mService.sendPendingThumbnail(null, token, null, null, true);
3356 }
3357 }
3358
3359 // Stop any activities that are scheduled to do so but have been
3360 // waiting for the next one to start.
3361 for (i=0; i<NS; i++) {
3362 ActivityRecord r = (ActivityRecord)stops.get(i);
3363 synchronized (mService) {
3364 if (r.finishing) {
3365 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY);
3366 } else {
3367 stopActivityLocked(r);
3368 }
3369 }
3370 }
3371
3372 // Finish any activities that are scheduled to do so but have been
3373 // waiting for the next one to start.
3374 for (i=0; i<NF; i++) {
3375 ActivityRecord r = (ActivityRecord)finishes.get(i);
3376 synchronized (mService) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003377 destroyActivityLocked(r, true, false, "finish-idle");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003378 }
3379 }
3380
3381 // Report back to any thumbnail receivers.
3382 for (i=0; i<NT; i++) {
3383 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3384 mService.sendPendingThumbnail(r, null, null, null, true);
3385 }
3386
3387 if (booting) {
3388 mService.finishBooting();
3389 }
3390
3391 mService.trimApplications();
3392 //dump();
3393 //mWindowManager.dump();
3394
3395 if (enableScreen) {
3396 mService.enableScreenAfterBoot();
3397 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003398
3399 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003400 }
3401
3402 /**
3403 * @return Returns true if the activity is being finished, false if for
3404 * some reason it is being left as-is.
3405 */
3406 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
3407 Intent resultData, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003408 int index = indexOfTokenLocked(token);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003409 if (DEBUG_RESULTS) Slog.v(
3410 TAG, "Finishing activity @" + index + ": token=" + token
3411 + ", result=" + resultCode + ", data=" + resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003412 if (index < 0) {
3413 return false;
3414 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003415 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003416
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003417 finishActivityLocked(r, index, resultCode, resultData, reason);
3418 return true;
3419 }
3420
Dianne Hackborn5c607432012-02-28 14:44:19 -08003421 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
3422 // send the result
3423 ActivityRecord resultTo = r.resultTo;
3424 if (resultTo != null) {
3425 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3426 + " who=" + r.resultWho + " req=" + r.requestCode
3427 + " res=" + resultCode + " data=" + resultData);
3428 if (r.info.applicationInfo.uid > 0) {
3429 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3430 resultTo.packageName, resultData,
3431 resultTo.getUriPermissionsLocked());
3432 }
3433 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3434 resultData);
3435 r.resultTo = null;
3436 }
3437 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3438
3439 // Make sure this HistoryRecord is not holding on to other resources,
3440 // because clients have remote IPC references to this object so we
3441 // can't assume that will go away and want to avoid circular IPC refs.
3442 r.results = null;
3443 r.pendingResults = null;
3444 r.newIntents = null;
3445 r.icicle = null;
3446 }
3447
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003448 /**
3449 * @return Returns true if this activity has been removed from the history
3450 * list, or false if it is still in the list and will be removed later.
3451 */
3452 final boolean finishActivityLocked(ActivityRecord r, int index,
3453 int resultCode, Intent resultData, String reason) {
3454 if (r.finishing) {
3455 Slog.w(TAG, "Duplicate finish request for " + r);
3456 return false;
3457 }
3458
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003459 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003460 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3461 System.identityHashCode(r),
3462 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003463 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003464 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003465 if (next.task == r.task) {
3466 if (r.frontOfTask) {
3467 // The next activity is now the front of the task.
3468 next.frontOfTask = true;
3469 }
3470 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3471 // If the caller asked that this activity (and all above it)
3472 // be cleared when the task is reset, don't lose that information,
3473 // but propagate it up to the next activity.
3474 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3475 }
3476 }
3477 }
3478
3479 r.pauseKeyDispatchingLocked();
3480 if (mMainStack) {
3481 if (mService.mFocusedActivity == r) {
3482 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3483 }
3484 }
3485
Dianne Hackborn5c607432012-02-28 14:44:19 -08003486 finishActivityResultsLocked(r, resultCode, resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003487
3488 if (mService.mPendingThumbnails.size() > 0) {
3489 // There are clients waiting to receive thumbnails so, in case
3490 // this is an activity that someone is waiting for, add it
3491 // to the pending list so we can correctly update the clients.
3492 mService.mCancelledThumbnails.add(r);
3493 }
3494
3495 if (mResumedActivity == r) {
3496 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003497 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003498 if (DEBUG_TRANSITION) Slog.v(TAG,
3499 "Prepare close transition: finishing " + r);
3500 mService.mWindowManager.prepareAppTransition(endTask
3501 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003502 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003503
3504 // Tell window manager to prepare for this one to be removed.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003505 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003506
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003507 if (mPausingActivity == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003508 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3509 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3510 startPausingLocked(false, false);
3511 }
3512
3513 } else if (r.state != ActivityState.PAUSING) {
3514 // If the activity is PAUSING, we will complete the finish once
3515 // it is done pausing; else we can just directly finish it here.
3516 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3517 return finishCurrentActivityLocked(r, index,
3518 FINISH_AFTER_PAUSE) == null;
3519 } else {
3520 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3521 }
3522
3523 return false;
3524 }
3525
3526 private static final int FINISH_IMMEDIATELY = 0;
3527 private static final int FINISH_AFTER_PAUSE = 1;
3528 private static final int FINISH_AFTER_VISIBLE = 2;
3529
3530 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3531 int mode) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003532 final int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003533 if (index < 0) {
3534 return null;
3535 }
3536
3537 return finishCurrentActivityLocked(r, index, mode);
3538 }
3539
3540 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3541 int index, int mode) {
3542 // First things first: if this activity is currently visible,
3543 // and the resumed activity is not yet visible, then hold off on
3544 // finishing until the resumed one becomes visible.
3545 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3546 if (!mStoppingActivities.contains(r)) {
3547 mStoppingActivities.add(r);
3548 if (mStoppingActivities.size() > 3) {
3549 // If we already have a few activities waiting to stop,
3550 // then give up on things going idle and start clearing
3551 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003552 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003553 } else {
3554 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003555 }
3556 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003557 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3558 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003559 r.state = ActivityState.STOPPING;
3560 mService.updateOomAdjLocked();
3561 return r;
3562 }
3563
3564 // make sure the record is cleaned out of other places.
3565 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003566 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003567 mWaitingVisibleActivities.remove(r);
3568 if (mResumedActivity == r) {
3569 mResumedActivity = null;
3570 }
3571 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003572 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003573 r.state = ActivityState.FINISHING;
3574
3575 if (mode == FINISH_IMMEDIATELY
3576 || prevState == ActivityState.STOPPED
3577 || prevState == ActivityState.INITIALIZING) {
3578 // If this activity is already stopped, we can just finish
3579 // it right now.
Dianne Hackborn28695e02011-11-02 21:59:51 -07003580 return destroyActivityLocked(r, true, true, "finish-imm") ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003581 } else {
3582 // Need to go through the full pause cycle to get this
3583 // activity into the stopped state and then finish it.
3584 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3585 mFinishingActivities.add(r);
3586 resumeTopActivityLocked(null);
3587 }
3588 return r;
3589 }
3590
3591 /**
3592 * Perform the common clean-up of an activity record. This is called both
3593 * as part of destroyActivityLocked() (when destroying the client-side
3594 * representation) and cleaning things up as a result of its hosting
3595 * processing going away, in which case there is no remaining client-side
3596 * state to destroy so only the cleanup here is needed.
3597 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003598 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3599 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003600 if (mResumedActivity == r) {
3601 mResumedActivity = null;
3602 }
3603 if (mService.mFocusedActivity == r) {
3604 mService.mFocusedActivity = null;
3605 }
3606
3607 r.configDestroy = false;
3608 r.frozenBeforeDestroy = false;
3609
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003610 if (setState) {
3611 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3612 r.state = ActivityState.DESTROYED;
3613 }
3614
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003615 // Make sure this record is no longer in the pending finishes list.
3616 // This could happen, for example, if we are trimming activities
3617 // down to the max limit while they are still waiting to finish.
3618 mFinishingActivities.remove(r);
3619 mWaitingVisibleActivities.remove(r);
3620
3621 // Remove any pending results.
3622 if (r.finishing && r.pendingResults != null) {
3623 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3624 PendingIntentRecord rec = apr.get();
3625 if (rec != null) {
3626 mService.cancelIntentSenderLocked(rec, false);
3627 }
3628 }
3629 r.pendingResults = null;
3630 }
3631
3632 if (cleanServices) {
3633 cleanUpActivityServicesLocked(r);
3634 }
3635
3636 if (mService.mPendingThumbnails.size() > 0) {
3637 // There are clients waiting to receive thumbnails so, in case
3638 // this is an activity that someone is waiting for, add it
3639 // to the pending list so we can correctly update the clients.
3640 mService.mCancelledThumbnails.add(r);
3641 }
3642
3643 // Get rid of any pending idle timeouts.
3644 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
3645 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003646 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003647 }
3648
Dianne Hackborn5c607432012-02-28 14:44:19 -08003649 final void removeActivityFromHistoryLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003650 if (r.state != ActivityState.DESTROYED) {
Dianne Hackborn5c607432012-02-28 14:44:19 -08003651 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003652 r.makeFinishing();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003653 if (DEBUG_ADD_REMOVE) {
3654 RuntimeException here = new RuntimeException("here");
3655 here.fillInStackTrace();
3656 Slog.i(TAG, "Removing activity " + r + " from stack");
3657 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003658 mHistory.remove(r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003659 r.takeFromHistory();
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003660 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3661 + " (removed from history)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003662 r.state = ActivityState.DESTROYED;
Dianne Hackbornbe707852011-11-11 14:32:10 -08003663 mService.mWindowManager.removeAppToken(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003664 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003665 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003666 }
3667 cleanUpActivityServicesLocked(r);
3668 r.removeUriPermissionsLocked();
3669 }
3670 }
3671
3672 /**
3673 * Perform clean-up of service connections in an activity record.
3674 */
3675 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3676 // Throw away any services that have been bound by this activity.
3677 if (r.connections != null) {
3678 Iterator<ConnectionRecord> it = r.connections.iterator();
3679 while (it.hasNext()) {
3680 ConnectionRecord c = it.next();
3681 mService.removeConnectionLocked(c, null, r);
3682 }
3683 r.connections = null;
3684 }
3685 }
3686
Dianne Hackborn28695e02011-11-02 21:59:51 -07003687 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003688 for (int i=mHistory.size()-1; i>=0; i--) {
3689 ActivityRecord r = mHistory.get(i);
3690 if (owner != null && r.app != owner) {
3691 continue;
3692 }
3693 // We can destroy this one if we have its icicle saved and
3694 // it is not in the process of pausing/stopping/finishing.
3695 if (r.app != null && r.haveState && !r.visible && r.stopped && !r.finishing
3696 && r.state != ActivityState.DESTROYING
3697 && r.state != ActivityState.DESTROYED) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003698 destroyActivityLocked(r, true, oomAdj, "trim");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003699 }
3700 }
3701 }
3702
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003703 /**
3704 * Destroy the current CLIENT SIDE instance of an activity. This may be
3705 * called both when actually finishing an activity, or when performing
3706 * a configuration switch where we destroy the current client-side object
3707 * but then create a new client-side object for this same HistoryRecord.
3708 */
3709 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackborn28695e02011-11-02 21:59:51 -07003710 boolean removeFromApp, boolean oomAdj, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003711 if (DEBUG_SWITCH) Slog.v(
3712 TAG, "Removing activity: token=" + r
3713 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3714 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3715 System.identityHashCode(r),
Dianne Hackborn28695e02011-11-02 21:59:51 -07003716 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003717
3718 boolean removedFromHistory = false;
3719
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003720 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003721
3722 final boolean hadApp = r.app != null;
3723
3724 if (hadApp) {
3725 if (removeFromApp) {
3726 int idx = r.app.activities.indexOf(r);
3727 if (idx >= 0) {
3728 r.app.activities.remove(idx);
3729 }
3730 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
3731 mService.mHeavyWeightProcess = null;
3732 mService.mHandler.sendEmptyMessage(
3733 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
3734 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003735 if (r.app.activities.size() == 0) {
3736 // No longer have activities, so update location in
3737 // LRU list.
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003738 mService.updateLruProcessLocked(r.app, oomAdj, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003739 }
3740 }
3741
3742 boolean skipDestroy = false;
3743
3744 try {
3745 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003746 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003747 r.configChangeFlags);
3748 } catch (Exception e) {
3749 // We can just ignore exceptions here... if the process
3750 // has crashed, our death notification will clean things
3751 // up.
3752 //Slog.w(TAG, "Exception thrown during finish", e);
3753 if (r.finishing) {
3754 removeActivityFromHistoryLocked(r);
3755 removedFromHistory = true;
3756 skipDestroy = true;
3757 }
3758 }
3759
3760 r.app = null;
3761 r.nowVisible = false;
3762
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003763 // If the activity is finishing, we need to wait on removing it
3764 // from the list to give it a chance to do its cleanup. During
3765 // that time it may make calls back with its token so we need to
3766 // be able to find it on the list and so we don't want to remove
3767 // it from the list yet. Otherwise, we can just immediately put
3768 // it in the destroyed state since we are not removing it from the
3769 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003770 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003771 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
3772 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003773 r.state = ActivityState.DESTROYING;
3774 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
3775 msg.obj = r;
3776 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
3777 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003778 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3779 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003780 r.state = ActivityState.DESTROYED;
3781 }
3782 } else {
3783 // remove this record from the history.
3784 if (r.finishing) {
3785 removeActivityFromHistoryLocked(r);
3786 removedFromHistory = true;
3787 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003788 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3789 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003790 r.state = ActivityState.DESTROYED;
3791 }
3792 }
3793
3794 r.configChangeFlags = 0;
3795
3796 if (!mLRUActivities.remove(r) && hadApp) {
3797 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
3798 }
3799
3800 return removedFromHistory;
3801 }
3802
3803 final void activityDestroyed(IBinder token) {
3804 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003805 ActivityRecord r = ActivityRecord.forToken(token);
3806 if (r != null) {
3807 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
3808 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003809
Dianne Hackbornbe707852011-11-11 14:32:10 -08003810 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003811 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003812 if (r.state == ActivityState.DESTROYING) {
3813 final long origId = Binder.clearCallingIdentity();
3814 removeActivityFromHistoryLocked(r);
3815 Binder.restoreCallingIdentity(origId);
3816 }
3817 }
3818 }
3819 }
3820
3821 private static void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
3822 int i = list.size();
3823 if (localLOGV) Slog.v(
3824 TAG, "Removing app " + app + " from list " + list
3825 + " with " + i + " entries");
3826 while (i > 0) {
3827 i--;
3828 ActivityRecord r = (ActivityRecord)list.get(i);
3829 if (localLOGV) Slog.v(
3830 TAG, "Record #" + i + " " + r + ": app=" + r.app);
3831 if (r.app == app) {
3832 if (localLOGV) Slog.v(TAG, "Removing this entry!");
3833 list.remove(i);
3834 }
3835 }
3836 }
3837
3838 void removeHistoryRecordsForAppLocked(ProcessRecord app) {
3839 removeHistoryRecordsForAppLocked(mLRUActivities, app);
3840 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003841 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003842 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
3843 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
3844 }
3845
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003846 /**
3847 * Move the current home activity's task (if one exists) to the front
3848 * of the stack.
3849 */
3850 final void moveHomeToFrontLocked() {
3851 TaskRecord homeTask = null;
3852 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003853 ActivityRecord hr = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003854 if (hr.isHomeActivity) {
3855 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003856 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003857 }
3858 }
3859 if (homeTask != null) {
3860 moveTaskToFrontLocked(homeTask, null);
3861 }
3862 }
3863
3864
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003865 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason) {
3866 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
3867
3868 final int task = tr.taskId;
3869 int top = mHistory.size()-1;
3870
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003871 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003872 // nothing to do!
3873 return;
3874 }
3875
Dianne Hackbornbe707852011-11-11 14:32:10 -08003876 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003877
3878 // Applying the affinities may have removed entries from the history,
3879 // so get the size again.
3880 top = mHistory.size()-1;
3881 int pos = top;
3882
3883 // Shift all activities with this task up to the top
3884 // of the stack, keeping them in the same internal order.
3885 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003886 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003887 if (localLOGV) Slog.v(
3888 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003889 if (r.task.taskId == task) {
3890 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003891 if (DEBUG_ADD_REMOVE) {
3892 RuntimeException here = new RuntimeException("here");
3893 here.fillInStackTrace();
3894 Slog.i(TAG, "Removing and adding activity " + r + " to stack at " + top, here);
3895 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003896 mHistory.remove(pos);
3897 mHistory.add(top, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003898 moved.add(0, r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003899 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003900 }
3901 pos--;
3902 }
3903
3904 if (DEBUG_TRANSITION) Slog.v(TAG,
3905 "Prepare to front transition: task=" + tr);
3906 if (reason != null &&
3907 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003908 mService.mWindowManager.prepareAppTransition(
3909 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003910 ActivityRecord r = topRunningActivityLocked(null);
3911 if (r != null) {
3912 mNoAnimActivities.add(r);
3913 }
3914 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003915 mService.mWindowManager.prepareAppTransition(
3916 WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003917 }
3918
3919 mService.mWindowManager.moveAppTokensToTop(moved);
3920 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003921 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003922 }
3923
3924 finishTaskMoveLocked(task);
3925 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
3926 }
3927
3928 private final void finishTaskMoveLocked(int task) {
3929 resumeTopActivityLocked(null);
3930 }
3931
3932 /**
3933 * Worker method for rearranging history stack. Implements the function of moving all
3934 * activities for a specific task (gathering them if disjoint) into a single group at the
3935 * bottom of the stack.
3936 *
3937 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
3938 * to premeptively cancel the move.
3939 *
3940 * @param task The taskId to collect and move to the bottom.
3941 * @return Returns true if the move completed, false if not.
3942 */
3943 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
3944 Slog.i(TAG, "moveTaskToBack: " + task);
3945
3946 // If we have a watcher, preflight the move before committing to it. First check
3947 // for *other* available tasks, but if none are available, then try again allowing the
3948 // current task to be selected.
3949 if (mMainStack && mService.mController != null) {
3950 ActivityRecord next = topRunningActivityLocked(null, task);
3951 if (next == null) {
3952 next = topRunningActivityLocked(null, 0);
3953 }
3954 if (next != null) {
3955 // ask watcher if this is allowed
3956 boolean moveOK = true;
3957 try {
3958 moveOK = mService.mController.activityResuming(next.packageName);
3959 } catch (RemoteException e) {
3960 mService.mController = null;
3961 }
3962 if (!moveOK) {
3963 return false;
3964 }
3965 }
3966 }
3967
Dianne Hackbornbe707852011-11-11 14:32:10 -08003968 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003969
3970 if (DEBUG_TRANSITION) Slog.v(TAG,
3971 "Prepare to back transition: task=" + task);
3972
3973 final int N = mHistory.size();
3974 int bottom = 0;
3975 int pos = 0;
3976
3977 // Shift all activities with this task down to the bottom
3978 // of the stack, keeping them in the same internal order.
3979 while (pos < N) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003980 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003981 if (localLOGV) Slog.v(
3982 TAG, "At " + pos + " ckp " + r.task + ": " + r);
3983 if (r.task.taskId == task) {
3984 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003985 if (DEBUG_ADD_REMOVE) {
3986 RuntimeException here = new RuntimeException("here");
3987 here.fillInStackTrace();
3988 Slog.i(TAG, "Removing and adding activity " + r + " to stack at "
3989 + bottom, here);
3990 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003991 mHistory.remove(pos);
3992 mHistory.add(bottom, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003993 moved.add(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003994 bottom++;
3995 }
3996 pos++;
3997 }
3998
3999 if (reason != null &&
4000 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004001 mService.mWindowManager.prepareAppTransition(
4002 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004003 ActivityRecord r = topRunningActivityLocked(null);
4004 if (r != null) {
4005 mNoAnimActivities.add(r);
4006 }
4007 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004008 mService.mWindowManager.prepareAppTransition(
4009 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004010 }
4011 mService.mWindowManager.moveAppTokensToBottom(moved);
4012 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004013 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004014 }
4015
4016 finishTaskMoveLocked(task);
4017 return true;
4018 }
4019
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004020 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
4021 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4022 ActivityRecord resumed = mResumedActivity;
4023 if (resumed != null && resumed.thumbHolder == tr) {
4024 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
4025 } else {
4026 info.mainThumbnail = tr.lastThumbnail;
4027 }
4028 return info;
4029 }
4030
4031 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex) {
4032 TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
4033 if (info.root == null) {
4034 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
4035 return null;
4036 }
4037
4038 if (subTaskIndex < 0) {
4039 // Just remove the entire task.
4040 performClearTaskAtIndexLocked(taskId, info.rootIndex);
4041 return info.root;
4042 }
4043
4044 if (subTaskIndex >= info.subtasks.size()) {
4045 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
4046 return null;
4047 }
4048
4049 // Remove all of this task's activies starting at the sub task.
4050 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
4051 performClearTaskAtIndexLocked(taskId, subtask.index);
4052 return subtask.activity;
4053 }
4054
4055 public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
4056 ActivityRecord resumed = mResumedActivity;
4057 final TaskAccessInfo thumbs = new TaskAccessInfo();
4058 // How many different sub-thumbnails?
4059 final int NA = mHistory.size();
4060 int j = 0;
4061 ThumbnailHolder holder = null;
4062 while (j < NA) {
4063 ActivityRecord ar = mHistory.get(j);
4064 if (!ar.finishing && ar.task.taskId == taskId) {
4065 holder = ar.thumbHolder;
4066 break;
4067 }
4068 j++;
4069 }
4070
4071 if (j >= NA) {
4072 return thumbs;
4073 }
4074
4075 thumbs.root = mHistory.get(j);
4076 thumbs.rootIndex = j;
4077
4078 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
4079 thumbs.subtasks = subtasks;
4080 ActivityRecord lastActivity = null;
4081 while (j < NA) {
4082 ActivityRecord ar = mHistory.get(j);
4083 j++;
4084 if (ar.finishing) {
4085 continue;
4086 }
4087 if (ar.task.taskId != taskId) {
4088 break;
4089 }
4090 lastActivity = ar;
4091 if (ar.thumbHolder != holder && holder != null) {
4092 thumbs.numSubThumbbails++;
4093 holder = ar.thumbHolder;
4094 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
4095 sub.thumbnail = holder.lastThumbnail;
4096 sub.activity = ar;
4097 sub.index = j-1;
4098 subtasks.add(sub);
4099 }
4100 }
4101 if (lastActivity != null && subtasks.size() > 0) {
4102 if (resumed == lastActivity) {
4103 TaskAccessInfo.SubTask sub = subtasks.get(subtasks.size()-1);
4104 sub.thumbnail = lastActivity.stack.screenshotActivities(lastActivity);
4105 }
4106 }
4107 if (thumbs.numSubThumbbails > 0) {
4108 thumbs.retriever = new IThumbnailRetriever.Stub() {
4109 public Bitmap getThumbnail(int index) {
4110 if (index < 0 || index >= thumbs.subtasks.size()) {
4111 return null;
4112 }
4113 return thumbs.subtasks.get(index).thumbnail;
4114 }
4115 };
4116 }
4117 return thumbs;
4118 }
4119
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004120 private final void logStartActivity(int tag, ActivityRecord r,
4121 TaskRecord task) {
4122 EventLog.writeEvent(tag,
4123 System.identityHashCode(r), task.taskId,
4124 r.shortComponentName, r.intent.getAction(),
4125 r.intent.getType(), r.intent.getDataString(),
4126 r.intent.getFlags());
4127 }
4128
4129 /**
4130 * Make sure the given activity matches the current configuration. Returns
4131 * false if the activity had to be destroyed. Returns true if the
4132 * configuration is the same, or the activity will remain running as-is
4133 * for whatever reason. Ensures the HistoryRecord is updated with the
4134 * correct configuration and all other bookkeeping is handled.
4135 */
4136 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
4137 int globalChanges) {
4138 if (mConfigWillChange) {
4139 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4140 "Skipping config check (will change): " + r);
4141 return true;
4142 }
4143
4144 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4145 "Ensuring correct configuration: " + r);
4146
4147 // Short circuit: if the two configurations are the exact same
4148 // object (the common case), then there is nothing to do.
4149 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004150 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004151 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4152 "Configuration unchanged in " + r);
4153 return true;
4154 }
4155
4156 // We don't worry about activities that are finishing.
4157 if (r.finishing) {
4158 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4159 "Configuration doesn't matter in finishing " + r);
4160 r.stopFreezingScreenLocked(false);
4161 return true;
4162 }
4163
4164 // Okay we now are going to make this activity have the new config.
4165 // But then we need to figure out how it needs to deal with that.
4166 Configuration oldConfig = r.configuration;
4167 r.configuration = newConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004168
4169 // Determine what has changed. May be nothing, if this is a config
4170 // that has come back from the app after going idle. In that case
4171 // we just want to leave the official config object now in the
4172 // activity and do nothing else.
4173 final int changes = oldConfig.diff(newConfig);
4174 if (changes == 0 && !r.forceNewConfig) {
4175 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4176 "Configuration no differences in " + r);
4177 return true;
4178 }
4179
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004180 // If the activity isn't currently running, just leave the new
4181 // configuration and it will pick that up next time it starts.
4182 if (r.app == null || r.app.thread == null) {
4183 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4184 "Configuration doesn't matter not running " + r);
4185 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004186 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004187 return true;
4188 }
4189
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004190 // Figure out how to handle the changes between the configurations.
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004191 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4192 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
4193 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07004194 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004195 + ", newConfig=" + newConfig);
4196 }
Dianne Hackborne6676352011-06-01 16:51:20 -07004197 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004198 // Aha, the activity isn't handling the change, so DIE DIE DIE.
4199 r.configChangeFlags |= changes;
4200 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004201 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004202 if (r.app == null || r.app.thread == null) {
4203 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4204 "Switch is destroying non-running " + r);
Dianne Hackborn28695e02011-11-02 21:59:51 -07004205 destroyActivityLocked(r, true, false, "config");
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004206 } else if (r.state == ActivityState.PAUSING) {
4207 // A little annoying: we are waiting for this activity to
4208 // finish pausing. Let's not do anything now, but just
4209 // flag that it needs to be restarted when done pausing.
4210 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4211 "Switch is skipping already pausing " + r);
4212 r.configDestroy = true;
4213 return true;
4214 } else if (r.state == ActivityState.RESUMED) {
4215 // Try to optimize this case: the configuration is changing
4216 // and we need to restart the top, resumed activity.
4217 // Instead of doing the normal handshaking, just say
4218 // "restart!".
4219 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4220 "Switch is restarting resumed " + r);
4221 relaunchActivityLocked(r, r.configChangeFlags, true);
4222 r.configChangeFlags = 0;
4223 } else {
4224 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4225 "Switch is restarting non-resumed " + r);
4226 relaunchActivityLocked(r, r.configChangeFlags, false);
4227 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004228 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004229
4230 // All done... tell the caller we weren't able to keep this
4231 // activity around.
4232 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004233 }
4234
4235 // Default case: the activity can handle this new configuration, so
4236 // hand it over. Note that we don't need to give it the new
4237 // configuration, since we always send configuration changes to all
4238 // process when they happen so it can just use whatever configuration
4239 // it last got.
4240 if (r.app != null && r.app.thread != null) {
4241 try {
4242 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004243 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004244 } catch (RemoteException e) {
4245 // If process died, whatever.
4246 }
4247 }
4248 r.stopFreezingScreenLocked(false);
4249
4250 return true;
4251 }
4252
4253 private final boolean relaunchActivityLocked(ActivityRecord r,
4254 int changes, boolean andResume) {
4255 List<ResultInfo> results = null;
4256 List<Intent> newIntents = null;
4257 if (andResume) {
4258 results = r.results;
4259 newIntents = r.newIntents;
4260 }
4261 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4262 + " with results=" + results + " newIntents=" + newIntents
4263 + " andResume=" + andResume);
4264 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
4265 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
4266 r.task.taskId, r.shortComponentName);
4267
4268 r.startFreezingScreenLocked(r.app, 0);
4269
4270 try {
4271 if (DEBUG_SWITCH) Slog.i(TAG, "Switch is restarting resumed " + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004272 r.forceNewConfig = false;
Dianne Hackbornbe707852011-11-11 14:32:10 -08004273 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004274 changes, !andResume, new Configuration(mService.mConfiguration));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004275 // Note: don't need to call pauseIfSleepingLocked() here, because
4276 // the caller will only pass in 'andResume' if this activity is
4277 // currently resumed, which implies we aren't sleeping.
4278 } catch (RemoteException e) {
4279 return false;
4280 }
4281
4282 if (andResume) {
4283 r.results = null;
4284 r.newIntents = null;
4285 if (mMainStack) {
4286 mService.reportResumedActivityLocked(r);
4287 }
4288 }
4289
4290 return true;
4291 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004292
4293 public void dismissKeyguardOnNextActivityLocked() {
4294 mDismissKeyguardOnNextActivity = true;
4295 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004296}