blob: 7b8bc26e6e13e8bc64760aade086c67f6f6b4ee5 [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 }
1824 if (target == null) {
1825 target = below;
1826 targetI = i;
1827 // If we were in the middle of a reply chain before this
1828 // task, it doesn't appear like the root of the chain wants
1829 // anything interesting, so drop it.
1830 replyChainEnd = -1;
1831 continue;
1832 }
1833
1834 final int flags = target.info.flags;
1835
1836 final boolean finishOnTaskLaunch =
1837 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1838 final boolean allowTaskReparenting =
1839 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1840
1841 if (target.task == task) {
1842 // We are inside of the task being reset... we'll either
1843 // finish this activity, push it out for another task,
1844 // or leave it as-is. We only do this
1845 // for activities that are not the root of the task (since
1846 // if we finish the root, we may no longer have the task!).
1847 if (taskTopI < 0) {
1848 taskTopI = targetI;
1849 }
1850 if (below != null && below.task == task) {
1851 final boolean clearWhenTaskReset =
1852 (target.intent.getFlags()
1853 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
1854 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
1855 // If this activity is sending a reply to a previous
1856 // activity, we can't do anything with it now until
1857 // we reach the start of the reply chain.
1858 // XXX note that we are assuming the result is always
1859 // to the previous activity, which is almost always
1860 // the case but we really shouldn't count on.
1861 if (replyChainEnd < 0) {
1862 replyChainEnd = targetI;
1863 }
1864 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
1865 && target.taskAffinity != null
1866 && !target.taskAffinity.equals(task.affinity)) {
1867 // If this activity has an affinity for another
1868 // task, then we need to move it out of here. We will
1869 // move it as far out of the way as possible, to the
1870 // bottom of the activity stack. This also keeps it
1871 // correctly ordered with any activities we previously
1872 // moved.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001873 ActivityRecord p = mHistory.get(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001874 if (target.taskAffinity != null
1875 && target.taskAffinity.equals(p.task.affinity)) {
1876 // If the activity currently at the bottom has the
1877 // same task affinity as the one we are moving,
1878 // then merge it into the same task.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001879 target.setTask(p.task, p.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001880 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1881 + " out to bottom task " + p.task);
1882 } else {
1883 mService.mCurTask++;
1884 if (mService.mCurTask <= 0) {
1885 mService.mCurTask = 1;
1886 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001887 target.setTask(new TaskRecord(mService.mCurTask, target.info, null),
1888 null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001889 target.task.affinityIntent = target.intent;
1890 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1891 + " out to new task " + target.task);
1892 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001893 mService.mWindowManager.setAppGroupId(target.appToken, task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001894 if (replyChainEnd < 0) {
1895 replyChainEnd = targetI;
1896 }
1897 int dstPos = 0;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001898 ThumbnailHolder curThumbHolder = target.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001899 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001900 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001901 if (p.finishing) {
1902 continue;
1903 }
1904 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
1905 + " out to target's task " + target.task);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001906 p.setTask(target.task, curThumbHolder, false);
1907 curThumbHolder = p.thumbHolder;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001908 if (DEBUG_ADD_REMOVE) {
1909 RuntimeException here = new RuntimeException("here");
1910 here.fillInStackTrace();
1911 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
1912 + dstPos, here);
1913 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001914 mHistory.remove(srcPos);
1915 mHistory.add(dstPos, p);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001916 mService.mWindowManager.moveAppToken(dstPos, p.appToken);
1917 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001918 dstPos++;
1919 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001920 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001921 }
1922 i++;
1923 }
1924 if (taskTop == p) {
1925 taskTop = below;
1926 }
1927 if (taskTopI == replyChainEnd) {
1928 taskTopI = -1;
1929 }
1930 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001931 } else if (forceReset || finishOnTaskLaunch
1932 || clearWhenTaskReset) {
1933 // If the activity should just be removed -- either
1934 // because it asks for it, or the task should be
1935 // cleared -- then finish it and anything that is
1936 // part of its reply chain.
1937 if (clearWhenTaskReset) {
1938 // In this case, we want to finish this activity
1939 // and everything above it, so be sneaky and pretend
1940 // like these are all in the reply chain.
1941 replyChainEnd = targetI+1;
1942 while (replyChainEnd < mHistory.size() &&
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001943 (mHistory.get(
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001944 replyChainEnd)).task == task) {
1945 replyChainEnd++;
1946 }
1947 replyChainEnd--;
1948 } else if (replyChainEnd < 0) {
1949 replyChainEnd = targetI;
1950 }
1951 ActivityRecord p = null;
1952 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001953 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001954 if (p.finishing) {
1955 continue;
1956 }
1957 if (finishActivityLocked(p, srcPos,
1958 Activity.RESULT_CANCELED, null, "reset")) {
1959 replyChainEnd--;
1960 srcPos--;
1961 }
1962 }
1963 if (taskTop == p) {
1964 taskTop = below;
1965 }
1966 if (taskTopI == replyChainEnd) {
1967 taskTopI = -1;
1968 }
1969 replyChainEnd = -1;
1970 } else {
1971 // If we were in the middle of a chain, well the
1972 // activity that started it all doesn't want anything
1973 // special, so leave it all as-is.
1974 replyChainEnd = -1;
1975 }
1976 } else {
1977 // Reached the bottom of the task -- any reply chain
1978 // should be left as-is.
1979 replyChainEnd = -1;
1980 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08001981
1982 } else if (target.resultTo != null && (below == null
1983 || below.task == target.task)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001984 // If this activity is sending a reply to a previous
1985 // activity, we can't do anything with it now until
1986 // we reach the start of the reply chain.
1987 // XXX note that we are assuming the result is always
1988 // to the previous activity, which is almost always
1989 // the case but we really shouldn't count on.
1990 if (replyChainEnd < 0) {
1991 replyChainEnd = targetI;
1992 }
1993
1994 } else if (taskTopI >= 0 && allowTaskReparenting
1995 && task.affinity != null
1996 && task.affinity.equals(target.taskAffinity)) {
1997 // We are inside of another task... if this activity has
1998 // an affinity for our task, then either remove it if we are
1999 // clearing or move it over to our task. Note that
2000 // we currently punt on the case where we are resetting a
2001 // task that is not at the top but who has activities above
2002 // with an affinity to it... this is really not a normal
2003 // case, and we will need to later pull that task to the front
2004 // and usually at that point we will do the reset and pick
2005 // up those remaining activities. (This only happens if
2006 // someone starts an activity in a new task from an activity
2007 // in a task that is not currently on top.)
2008 if (forceReset || finishOnTaskLaunch) {
2009 if (replyChainEnd < 0) {
2010 replyChainEnd = targetI;
2011 }
2012 ActivityRecord p = null;
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002013 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index "
2014 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002015 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002016 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002017 if (p.finishing) {
2018 continue;
2019 }
2020 if (finishActivityLocked(p, srcPos,
2021 Activity.RESULT_CANCELED, null, "reset")) {
2022 taskTopI--;
2023 lastReparentPos--;
2024 replyChainEnd--;
2025 srcPos--;
2026 }
2027 }
2028 replyChainEnd = -1;
2029 } else {
2030 if (replyChainEnd < 0) {
2031 replyChainEnd = targetI;
2032 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002033 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting task at index "
2034 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002035 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002036 ActivityRecord p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002037 if (p.finishing) {
2038 continue;
2039 }
2040 if (lastReparentPos < 0) {
2041 lastReparentPos = taskTopI;
2042 taskTop = p;
2043 } else {
2044 lastReparentPos--;
2045 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002046 if (DEBUG_ADD_REMOVE) {
2047 RuntimeException here = new RuntimeException("here");
2048 here.fillInStackTrace();
2049 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2050 + lastReparentPos, here);
2051 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002052 mHistory.remove(srcPos);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002053 p.setTask(task, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002054 mHistory.add(lastReparentPos, p);
2055 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002056 + " from " + srcPos + " to " + lastReparentPos
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002057 + " in to resetting task " + task);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002058 mService.mWindowManager.moveAppToken(lastReparentPos, p.appToken);
2059 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002060 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002061 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002062 }
2063 }
2064 replyChainEnd = -1;
2065
2066 // Now we've moved it in to place... but what if this is
2067 // a singleTop activity and we have put it on top of another
2068 // instance of the same activity? Then we drop the instance
2069 // below so it remains singleTop.
2070 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2071 for (int j=lastReparentPos-1; j>=0; j--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002072 ActivityRecord p = mHistory.get(j);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002073 if (p.finishing) {
2074 continue;
2075 }
2076 if (p.intent.getComponent().equals(target.intent.getComponent())) {
2077 if (finishActivityLocked(p, j,
2078 Activity.RESULT_CANCELED, null, "replace")) {
2079 taskTopI--;
2080 lastReparentPos--;
2081 }
2082 }
2083 }
2084 }
2085 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002086
2087 } else if (below != null && below.task != target.task) {
2088 // We hit the botton of a task; the reply chain can't
2089 // pass through it.
2090 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002091 }
2092
2093 target = below;
2094 targetI = i;
2095 }
2096
2097 return taskTop;
2098 }
2099
2100 /**
2101 * Perform clear operation as requested by
2102 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2103 * stack to the given task, then look for
2104 * an instance of that activity in the stack and, if found, finish all
2105 * activities on top of it and return the instance.
2106 *
2107 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002108 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002109 * or null if none was found.
2110 */
2111 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002112 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002113 int i = mHistory.size();
2114
2115 // First find the requested task.
2116 while (i > 0) {
2117 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002118 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002119 if (r.task.taskId == taskId) {
2120 i++;
2121 break;
2122 }
2123 }
2124
2125 // Now clear it.
2126 while (i > 0) {
2127 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002128 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002129 if (r.finishing) {
2130 continue;
2131 }
2132 if (r.task.taskId != taskId) {
2133 return null;
2134 }
2135 if (r.realActivity.equals(newR.realActivity)) {
2136 // Here it is! Now finish everything in front...
2137 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002138 while (i < (mHistory.size()-1)) {
2139 i++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002140 r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002141 if (r.task.taskId != taskId) {
2142 break;
2143 }
2144 if (r.finishing) {
2145 continue;
2146 }
2147 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2148 null, "clear")) {
2149 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002150 }
2151 }
2152
2153 // Finally, if this is a normal launch mode (that is, not
2154 // expecting onNewIntent()), then we will finish the current
2155 // instance of the activity so a new fresh one can be started.
2156 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2157 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
2158 if (!ret.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002159 int index = indexOfTokenLocked(ret.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002160 if (index >= 0) {
2161 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
2162 null, "clear");
2163 }
2164 return null;
2165 }
2166 }
2167
2168 return ret;
2169 }
2170 }
2171
2172 return null;
2173 }
2174
2175 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002176 * Completely remove all activities associated with an existing
2177 * task starting at a specified index.
2178 */
2179 private final void performClearTaskAtIndexLocked(int taskId, int i) {
Dianne Hackborneabd3282011-10-13 16:26:49 -07002180 while (i < mHistory.size()) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002181 ActivityRecord r = mHistory.get(i);
2182 if (r.task.taskId != taskId) {
2183 // Whoops hit the end.
2184 return;
2185 }
2186 if (r.finishing) {
2187 i++;
2188 continue;
2189 }
2190 if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2191 null, "clear")) {
2192 i++;
2193 }
2194 }
2195 }
2196
2197 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002198 * Completely remove all activities associated with an existing task.
2199 */
2200 private final void performClearTaskLocked(int taskId) {
2201 int i = mHistory.size();
2202
2203 // First find the requested task.
2204 while (i > 0) {
2205 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002206 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002207 if (r.task.taskId == taskId) {
2208 i++;
2209 break;
2210 }
2211 }
2212
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002213 // Now find the start and clear it.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002214 while (i > 0) {
2215 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002216 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002217 if (r.finishing) {
2218 continue;
2219 }
2220 if (r.task.taskId != taskId) {
2221 // We hit the bottom. Now finish it all...
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002222 performClearTaskAtIndexLocked(taskId, i+1);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002223 return;
2224 }
2225 }
2226 }
2227
2228 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002229 * Find the activity in the history stack within the given task. Returns
2230 * the index within the history at which it's found, or < 0 if not found.
2231 */
2232 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2233 int i = mHistory.size();
2234 while (i > 0) {
2235 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002236 ActivityRecord candidate = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002237 if (candidate.task.taskId != task) {
2238 break;
2239 }
2240 if (candidate.realActivity.equals(r.realActivity)) {
2241 return i;
2242 }
2243 }
2244
2245 return -1;
2246 }
2247
2248 /**
2249 * Reorder the history stack so that the activity at the given index is
2250 * brought to the front.
2251 */
2252 private final ActivityRecord moveActivityToFrontLocked(int where) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002253 ActivityRecord newTop = mHistory.remove(where);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002254 int top = mHistory.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002255 ActivityRecord oldTop = mHistory.get(top-1);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002256 if (DEBUG_ADD_REMOVE) {
2257 RuntimeException here = new RuntimeException("here");
2258 here.fillInStackTrace();
2259 Slog.i(TAG, "Removing and adding activity " + newTop + " to stack at "
2260 + top, here);
2261 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002262 mHistory.add(top, newTop);
2263 oldTop.frontOfTask = false;
2264 newTop.frontOfTask = true;
2265 return newTop;
2266 }
2267
2268 final int startActivityLocked(IApplicationThread caller,
2269 Intent intent, String resolvedType,
2270 Uri[] grantedUriPermissions,
2271 int grantedMode, ActivityInfo aInfo, IBinder resultTo,
2272 String resultWho, int requestCode,
2273 int callingPid, int callingUid, boolean onlyIfNeeded,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002274 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002275
2276 int err = START_SUCCESS;
2277
2278 ProcessRecord callerApp = null;
2279 if (caller != null) {
2280 callerApp = mService.getRecordForAppLocked(caller);
2281 if (callerApp != null) {
2282 callingPid = callerApp.pid;
2283 callingUid = callerApp.info.uid;
2284 } else {
2285 Slog.w(TAG, "Unable to find app for caller " + caller
2286 + " (pid=" + callingPid + ") when starting: "
2287 + intent.toString());
2288 err = START_PERMISSION_DENIED;
2289 }
2290 }
2291
2292 if (err == START_SUCCESS) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002293 Slog.i(TAG, "START {" + intent.toShortString(true, true, true) + "} from pid "
Dianne Hackbornefb58102010-10-14 16:47:34 -07002294 + (callerApp != null ? callerApp.pid : callingPid));
2295 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002296
2297 ActivityRecord sourceRecord = null;
2298 ActivityRecord resultRecord = null;
2299 if (resultTo != null) {
2300 int index = indexOfTokenLocked(resultTo);
2301 if (DEBUG_RESULTS) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002302 TAG, "Will send result to " + resultTo + " (index " + index + ")");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002303 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002304 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002305 if (requestCode >= 0 && !sourceRecord.finishing) {
2306 resultRecord = sourceRecord;
2307 }
2308 }
2309 }
2310
2311 int launchFlags = intent.getFlags();
2312
2313 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2314 && sourceRecord != null) {
2315 // Transfer the result target from the source activity to the new
2316 // one being started, including any failures.
2317 if (requestCode >= 0) {
2318 return START_FORWARD_AND_REQUEST_CONFLICT;
2319 }
2320 resultRecord = sourceRecord.resultTo;
2321 resultWho = sourceRecord.resultWho;
2322 requestCode = sourceRecord.requestCode;
2323 sourceRecord.resultTo = null;
2324 if (resultRecord != null) {
2325 resultRecord.removeResultsLocked(
2326 sourceRecord, resultWho, requestCode);
2327 }
2328 }
2329
Dianne Hackbornefb58102010-10-14 16:47:34 -07002330 if (err == START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002331 // We couldn't find a class that can handle the given Intent.
2332 // That's the end of that!
2333 err = START_INTENT_NOT_RESOLVED;
2334 }
2335
2336 if (err == START_SUCCESS && aInfo == null) {
2337 // We couldn't find the specific class specified in the Intent.
2338 // Also the end of the line.
2339 err = START_CLASS_NOT_FOUND;
2340 }
2341
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002342 if (err != START_SUCCESS) {
2343 if (resultRecord != null) {
2344 sendActivityResultLocked(-1,
2345 resultRecord, resultWho, requestCode,
2346 Activity.RESULT_CANCELED, null);
2347 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002348 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002349 return err;
2350 }
2351
2352 final int perm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002353 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002354 if (perm != PackageManager.PERMISSION_GRANTED) {
2355 if (resultRecord != null) {
2356 sendActivityResultLocked(-1,
2357 resultRecord, resultWho, requestCode,
2358 Activity.RESULT_CANCELED, null);
2359 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002360 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002361 String msg;
2362 if (!aInfo.exported) {
2363 msg = "Permission Denial: starting " + intent.toString()
2364 + " from " + callerApp + " (pid=" + callingPid
2365 + ", uid=" + callingUid + ")"
2366 + " not exported from uid " + aInfo.applicationInfo.uid;
2367 } else {
2368 msg = "Permission Denial: starting " + intent.toString()
2369 + " from " + callerApp + " (pid=" + callingPid
2370 + ", uid=" + callingUid + ")"
2371 + " requires " + aInfo.permission;
2372 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002373 Slog.w(TAG, msg);
2374 throw new SecurityException(msg);
2375 }
2376
2377 if (mMainStack) {
2378 if (mService.mController != null) {
2379 boolean abort = false;
2380 try {
2381 // The Intent we give to the watcher has the extra data
2382 // stripped off, since it can contain private information.
2383 Intent watchIntent = intent.cloneFilter();
2384 abort = !mService.mController.activityStarting(watchIntent,
2385 aInfo.applicationInfo.packageName);
2386 } catch (RemoteException e) {
2387 mService.mController = null;
2388 }
2389
2390 if (abort) {
2391 if (resultRecord != null) {
2392 sendActivityResultLocked(-1,
2393 resultRecord, resultWho, requestCode,
2394 Activity.RESULT_CANCELED, null);
2395 }
2396 // We pretend to the caller that it was really started, but
2397 // they will just get a cancel result.
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002398 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002399 return START_SUCCESS;
2400 }
2401 }
2402 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002403
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002404 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2405 intent, resolvedType, aInfo, mService.mConfiguration,
2406 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002407 if (outActivity != null) {
2408 outActivity[0] = r;
2409 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002410
2411 if (mMainStack) {
2412 if (mResumedActivity == null
2413 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2414 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2415 PendingActivityLaunch pal = new PendingActivityLaunch();
2416 pal.r = r;
2417 pal.sourceRecord = sourceRecord;
2418 pal.grantedUriPermissions = grantedUriPermissions;
2419 pal.grantedMode = grantedMode;
2420 pal.onlyIfNeeded = onlyIfNeeded;
2421 mService.mPendingActivityLaunches.add(pal);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002422 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002423 return START_SWITCHES_CANCELED;
2424 }
2425 }
2426
2427 if (mService.mDidAppSwitch) {
2428 // This is the second allowed switch since we stopped switches,
2429 // so now just generally allow switches. Use case: user presses
2430 // home (switches disabled, switch to home, mDidAppSwitch now true);
2431 // user taps a home icon (coming from home so allowed, we hit here
2432 // and now allow anyone to switch again).
2433 mService.mAppSwitchesAllowedTime = 0;
2434 } else {
2435 mService.mDidAppSwitch = true;
2436 }
2437
2438 mService.doPendingActivityLaunchesLocked(false);
2439 }
2440
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002441 err = startActivityUncheckedLocked(r, sourceRecord,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002442 grantedUriPermissions, grantedMode, onlyIfNeeded, true);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002443 if (mDismissKeyguardOnNextActivity && mPausingActivity == null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002444 // Someone asked to have the keyguard dismissed on the next
2445 // activity start, but we are not actually doing an activity
2446 // switch... just dismiss the keyguard now, because we
2447 // probably want to see whatever is behind it.
2448 mDismissKeyguardOnNextActivity = false;
2449 mService.mWindowManager.dismissKeyguard();
2450 }
2451 return err;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002452 }
2453
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002454 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2455 if ((launchFlags &
2456 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2457 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2458 // Caller wants to appear on home activity, so before starting
2459 // their own activity we will bring home to the front.
2460 moveHomeToFrontLocked();
2461 }
2462 }
2463
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002464 final int startActivityUncheckedLocked(ActivityRecord r,
2465 ActivityRecord sourceRecord, Uri[] grantedUriPermissions,
2466 int grantedMode, boolean onlyIfNeeded, boolean doResume) {
2467 final Intent intent = r.intent;
2468 final int callingUid = r.launchedFromUid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002469 final int userId = r.userId;
2470
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002471 int launchFlags = intent.getFlags();
2472
2473 // We'll invoke onUserLeaving before onPause only if the launching
2474 // activity did not explicitly state that this is an automated launch.
2475 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2476 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2477 "startActivity() => mUserLeaving=" + mUserLeaving);
2478
2479 // If the caller has asked not to resume at this point, we make note
2480 // of this in the record so that we can skip it when trying to find
2481 // the top running activity.
2482 if (!doResume) {
2483 r.delayedResume = true;
2484 }
2485
2486 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2487 != 0 ? r : null;
2488
2489 // If the onlyIfNeeded flag is set, then we can do this if the activity
2490 // being launched is the same as the one making the call... or, as
2491 // a special case, if we do not know the caller then we count the
2492 // current top activity as the caller.
2493 if (onlyIfNeeded) {
2494 ActivityRecord checkedCaller = sourceRecord;
2495 if (checkedCaller == null) {
2496 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2497 }
2498 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2499 // Caller is not the same as launcher, so always needed.
2500 onlyIfNeeded = false;
2501 }
2502 }
2503
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002504 if (sourceRecord == null) {
2505 // This activity is not being started from another... in this
2506 // case we -always- start a new task.
2507 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2508 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2509 + intent);
2510 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2511 }
2512 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2513 // The original activity who is starting us is running as a single
2514 // instance... this new activity it is starting must go on its
2515 // own task.
2516 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2517 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2518 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2519 // The activity being started is a single instance... it always
2520 // gets launched into its own task.
2521 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2522 }
2523
2524 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2525 // For whatever reason this activity is being launched into a new
2526 // task... yet the caller has requested a result back. Well, that
2527 // is pretty messed up, so instead immediately send back a cancel
2528 // and let the new task continue launched as normal without a
2529 // dependency on its originator.
2530 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2531 sendActivityResultLocked(-1,
2532 r.resultTo, r.resultWho, r.requestCode,
2533 Activity.RESULT_CANCELED, null);
2534 r.resultTo = null;
2535 }
2536
2537 boolean addingToTask = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002538 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002539 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2540 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2541 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2542 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2543 // If bring to front is requested, and no result is requested, and
2544 // we can find a task that was started with this same
2545 // component, then instead of launching bring that one to the front.
2546 if (r.resultTo == null) {
2547 // See if there is a task to bring to the front. If this is
2548 // a SINGLE_INSTANCE activity, there can be one and only one
2549 // instance of it in the history, and it is always in its own
2550 // unique task, so we do a special search.
2551 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2552 ? findTaskLocked(intent, r.info)
2553 : findActivityLocked(intent, r.info);
2554 if (taskTop != null) {
2555 if (taskTop.task.intent == null) {
2556 // This task was started because of movement of
2557 // the activity based on affinity... now that we
2558 // are actually launching it, we can assign the
2559 // base intent.
2560 taskTop.task.setIntent(intent, r.info);
2561 }
2562 // If the target task is not in the front, then we need
2563 // to bring it to the front... except... well, with
2564 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2565 // to have the same behavior as if a new instance was
2566 // being started, which means not bringing it to the front
2567 // if the caller is not itself in the front.
2568 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002569 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002570 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2571 boolean callerAtFront = sourceRecord == null
2572 || curTop.task == sourceRecord.task;
2573 if (callerAtFront) {
2574 // We really do want to push this one into the
2575 // user's face, right now.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002576 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002577 moveTaskToFrontLocked(taskTop.task, r);
2578 }
2579 }
2580 // If the caller has requested that the target task be
2581 // reset, then do so.
2582 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2583 taskTop = resetTaskIfNeededLocked(taskTop, r);
2584 }
2585 if (onlyIfNeeded) {
2586 // We don't need to start a new activity, and
2587 // the client said not to do anything if that
2588 // is the case, so this is it! And for paranoia, make
2589 // sure we have correctly resumed the top activity.
2590 if (doResume) {
2591 resumeTopActivityLocked(null);
2592 }
2593 return START_RETURN_INTENT_TO_CALLER;
2594 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002595 if ((launchFlags &
2596 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2597 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2598 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002599 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002600 // not be too hard...
2601 reuseTask = taskTop.task;
2602 performClearTaskLocked(taskTop.task.taskId);
2603 reuseTask.setIntent(r.intent, r.info);
2604 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002605 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2606 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2607 // In this situation we want to remove all activities
2608 // from the task up to the one being started. In most
2609 // cases this means we are resetting the task to its
2610 // initial state.
2611 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002612 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002613 if (top != null) {
2614 if (top.frontOfTask) {
2615 // Activity aliases may mean we use different
2616 // intents for the top activity, so make sure
2617 // the task now has the identity of the new
2618 // intent.
2619 top.task.setIntent(r.intent, r.info);
2620 }
2621 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002622 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002623 } else {
2624 // A special case: we need to
2625 // start the activity because it is not currently
2626 // running, and the caller has asked to clear the
2627 // current task to have this activity at the top.
2628 addingToTask = true;
2629 // Now pretend like this activity is being started
2630 // by the top of its task, so it is put in the
2631 // right place.
2632 sourceRecord = taskTop;
2633 }
2634 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2635 // In this case the top activity on the task is the
2636 // same as the one being launched, so we take that
2637 // as a request to bring the task to the foreground.
2638 // If the top activity in the task is the root
2639 // activity, deliver this new intent to it if it
2640 // desires.
2641 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2642 && taskTop.realActivity.equals(r.realActivity)) {
2643 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2644 if (taskTop.frontOfTask) {
2645 taskTop.task.setIntent(r.intent, r.info);
2646 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002647 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002648 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2649 // In this case we are launching the root activity
2650 // of the task, but with a different intent. We
2651 // should start a new instance on top.
2652 addingToTask = true;
2653 sourceRecord = taskTop;
2654 }
2655 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2656 // In this case an activity is being launched in to an
2657 // existing task, without resetting that task. This
2658 // is typically the situation of launching an activity
2659 // from a notification or shortcut. We want to place
2660 // the new activity on top of the current task.
2661 addingToTask = true;
2662 sourceRecord = taskTop;
2663 } else if (!taskTop.task.rootWasReset) {
2664 // In this case we are launching in to an existing task
2665 // that has not yet been started from its front door.
2666 // The current task has been brought to the front.
2667 // Ideally, we'd probably like to place this new task
2668 // at the bottom of its stack, but that's a little hard
2669 // to do with the current organization of the code so
2670 // for now we'll just drop it.
2671 taskTop.task.setIntent(r.intent, r.info);
2672 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002673 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002674 // We didn't do anything... but it was needed (a.k.a., client
2675 // don't use that intent!) And for paranoia, make
2676 // sure we have correctly resumed the top activity.
2677 if (doResume) {
2678 resumeTopActivityLocked(null);
2679 }
2680 return START_TASK_TO_FRONT;
2681 }
2682 }
2683 }
2684 }
2685
2686 //String uri = r.intent.toURI();
2687 //Intent intent2 = new Intent(uri);
2688 //Slog.i(TAG, "Given intent: " + r.intent);
2689 //Slog.i(TAG, "URI is: " + uri);
2690 //Slog.i(TAG, "To intent: " + intent2);
2691
2692 if (r.packageName != null) {
2693 // If the activity being launched is the same as the one currently
2694 // at the top, then we need to check if it should only be launched
2695 // once.
2696 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2697 if (top != null && r.resultTo == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002698 if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002699 if (top.app != null && top.app.thread != null) {
2700 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2701 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2702 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2703 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2704 // For paranoia, make sure we have correctly
2705 // resumed the top activity.
2706 if (doResume) {
2707 resumeTopActivityLocked(null);
2708 }
2709 if (onlyIfNeeded) {
2710 // We don't need to start a new activity, and
2711 // the client said not to do anything if that
2712 // is the case, so this is it!
2713 return START_RETURN_INTENT_TO_CALLER;
2714 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002715 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002716 return START_DELIVERED_TO_TOP;
2717 }
2718 }
2719 }
2720 }
2721
2722 } else {
2723 if (r.resultTo != null) {
2724 sendActivityResultLocked(-1,
2725 r.resultTo, r.resultWho, r.requestCode,
2726 Activity.RESULT_CANCELED, null);
2727 }
2728 return START_CLASS_NOT_FOUND;
2729 }
2730
2731 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002732 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002733
2734 // Should this be considered a new task?
2735 if (r.resultTo == null && !addingToTask
2736 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002737 if (reuseTask == null) {
2738 // todo: should do better management of integers.
2739 mService.mCurTask++;
2740 if (mService.mCurTask <= 0) {
2741 mService.mCurTask = 1;
2742 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002743 r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002744 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2745 + " in new task " + r.task);
2746 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002747 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002748 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002749 newTask = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002750 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002751
2752 } else if (sourceRecord != null) {
2753 if (!addingToTask &&
2754 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2755 // In this case, we are adding the activity to an existing
2756 // task, but the caller has asked to clear that task if the
2757 // activity is already running.
2758 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002759 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002760 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002761 if (top != null) {
2762 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002763 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002764 // For paranoia, make sure we have correctly
2765 // resumed the top activity.
2766 if (doResume) {
2767 resumeTopActivityLocked(null);
2768 }
2769 return START_DELIVERED_TO_TOP;
2770 }
2771 } else if (!addingToTask &&
2772 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2773 // In this case, we are launching an activity in our own task
2774 // that may already be running somewhere in the history, and
2775 // we want to shuffle it to the front of the stack if so.
2776 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2777 if (where >= 0) {
2778 ActivityRecord top = moveActivityToFrontLocked(where);
2779 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002780 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002781 if (doResume) {
2782 resumeTopActivityLocked(null);
2783 }
2784 return START_DELIVERED_TO_TOP;
2785 }
2786 }
2787 // An existing activity is starting this new activity, so we want
2788 // to keep the new one in the same task as the one that is starting
2789 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002790 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002791 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2792 + " in existing task " + r.task);
2793
2794 } else {
2795 // This not being started from an existing activity, and not part
2796 // of a new task... just put it in the top task, though these days
2797 // this case should never happen.
2798 final int N = mHistory.size();
2799 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002800 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002801 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002802 ? prev.task
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002803 : new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002804 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2805 + " in new guessed " + r.task);
2806 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002807
2808 if (grantedUriPermissions != null && callingUid > 0) {
2809 for (int i=0; i<grantedUriPermissions.length; i++) {
2810 mService.grantUriPermissionLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002811 grantedUriPermissions[i], grantedMode, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002812 }
2813 }
2814
2815 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002816 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002817
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002818 if (newTask) {
2819 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
2820 }
2821 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002822 startActivityLocked(r, newTask, doResume, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002823 return START_SUCCESS;
2824 }
2825
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002826 ActivityInfo resolveActivity(Intent intent, String resolvedType, boolean debug,
2827 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002828 // Collect information about the target of the Intent.
2829 ActivityInfo aInfo;
2830 try {
2831 ResolveInfo rInfo =
2832 AppGlobals.getPackageManager().resolveIntent(
2833 intent, resolvedType,
2834 PackageManager.MATCH_DEFAULT_ONLY
2835 | ActivityManagerService.STOCK_PM_FLAGS);
2836 aInfo = rInfo != null ? rInfo.activityInfo : null;
2837 } catch (RemoteException e) {
2838 aInfo = null;
2839 }
2840
2841 if (aInfo != null) {
2842 // Store the found target back into the intent, because now that
2843 // we have it we never want to do this again. For example, if the
2844 // user navigates back to this point in the history, we should
2845 // always restart the exact same activity.
2846 intent.setComponent(new ComponentName(
2847 aInfo.applicationInfo.packageName, aInfo.name));
2848
2849 // Don't debug things in the system process
2850 if (debug) {
2851 if (!aInfo.processName.equals("system")) {
2852 mService.setDebugApp(aInfo.processName, true, false);
2853 }
2854 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002855
2856 if (profileFile != null) {
2857 if (!aInfo.processName.equals("system")) {
2858 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
2859 profileFile, profileFd, autoStopProfiler);
2860 }
2861 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002862 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002863 return aInfo;
2864 }
2865
2866 final int startActivityMayWait(IApplicationThread caller, int callingUid,
2867 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2868 int grantedMode, IBinder resultTo,
2869 String resultWho, int requestCode, boolean onlyIfNeeded,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002870 boolean debug, String profileFile, ParcelFileDescriptor profileFd,
Amith Yamasani742a6712011-05-04 14:49:28 -07002871 boolean autoStopProfiler,
2872 WaitResult outResult, Configuration config, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002873 // Refuse possible leaked file descriptors
2874 if (intent != null && intent.hasFileDescriptors()) {
2875 throw new IllegalArgumentException("File descriptors passed in Intent");
2876 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002877 boolean componentSpecified = intent.getComponent() != null;
2878
2879 // Don't modify the client's object!
2880 intent = new Intent(intent);
2881
2882 // Collect information about the target of the Intent.
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002883 ActivityInfo aInfo = resolveActivity(intent, resolvedType, debug,
2884 profileFile, profileFd, autoStopProfiler);
Amith Yamasani742a6712011-05-04 14:49:28 -07002885 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002886
2887 synchronized (mService) {
2888 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002889 if (callingUid >= 0) {
2890 callingPid = -1;
2891 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002892 callingPid = Binder.getCallingPid();
2893 callingUid = Binder.getCallingUid();
2894 } else {
2895 callingPid = callingUid = -1;
2896 }
2897
2898 mConfigWillChange = config != null
2899 && mService.mConfiguration.diff(config) != 0;
2900 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2901 "Starting activity when config will change = " + mConfigWillChange);
2902
2903 final long origId = Binder.clearCallingIdentity();
2904
2905 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07002906 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002907 // This may be a heavy-weight process! Check to see if we already
2908 // have another, different heavy-weight process running.
2909 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
2910 if (mService.mHeavyWeightProcess != null &&
2911 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
2912 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
2913 int realCallingPid = callingPid;
2914 int realCallingUid = callingUid;
2915 if (caller != null) {
2916 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
2917 if (callerApp != null) {
2918 realCallingPid = callerApp.pid;
2919 realCallingUid = callerApp.info.uid;
2920 } else {
2921 Slog.w(TAG, "Unable to find app for caller " + caller
2922 + " (pid=" + realCallingPid + ") when starting: "
2923 + intent.toString());
2924 return START_PERMISSION_DENIED;
2925 }
2926 }
2927
2928 IIntentSender target = mService.getIntentSenderLocked(
2929 IActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002930 realCallingUid, null, null, 0, new Intent[] { intent },
2931 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002932 | PendingIntent.FLAG_ONE_SHOT);
2933
2934 Intent newIntent = new Intent();
2935 if (requestCode >= 0) {
2936 // Caller is requesting a result.
2937 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
2938 }
2939 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
2940 new IntentSender(target));
2941 if (mService.mHeavyWeightProcess.activities.size() > 0) {
2942 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
2943 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
2944 hist.packageName);
2945 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
2946 hist.task.taskId);
2947 }
2948 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
2949 aInfo.packageName);
2950 newIntent.setFlags(intent.getFlags());
2951 newIntent.setClassName("android",
2952 HeavyWeightSwitcherActivity.class.getName());
2953 intent = newIntent;
2954 resolvedType = null;
2955 caller = null;
2956 callingUid = Binder.getCallingUid();
2957 callingPid = Binder.getCallingPid();
2958 componentSpecified = true;
2959 try {
2960 ResolveInfo rInfo =
2961 AppGlobals.getPackageManager().resolveIntent(
2962 intent, null,
2963 PackageManager.MATCH_DEFAULT_ONLY
2964 | ActivityManagerService.STOCK_PM_FLAGS);
2965 aInfo = rInfo != null ? rInfo.activityInfo : null;
Amith Yamasani742a6712011-05-04 14:49:28 -07002966 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002967 } catch (RemoteException e) {
2968 aInfo = null;
2969 }
2970 }
2971 }
2972 }
2973
2974 int res = startActivityLocked(caller, intent, resolvedType,
2975 grantedUriPermissions, grantedMode, aInfo,
2976 resultTo, resultWho, requestCode, callingPid, callingUid,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002977 onlyIfNeeded, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002978
2979 if (mConfigWillChange && mMainStack) {
2980 // If the caller also wants to switch to a new configuration,
2981 // do so now. This allows a clean switch, as we are waiting
2982 // for the current activity to pause (so we will not destroy
2983 // it), and have not yet started the next activity.
2984 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
2985 "updateConfiguration()");
2986 mConfigWillChange = false;
2987 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2988 "Updating to new configuration after starting activity.");
Dianne Hackborn813075a62011-11-14 17:45:19 -08002989 mService.updateConfigurationLocked(config, null, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002990 }
2991
2992 Binder.restoreCallingIdentity(origId);
2993
2994 if (outResult != null) {
2995 outResult.result = res;
2996 if (res == IActivityManager.START_SUCCESS) {
2997 mWaitingActivityLaunched.add(outResult);
2998 do {
2999 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003000 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003001 } catch (InterruptedException e) {
3002 }
3003 } while (!outResult.timeout && outResult.who == null);
3004 } else if (res == IActivityManager.START_TASK_TO_FRONT) {
3005 ActivityRecord r = this.topRunningActivityLocked(null);
3006 if (r.nowVisible) {
3007 outResult.timeout = false;
3008 outResult.who = new ComponentName(r.info.packageName, r.info.name);
3009 outResult.totalTime = 0;
3010 outResult.thisTime = 0;
3011 } else {
3012 outResult.thisTime = SystemClock.uptimeMillis();
3013 mWaitingActivityVisible.add(outResult);
3014 do {
3015 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003016 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003017 } catch (InterruptedException e) {
3018 }
3019 } while (!outResult.timeout && outResult.who == null);
3020 }
3021 }
3022 }
3023
3024 return res;
3025 }
3026 }
3027
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003028 final int startActivities(IApplicationThread caller, int callingUid,
Amith Yamasani742a6712011-05-04 14:49:28 -07003029 Intent[] intents,
3030 String[] resolvedTypes, IBinder resultTo, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003031 if (intents == null) {
3032 throw new NullPointerException("intents is null");
3033 }
3034 if (resolvedTypes == null) {
3035 throw new NullPointerException("resolvedTypes is null");
3036 }
3037 if (intents.length != resolvedTypes.length) {
3038 throw new IllegalArgumentException("intents are length different than resolvedTypes");
3039 }
3040
3041 ActivityRecord[] outActivity = new ActivityRecord[1];
3042
3043 int callingPid;
3044 if (callingUid >= 0) {
3045 callingPid = -1;
3046 } else if (caller == null) {
3047 callingPid = Binder.getCallingPid();
3048 callingUid = Binder.getCallingUid();
3049 } else {
3050 callingPid = callingUid = -1;
3051 }
3052 final long origId = Binder.clearCallingIdentity();
3053 try {
3054 synchronized (mService) {
3055
3056 for (int i=0; i<intents.length; i++) {
3057 Intent intent = intents[i];
3058 if (intent == null) {
3059 continue;
3060 }
3061
3062 // Refuse possible leaked file descriptors
3063 if (intent != null && intent.hasFileDescriptors()) {
3064 throw new IllegalArgumentException("File descriptors passed in Intent");
3065 }
3066
3067 boolean componentSpecified = intent.getComponent() != null;
3068
3069 // Don't modify the client's object!
3070 intent = new Intent(intent);
3071
3072 // Collect information about the target of the Intent.
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003073 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i], false,
3074 null, null, false);
Amith Yamasani742a6712011-05-04 14:49:28 -07003075 // TODO: New, check if this is correct
3076 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003077
3078 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
3079 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
3080 throw new IllegalArgumentException(
3081 "FLAG_CANT_SAVE_STATE not supported here");
3082 }
3083
3084 int res = startActivityLocked(caller, intent, resolvedTypes[i],
3085 null, 0, aInfo, resultTo, null, -1, callingPid, callingUid,
3086 false, componentSpecified, outActivity);
3087 if (res < 0) {
3088 return res;
3089 }
3090
Dianne Hackbornbe707852011-11-11 14:32:10 -08003091 resultTo = outActivity[0] != null ? outActivity[0].appToken : null;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003092 }
3093 }
3094 } finally {
3095 Binder.restoreCallingIdentity(origId);
3096 }
3097
3098 return IActivityManager.START_SUCCESS;
3099 }
3100
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003101 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
3102 long thisTime, long totalTime) {
3103 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
3104 WaitResult w = mWaitingActivityLaunched.get(i);
3105 w.timeout = timeout;
3106 if (r != null) {
3107 w.who = new ComponentName(r.info.packageName, r.info.name);
3108 }
3109 w.thisTime = thisTime;
3110 w.totalTime = totalTime;
3111 }
3112 mService.notifyAll();
3113 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003114
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003115 void reportActivityVisibleLocked(ActivityRecord r) {
3116 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
3117 WaitResult w = mWaitingActivityVisible.get(i);
3118 w.timeout = false;
3119 if (r != null) {
3120 w.who = new ComponentName(r.info.packageName, r.info.name);
3121 }
3122 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
3123 w.thisTime = w.totalTime;
3124 }
3125 mService.notifyAll();
Dianne Hackborn90c52de2011-09-23 12:57:44 -07003126
3127 if (mDismissKeyguardOnNextActivity) {
3128 mDismissKeyguardOnNextActivity = false;
3129 mService.mWindowManager.dismissKeyguard();
3130 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003131 }
3132
3133 void sendActivityResultLocked(int callingUid, ActivityRecord r,
3134 String resultWho, int requestCode, int resultCode, Intent data) {
3135
3136 if (callingUid > 0) {
3137 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003138 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003139 }
3140
3141 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3142 + " : who=" + resultWho + " req=" + requestCode
3143 + " res=" + resultCode + " data=" + data);
3144 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3145 try {
3146 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3147 list.add(new ResultInfo(resultWho, requestCode,
3148 resultCode, data));
Dianne Hackbornbe707852011-11-11 14:32:10 -08003149 r.app.thread.scheduleSendResult(r.appToken, list);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003150 return;
3151 } catch (Exception e) {
3152 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3153 }
3154 }
3155
3156 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3157 }
3158
3159 private final void stopActivityLocked(ActivityRecord r) {
3160 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3161 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3162 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3163 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003164 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003165 "no-history");
3166 }
3167 } else if (r.app != null && r.app.thread != null) {
3168 if (mMainStack) {
3169 if (mService.mFocusedActivity == r) {
3170 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3171 }
3172 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003173 r.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003174 try {
3175 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003176 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3177 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003178 r.state = ActivityState.STOPPING;
3179 if (DEBUG_VISBILITY) Slog.v(
3180 TAG, "Stopping visible=" + r.visible + " for " + r);
3181 if (!r.visible) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003182 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003183 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003184 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003185 if (mService.isSleeping()) {
3186 r.setSleeping(true);
3187 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003188 } catch (Exception e) {
3189 // Maybe just ignore exceptions here... if the process
3190 // has crashed, our death notification will clean things
3191 // up.
3192 Slog.w(TAG, "Exception thrown during pause", e);
3193 // Just in case, assume it to be stopped.
3194 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003195 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003196 r.state = ActivityState.STOPPED;
3197 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003198 destroyActivityLocked(r, true, false, "stop-except");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003199 }
3200 }
3201 }
3202 }
3203
3204 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3205 boolean remove) {
3206 int N = mStoppingActivities.size();
3207 if (N <= 0) return null;
3208
3209 ArrayList<ActivityRecord> stops = null;
3210
3211 final boolean nowVisible = mResumedActivity != null
3212 && mResumedActivity.nowVisible
3213 && !mResumedActivity.waitingVisible;
3214 for (int i=0; i<N; i++) {
3215 ActivityRecord s = mStoppingActivities.get(i);
3216 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3217 + nowVisible + " waitingVisible=" + s.waitingVisible
3218 + " finishing=" + s.finishing);
3219 if (s.waitingVisible && nowVisible) {
3220 mWaitingVisibleActivities.remove(s);
3221 s.waitingVisible = false;
3222 if (s.finishing) {
3223 // If this activity is finishing, it is sitting on top of
3224 // everyone else but we now know it is no longer needed...
3225 // so get rid of it. Otherwise, we need to go through the
3226 // normal flow and hide it once we determine that it is
3227 // hidden by the activities in front of it.
3228 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003229 mService.mWindowManager.setAppVisibility(s.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003230 }
3231 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003232 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003233 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3234 if (stops == null) {
3235 stops = new ArrayList<ActivityRecord>();
3236 }
3237 stops.add(s);
3238 mStoppingActivities.remove(i);
3239 N--;
3240 i--;
3241 }
3242 }
3243
3244 return stops;
3245 }
3246
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003247 final void scheduleIdleLocked() {
3248 Message msg = Message.obtain();
3249 msg.what = IDLE_NOW_MSG;
3250 mHandler.sendMessage(msg);
3251 }
3252
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003253 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003254 Configuration config) {
3255 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3256
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003257 ActivityRecord res = null;
3258
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003259 ArrayList<ActivityRecord> stops = null;
3260 ArrayList<ActivityRecord> finishes = null;
3261 ArrayList<ActivityRecord> thumbnails = null;
3262 int NS = 0;
3263 int NF = 0;
3264 int NT = 0;
3265 IApplicationThread sendThumbnail = null;
3266 boolean booting = false;
3267 boolean enableScreen = false;
3268
3269 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003270 ActivityRecord r = ActivityRecord.forToken(token);
3271 if (r != null) {
3272 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003273 }
3274
3275 // Get the activity record.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003276 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003277 if (index >= 0) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003278 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003279
3280 if (fromTimeout) {
3281 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3282 }
3283
3284 // This is a hack to semi-deal with a race condition
3285 // in the client where it can be constructed with a
3286 // newer configuration from when we asked it to launch.
3287 // We'll update with whatever configuration it now says
3288 // it used to launch.
3289 if (config != null) {
3290 r.configuration = config;
3291 }
3292
3293 // No longer need to keep the device awake.
3294 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3295 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3296 mLaunchingActivity.release();
3297 }
3298
3299 // We are now idle. If someone is waiting for a thumbnail from
3300 // us, we can now deliver.
3301 r.idle = true;
3302 mService.scheduleAppGcsLocked();
3303 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3304 sendThumbnail = r.app.thread;
3305 r.thumbnailNeeded = false;
3306 }
3307
3308 // If this activity is fullscreen, set up to hide those under it.
3309
3310 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3311 ensureActivitiesVisibleLocked(null, 0);
3312
3313 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3314 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003315 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003316 mService.mBooted = true;
3317 enableScreen = true;
3318 }
3319 }
3320
3321 } else if (fromTimeout) {
3322 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3323 }
3324
3325 // Atomically retrieve all of the other things to do.
3326 stops = processStoppingActivitiesLocked(true);
3327 NS = stops != null ? stops.size() : 0;
3328 if ((NF=mFinishingActivities.size()) > 0) {
3329 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3330 mFinishingActivities.clear();
3331 }
3332 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3333 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3334 mService.mCancelledThumbnails.clear();
3335 }
3336
3337 if (mMainStack) {
3338 booting = mService.mBooting;
3339 mService.mBooting = false;
3340 }
3341 }
3342
3343 int i;
3344
3345 // Send thumbnail if requested.
3346 if (sendThumbnail != null) {
3347 try {
3348 sendThumbnail.requestThumbnail(token);
3349 } catch (Exception e) {
3350 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3351 mService.sendPendingThumbnail(null, token, null, null, true);
3352 }
3353 }
3354
3355 // Stop any activities that are scheduled to do so but have been
3356 // waiting for the next one to start.
3357 for (i=0; i<NS; i++) {
3358 ActivityRecord r = (ActivityRecord)stops.get(i);
3359 synchronized (mService) {
3360 if (r.finishing) {
3361 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY);
3362 } else {
3363 stopActivityLocked(r);
3364 }
3365 }
3366 }
3367
3368 // Finish any activities that are scheduled to do so but have been
3369 // waiting for the next one to start.
3370 for (i=0; i<NF; i++) {
3371 ActivityRecord r = (ActivityRecord)finishes.get(i);
3372 synchronized (mService) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003373 destroyActivityLocked(r, true, false, "finish-idle");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003374 }
3375 }
3376
3377 // Report back to any thumbnail receivers.
3378 for (i=0; i<NT; i++) {
3379 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3380 mService.sendPendingThumbnail(r, null, null, null, true);
3381 }
3382
3383 if (booting) {
3384 mService.finishBooting();
3385 }
3386
3387 mService.trimApplications();
3388 //dump();
3389 //mWindowManager.dump();
3390
3391 if (enableScreen) {
3392 mService.enableScreenAfterBoot();
3393 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003394
3395 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003396 }
3397
3398 /**
3399 * @return Returns true if the activity is being finished, false if for
3400 * some reason it is being left as-is.
3401 */
3402 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
3403 Intent resultData, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003404 int index = indexOfTokenLocked(token);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003405 if (DEBUG_RESULTS) Slog.v(
3406 TAG, "Finishing activity @" + index + ": token=" + token
3407 + ", result=" + resultCode + ", data=" + resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003408 if (index < 0) {
3409 return false;
3410 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003411 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003412
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003413 finishActivityLocked(r, index, resultCode, resultData, reason);
3414 return true;
3415 }
3416
3417 /**
3418 * @return Returns true if this activity has been removed from the history
3419 * list, or false if it is still in the list and will be removed later.
3420 */
3421 final boolean finishActivityLocked(ActivityRecord r, int index,
3422 int resultCode, Intent resultData, String reason) {
3423 if (r.finishing) {
3424 Slog.w(TAG, "Duplicate finish request for " + r);
3425 return false;
3426 }
3427
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003428 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003429 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3430 System.identityHashCode(r),
3431 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003432 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003433 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003434 if (next.task == r.task) {
3435 if (r.frontOfTask) {
3436 // The next activity is now the front of the task.
3437 next.frontOfTask = true;
3438 }
3439 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3440 // If the caller asked that this activity (and all above it)
3441 // be cleared when the task is reset, don't lose that information,
3442 // but propagate it up to the next activity.
3443 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3444 }
3445 }
3446 }
3447
3448 r.pauseKeyDispatchingLocked();
3449 if (mMainStack) {
3450 if (mService.mFocusedActivity == r) {
3451 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3452 }
3453 }
3454
3455 // send the result
3456 ActivityRecord resultTo = r.resultTo;
3457 if (resultTo != null) {
3458 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3459 + " who=" + r.resultWho + " req=" + r.requestCode
3460 + " res=" + resultCode + " data=" + resultData);
3461 if (r.info.applicationInfo.uid > 0) {
3462 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
Dianne Hackborna1c69e02010-09-01 22:55:02 -07003463 resultTo.packageName, resultData,
3464 resultTo.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003465 }
3466 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3467 resultData);
3468 r.resultTo = null;
3469 }
3470 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3471
3472 // Make sure this HistoryRecord is not holding on to other resources,
3473 // because clients have remote IPC references to this object so we
3474 // can't assume that will go away and want to avoid circular IPC refs.
3475 r.results = null;
3476 r.pendingResults = null;
3477 r.newIntents = null;
3478 r.icicle = null;
3479
3480 if (mService.mPendingThumbnails.size() > 0) {
3481 // There are clients waiting to receive thumbnails so, in case
3482 // this is an activity that someone is waiting for, add it
3483 // to the pending list so we can correctly update the clients.
3484 mService.mCancelledThumbnails.add(r);
3485 }
3486
3487 if (mResumedActivity == r) {
3488 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003489 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003490 if (DEBUG_TRANSITION) Slog.v(TAG,
3491 "Prepare close transition: finishing " + r);
3492 mService.mWindowManager.prepareAppTransition(endTask
3493 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003494 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003495
3496 // Tell window manager to prepare for this one to be removed.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003497 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003498
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003499 if (mPausingActivity == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003500 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3501 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3502 startPausingLocked(false, false);
3503 }
3504
3505 } else if (r.state != ActivityState.PAUSING) {
3506 // If the activity is PAUSING, we will complete the finish once
3507 // it is done pausing; else we can just directly finish it here.
3508 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3509 return finishCurrentActivityLocked(r, index,
3510 FINISH_AFTER_PAUSE) == null;
3511 } else {
3512 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3513 }
3514
3515 return false;
3516 }
3517
3518 private static final int FINISH_IMMEDIATELY = 0;
3519 private static final int FINISH_AFTER_PAUSE = 1;
3520 private static final int FINISH_AFTER_VISIBLE = 2;
3521
3522 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3523 int mode) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003524 final int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003525 if (index < 0) {
3526 return null;
3527 }
3528
3529 return finishCurrentActivityLocked(r, index, mode);
3530 }
3531
3532 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3533 int index, int mode) {
3534 // First things first: if this activity is currently visible,
3535 // and the resumed activity is not yet visible, then hold off on
3536 // finishing until the resumed one becomes visible.
3537 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3538 if (!mStoppingActivities.contains(r)) {
3539 mStoppingActivities.add(r);
3540 if (mStoppingActivities.size() > 3) {
3541 // If we already have a few activities waiting to stop,
3542 // then give up on things going idle and start clearing
3543 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003544 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003545 } else {
3546 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003547 }
3548 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003549 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3550 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003551 r.state = ActivityState.STOPPING;
3552 mService.updateOomAdjLocked();
3553 return r;
3554 }
3555
3556 // make sure the record is cleaned out of other places.
3557 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003558 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003559 mWaitingVisibleActivities.remove(r);
3560 if (mResumedActivity == r) {
3561 mResumedActivity = null;
3562 }
3563 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003564 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003565 r.state = ActivityState.FINISHING;
3566
3567 if (mode == FINISH_IMMEDIATELY
3568 || prevState == ActivityState.STOPPED
3569 || prevState == ActivityState.INITIALIZING) {
3570 // If this activity is already stopped, we can just finish
3571 // it right now.
Dianne Hackborn28695e02011-11-02 21:59:51 -07003572 return destroyActivityLocked(r, true, true, "finish-imm") ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003573 } else {
3574 // Need to go through the full pause cycle to get this
3575 // activity into the stopped state and then finish it.
3576 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3577 mFinishingActivities.add(r);
3578 resumeTopActivityLocked(null);
3579 }
3580 return r;
3581 }
3582
3583 /**
3584 * Perform the common clean-up of an activity record. This is called both
3585 * as part of destroyActivityLocked() (when destroying the client-side
3586 * representation) and cleaning things up as a result of its hosting
3587 * processing going away, in which case there is no remaining client-side
3588 * state to destroy so only the cleanup here is needed.
3589 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003590 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3591 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003592 if (mResumedActivity == r) {
3593 mResumedActivity = null;
3594 }
3595 if (mService.mFocusedActivity == r) {
3596 mService.mFocusedActivity = null;
3597 }
3598
3599 r.configDestroy = false;
3600 r.frozenBeforeDestroy = false;
3601
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003602 if (setState) {
3603 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3604 r.state = ActivityState.DESTROYED;
3605 }
3606
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003607 // Make sure this record is no longer in the pending finishes list.
3608 // This could happen, for example, if we are trimming activities
3609 // down to the max limit while they are still waiting to finish.
3610 mFinishingActivities.remove(r);
3611 mWaitingVisibleActivities.remove(r);
3612
3613 // Remove any pending results.
3614 if (r.finishing && r.pendingResults != null) {
3615 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3616 PendingIntentRecord rec = apr.get();
3617 if (rec != null) {
3618 mService.cancelIntentSenderLocked(rec, false);
3619 }
3620 }
3621 r.pendingResults = null;
3622 }
3623
3624 if (cleanServices) {
3625 cleanUpActivityServicesLocked(r);
3626 }
3627
3628 if (mService.mPendingThumbnails.size() > 0) {
3629 // There are clients waiting to receive thumbnails so, in case
3630 // this is an activity that someone is waiting for, add it
3631 // to the pending list so we can correctly update the clients.
3632 mService.mCancelledThumbnails.add(r);
3633 }
3634
3635 // Get rid of any pending idle timeouts.
3636 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
3637 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003638 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003639 }
3640
3641 private final void removeActivityFromHistoryLocked(ActivityRecord r) {
3642 if (r.state != ActivityState.DESTROYED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003643 r.makeFinishing();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003644 if (DEBUG_ADD_REMOVE) {
3645 RuntimeException here = new RuntimeException("here");
3646 here.fillInStackTrace();
3647 Slog.i(TAG, "Removing activity " + r + " from stack");
3648 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003649 mHistory.remove(r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003650 r.takeFromHistory();
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003651 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3652 + " (removed from history)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003653 r.state = ActivityState.DESTROYED;
Dianne Hackbornbe707852011-11-11 14:32:10 -08003654 mService.mWindowManager.removeAppToken(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003655 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003656 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003657 }
3658 cleanUpActivityServicesLocked(r);
3659 r.removeUriPermissionsLocked();
3660 }
3661 }
3662
3663 /**
3664 * Perform clean-up of service connections in an activity record.
3665 */
3666 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3667 // Throw away any services that have been bound by this activity.
3668 if (r.connections != null) {
3669 Iterator<ConnectionRecord> it = r.connections.iterator();
3670 while (it.hasNext()) {
3671 ConnectionRecord c = it.next();
3672 mService.removeConnectionLocked(c, null, r);
3673 }
3674 r.connections = null;
3675 }
3676 }
3677
Dianne Hackborn28695e02011-11-02 21:59:51 -07003678 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003679 for (int i=mHistory.size()-1; i>=0; i--) {
3680 ActivityRecord r = mHistory.get(i);
3681 if (owner != null && r.app != owner) {
3682 continue;
3683 }
3684 // We can destroy this one if we have its icicle saved and
3685 // it is not in the process of pausing/stopping/finishing.
3686 if (r.app != null && r.haveState && !r.visible && r.stopped && !r.finishing
3687 && r.state != ActivityState.DESTROYING
3688 && r.state != ActivityState.DESTROYED) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003689 destroyActivityLocked(r, true, oomAdj, "trim");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003690 }
3691 }
3692 }
3693
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003694 /**
3695 * Destroy the current CLIENT SIDE instance of an activity. This may be
3696 * called both when actually finishing an activity, or when performing
3697 * a configuration switch where we destroy the current client-side object
3698 * but then create a new client-side object for this same HistoryRecord.
3699 */
3700 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackborn28695e02011-11-02 21:59:51 -07003701 boolean removeFromApp, boolean oomAdj, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003702 if (DEBUG_SWITCH) Slog.v(
3703 TAG, "Removing activity: token=" + r
3704 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3705 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3706 System.identityHashCode(r),
Dianne Hackborn28695e02011-11-02 21:59:51 -07003707 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003708
3709 boolean removedFromHistory = false;
3710
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003711 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003712
3713 final boolean hadApp = r.app != null;
3714
3715 if (hadApp) {
3716 if (removeFromApp) {
3717 int idx = r.app.activities.indexOf(r);
3718 if (idx >= 0) {
3719 r.app.activities.remove(idx);
3720 }
3721 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
3722 mService.mHeavyWeightProcess = null;
3723 mService.mHandler.sendEmptyMessage(
3724 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
3725 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003726 if (r.app.activities.size() == 0) {
3727 // No longer have activities, so update location in
3728 // LRU list.
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003729 mService.updateLruProcessLocked(r.app, oomAdj, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003730 }
3731 }
3732
3733 boolean skipDestroy = false;
3734
3735 try {
3736 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003737 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003738 r.configChangeFlags);
3739 } catch (Exception e) {
3740 // We can just ignore exceptions here... if the process
3741 // has crashed, our death notification will clean things
3742 // up.
3743 //Slog.w(TAG, "Exception thrown during finish", e);
3744 if (r.finishing) {
3745 removeActivityFromHistoryLocked(r);
3746 removedFromHistory = true;
3747 skipDestroy = true;
3748 }
3749 }
3750
3751 r.app = null;
3752 r.nowVisible = false;
3753
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003754 // If the activity is finishing, we need to wait on removing it
3755 // from the list to give it a chance to do its cleanup. During
3756 // that time it may make calls back with its token so we need to
3757 // be able to find it on the list and so we don't want to remove
3758 // it from the list yet. Otherwise, we can just immediately put
3759 // it in the destroyed state since we are not removing it from the
3760 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003761 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003762 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
3763 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003764 r.state = ActivityState.DESTROYING;
3765 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
3766 msg.obj = r;
3767 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
3768 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003769 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3770 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003771 r.state = ActivityState.DESTROYED;
3772 }
3773 } else {
3774 // remove this record from the history.
3775 if (r.finishing) {
3776 removeActivityFromHistoryLocked(r);
3777 removedFromHistory = true;
3778 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003779 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3780 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003781 r.state = ActivityState.DESTROYED;
3782 }
3783 }
3784
3785 r.configChangeFlags = 0;
3786
3787 if (!mLRUActivities.remove(r) && hadApp) {
3788 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
3789 }
3790
3791 return removedFromHistory;
3792 }
3793
3794 final void activityDestroyed(IBinder token) {
3795 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003796 ActivityRecord r = ActivityRecord.forToken(token);
3797 if (r != null) {
3798 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
3799 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003800
Dianne Hackbornbe707852011-11-11 14:32:10 -08003801 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003802 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003803 if (r.state == ActivityState.DESTROYING) {
3804 final long origId = Binder.clearCallingIdentity();
3805 removeActivityFromHistoryLocked(r);
3806 Binder.restoreCallingIdentity(origId);
3807 }
3808 }
3809 }
3810 }
3811
3812 private static void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
3813 int i = list.size();
3814 if (localLOGV) Slog.v(
3815 TAG, "Removing app " + app + " from list " + list
3816 + " with " + i + " entries");
3817 while (i > 0) {
3818 i--;
3819 ActivityRecord r = (ActivityRecord)list.get(i);
3820 if (localLOGV) Slog.v(
3821 TAG, "Record #" + i + " " + r + ": app=" + r.app);
3822 if (r.app == app) {
3823 if (localLOGV) Slog.v(TAG, "Removing this entry!");
3824 list.remove(i);
3825 }
3826 }
3827 }
3828
3829 void removeHistoryRecordsForAppLocked(ProcessRecord app) {
3830 removeHistoryRecordsForAppLocked(mLRUActivities, app);
3831 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003832 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003833 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
3834 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
3835 }
3836
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003837 /**
3838 * Move the current home activity's task (if one exists) to the front
3839 * of the stack.
3840 */
3841 final void moveHomeToFrontLocked() {
3842 TaskRecord homeTask = null;
3843 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003844 ActivityRecord hr = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003845 if (hr.isHomeActivity) {
3846 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003847 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003848 }
3849 }
3850 if (homeTask != null) {
3851 moveTaskToFrontLocked(homeTask, null);
3852 }
3853 }
3854
3855
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003856 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason) {
3857 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
3858
3859 final int task = tr.taskId;
3860 int top = mHistory.size()-1;
3861
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003862 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003863 // nothing to do!
3864 return;
3865 }
3866
Dianne Hackbornbe707852011-11-11 14:32:10 -08003867 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003868
3869 // Applying the affinities may have removed entries from the history,
3870 // so get the size again.
3871 top = mHistory.size()-1;
3872 int pos = top;
3873
3874 // Shift all activities with this task up to the top
3875 // of the stack, keeping them in the same internal order.
3876 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003877 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003878 if (localLOGV) Slog.v(
3879 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003880 if (r.task.taskId == task) {
3881 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003882 if (DEBUG_ADD_REMOVE) {
3883 RuntimeException here = new RuntimeException("here");
3884 here.fillInStackTrace();
3885 Slog.i(TAG, "Removing and adding activity " + r + " to stack at " + top, here);
3886 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003887 mHistory.remove(pos);
3888 mHistory.add(top, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003889 moved.add(0, r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003890 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003891 }
3892 pos--;
3893 }
3894
3895 if (DEBUG_TRANSITION) Slog.v(TAG,
3896 "Prepare to front transition: task=" + tr);
3897 if (reason != null &&
3898 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003899 mService.mWindowManager.prepareAppTransition(
3900 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003901 ActivityRecord r = topRunningActivityLocked(null);
3902 if (r != null) {
3903 mNoAnimActivities.add(r);
3904 }
3905 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003906 mService.mWindowManager.prepareAppTransition(
3907 WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003908 }
3909
3910 mService.mWindowManager.moveAppTokensToTop(moved);
3911 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003912 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003913 }
3914
3915 finishTaskMoveLocked(task);
3916 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
3917 }
3918
3919 private final void finishTaskMoveLocked(int task) {
3920 resumeTopActivityLocked(null);
3921 }
3922
3923 /**
3924 * Worker method for rearranging history stack. Implements the function of moving all
3925 * activities for a specific task (gathering them if disjoint) into a single group at the
3926 * bottom of the stack.
3927 *
3928 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
3929 * to premeptively cancel the move.
3930 *
3931 * @param task The taskId to collect and move to the bottom.
3932 * @return Returns true if the move completed, false if not.
3933 */
3934 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
3935 Slog.i(TAG, "moveTaskToBack: " + task);
3936
3937 // If we have a watcher, preflight the move before committing to it. First check
3938 // for *other* available tasks, but if none are available, then try again allowing the
3939 // current task to be selected.
3940 if (mMainStack && mService.mController != null) {
3941 ActivityRecord next = topRunningActivityLocked(null, task);
3942 if (next == null) {
3943 next = topRunningActivityLocked(null, 0);
3944 }
3945 if (next != null) {
3946 // ask watcher if this is allowed
3947 boolean moveOK = true;
3948 try {
3949 moveOK = mService.mController.activityResuming(next.packageName);
3950 } catch (RemoteException e) {
3951 mService.mController = null;
3952 }
3953 if (!moveOK) {
3954 return false;
3955 }
3956 }
3957 }
3958
Dianne Hackbornbe707852011-11-11 14:32:10 -08003959 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003960
3961 if (DEBUG_TRANSITION) Slog.v(TAG,
3962 "Prepare to back transition: task=" + task);
3963
3964 final int N = mHistory.size();
3965 int bottom = 0;
3966 int pos = 0;
3967
3968 // Shift all activities with this task down to the bottom
3969 // of the stack, keeping them in the same internal order.
3970 while (pos < N) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003971 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003972 if (localLOGV) Slog.v(
3973 TAG, "At " + pos + " ckp " + r.task + ": " + r);
3974 if (r.task.taskId == task) {
3975 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003976 if (DEBUG_ADD_REMOVE) {
3977 RuntimeException here = new RuntimeException("here");
3978 here.fillInStackTrace();
3979 Slog.i(TAG, "Removing and adding activity " + r + " to stack at "
3980 + bottom, here);
3981 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003982 mHistory.remove(pos);
3983 mHistory.add(bottom, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003984 moved.add(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003985 bottom++;
3986 }
3987 pos++;
3988 }
3989
3990 if (reason != null &&
3991 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003992 mService.mWindowManager.prepareAppTransition(
3993 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003994 ActivityRecord r = topRunningActivityLocked(null);
3995 if (r != null) {
3996 mNoAnimActivities.add(r);
3997 }
3998 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003999 mService.mWindowManager.prepareAppTransition(
4000 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004001 }
4002 mService.mWindowManager.moveAppTokensToBottom(moved);
4003 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004004 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004005 }
4006
4007 finishTaskMoveLocked(task);
4008 return true;
4009 }
4010
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004011 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
4012 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4013 ActivityRecord resumed = mResumedActivity;
4014 if (resumed != null && resumed.thumbHolder == tr) {
4015 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
4016 } else {
4017 info.mainThumbnail = tr.lastThumbnail;
4018 }
4019 return info;
4020 }
4021
4022 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex) {
4023 TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
4024 if (info.root == null) {
4025 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
4026 return null;
4027 }
4028
4029 if (subTaskIndex < 0) {
4030 // Just remove the entire task.
4031 performClearTaskAtIndexLocked(taskId, info.rootIndex);
4032 return info.root;
4033 }
4034
4035 if (subTaskIndex >= info.subtasks.size()) {
4036 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
4037 return null;
4038 }
4039
4040 // Remove all of this task's activies starting at the sub task.
4041 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
4042 performClearTaskAtIndexLocked(taskId, subtask.index);
4043 return subtask.activity;
4044 }
4045
4046 public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
4047 ActivityRecord resumed = mResumedActivity;
4048 final TaskAccessInfo thumbs = new TaskAccessInfo();
4049 // How many different sub-thumbnails?
4050 final int NA = mHistory.size();
4051 int j = 0;
4052 ThumbnailHolder holder = null;
4053 while (j < NA) {
4054 ActivityRecord ar = mHistory.get(j);
4055 if (!ar.finishing && ar.task.taskId == taskId) {
4056 holder = ar.thumbHolder;
4057 break;
4058 }
4059 j++;
4060 }
4061
4062 if (j >= NA) {
4063 return thumbs;
4064 }
4065
4066 thumbs.root = mHistory.get(j);
4067 thumbs.rootIndex = j;
4068
4069 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
4070 thumbs.subtasks = subtasks;
4071 ActivityRecord lastActivity = null;
4072 while (j < NA) {
4073 ActivityRecord ar = mHistory.get(j);
4074 j++;
4075 if (ar.finishing) {
4076 continue;
4077 }
4078 if (ar.task.taskId != taskId) {
4079 break;
4080 }
4081 lastActivity = ar;
4082 if (ar.thumbHolder != holder && holder != null) {
4083 thumbs.numSubThumbbails++;
4084 holder = ar.thumbHolder;
4085 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
4086 sub.thumbnail = holder.lastThumbnail;
4087 sub.activity = ar;
4088 sub.index = j-1;
4089 subtasks.add(sub);
4090 }
4091 }
4092 if (lastActivity != null && subtasks.size() > 0) {
4093 if (resumed == lastActivity) {
4094 TaskAccessInfo.SubTask sub = subtasks.get(subtasks.size()-1);
4095 sub.thumbnail = lastActivity.stack.screenshotActivities(lastActivity);
4096 }
4097 }
4098 if (thumbs.numSubThumbbails > 0) {
4099 thumbs.retriever = new IThumbnailRetriever.Stub() {
4100 public Bitmap getThumbnail(int index) {
4101 if (index < 0 || index >= thumbs.subtasks.size()) {
4102 return null;
4103 }
4104 return thumbs.subtasks.get(index).thumbnail;
4105 }
4106 };
4107 }
4108 return thumbs;
4109 }
4110
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004111 private final void logStartActivity(int tag, ActivityRecord r,
4112 TaskRecord task) {
4113 EventLog.writeEvent(tag,
4114 System.identityHashCode(r), task.taskId,
4115 r.shortComponentName, r.intent.getAction(),
4116 r.intent.getType(), r.intent.getDataString(),
4117 r.intent.getFlags());
4118 }
4119
4120 /**
4121 * Make sure the given activity matches the current configuration. Returns
4122 * false if the activity had to be destroyed. Returns true if the
4123 * configuration is the same, or the activity will remain running as-is
4124 * for whatever reason. Ensures the HistoryRecord is updated with the
4125 * correct configuration and all other bookkeeping is handled.
4126 */
4127 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
4128 int globalChanges) {
4129 if (mConfigWillChange) {
4130 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4131 "Skipping config check (will change): " + r);
4132 return true;
4133 }
4134
4135 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4136 "Ensuring correct configuration: " + r);
4137
4138 // Short circuit: if the two configurations are the exact same
4139 // object (the common case), then there is nothing to do.
4140 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004141 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004142 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4143 "Configuration unchanged in " + r);
4144 return true;
4145 }
4146
4147 // We don't worry about activities that are finishing.
4148 if (r.finishing) {
4149 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4150 "Configuration doesn't matter in finishing " + r);
4151 r.stopFreezingScreenLocked(false);
4152 return true;
4153 }
4154
4155 // Okay we now are going to make this activity have the new config.
4156 // But then we need to figure out how it needs to deal with that.
4157 Configuration oldConfig = r.configuration;
4158 r.configuration = newConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004159
4160 // Determine what has changed. May be nothing, if this is a config
4161 // that has come back from the app after going idle. In that case
4162 // we just want to leave the official config object now in the
4163 // activity and do nothing else.
4164 final int changes = oldConfig.diff(newConfig);
4165 if (changes == 0 && !r.forceNewConfig) {
4166 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4167 "Configuration no differences in " + r);
4168 return true;
4169 }
4170
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004171 // If the activity isn't currently running, just leave the new
4172 // configuration and it will pick that up next time it starts.
4173 if (r.app == null || r.app.thread == null) {
4174 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4175 "Configuration doesn't matter not running " + r);
4176 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004177 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004178 return true;
4179 }
4180
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004181 // Figure out how to handle the changes between the configurations.
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004182 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4183 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
4184 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07004185 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004186 + ", newConfig=" + newConfig);
4187 }
Dianne Hackborne6676352011-06-01 16:51:20 -07004188 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004189 // Aha, the activity isn't handling the change, so DIE DIE DIE.
4190 r.configChangeFlags |= changes;
4191 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004192 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004193 if (r.app == null || r.app.thread == null) {
4194 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4195 "Switch is destroying non-running " + r);
Dianne Hackborn28695e02011-11-02 21:59:51 -07004196 destroyActivityLocked(r, true, false, "config");
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004197 } else if (r.state == ActivityState.PAUSING) {
4198 // A little annoying: we are waiting for this activity to
4199 // finish pausing. Let's not do anything now, but just
4200 // flag that it needs to be restarted when done pausing.
4201 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4202 "Switch is skipping already pausing " + r);
4203 r.configDestroy = true;
4204 return true;
4205 } else if (r.state == ActivityState.RESUMED) {
4206 // Try to optimize this case: the configuration is changing
4207 // and we need to restart the top, resumed activity.
4208 // Instead of doing the normal handshaking, just say
4209 // "restart!".
4210 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4211 "Switch is restarting resumed " + r);
4212 relaunchActivityLocked(r, r.configChangeFlags, true);
4213 r.configChangeFlags = 0;
4214 } else {
4215 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4216 "Switch is restarting non-resumed " + r);
4217 relaunchActivityLocked(r, r.configChangeFlags, false);
4218 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004219 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004220
4221 // All done... tell the caller we weren't able to keep this
4222 // activity around.
4223 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004224 }
4225
4226 // Default case: the activity can handle this new configuration, so
4227 // hand it over. Note that we don't need to give it the new
4228 // configuration, since we always send configuration changes to all
4229 // process when they happen so it can just use whatever configuration
4230 // it last got.
4231 if (r.app != null && r.app.thread != null) {
4232 try {
4233 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004234 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004235 } catch (RemoteException e) {
4236 // If process died, whatever.
4237 }
4238 }
4239 r.stopFreezingScreenLocked(false);
4240
4241 return true;
4242 }
4243
4244 private final boolean relaunchActivityLocked(ActivityRecord r,
4245 int changes, boolean andResume) {
4246 List<ResultInfo> results = null;
4247 List<Intent> newIntents = null;
4248 if (andResume) {
4249 results = r.results;
4250 newIntents = r.newIntents;
4251 }
4252 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4253 + " with results=" + results + " newIntents=" + newIntents
4254 + " andResume=" + andResume);
4255 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
4256 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
4257 r.task.taskId, r.shortComponentName);
4258
4259 r.startFreezingScreenLocked(r.app, 0);
4260
4261 try {
4262 if (DEBUG_SWITCH) Slog.i(TAG, "Switch is restarting resumed " + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004263 r.forceNewConfig = false;
Dianne Hackbornbe707852011-11-11 14:32:10 -08004264 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004265 changes, !andResume, new Configuration(mService.mConfiguration));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004266 // Note: don't need to call pauseIfSleepingLocked() here, because
4267 // the caller will only pass in 'andResume' if this activity is
4268 // currently resumed, which implies we aren't sleeping.
4269 } catch (RemoteException e) {
4270 return false;
4271 }
4272
4273 if (andResume) {
4274 r.results = null;
4275 r.newIntents = null;
4276 if (mMainStack) {
4277 mService.reportResumedActivityLocked(r);
4278 }
4279 }
4280
4281 return true;
4282 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004283
4284 public void dismissKeyguardOnNextActivityLocked() {
4285 mDismissKeyguardOnNextActivity = true;
4286 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004287}