blob: a375d307fe480ba4880470f1dc20a38fb45909fd [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 android.app.IApplicationThread;
29import android.app.PendingIntent;
30import android.app.ResultInfo;
31import android.app.IActivityManager.WaitResult;
32import android.content.ComponentName;
33import android.content.Context;
34import android.content.IIntentSender;
35import android.content.Intent;
36import android.content.IntentSender;
37import android.content.pm.ActivityInfo;
38import android.content.pm.ApplicationInfo;
39import android.content.pm.PackageManager;
40import android.content.pm.ResolveInfo;
41import android.content.res.Configuration;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -080042import android.content.res.Resources;
43import android.graphics.Bitmap;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070044import android.net.Uri;
45import android.os.Binder;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070046import android.os.Bundle;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070047import android.os.Handler;
48import android.os.IBinder;
49import android.os.Message;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070050import android.os.ParcelFileDescriptor;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070051import android.os.PowerManager;
52import android.os.RemoteException;
53import android.os.SystemClock;
Amith Yamasani742a6712011-05-04 14:49:28 -070054import android.os.UserId;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070055import android.util.EventLog;
56import android.util.Log;
57import android.util.Slog;
58import android.view.WindowManagerPolicy;
59
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070060import java.io.IOException;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070061import java.lang.ref.WeakReference;
62import java.util.ArrayList;
63import java.util.Iterator;
64import java.util.List;
65
66/**
67 * State and management of a single stack of activities.
68 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070069final class ActivityStack {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070070 static final String TAG = ActivityManagerService.TAG;
Dianne Hackbornb961cd22011-06-21 12:13:37 -070071 static final boolean localLOGV = ActivityManagerService.localLOGV;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070072 static final boolean DEBUG_SWITCH = ActivityManagerService.DEBUG_SWITCH;
73 static final boolean DEBUG_PAUSE = ActivityManagerService.DEBUG_PAUSE;
74 static final boolean DEBUG_VISBILITY = ActivityManagerService.DEBUG_VISBILITY;
75 static final boolean DEBUG_USER_LEAVING = ActivityManagerService.DEBUG_USER_LEAVING;
76 static final boolean DEBUG_TRANSITION = ActivityManagerService.DEBUG_TRANSITION;
77 static final boolean DEBUG_RESULTS = ActivityManagerService.DEBUG_RESULTS;
78 static final boolean DEBUG_CONFIGURATION = ActivityManagerService.DEBUG_CONFIGURATION;
79 static final boolean DEBUG_TASKS = ActivityManagerService.DEBUG_TASKS;
80
Dianne Hackbornce86ba82011-07-13 19:33:41 -070081 static final boolean DEBUG_STATES = false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070082 static final boolean DEBUG_ADD_REMOVE = false;
83 static final boolean DEBUG_SAVED_STATE = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070084
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070085 static final boolean VALIDATE_TOKENS = ActivityManagerService.VALIDATE_TOKENS;
86
87 // How long we wait until giving up on the last activity telling us it
88 // is idle.
89 static final int IDLE_TIMEOUT = 10*1000;
90
91 // How long we wait until giving up on the last activity to pause. This
92 // is short because it directly impacts the responsiveness of starting the
93 // next activity.
94 static final int PAUSE_TIMEOUT = 500;
95
Dianne Hackborn4eba96b2011-01-21 13:34:36 -080096 // How long we can hold the sleep wake lock before giving up.
97 static final int SLEEP_TIMEOUT = 5*1000;
98
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070099 // How long we can hold the launch wake lock before giving up.
100 static final int LAUNCH_TIMEOUT = 10*1000;
101
102 // How long we wait until giving up on an activity telling us it has
103 // finished destroying itself.
104 static final int DESTROY_TIMEOUT = 10*1000;
105
106 // How long until we reset a task when the user returns to it. Currently
Dianne Hackborn621e17d2010-11-22 15:59:56 -0800107 // disabled.
108 static final long ACTIVITY_INACTIVE_RESET_TIME = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700109
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700110 // How long between activity launches that we consider safe to not warn
111 // the user about an unexpected activity being launched on top.
112 static final long START_WARN_TIME = 5*1000;
113
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700114 // Set to false to disable the preview that is shown while a new activity
115 // is being started.
116 static final boolean SHOW_APP_STARTING_PREVIEW = true;
117
118 enum ActivityState {
119 INITIALIZING,
120 RESUMED,
121 PAUSING,
122 PAUSED,
123 STOPPING,
124 STOPPED,
125 FINISHING,
126 DESTROYING,
127 DESTROYED
128 }
129
130 final ActivityManagerService mService;
131 final boolean mMainStack;
132
133 final Context mContext;
134
135 /**
136 * The back history of all previous (and possibly still
137 * running) activities. It contains HistoryRecord objects.
138 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700139 final ArrayList<ActivityRecord> mHistory = new ArrayList<ActivityRecord>();
Dianne Hackbornbe707852011-11-11 14:32:10 -0800140
141 /**
142 * Used for validating app tokens with window manager.
143 */
144 final ArrayList<IBinder> mValidateAppTokens = new ArrayList<IBinder>();
145
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700146 /**
147 * List of running activities, sorted by recent usage.
148 * The first entry in the list is the least recently used.
149 * It contains HistoryRecord objects.
150 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700151 final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700152
153 /**
154 * List of activities that are waiting for a new activity
155 * to become visible before completing whatever operation they are
156 * supposed to do.
157 */
158 final ArrayList<ActivityRecord> mWaitingVisibleActivities
159 = new ArrayList<ActivityRecord>();
160
161 /**
162 * List of activities that are ready to be stopped, but waiting
163 * for the next activity to settle down before doing so. It contains
164 * HistoryRecord objects.
165 */
166 final ArrayList<ActivityRecord> mStoppingActivities
167 = new ArrayList<ActivityRecord>();
168
169 /**
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800170 * List of activities that are in the process of going to sleep.
171 */
172 final ArrayList<ActivityRecord> mGoingToSleepActivities
173 = new ArrayList<ActivityRecord>();
174
175 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700176 * Animations that for the current transition have requested not to
177 * be considered for the transition animation.
178 */
179 final ArrayList<ActivityRecord> mNoAnimActivities
180 = new ArrayList<ActivityRecord>();
181
182 /**
183 * List of activities that are ready to be finished, but waiting
184 * for the previous activity to settle down before doing so. It contains
185 * HistoryRecord objects.
186 */
187 final ArrayList<ActivityRecord> mFinishingActivities
188 = new ArrayList<ActivityRecord>();
189
190 /**
191 * List of people waiting to find out about the next launched activity.
192 */
193 final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched
194 = new ArrayList<IActivityManager.WaitResult>();
195
196 /**
197 * List of people waiting to find out about the next visible activity.
198 */
199 final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible
200 = new ArrayList<IActivityManager.WaitResult>();
201
202 /**
203 * Set when the system is going to sleep, until we have
204 * successfully paused the current activity and released our wake lock.
205 * At that point the system is allowed to actually sleep.
206 */
207 final PowerManager.WakeLock mGoingToSleep;
208
209 /**
210 * We don't want to allow the device to go to sleep while in the process
211 * of launching an activity. This is primarily to allow alarm intent
212 * receivers to launch an activity and get that to run before the device
213 * goes back to sleep.
214 */
215 final PowerManager.WakeLock mLaunchingActivity;
216
217 /**
218 * When we are in the process of pausing an activity, before starting the
219 * next one, this variable holds the activity that is currently being paused.
220 */
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800221 ActivityRecord mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700222
223 /**
224 * This is the last activity that we put into the paused state. This is
225 * used to determine if we need to do an activity transition while sleeping,
226 * when we normally hold the top activity paused.
227 */
228 ActivityRecord mLastPausedActivity = null;
229
230 /**
231 * Current activity that is resumed, or null if there is none.
232 */
233 ActivityRecord mResumedActivity = null;
234
235 /**
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700236 * This is the last activity that has been started. It is only used to
237 * identify when multiple activities are started at once so that the user
238 * can be warned they may not be in the activity they think they are.
239 */
240 ActivityRecord mLastStartedActivity = null;
241
242 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700243 * Set when we know we are going to be calling updateConfiguration()
244 * soon, so want to skip intermediate config checks.
245 */
246 boolean mConfigWillChange;
247
248 /**
249 * Set to indicate whether to issue an onUserLeaving callback when a
250 * newly launched activity is being brought in front of us.
251 */
252 boolean mUserLeaving = false;
253
254 long mInitialStartTime = 0;
255
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800256 /**
257 * Set when we have taken too long waiting to go to sleep.
258 */
259 boolean mSleepTimeout = false;
260
Dianne Hackborn90c52de2011-09-23 12:57:44 -0700261 /**
262 * Dismiss the keyguard after the next activity is displayed?
263 */
264 boolean mDismissKeyguardOnNextActivity = false;
265
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800266 int mThumbnailWidth = -1;
267 int mThumbnailHeight = -1;
268
Amith Yamasani742a6712011-05-04 14:49:28 -0700269 private int mCurrentUser;
270
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800271 static final int SLEEP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG;
272 static final int PAUSE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 1;
273 static final int IDLE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 2;
274 static final int IDLE_NOW_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 3;
275 static final int LAUNCH_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 4;
276 static final int DESTROY_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 5;
277 static final int RESUME_TOP_ACTIVITY_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 6;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700278
279 final Handler mHandler = new Handler() {
280 //public Handler() {
281 // if (localLOGV) Slog.v(TAG, "Handler started!");
282 //}
283
284 public void handleMessage(Message msg) {
285 switch (msg.what) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800286 case SLEEP_TIMEOUT_MSG: {
Dianne Hackborn8e8d65f2011-08-11 19:36:18 -0700287 synchronized (mService) {
288 if (mService.isSleeping()) {
289 Slog.w(TAG, "Sleep timeout! Sleeping now.");
290 mSleepTimeout = true;
291 checkReadyForSleepLocked();
292 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800293 }
294 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700295 case PAUSE_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800296 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700297 // We don't at this point know if the activity is fullscreen,
298 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800299 Slog.w(TAG, "Activity pause timeout for " + r);
300 activityPaused(r != null ? r.appToken : null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700301 } break;
302 case IDLE_TIMEOUT_MSG: {
303 if (mService.mDidDexOpt) {
304 mService.mDidDexOpt = false;
305 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
306 nmsg.obj = msg.obj;
307 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
308 return;
309 }
310 // We don't at this point know if the activity is fullscreen,
311 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800312 ActivityRecord r = (ActivityRecord)msg.obj;
313 Slog.w(TAG, "Activity idle timeout for " + r);
314 activityIdleInternal(r != null ? r.appToken : null, true, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700315 } break;
316 case DESTROY_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800317 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700318 // We don't at this point know if the activity is fullscreen,
319 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800320 Slog.w(TAG, "Activity destroy timeout for " + r);
321 activityDestroyed(r != null ? r.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700322 } break;
323 case IDLE_NOW_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800324 ActivityRecord r = (ActivityRecord)msg.obj;
325 activityIdleInternal(r != null ? r.appToken : null, false, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700326 } break;
327 case LAUNCH_TIMEOUT_MSG: {
328 if (mService.mDidDexOpt) {
329 mService.mDidDexOpt = false;
330 Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
331 mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
332 return;
333 }
334 synchronized (mService) {
335 if (mLaunchingActivity.isHeld()) {
336 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
337 mLaunchingActivity.release();
338 }
339 }
340 } break;
341 case RESUME_TOP_ACTIVITY_MSG: {
342 synchronized (mService) {
343 resumeTopActivityLocked(null);
344 }
345 } break;
346 }
347 }
348 };
349
350 ActivityStack(ActivityManagerService service, Context context, boolean mainStack) {
351 mService = service;
352 mContext = context;
353 mMainStack = mainStack;
354 PowerManager pm =
355 (PowerManager)context.getSystemService(Context.POWER_SERVICE);
356 mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
357 mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
358 mLaunchingActivity.setReferenceCounted(false);
359 }
360
361 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700362 // TODO: Don't look for any tasks from other users
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700363 int i = mHistory.size()-1;
364 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700365 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700366 if (!r.finishing && r != notTop) {
367 return r;
368 }
369 i--;
370 }
371 return null;
372 }
373
374 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700375 // TODO: Don't look for any tasks from other users
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700376 int i = mHistory.size()-1;
377 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700378 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700379 if (!r.finishing && !r.delayedResume && r != notTop) {
380 return r;
381 }
382 i--;
383 }
384 return null;
385 }
386
387 /**
388 * This is a simplified version of topRunningActivityLocked that provides a number of
389 * optional skip-over modes. It is intended for use with the ActivityController hook only.
390 *
391 * @param token If non-null, any history records matching this token will be skipped.
392 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
393 *
394 * @return Returns the HistoryRecord of the next activity on the stack.
395 */
396 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700397 // TODO: Don't look for any tasks from other users
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700398 int i = mHistory.size()-1;
399 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700400 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700401 // Note: the taskId check depends on real taskId fields being non-zero
Dianne Hackbornbe707852011-11-11 14:32:10 -0800402 if (!r.finishing && (token != r.appToken) && (taskId != r.task.taskId)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700403 return r;
404 }
405 i--;
406 }
407 return null;
408 }
409
410 final int indexOfTokenLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800411 return mHistory.indexOf(ActivityRecord.forToken(token));
412 }
413
414 final int indexOfActivityLocked(ActivityRecord r) {
415 return mHistory.indexOf(r);
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700416 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700417
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700418 final ActivityRecord isInStackLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800419 ActivityRecord r = ActivityRecord.forToken(token);
420 if (mHistory.contains(r)) {
421 return r;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700422 }
423 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700424 }
425
426 private final boolean updateLRUListLocked(ActivityRecord r) {
427 final boolean hadit = mLRUActivities.remove(r);
428 mLRUActivities.add(r);
429 return hadit;
430 }
431
432 /**
433 * Returns the top activity in any existing task matching the given
434 * Intent. Returns null if no such task is found.
435 */
436 private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
437 ComponentName cls = intent.getComponent();
438 if (info.targetActivity != null) {
439 cls = new ComponentName(info.packageName, info.targetActivity);
440 }
441
442 TaskRecord cp = null;
443
Amith Yamasani742a6712011-05-04 14:49:28 -0700444 final int userId = UserId.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700445 final int N = mHistory.size();
446 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700447 ActivityRecord r = mHistory.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -0700448 if (!r.finishing && r.task != cp && r.userId == userId
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700449 && r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
450 cp = r.task;
451 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
452 // + "/aff=" + r.task.affinity + " to new cls="
453 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
454 if (r.task.affinity != null) {
455 if (r.task.affinity.equals(info.taskAffinity)) {
456 //Slog.i(TAG, "Found matching affinity!");
457 return r;
458 }
459 } else if (r.task.intent != null
460 && r.task.intent.getComponent().equals(cls)) {
461 //Slog.i(TAG, "Found matching class!");
462 //dump();
463 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
464 return r;
465 } else if (r.task.affinityIntent != null
466 && r.task.affinityIntent.getComponent().equals(cls)) {
467 //Slog.i(TAG, "Found matching class!");
468 //dump();
469 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
470 return r;
471 }
472 }
473 }
474
475 return null;
476 }
477
478 /**
479 * Returns the first activity (starting from the top of the stack) that
480 * is the same as the given activity. Returns null if no such activity
481 * is found.
482 */
483 private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
484 ComponentName cls = intent.getComponent();
485 if (info.targetActivity != null) {
486 cls = new ComponentName(info.packageName, info.targetActivity);
487 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700488 final int userId = UserId.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700489
490 final int N = mHistory.size();
491 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700492 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700493 if (!r.finishing) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700494 if (r.intent.getComponent().equals(cls) && r.userId == userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700495 //Slog.i(TAG, "Found matching class!");
496 //dump();
497 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
498 return r;
499 }
500 }
501 }
502
503 return null;
504 }
505
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700506 final void showAskCompatModeDialogLocked(ActivityRecord r) {
507 Message msg = Message.obtain();
508 msg.what = ActivityManagerService.SHOW_COMPAT_MODE_DIALOG_MSG;
509 msg.obj = r.task.askedCompatMode ? null : r;
510 mService.mHandler.sendMessage(msg);
511 }
512
Amith Yamasani742a6712011-05-04 14:49:28 -0700513 /*
514 * Move the activities around in the stack to bring a user to the foreground.
515 * @return whether there are any activities for the specified user.
516 */
517 final boolean switchUser(int userId) {
518 synchronized (mService) {
519 mCurrentUser = userId;
520
521 // Only one activity? Nothing to do...
522 if (mHistory.size() < 2)
523 return false;
524
525 boolean haveActivities = false;
526 // Check if the top activity is from the new user.
527 ActivityRecord top = mHistory.get(mHistory.size() - 1);
528 if (top.userId == userId) return true;
529 // Otherwise, move the user's activities to the top.
530 int N = mHistory.size();
531 int i = 0;
532 while (i < N) {
533 ActivityRecord r = mHistory.get(i);
534 if (r.userId == userId) {
535 ActivityRecord moveToTop = mHistory.remove(i);
536 mHistory.add(moveToTop);
537 // No need to check the top one now
538 N--;
539 haveActivities = true;
540 } else {
541 i++;
542 }
543 }
544 // Transition from the old top to the new top
545 resumeTopActivityLocked(top);
546 return haveActivities;
547 }
548 }
549
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700550 final boolean realStartActivityLocked(ActivityRecord r,
551 ProcessRecord app, boolean andResume, boolean checkConfig)
552 throws RemoteException {
553
554 r.startFreezingScreenLocked(app, 0);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800555 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700556
557 // Have the window manager re-evaluate the orientation of
558 // the screen based on the new activity order. Note that
559 // as a result of this, it can call back into the activity
560 // manager with a new orientation. We don't care about that,
561 // because the activity is not currently running so we are
562 // just restarting it anyway.
563 if (checkConfig) {
564 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
565 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -0800566 r.mayFreezeScreenLocked(app) ? r.appToken : null);
Dianne Hackborn813075a62011-11-14 17:45:19 -0800567 mService.updateConfigurationLocked(config, r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700568 }
569
570 r.app = app;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700571 app.waitingToKill = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700572
573 if (localLOGV) Slog.v(TAG, "Launching: " + r);
574
575 int idx = app.activities.indexOf(r);
576 if (idx < 0) {
577 app.activities.add(r);
578 }
579 mService.updateLruProcessLocked(app, true, true);
580
581 try {
582 if (app.thread == null) {
583 throw new RemoteException();
584 }
585 List<ResultInfo> results = null;
586 List<Intent> newIntents = null;
587 if (andResume) {
588 results = r.results;
589 newIntents = r.newIntents;
590 }
591 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
592 + " icicle=" + r.icicle
593 + " with results=" + results + " newIntents=" + newIntents
594 + " andResume=" + andResume);
595 if (andResume) {
596 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
597 System.identityHashCode(r),
598 r.task.taskId, r.shortComponentName);
599 }
600 if (r.isHomeActivity) {
601 mService.mHomeProcess = app;
602 }
603 mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800604 r.sleeping = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400605 r.forceNewConfig = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700606 showAskCompatModeDialogLocked(r);
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700607 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700608 String profileFile = null;
609 ParcelFileDescriptor profileFd = null;
610 boolean profileAutoStop = false;
611 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
612 if (mService.mProfileProc == null || mService.mProfileProc == app) {
613 mService.mProfileProc = app;
614 profileFile = mService.mProfileFile;
615 profileFd = mService.mProfileFd;
616 profileAutoStop = mService.mAutoStopProfiler;
617 }
618 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -0700619 app.hasShownUi = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700620 app.pendingUiClean = true;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700621 if (profileFd != null) {
622 try {
623 profileFd = profileFd.dup();
624 } catch (IOException e) {
625 profileFd = null;
626 }
627 }
Dianne Hackbornbe707852011-11-11 14:32:10 -0800628 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
Dianne Hackborn813075a62011-11-14 17:45:19 -0800629 System.identityHashCode(r), r.info,
630 new Configuration(mService.mConfiguration),
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700631 r.compat, r.icicle, results, newIntents, !andResume,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700632 mService.isNextTransitionForward(), profileFile, profileFd,
633 profileAutoStop);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700634
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700635 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700636 // This may be a heavy-weight process! Note that the package
637 // manager will ensure that only activity can run in the main
638 // process of the .apk, which is the only thing that will be
639 // considered heavy-weight.
640 if (app.processName.equals(app.info.packageName)) {
641 if (mService.mHeavyWeightProcess != null
642 && mService.mHeavyWeightProcess != app) {
643 Log.w(TAG, "Starting new heavy weight process " + app
644 + " when already running "
645 + mService.mHeavyWeightProcess);
646 }
647 mService.mHeavyWeightProcess = app;
648 Message msg = mService.mHandler.obtainMessage(
649 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
650 msg.obj = r;
651 mService.mHandler.sendMessage(msg);
652 }
653 }
654
655 } catch (RemoteException e) {
656 if (r.launchFailed) {
657 // This is the second time we failed -- finish activity
658 // and give up.
659 Slog.e(TAG, "Second failure launching "
660 + r.intent.getComponent().flattenToShortString()
661 + ", giving up", e);
662 mService.appDiedLocked(app, app.pid, app.thread);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800663 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700664 "2nd-crash");
665 return false;
666 }
667
668 // This is the first time we failed -- restart process and
669 // retry.
670 app.activities.remove(r);
671 throw e;
672 }
673
674 r.launchFailed = false;
675 if (updateLRUListLocked(r)) {
676 Slog.w(TAG, "Activity " + r
677 + " being launched, but already in LRU list");
678 }
679
680 if (andResume) {
681 // As part of the process of launching, ActivityThread also performs
682 // a resume.
683 r.state = ActivityState.RESUMED;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700684 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
685 + " (starting new instance)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700686 r.stopped = false;
687 mResumedActivity = r;
688 r.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -0800689 if (mMainStack) {
690 mService.addRecentTaskLocked(r.task);
691 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700692 completeResumeLocked(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800693 checkReadyForSleepLocked();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700694 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Launch completed; removing icicle of " + r.icicle);
695 r.icicle = null;
696 r.haveState = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700697 } else {
698 // This activity is not starting in the resumed state... which
699 // should look like we asked it to pause+stop (but remain visible),
700 // and it has done so and reported back the current icicle and
701 // other state.
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700702 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
703 + " (starting in stopped state)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700704 r.state = ActivityState.STOPPED;
705 r.stopped = true;
706 }
707
708 // Launch the new version setup screen if needed. We do this -after-
709 // launching the initial activity (that is, home), so that it can have
710 // a chance to initialize itself while in the background, making the
711 // switch back to it faster and look better.
712 if (mMainStack) {
713 mService.startSetupActivityLocked();
714 }
715
716 return true;
717 }
718
719 private final void startSpecificActivityLocked(ActivityRecord r,
720 boolean andResume, boolean checkConfig) {
721 // Is this activity's application already running?
722 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
723 r.info.applicationInfo.uid);
724
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700725 if (r.launchTime == 0) {
726 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700727 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700728 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700729 }
730 } else if (mInitialStartTime == 0) {
731 mInitialStartTime = SystemClock.uptimeMillis();
732 }
733
734 if (app != null && app.thread != null) {
735 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700736 app.addPackage(r.info.packageName);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700737 realStartActivityLocked(r, app, andResume, checkConfig);
738 return;
739 } catch (RemoteException e) {
740 Slog.w(TAG, "Exception when starting activity "
741 + r.intent.getComponent().flattenToShortString(), e);
742 }
743
744 // If a dead object exception was thrown -- fall through to
745 // restart the application.
746 }
747
748 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800749 "activity", r.intent.getComponent(), false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700750 }
751
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800752 void stopIfSleepingLocked() {
753 if (mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700754 if (!mGoingToSleep.isHeld()) {
755 mGoingToSleep.acquire();
756 if (mLaunchingActivity.isHeld()) {
757 mLaunchingActivity.release();
758 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
759 }
760 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800761 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
762 Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
763 mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
764 checkReadyForSleepLocked();
765 }
766 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700767
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800768 void awakeFromSleepingLocked() {
769 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
770 mSleepTimeout = false;
771 if (mGoingToSleep.isHeld()) {
772 mGoingToSleep.release();
773 }
774 // Ensure activities are no longer sleeping.
775 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700776 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800777 r.setSleeping(false);
778 }
779 mGoingToSleepActivities.clear();
780 }
781
782 void activitySleptLocked(ActivityRecord r) {
783 mGoingToSleepActivities.remove(r);
784 checkReadyForSleepLocked();
785 }
786
787 void checkReadyForSleepLocked() {
788 if (!mService.isSleeping()) {
789 // Do not care.
790 return;
791 }
792
793 if (!mSleepTimeout) {
794 if (mResumedActivity != null) {
795 // Still have something resumed; can't sleep until it is paused.
796 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700797 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
798 startPausingLocked(false, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800799 return;
800 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800801 if (mPausingActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800802 // Still waiting for something to pause; can't sleep yet.
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800803 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800804 return;
805 }
806
807 if (mStoppingActivities.size() > 0) {
808 // Still need to tell some activities to stop; can't sleep yet.
809 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
810 + mStoppingActivities.size() + " activities");
Dianne Hackborn80a7ac12011-09-22 18:32:52 -0700811 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800812 return;
813 }
814
815 ensureActivitiesVisibleLocked(null, 0);
816
817 // Make sure any stopped but visible activities are now sleeping.
818 // This ensures that the activity's onStop() is called.
819 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700820 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800821 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
822 r.setSleeping(true);
823 }
824 }
825
826 if (mGoingToSleepActivities.size() > 0) {
827 // Still need to tell some activities to sleep; can't sleep yet.
828 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
829 + mGoingToSleepActivities.size() + " activities");
830 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700831 }
832 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800833
834 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
835
836 if (mGoingToSleep.isHeld()) {
837 mGoingToSleep.release();
838 }
839 if (mService.mShuttingDown) {
840 mService.notifyAll();
841 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700842 }
843
Dianne Hackbornd2835932010-12-13 16:28:46 -0800844 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -0800845 if (who.noDisplay) {
846 return null;
847 }
848
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800849 Resources res = mService.mContext.getResources();
850 int w = mThumbnailWidth;
851 int h = mThumbnailHeight;
852 if (w < 0) {
853 mThumbnailWidth = w =
854 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
855 mThumbnailHeight = h =
856 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
857 }
858
859 if (w > 0) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800860 return mService.mWindowManager.screenshotApplications(who.appToken, w, h);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800861 }
862 return null;
863 }
864
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700865 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800866 if (mPausingActivity != null) {
867 RuntimeException e = new RuntimeException();
868 Slog.e(TAG, "Trying to pause when pause is already pending for "
869 + mPausingActivity, e);
870 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700871 ActivityRecord prev = mResumedActivity;
872 if (prev == null) {
873 RuntimeException e = new RuntimeException();
874 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
875 resumeTopActivityLocked(null);
876 return;
877 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700878 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
879 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700880 mResumedActivity = null;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800881 mPausingActivity = prev;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700882 mLastPausedActivity = prev;
883 prev.state = ActivityState.PAUSING;
884 prev.task.touchActiveTime();
Dianne Hackbornf26fd992011-04-08 18:14:09 -0700885 prev.updateThumbnail(screenshotActivities(prev), null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700886
887 mService.updateCpuStats();
888
889 if (prev.app != null && prev.app.thread != null) {
890 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
891 try {
892 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
893 System.identityHashCode(prev),
894 prev.shortComponentName);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800895 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
896 userLeaving, prev.configChangeFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700897 if (mMainStack) {
898 mService.updateUsageStats(prev, false);
899 }
900 } catch (Exception e) {
901 // Ignore exception, if process died other code will cleanup.
902 Slog.w(TAG, "Exception thrown during pause", e);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800903 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700904 mLastPausedActivity = null;
905 }
906 } else {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800907 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700908 mLastPausedActivity = null;
909 }
910
911 // If we are not going to sleep, we want to ensure the device is
912 // awake until the next activity is started.
913 if (!mService.mSleeping && !mService.mShuttingDown) {
914 mLaunchingActivity.acquire();
915 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
916 // To be safe, don't allow the wake lock to be held for too long.
917 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
918 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
919 }
920 }
921
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800922
923 if (mPausingActivity != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700924 // Have the window manager pause its key dispatching until the new
925 // activity has started. If we're pausing the activity just because
926 // the screen is being turned off and the UI is sleeping, don't interrupt
927 // key dispatch; the same activity will pick it up again on wakeup.
928 if (!uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800929 prev.pauseKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700930 } else {
931 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
932 }
933
934 // Schedule a pause timeout in case the app doesn't respond.
935 // We don't give it much time because this directly impacts the
936 // responsiveness seen by the user.
937 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
938 msg.obj = prev;
939 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
940 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
941 } else {
942 // This activity failed to schedule the
943 // pause, so just treat it as being paused now.
944 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800945 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700946 }
947 }
948
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800949 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700950 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800951 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700952
953 ActivityRecord r = null;
954
955 synchronized (mService) {
956 int index = indexOfTokenLocked(token);
957 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700958 r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700959 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800960 if (mPausingActivity == r) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700961 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
962 + (timeout ? " (due to timeout)" : " (pause complete)"));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700963 r.state = ActivityState.PAUSED;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800964 completePauseLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700965 } else {
966 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
967 System.identityHashCode(r), r.shortComponentName,
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800968 mPausingActivity != null
969 ? mPausingActivity.shortComponentName : "(none)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700970 }
971 }
972 }
973 }
974
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700975 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
976 CharSequence description) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700977 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Saving icicle of " + r + ": " + icicle);
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700978 r.icicle = icicle;
979 r.haveState = true;
980 r.updateThumbnail(thumbnail, description);
981 r.stopped = true;
982 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
983 r.state = ActivityState.STOPPED;
984 if (!r.finishing) {
985 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -0700986 destroyActivityLocked(r, true, false, "stop-config");
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700987 resumeTopActivityLocked(null);
Dianne Hackborn50685602011-12-01 12:23:37 -0800988 } else {
989 // Now that this process has stopped, we may want to consider
990 // it to be the previous app to try to keep around in case
991 // the user wants to return to it.
992 ProcessRecord fgApp = null;
993 if (mResumedActivity != null) {
994 fgApp = mResumedActivity.app;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800995 } else if (mPausingActivity != null) {
996 fgApp = mPausingActivity.app;
Dianne Hackborn50685602011-12-01 12:23:37 -0800997 }
998 if (r.app != null && fgApp != null && r.app != fgApp
999 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
1000 && r.app != mService.mHomeProcess) {
1001 mService.mPreviousProcess = r.app;
1002 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
1003 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001004 }
1005 }
1006 }
1007
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001008 private final void completePauseLocked() {
1009 ActivityRecord prev = mPausingActivity;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001010 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
1011
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001012 if (prev != null) {
1013 if (prev.finishing) {
1014 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
1015 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE);
1016 } else if (prev.app != null) {
1017 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
1018 if (prev.waitingVisible) {
1019 prev.waitingVisible = false;
1020 mWaitingVisibleActivities.remove(prev);
1021 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
1022 TAG, "Complete pause, no longer waiting: " + prev);
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001023 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001024 if (prev.configDestroy) {
1025 // The previous is being paused because the configuration
1026 // is changing, which means it is actually stopping...
1027 // To juggle the fact that we are also starting a new
1028 // instance right now, we need to first completely stop
1029 // the current instance before starting the new one.
1030 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
1031 destroyActivityLocked(prev, true, false, "pause-config");
1032 } else {
1033 mStoppingActivities.add(prev);
1034 if (mStoppingActivities.size() > 3) {
1035 // If we already have a few activities waiting to stop,
1036 // then give up on things going idle and start clearing
1037 // them out.
1038 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
1039 scheduleIdleLocked();
1040 } else {
1041 checkReadyForSleepLocked();
1042 }
1043 }
1044 } else {
1045 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
1046 prev = null;
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001047 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001048 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001049 }
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001050
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001051 if (!mService.isSleeping()) {
1052 resumeTopActivityLocked(prev);
1053 } else {
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001054 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001055 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001056
1057 if (prev != null) {
1058 prev.resumeKeyDispatchingLocked();
1059 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001060
1061 if (prev.app != null && prev.cpuTimeAtResume > 0
1062 && mService.mBatteryStatsService.isOnBattery()) {
1063 long diff = 0;
1064 synchronized (mService.mProcessStatsThread) {
1065 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
1066 - prev.cpuTimeAtResume;
1067 }
1068 if (diff > 0) {
1069 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
1070 synchronized (bsi) {
1071 BatteryStatsImpl.Uid.Proc ps =
1072 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
1073 prev.info.packageName);
1074 if (ps != null) {
1075 ps.addForegroundTimeLocked(diff);
1076 }
1077 }
1078 }
1079 }
1080 prev.cpuTimeAtResume = 0; // reset it
1081 }
1082
1083 /**
1084 * Once we know that we have asked an application to put an activity in
1085 * the resumed state (either by launching it or explicitly telling it),
1086 * this function updates the rest of our state to match that fact.
1087 */
1088 private final void completeResumeLocked(ActivityRecord next) {
1089 next.idle = false;
1090 next.results = null;
1091 next.newIntents = null;
1092
1093 // schedule an idle timeout in case the app doesn't do it for us.
1094 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1095 msg.obj = next;
1096 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
1097
1098 if (false) {
1099 // The activity was never told to pause, so just keep
1100 // things going as-is. To maintain our own state,
1101 // we need to emulate it coming back and saying it is
1102 // idle.
1103 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
1104 msg.obj = next;
1105 mHandler.sendMessage(msg);
1106 }
1107
1108 if (mMainStack) {
1109 mService.reportResumedActivityLocked(next);
1110 }
1111
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001112 next.clearThumbnail();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001113 if (mMainStack) {
1114 mService.setFocusedActivityLocked(next);
1115 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001116 next.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001117 ensureActivitiesVisibleLocked(null, 0);
1118 mService.mWindowManager.executeAppTransition();
1119 mNoAnimActivities.clear();
1120
1121 // Mark the point when the activity is resuming
1122 // TODO: To be more accurate, the mark should be before the onCreate,
1123 // not after the onResume. But for subsequent starts, onResume is fine.
1124 if (next.app != null) {
1125 synchronized (mService.mProcessStatsThread) {
1126 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1127 }
1128 } else {
1129 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1130 }
1131 }
1132
1133 /**
1134 * Make sure that all activities that need to be visible (that is, they
1135 * currently can be seen by the user) actually are.
1136 */
1137 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1138 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1139 if (DEBUG_VISBILITY) Slog.v(
1140 TAG, "ensureActivitiesVisible behind " + top
1141 + " configChanges=0x" + Integer.toHexString(configChanges));
1142
1143 // If the top activity is not fullscreen, then we need to
1144 // make sure any activities under it are now visible.
1145 final int count = mHistory.size();
1146 int i = count-1;
1147 while (mHistory.get(i) != top) {
1148 i--;
1149 }
1150 ActivityRecord r;
1151 boolean behindFullscreen = false;
1152 for (; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001153 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001154 if (DEBUG_VISBILITY) Slog.v(
1155 TAG, "Make visible? " + r + " finishing=" + r.finishing
1156 + " state=" + r.state);
1157 if (r.finishing) {
1158 continue;
1159 }
1160
1161 final boolean doThisProcess = onlyThisProcess == null
1162 || onlyThisProcess.equals(r.processName);
1163
1164 // First: if this is not the current activity being started, make
1165 // sure it matches the current configuration.
1166 if (r != starting && doThisProcess) {
1167 ensureActivityConfigurationLocked(r, 0);
1168 }
1169
1170 if (r.app == null || r.app.thread == null) {
1171 if (onlyThisProcess == null
1172 || onlyThisProcess.equals(r.processName)) {
1173 // This activity needs to be visible, but isn't even
1174 // running... get it started, but don't resume it
1175 // at this point.
1176 if (DEBUG_VISBILITY) Slog.v(
1177 TAG, "Start and freeze screen for " + r);
1178 if (r != starting) {
1179 r.startFreezingScreenLocked(r.app, configChanges);
1180 }
1181 if (!r.visible) {
1182 if (DEBUG_VISBILITY) Slog.v(
1183 TAG, "Starting and making visible: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001184 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001185 }
1186 if (r != starting) {
1187 startSpecificActivityLocked(r, false, false);
1188 }
1189 }
1190
1191 } else if (r.visible) {
1192 // If this activity is already visible, then there is nothing
1193 // else to do here.
1194 if (DEBUG_VISBILITY) Slog.v(
1195 TAG, "Skipping: already visible at " + r);
1196 r.stopFreezingScreenLocked(false);
1197
1198 } else if (onlyThisProcess == null) {
1199 // This activity is not currently visible, but is running.
1200 // Tell it to become visible.
1201 r.visible = true;
1202 if (r.state != ActivityState.RESUMED && r != starting) {
1203 // If this activity is paused, tell it
1204 // to now show its window.
1205 if (DEBUG_VISBILITY) Slog.v(
1206 TAG, "Making visible and scheduling visibility: " + r);
1207 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001208 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001209 r.sleeping = false;
Dianne Hackborn905577f2011-09-07 18:31:28 -07001210 r.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001211 r.app.thread.scheduleWindowVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001212 r.stopFreezingScreenLocked(false);
1213 } catch (Exception e) {
1214 // Just skip on any failure; we'll make it
1215 // visible when it next restarts.
1216 Slog.w(TAG, "Exception thrown making visibile: "
1217 + r.intent.getComponent(), e);
1218 }
1219 }
1220 }
1221
1222 // Aggregate current change flags.
1223 configChanges |= r.configChangeFlags;
1224
1225 if (r.fullscreen) {
1226 // At this point, nothing else needs to be shown
1227 if (DEBUG_VISBILITY) Slog.v(
1228 TAG, "Stopping: fullscreen at " + r);
1229 behindFullscreen = true;
1230 i--;
1231 break;
1232 }
1233 }
1234
1235 // Now for any activities that aren't visible to the user, make
1236 // sure they no longer are keeping the screen frozen.
1237 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001238 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001239 if (DEBUG_VISBILITY) Slog.v(
1240 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1241 + " state=" + r.state
1242 + " behindFullscreen=" + behindFullscreen);
1243 if (!r.finishing) {
1244 if (behindFullscreen) {
1245 if (r.visible) {
1246 if (DEBUG_VISBILITY) Slog.v(
1247 TAG, "Making invisible: " + r);
1248 r.visible = false;
1249 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001250 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001251 if ((r.state == ActivityState.STOPPING
1252 || r.state == ActivityState.STOPPED)
1253 && r.app != null && r.app.thread != null) {
1254 if (DEBUG_VISBILITY) Slog.v(
1255 TAG, "Scheduling invisibility: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001256 r.app.thread.scheduleWindowVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001257 }
1258 } catch (Exception e) {
1259 // Just skip on any failure; we'll make it
1260 // visible when it next restarts.
1261 Slog.w(TAG, "Exception thrown making hidden: "
1262 + r.intent.getComponent(), e);
1263 }
1264 } else {
1265 if (DEBUG_VISBILITY) Slog.v(
1266 TAG, "Already invisible: " + r);
1267 }
1268 } else if (r.fullscreen) {
1269 if (DEBUG_VISBILITY) Slog.v(
1270 TAG, "Now behindFullscreen: " + r);
1271 behindFullscreen = true;
1272 }
1273 }
1274 i--;
1275 }
1276 }
1277
1278 /**
1279 * Version of ensureActivitiesVisible that can easily be called anywhere.
1280 */
1281 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1282 int configChanges) {
1283 ActivityRecord r = topRunningActivityLocked(null);
1284 if (r != null) {
1285 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1286 }
1287 }
1288
1289 /**
1290 * Ensure that the top activity in the stack is resumed.
1291 *
1292 * @param prev The previously resumed activity, for when in the process
1293 * of pausing; can be null to call from elsewhere.
1294 *
1295 * @return Returns true if something is being resumed, or false if
1296 * nothing happened.
1297 */
1298 final boolean resumeTopActivityLocked(ActivityRecord prev) {
1299 // Find the first activity that is not finishing.
1300 ActivityRecord next = topRunningActivityLocked(null);
1301
1302 // Remember how we'll process this pause/resume situation, and ensure
1303 // that the state is reset however we wind up proceeding.
1304 final boolean userLeaving = mUserLeaving;
1305 mUserLeaving = false;
1306
1307 if (next == null) {
1308 // There are no more activities! Let's just start up the
1309 // Launcher...
1310 if (mMainStack) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001311 return mService.startHomeActivityLocked(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001312 }
1313 }
1314
1315 next.delayedResume = false;
1316
1317 // If the top activity is the resumed one, nothing to do.
1318 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1319 // Make sure we have executed any pending transitions, since there
1320 // should be nothing left to do at this point.
1321 mService.mWindowManager.executeAppTransition();
1322 mNoAnimActivities.clear();
1323 return false;
1324 }
1325
1326 // If we are sleeping, and there is no resumed activity, and the top
1327 // activity is paused, well that is the state we want.
1328 if ((mService.mSleeping || mService.mShuttingDown)
1329 && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
1330 // Make sure we have executed any pending transitions, since there
1331 // should be nothing left to do at this point.
1332 mService.mWindowManager.executeAppTransition();
1333 mNoAnimActivities.clear();
1334 return false;
1335 }
1336
1337 // The activity may be waiting for stop, but that is no longer
1338 // appropriate for it.
1339 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001340 mGoingToSleepActivities.remove(next);
1341 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001342 mWaitingVisibleActivities.remove(next);
1343
1344 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1345
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001346 // If we are currently pausing an activity, then don't do anything
1347 // until that is done.
1348 if (mPausingActivity != null) {
1349 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
1350 return false;
1351 }
1352
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001353 // Okay we are now going to start a switch, to 'next'. We may first
1354 // have to pause the current activity, but this is an important point
1355 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001356 // XXX "App Redirected" dialog is getting too many false positives
1357 // at this point, so turn off for now.
1358 if (false) {
1359 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1360 long now = SystemClock.uptimeMillis();
1361 final boolean inTime = mLastStartedActivity.startTime != 0
1362 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1363 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1364 final int nextUid = next.info.applicationInfo.uid;
1365 if (inTime && lastUid != nextUid
1366 && lastUid != next.launchedFromUid
1367 && mService.checkPermission(
1368 android.Manifest.permission.STOP_APP_SWITCHES,
1369 -1, next.launchedFromUid)
1370 != PackageManager.PERMISSION_GRANTED) {
1371 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1372 } else {
1373 next.startTime = now;
1374 mLastStartedActivity = next;
1375 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001376 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001377 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001378 mLastStartedActivity = next;
1379 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001380 }
1381
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001382 // We need to start pausing the current activity so the top one
1383 // can be resumed...
1384 if (mResumedActivity != null) {
1385 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
1386 startPausingLocked(userLeaving, false);
1387 return true;
1388 }
1389
1390 if (prev != null && prev != next) {
1391 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1392 prev.waitingVisible = true;
1393 mWaitingVisibleActivities.add(prev);
1394 if (DEBUG_SWITCH) Slog.v(
1395 TAG, "Resuming top, waiting visible to hide: " + prev);
1396 } else {
1397 // The next activity is already visible, so hide the previous
1398 // activity's windows right now so we can show the new one ASAP.
1399 // We only do this if the previous is finishing, which should mean
1400 // it is on top of the one being resumed so hiding it quickly
1401 // is good. Otherwise, we want to do the normal route of allowing
1402 // the resumed activity to be shown so we can decide if the
1403 // previous should actually be hidden depending on whether the
1404 // new one is found to be full-screen or not.
1405 if (prev.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001406 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001407 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1408 + prev + ", waitingVisible="
1409 + (prev != null ? prev.waitingVisible : null)
1410 + ", nowVisible=" + next.nowVisible);
1411 } else {
1412 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1413 + prev + ", waitingVisible="
1414 + (prev != null ? prev.waitingVisible : null)
1415 + ", nowVisible=" + next.nowVisible);
1416 }
1417 }
1418 }
1419
Dianne Hackborne7f97212011-02-24 14:40:20 -08001420 // Launching this app's activity, make sure the app is no longer
1421 // considered stopped.
1422 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07001423 // TODO: Apply to the correct userId
Dianne Hackborne7f97212011-02-24 14:40:20 -08001424 AppGlobals.getPackageManager().setPackageStoppedState(
1425 next.packageName, false);
1426 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001427 } catch (IllegalArgumentException e) {
1428 Slog.w(TAG, "Failed trying to unstop package "
1429 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001430 }
1431
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001432 // We are starting up the next activity, so tell the window manager
1433 // that the previous one will be hidden soon. This way it can know
1434 // to ignore it when computing the desired screen orientation.
1435 if (prev != null) {
1436 if (prev.finishing) {
1437 if (DEBUG_TRANSITION) Slog.v(TAG,
1438 "Prepare close transition: prev=" + prev);
1439 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001440 mService.mWindowManager.prepareAppTransition(
1441 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001442 } else {
1443 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1444 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001445 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001446 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001447 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1448 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001449 } else {
1450 if (DEBUG_TRANSITION) Slog.v(TAG,
1451 "Prepare open transition: prev=" + prev);
1452 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001453 mService.mWindowManager.prepareAppTransition(
1454 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001455 } else {
1456 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1457 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001458 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001459 }
1460 }
1461 if (false) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001462 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1463 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001464 }
1465 } else if (mHistory.size() > 1) {
1466 if (DEBUG_TRANSITION) Slog.v(TAG,
1467 "Prepare open transition: no previous");
1468 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001469 mService.mWindowManager.prepareAppTransition(
1470 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001471 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001472 mService.mWindowManager.prepareAppTransition(
1473 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001474 }
1475 }
1476
1477 if (next.app != null && next.app.thread != null) {
1478 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1479
1480 // This activity is now becoming visible.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001481 mService.mWindowManager.setAppVisibility(next.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001482
1483 ActivityRecord lastResumedActivity = mResumedActivity;
1484 ActivityState lastState = next.state;
1485
1486 mService.updateCpuStats();
1487
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001488 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001489 next.state = ActivityState.RESUMED;
1490 mResumedActivity = next;
1491 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001492 if (mMainStack) {
1493 mService.addRecentTaskLocked(next.task);
1494 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001495 mService.updateLruProcessLocked(next.app, true, true);
1496 updateLRUListLocked(next);
1497
1498 // Have the window manager re-evaluate the orientation of
1499 // the screen based on the new activity order.
1500 boolean updated = false;
1501 if (mMainStack) {
1502 synchronized (mService) {
1503 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1504 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001505 next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001506 if (config != null) {
1507 next.frozenBeforeDestroy = true;
1508 }
Dianne Hackborn813075a62011-11-14 17:45:19 -08001509 updated = mService.updateConfigurationLocked(config, next, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001510 }
1511 }
1512 if (!updated) {
1513 // The configuration update wasn't able to keep the existing
1514 // instance of the activity, and instead started a new one.
1515 // We should be all done, but let's just make sure our activity
1516 // is still at the top and schedule another run if something
1517 // weird happened.
1518 ActivityRecord nextNext = topRunningActivityLocked(null);
1519 if (DEBUG_SWITCH) Slog.i(TAG,
1520 "Activity config changed during resume: " + next
1521 + ", new next: " + nextNext);
1522 if (nextNext != next) {
1523 // Do over!
1524 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1525 }
1526 if (mMainStack) {
1527 mService.setFocusedActivityLocked(next);
1528 }
1529 ensureActivitiesVisibleLocked(null, 0);
1530 mService.mWindowManager.executeAppTransition();
1531 mNoAnimActivities.clear();
1532 return true;
1533 }
1534
1535 try {
1536 // Deliver all pending results.
1537 ArrayList a = next.results;
1538 if (a != null) {
1539 final int N = a.size();
1540 if (!next.finishing && N > 0) {
1541 if (DEBUG_RESULTS) Slog.v(
1542 TAG, "Delivering results to " + next
1543 + ": " + a);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001544 next.app.thread.scheduleSendResult(next.appToken, a);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001545 }
1546 }
1547
1548 if (next.newIntents != null) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001549 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001550 }
1551
1552 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
1553 System.identityHashCode(next),
1554 next.task.taskId, next.shortComponentName);
1555
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001556 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001557 showAskCompatModeDialogLocked(next);
Dianne Hackborn905577f2011-09-07 18:31:28 -07001558 next.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001559 next.app.thread.scheduleResumeActivity(next.appToken,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001560 mService.isNextTransitionForward());
1561
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001562 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001563
1564 } catch (Exception e) {
1565 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001566 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1567 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001568 next.state = lastState;
1569 mResumedActivity = lastResumedActivity;
1570 Slog.i(TAG, "Restarting because process died: " + next);
1571 if (!next.hasBeenLaunched) {
1572 next.hasBeenLaunched = true;
1573 } else {
1574 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1575 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001576 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001577 mService.compatibilityInfoForPackageLocked(
1578 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001579 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001580 next.labelRes, next.icon, next.windowFlags,
1581 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001582 }
1583 }
1584 startSpecificActivityLocked(next, true, false);
1585 return true;
1586 }
1587
1588 // From this point on, if something goes wrong there is no way
1589 // to recover the activity.
1590 try {
1591 next.visible = true;
1592 completeResumeLocked(next);
1593 } catch (Exception e) {
1594 // If any exception gets thrown, toss away this
1595 // activity and try the next one.
1596 Slog.w(TAG, "Exception thrown during resume of " + next, e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001597 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001598 "resume-exception");
1599 return true;
1600 }
1601
1602 // Didn't need to use the icicle, and it is now out of date.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001603 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Resumed activity; didn't need icicle of: " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001604 next.icicle = null;
1605 next.haveState = false;
1606 next.stopped = false;
1607
1608 } else {
1609 // Whoops, need to restart this activity!
1610 if (!next.hasBeenLaunched) {
1611 next.hasBeenLaunched = true;
1612 } else {
1613 if (SHOW_APP_STARTING_PREVIEW) {
1614 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001615 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001616 mService.compatibilityInfoForPackageLocked(
1617 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001618 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001619 next.labelRes, next.icon, next.windowFlags,
1620 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001621 }
1622 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1623 }
1624 startSpecificActivityLocked(next, true, true);
1625 }
1626
1627 return true;
1628 }
1629
1630 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001631 boolean doResume, boolean keepCurTransition) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001632 final int NH = mHistory.size();
1633
1634 int addPos = -1;
1635
1636 if (!newTask) {
1637 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001638 boolean startIt = true;
1639 for (int i = NH-1; i >= 0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001640 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001641 if (p.finishing) {
1642 continue;
1643 }
1644 if (p.task == r.task) {
1645 // Here it is! Now, if this is not yet visible to the
1646 // user, then just add it without starting; it will
1647 // get started when the user navigates back to it.
1648 addPos = i+1;
1649 if (!startIt) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001650 if (DEBUG_ADD_REMOVE) {
1651 RuntimeException here = new RuntimeException("here");
1652 here.fillInStackTrace();
1653 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos,
1654 here);
1655 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001656 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001657 r.putInHistory();
Dianne Hackbornbe707852011-11-11 14:32:10 -08001658 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001659 r.info.screenOrientation, r.fullscreen);
1660 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001661 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001662 }
1663 return;
1664 }
1665 break;
1666 }
1667 if (p.fullscreen) {
1668 startIt = false;
1669 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001670 }
1671 }
1672
1673 // Place a new activity at top of stack, so it is next to interact
1674 // with the user.
1675 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001676 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001677 }
1678
1679 // If we are not placing the new activity frontmost, we do not want
1680 // to deliver the onUserLeaving callback to the actual frontmost
1681 // activity
1682 if (addPos < NH) {
1683 mUserLeaving = false;
1684 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1685 }
1686
1687 // Slot the activity into the history stack and proceed
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001688 if (DEBUG_ADD_REMOVE) {
1689 RuntimeException here = new RuntimeException("here");
1690 here.fillInStackTrace();
1691 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos, here);
1692 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001693 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001694 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001695 r.frontOfTask = newTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001696 if (NH > 0) {
1697 // We want to show the starting preview window if we are
1698 // switching to a new task, or the next activity's process is
1699 // not currently running.
1700 boolean showStartingIcon = newTask;
1701 ProcessRecord proc = r.app;
1702 if (proc == null) {
1703 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1704 }
1705 if (proc == null || proc.thread == null) {
1706 showStartingIcon = true;
1707 }
1708 if (DEBUG_TRANSITION) Slog.v(TAG,
1709 "Prepare open transition: starting " + r);
1710 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001711 mService.mWindowManager.prepareAppTransition(
1712 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001713 mNoAnimActivities.add(r);
1714 } else if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
1715 mService.mWindowManager.prepareAppTransition(
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001716 WindowManagerPolicy.TRANSIT_TASK_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001717 mNoAnimActivities.remove(r);
1718 } else {
1719 mService.mWindowManager.prepareAppTransition(newTask
1720 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001721 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001722 mNoAnimActivities.remove(r);
1723 }
1724 mService.mWindowManager.addAppToken(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001725 addPos, r.appToken, r.task.taskId, r.info.screenOrientation, r.fullscreen);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001726 boolean doShow = true;
1727 if (newTask) {
1728 // Even though this activity is starting fresh, we still need
1729 // to reset it to make sure we apply affinities to move any
1730 // existing activities from other tasks in to it.
1731 // If the caller has requested that the target task be
1732 // reset, then do so.
1733 if ((r.intent.getFlags()
1734 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1735 resetTaskIfNeededLocked(r, r);
1736 doShow = topRunningNonDelayedActivityLocked(null) == r;
1737 }
1738 }
1739 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1740 // Figure out if we are transitioning from another activity that is
1741 // "has the same starting icon" as the next one. This allows the
1742 // window manager to keep the previous window it had previously
1743 // created, if it still had one.
1744 ActivityRecord prev = mResumedActivity;
1745 if (prev != null) {
1746 // We don't want to reuse the previous starting preview if:
1747 // (1) The current activity is in a different task.
1748 if (prev.task != r.task) prev = null;
1749 // (2) The current activity is already displayed.
1750 else if (prev.nowVisible) prev = null;
1751 }
1752 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001753 r.appToken, r.packageName, r.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001754 mService.compatibilityInfoForPackageLocked(
1755 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001756 r.labelRes, r.icon, r.windowFlags,
1757 prev != null ? prev.appToken : null, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001758 }
1759 } else {
1760 // If this is the first activity, don't do any fancy animations,
1761 // because there is nothing for it to animate on top of.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001762 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001763 r.info.screenOrientation, r.fullscreen);
1764 }
1765 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001766 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001767 }
1768
1769 if (doResume) {
1770 resumeTopActivityLocked(null);
1771 }
1772 }
1773
Dianne Hackbornbe707852011-11-11 14:32:10 -08001774 final void validateAppTokensLocked() {
1775 mValidateAppTokens.clear();
1776 mValidateAppTokens.ensureCapacity(mHistory.size());
1777 for (int i=0; i<mHistory.size(); i++) {
1778 mValidateAppTokens.add(mHistory.get(i).appToken);
1779 }
1780 mService.mWindowManager.validateAppTokens(mValidateAppTokens);
1781 }
1782
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001783 /**
1784 * Perform a reset of the given task, if needed as part of launching it.
1785 * Returns the new HistoryRecord at the top of the task.
1786 */
1787 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1788 ActivityRecord newActivity) {
1789 boolean forceReset = (newActivity.info.flags
1790 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001791 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1792 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001793 if ((newActivity.info.flags
1794 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1795 forceReset = true;
1796 }
1797 }
1798
1799 final TaskRecord task = taskTop.task;
1800
1801 // We are going to move through the history list so that we can look
1802 // at each activity 'target' with 'below' either the interesting
1803 // activity immediately below it in the stack or null.
1804 ActivityRecord target = null;
1805 int targetI = 0;
1806 int taskTopI = -1;
1807 int replyChainEnd = -1;
1808 int lastReparentPos = -1;
1809 for (int i=mHistory.size()-1; i>=-1; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001810 ActivityRecord below = i >= 0 ? mHistory.get(i) : null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001811
1812 if (below != null && below.finishing) {
1813 continue;
1814 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001815 // Don't check any lower in the stack if we're crossing a user boundary.
1816 if (below != null && below.userId != taskTop.userId) {
1817 break;
1818 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001819 if (target == null) {
1820 target = below;
1821 targetI = i;
1822 // If we were in the middle of a reply chain before this
1823 // task, it doesn't appear like the root of the chain wants
1824 // anything interesting, so drop it.
1825 replyChainEnd = -1;
1826 continue;
1827 }
1828
1829 final int flags = target.info.flags;
1830
1831 final boolean finishOnTaskLaunch =
1832 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1833 final boolean allowTaskReparenting =
1834 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1835
1836 if (target.task == task) {
1837 // We are inside of the task being reset... we'll either
1838 // finish this activity, push it out for another task,
1839 // or leave it as-is. We only do this
1840 // for activities that are not the root of the task (since
1841 // if we finish the root, we may no longer have the task!).
1842 if (taskTopI < 0) {
1843 taskTopI = targetI;
1844 }
1845 if (below != null && below.task == task) {
1846 final boolean clearWhenTaskReset =
1847 (target.intent.getFlags()
1848 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
1849 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
1850 // If this activity is sending a reply to a previous
1851 // activity, we can't do anything with it now until
1852 // we reach the start of the reply chain.
1853 // XXX note that we are assuming the result is always
1854 // to the previous activity, which is almost always
1855 // the case but we really shouldn't count on.
1856 if (replyChainEnd < 0) {
1857 replyChainEnd = targetI;
1858 }
1859 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
1860 && target.taskAffinity != null
1861 && !target.taskAffinity.equals(task.affinity)) {
1862 // If this activity has an affinity for another
1863 // task, then we need to move it out of here. We will
1864 // move it as far out of the way as possible, to the
1865 // bottom of the activity stack. This also keeps it
1866 // correctly ordered with any activities we previously
1867 // moved.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001868 ActivityRecord p = mHistory.get(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001869 if (target.taskAffinity != null
1870 && target.taskAffinity.equals(p.task.affinity)) {
1871 // If the activity currently at the bottom has the
1872 // same task affinity as the one we are moving,
1873 // then merge it into the same task.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001874 target.setTask(p.task, p.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001875 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1876 + " out to bottom task " + p.task);
1877 } else {
1878 mService.mCurTask++;
1879 if (mService.mCurTask <= 0) {
1880 mService.mCurTask = 1;
1881 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001882 target.setTask(new TaskRecord(mService.mCurTask, target.info, null),
1883 null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001884 target.task.affinityIntent = target.intent;
1885 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1886 + " out to new task " + target.task);
1887 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001888 mService.mWindowManager.setAppGroupId(target.appToken, task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001889 if (replyChainEnd < 0) {
1890 replyChainEnd = targetI;
1891 }
1892 int dstPos = 0;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001893 ThumbnailHolder curThumbHolder = target.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001894 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001895 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001896 if (p.finishing) {
1897 continue;
1898 }
1899 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
1900 + " out to target's task " + target.task);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001901 p.setTask(target.task, curThumbHolder, false);
1902 curThumbHolder = p.thumbHolder;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001903 if (DEBUG_ADD_REMOVE) {
1904 RuntimeException here = new RuntimeException("here");
1905 here.fillInStackTrace();
1906 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
1907 + dstPos, here);
1908 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001909 mHistory.remove(srcPos);
1910 mHistory.add(dstPos, p);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001911 mService.mWindowManager.moveAppToken(dstPos, p.appToken);
1912 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001913 dstPos++;
1914 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001915 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001916 }
1917 i++;
1918 }
1919 if (taskTop == p) {
1920 taskTop = below;
1921 }
1922 if (taskTopI == replyChainEnd) {
1923 taskTopI = -1;
1924 }
1925 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001926 } else if (forceReset || finishOnTaskLaunch
1927 || clearWhenTaskReset) {
1928 // If the activity should just be removed -- either
1929 // because it asks for it, or the task should be
1930 // cleared -- then finish it and anything that is
1931 // part of its reply chain.
1932 if (clearWhenTaskReset) {
1933 // In this case, we want to finish this activity
1934 // and everything above it, so be sneaky and pretend
1935 // like these are all in the reply chain.
1936 replyChainEnd = targetI+1;
1937 while (replyChainEnd < mHistory.size() &&
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001938 (mHistory.get(
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001939 replyChainEnd)).task == task) {
1940 replyChainEnd++;
1941 }
1942 replyChainEnd--;
1943 } else if (replyChainEnd < 0) {
1944 replyChainEnd = targetI;
1945 }
1946 ActivityRecord p = null;
1947 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001948 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001949 if (p.finishing) {
1950 continue;
1951 }
1952 if (finishActivityLocked(p, srcPos,
1953 Activity.RESULT_CANCELED, null, "reset")) {
1954 replyChainEnd--;
1955 srcPos--;
1956 }
1957 }
1958 if (taskTop == p) {
1959 taskTop = below;
1960 }
1961 if (taskTopI == replyChainEnd) {
1962 taskTopI = -1;
1963 }
1964 replyChainEnd = -1;
1965 } else {
1966 // If we were in the middle of a chain, well the
1967 // activity that started it all doesn't want anything
1968 // special, so leave it all as-is.
1969 replyChainEnd = -1;
1970 }
1971 } else {
1972 // Reached the bottom of the task -- any reply chain
1973 // should be left as-is.
1974 replyChainEnd = -1;
1975 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08001976
1977 } else if (target.resultTo != null && (below == null
1978 || below.task == target.task)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001979 // If this activity is sending a reply to a previous
1980 // activity, we can't do anything with it now until
1981 // we reach the start of the reply chain.
1982 // XXX note that we are assuming the result is always
1983 // to the previous activity, which is almost always
1984 // the case but we really shouldn't count on.
1985 if (replyChainEnd < 0) {
1986 replyChainEnd = targetI;
1987 }
1988
1989 } else if (taskTopI >= 0 && allowTaskReparenting
1990 && task.affinity != null
1991 && task.affinity.equals(target.taskAffinity)) {
1992 // We are inside of another task... if this activity has
1993 // an affinity for our task, then either remove it if we are
1994 // clearing or move it over to our task. Note that
1995 // we currently punt on the case where we are resetting a
1996 // task that is not at the top but who has activities above
1997 // with an affinity to it... this is really not a normal
1998 // case, and we will need to later pull that task to the front
1999 // and usually at that point we will do the reset and pick
2000 // up those remaining activities. (This only happens if
2001 // someone starts an activity in a new task from an activity
2002 // in a task that is not currently on top.)
2003 if (forceReset || finishOnTaskLaunch) {
2004 if (replyChainEnd < 0) {
2005 replyChainEnd = targetI;
2006 }
2007 ActivityRecord p = null;
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002008 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index "
2009 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002010 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002011 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002012 if (p.finishing) {
2013 continue;
2014 }
2015 if (finishActivityLocked(p, srcPos,
2016 Activity.RESULT_CANCELED, null, "reset")) {
2017 taskTopI--;
2018 lastReparentPos--;
2019 replyChainEnd--;
2020 srcPos--;
2021 }
2022 }
2023 replyChainEnd = -1;
2024 } else {
2025 if (replyChainEnd < 0) {
2026 replyChainEnd = targetI;
2027 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002028 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting task at index "
2029 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002030 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002031 ActivityRecord p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002032 if (p.finishing) {
2033 continue;
2034 }
2035 if (lastReparentPos < 0) {
2036 lastReparentPos = taskTopI;
2037 taskTop = p;
2038 } else {
2039 lastReparentPos--;
2040 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002041 if (DEBUG_ADD_REMOVE) {
2042 RuntimeException here = new RuntimeException("here");
2043 here.fillInStackTrace();
2044 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2045 + lastReparentPos, here);
2046 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002047 mHistory.remove(srcPos);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002048 p.setTask(task, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002049 mHistory.add(lastReparentPos, p);
2050 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002051 + " from " + srcPos + " to " + lastReparentPos
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002052 + " in to resetting task " + task);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002053 mService.mWindowManager.moveAppToken(lastReparentPos, p.appToken);
2054 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002055 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002056 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002057 }
2058 }
2059 replyChainEnd = -1;
2060
2061 // Now we've moved it in to place... but what if this is
2062 // a singleTop activity and we have put it on top of another
2063 // instance of the same activity? Then we drop the instance
2064 // below so it remains singleTop.
2065 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2066 for (int j=lastReparentPos-1; j>=0; j--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002067 ActivityRecord p = mHistory.get(j);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002068 if (p.finishing) {
2069 continue;
2070 }
2071 if (p.intent.getComponent().equals(target.intent.getComponent())) {
2072 if (finishActivityLocked(p, j,
2073 Activity.RESULT_CANCELED, null, "replace")) {
2074 taskTopI--;
2075 lastReparentPos--;
2076 }
2077 }
2078 }
2079 }
2080 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002081
2082 } else if (below != null && below.task != target.task) {
2083 // We hit the botton of a task; the reply chain can't
2084 // pass through it.
2085 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002086 }
2087
2088 target = below;
2089 targetI = i;
2090 }
2091
2092 return taskTop;
2093 }
2094
2095 /**
2096 * Perform clear operation as requested by
2097 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2098 * stack to the given task, then look for
2099 * an instance of that activity in the stack and, if found, finish all
2100 * activities on top of it and return the instance.
2101 *
2102 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002103 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002104 * or null if none was found.
2105 */
2106 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002107 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002108 int i = mHistory.size();
2109
2110 // First find the requested task.
2111 while (i > 0) {
2112 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002113 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002114 if (r.task.taskId == taskId) {
2115 i++;
2116 break;
2117 }
2118 }
2119
2120 // Now clear it.
2121 while (i > 0) {
2122 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002123 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002124 if (r.finishing) {
2125 continue;
2126 }
2127 if (r.task.taskId != taskId) {
2128 return null;
2129 }
2130 if (r.realActivity.equals(newR.realActivity)) {
2131 // Here it is! Now finish everything in front...
2132 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002133 while (i < (mHistory.size()-1)) {
2134 i++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002135 r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002136 if (r.task.taskId != taskId) {
2137 break;
2138 }
2139 if (r.finishing) {
2140 continue;
2141 }
2142 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2143 null, "clear")) {
2144 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002145 }
2146 }
2147
2148 // Finally, if this is a normal launch mode (that is, not
2149 // expecting onNewIntent()), then we will finish the current
2150 // instance of the activity so a new fresh one can be started.
2151 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2152 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
2153 if (!ret.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002154 int index = indexOfTokenLocked(ret.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002155 if (index >= 0) {
2156 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
2157 null, "clear");
2158 }
2159 return null;
2160 }
2161 }
2162
2163 return ret;
2164 }
2165 }
2166
2167 return null;
2168 }
2169
2170 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002171 * Completely remove all activities associated with an existing
2172 * task starting at a specified index.
2173 */
2174 private final void performClearTaskAtIndexLocked(int taskId, int i) {
Dianne Hackborneabd3282011-10-13 16:26:49 -07002175 while (i < mHistory.size()) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002176 ActivityRecord r = mHistory.get(i);
2177 if (r.task.taskId != taskId) {
2178 // Whoops hit the end.
2179 return;
2180 }
2181 if (r.finishing) {
2182 i++;
2183 continue;
2184 }
2185 if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2186 null, "clear")) {
2187 i++;
2188 }
2189 }
2190 }
2191
2192 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002193 * Completely remove all activities associated with an existing task.
2194 */
2195 private final void performClearTaskLocked(int taskId) {
2196 int i = mHistory.size();
2197
2198 // First find the requested task.
2199 while (i > 0) {
2200 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002201 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002202 if (r.task.taskId == taskId) {
2203 i++;
2204 break;
2205 }
2206 }
2207
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002208 // Now find the start and clear it.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002209 while (i > 0) {
2210 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002211 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002212 if (r.finishing) {
2213 continue;
2214 }
2215 if (r.task.taskId != taskId) {
2216 // We hit the bottom. Now finish it all...
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002217 performClearTaskAtIndexLocked(taskId, i+1);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002218 return;
2219 }
2220 }
2221 }
2222
2223 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002224 * Find the activity in the history stack within the given task. Returns
2225 * the index within the history at which it's found, or < 0 if not found.
2226 */
2227 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2228 int i = mHistory.size();
2229 while (i > 0) {
2230 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002231 ActivityRecord candidate = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002232 if (candidate.task.taskId != task) {
2233 break;
2234 }
2235 if (candidate.realActivity.equals(r.realActivity)) {
2236 return i;
2237 }
2238 }
2239
2240 return -1;
2241 }
2242
2243 /**
2244 * Reorder the history stack so that the activity at the given index is
2245 * brought to the front.
2246 */
2247 private final ActivityRecord moveActivityToFrontLocked(int where) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002248 ActivityRecord newTop = mHistory.remove(where);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002249 int top = mHistory.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002250 ActivityRecord oldTop = mHistory.get(top-1);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002251 if (DEBUG_ADD_REMOVE) {
2252 RuntimeException here = new RuntimeException("here");
2253 here.fillInStackTrace();
2254 Slog.i(TAG, "Removing and adding activity " + newTop + " to stack at "
2255 + top, here);
2256 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002257 mHistory.add(top, newTop);
2258 oldTop.frontOfTask = false;
2259 newTop.frontOfTask = true;
2260 return newTop;
2261 }
2262
2263 final int startActivityLocked(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002264 Intent intent, String resolvedType, ActivityInfo aInfo, IBinder resultTo,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002265 String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002266 int callingPid, int callingUid, int startFlags, Bundle options,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002267 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002268
Dianne Hackborna4972e92012-03-14 10:38:05 -07002269 int err = ActivityManager.START_SUCCESS;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002270
2271 ProcessRecord callerApp = null;
2272 if (caller != null) {
2273 callerApp = mService.getRecordForAppLocked(caller);
2274 if (callerApp != null) {
2275 callingPid = callerApp.pid;
2276 callingUid = callerApp.info.uid;
2277 } else {
2278 Slog.w(TAG, "Unable to find app for caller " + caller
2279 + " (pid=" + callingPid + ") when starting: "
2280 + intent.toString());
Dianne Hackborna4972e92012-03-14 10:38:05 -07002281 err = ActivityManager.START_PERMISSION_DENIED;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002282 }
2283 }
2284
Dianne Hackborna4972e92012-03-14 10:38:05 -07002285 if (err == ActivityManager.START_SUCCESS) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08002286 Slog.i(TAG, "START {" + intent.toShortString(true, true, true, false)
2287 + "} from pid " + (callerApp != null ? callerApp.pid : callingPid));
Dianne Hackbornefb58102010-10-14 16:47:34 -07002288 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002289
2290 ActivityRecord sourceRecord = null;
2291 ActivityRecord resultRecord = null;
2292 if (resultTo != null) {
2293 int index = indexOfTokenLocked(resultTo);
2294 if (DEBUG_RESULTS) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002295 TAG, "Will send result to " + resultTo + " (index " + index + ")");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002296 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002297 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002298 if (requestCode >= 0 && !sourceRecord.finishing) {
2299 resultRecord = sourceRecord;
2300 }
2301 }
2302 }
2303
2304 int launchFlags = intent.getFlags();
2305
2306 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2307 && sourceRecord != null) {
2308 // Transfer the result target from the source activity to the new
2309 // one being started, including any failures.
2310 if (requestCode >= 0) {
Dianne Hackborna4972e92012-03-14 10:38:05 -07002311 return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002312 }
2313 resultRecord = sourceRecord.resultTo;
2314 resultWho = sourceRecord.resultWho;
2315 requestCode = sourceRecord.requestCode;
2316 sourceRecord.resultTo = null;
2317 if (resultRecord != null) {
2318 resultRecord.removeResultsLocked(
2319 sourceRecord, resultWho, requestCode);
2320 }
2321 }
2322
Dianne Hackborna4972e92012-03-14 10:38:05 -07002323 if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002324 // We couldn't find a class that can handle the given Intent.
2325 // That's the end of that!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002326 err = ActivityManager.START_INTENT_NOT_RESOLVED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002327 }
2328
Dianne Hackborna4972e92012-03-14 10:38:05 -07002329 if (err == ActivityManager.START_SUCCESS && aInfo == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002330 // We couldn't find the specific class specified in the Intent.
2331 // Also the end of the line.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002332 err = ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002333 }
2334
Dianne Hackborna4972e92012-03-14 10:38:05 -07002335 if (err != ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002336 if (resultRecord != null) {
2337 sendActivityResultLocked(-1,
2338 resultRecord, resultWho, requestCode,
2339 Activity.RESULT_CANCELED, null);
2340 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002341 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002342 return err;
2343 }
2344
2345 final int perm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002346 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002347 if (perm != PackageManager.PERMISSION_GRANTED) {
2348 if (resultRecord != null) {
2349 sendActivityResultLocked(-1,
2350 resultRecord, resultWho, requestCode,
2351 Activity.RESULT_CANCELED, null);
2352 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002353 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002354 String msg;
2355 if (!aInfo.exported) {
2356 msg = "Permission Denial: starting " + intent.toString()
2357 + " from " + callerApp + " (pid=" + callingPid
2358 + ", uid=" + callingUid + ")"
2359 + " not exported from uid " + aInfo.applicationInfo.uid;
2360 } else {
2361 msg = "Permission Denial: starting " + intent.toString()
2362 + " from " + callerApp + " (pid=" + callingPid
2363 + ", uid=" + callingUid + ")"
2364 + " requires " + aInfo.permission;
2365 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002366 Slog.w(TAG, msg);
2367 throw new SecurityException(msg);
2368 }
2369
2370 if (mMainStack) {
2371 if (mService.mController != null) {
2372 boolean abort = false;
2373 try {
2374 // The Intent we give to the watcher has the extra data
2375 // stripped off, since it can contain private information.
2376 Intent watchIntent = intent.cloneFilter();
2377 abort = !mService.mController.activityStarting(watchIntent,
2378 aInfo.applicationInfo.packageName);
2379 } catch (RemoteException e) {
2380 mService.mController = null;
2381 }
2382
2383 if (abort) {
2384 if (resultRecord != null) {
2385 sendActivityResultLocked(-1,
2386 resultRecord, resultWho, requestCode,
2387 Activity.RESULT_CANCELED, null);
2388 }
2389 // We pretend to the caller that it was really started, but
2390 // they will just get a cancel result.
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002391 mDismissKeyguardOnNextActivity = false;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002392 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002393 }
2394 }
2395 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002396
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002397 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2398 intent, resolvedType, aInfo, mService.mConfiguration,
2399 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002400 if (outActivity != null) {
2401 outActivity[0] = r;
2402 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002403
2404 if (mMainStack) {
2405 if (mResumedActivity == null
2406 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2407 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2408 PendingActivityLaunch pal = new PendingActivityLaunch();
2409 pal.r = r;
2410 pal.sourceRecord = sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002411 pal.startFlags = startFlags;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002412 mService.mPendingActivityLaunches.add(pal);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002413 mDismissKeyguardOnNextActivity = false;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002414 return ActivityManager.START_SWITCHES_CANCELED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002415 }
2416 }
2417
2418 if (mService.mDidAppSwitch) {
2419 // This is the second allowed switch since we stopped switches,
2420 // so now just generally allow switches. Use case: user presses
2421 // home (switches disabled, switch to home, mDidAppSwitch now true);
2422 // user taps a home icon (coming from home so allowed, we hit here
2423 // and now allow anyone to switch again).
2424 mService.mAppSwitchesAllowedTime = 0;
2425 } else {
2426 mService.mDidAppSwitch = true;
2427 }
2428
2429 mService.doPendingActivityLaunchesLocked(false);
2430 }
2431
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002432 err = startActivityUncheckedLocked(r, sourceRecord,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002433 startFlags, true);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002434 if (mDismissKeyguardOnNextActivity && mPausingActivity == null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002435 // Someone asked to have the keyguard dismissed on the next
2436 // activity start, but we are not actually doing an activity
2437 // switch... just dismiss the keyguard now, because we
2438 // probably want to see whatever is behind it.
2439 mDismissKeyguardOnNextActivity = false;
2440 mService.mWindowManager.dismissKeyguard();
2441 }
2442 return err;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002443 }
2444
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002445 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2446 if ((launchFlags &
2447 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2448 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2449 // Caller wants to appear on home activity, so before starting
2450 // their own activity we will bring home to the front.
2451 moveHomeToFrontLocked();
2452 }
2453 }
2454
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002455 final int startActivityUncheckedLocked(ActivityRecord r,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002456 ActivityRecord sourceRecord, int startFlags, boolean doResume) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002457 final Intent intent = r.intent;
2458 final int callingUid = r.launchedFromUid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002459 final int userId = r.userId;
2460
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002461 int launchFlags = intent.getFlags();
2462
2463 // We'll invoke onUserLeaving before onPause only if the launching
2464 // activity did not explicitly state that this is an automated launch.
2465 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2466 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2467 "startActivity() => mUserLeaving=" + mUserLeaving);
2468
2469 // If the caller has asked not to resume at this point, we make note
2470 // of this in the record so that we can skip it when trying to find
2471 // the top running activity.
2472 if (!doResume) {
2473 r.delayedResume = true;
2474 }
2475
2476 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2477 != 0 ? r : null;
2478
2479 // If the onlyIfNeeded flag is set, then we can do this if the activity
2480 // being launched is the same as the one making the call... or, as
2481 // a special case, if we do not know the caller then we count the
2482 // current top activity as the caller.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002483 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002484 ActivityRecord checkedCaller = sourceRecord;
2485 if (checkedCaller == null) {
2486 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2487 }
2488 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2489 // Caller is not the same as launcher, so always needed.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002490 startFlags &= ~ActivityManager.START_FLAG_ONLY_IF_NEEDED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002491 }
2492 }
2493
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002494 if (sourceRecord == null) {
2495 // This activity is not being started from another... in this
2496 // case we -always- start a new task.
2497 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2498 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2499 + intent);
2500 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2501 }
2502 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2503 // The original activity who is starting us is running as a single
2504 // instance... this new activity it is starting must go on its
2505 // own task.
2506 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2507 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2508 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2509 // The activity being started is a single instance... it always
2510 // gets launched into its own task.
2511 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2512 }
2513
2514 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2515 // For whatever reason this activity is being launched into a new
2516 // task... yet the caller has requested a result back. Well, that
2517 // is pretty messed up, so instead immediately send back a cancel
2518 // and let the new task continue launched as normal without a
2519 // dependency on its originator.
2520 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2521 sendActivityResultLocked(-1,
2522 r.resultTo, r.resultWho, r.requestCode,
2523 Activity.RESULT_CANCELED, null);
2524 r.resultTo = null;
2525 }
2526
2527 boolean addingToTask = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002528 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002529 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2530 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2531 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2532 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2533 // If bring to front is requested, and no result is requested, and
2534 // we can find a task that was started with this same
2535 // component, then instead of launching bring that one to the front.
2536 if (r.resultTo == null) {
2537 // See if there is a task to bring to the front. If this is
2538 // a SINGLE_INSTANCE activity, there can be one and only one
2539 // instance of it in the history, and it is always in its own
2540 // unique task, so we do a special search.
2541 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2542 ? findTaskLocked(intent, r.info)
2543 : findActivityLocked(intent, r.info);
2544 if (taskTop != null) {
2545 if (taskTop.task.intent == null) {
2546 // This task was started because of movement of
2547 // the activity based on affinity... now that we
2548 // are actually launching it, we can assign the
2549 // base intent.
2550 taskTop.task.setIntent(intent, r.info);
2551 }
2552 // If the target task is not in the front, then we need
2553 // to bring it to the front... except... well, with
2554 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2555 // to have the same behavior as if a new instance was
2556 // being started, which means not bringing it to the front
2557 // if the caller is not itself in the front.
2558 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002559 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002560 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2561 boolean callerAtFront = sourceRecord == null
2562 || curTop.task == sourceRecord.task;
2563 if (callerAtFront) {
2564 // We really do want to push this one into the
2565 // user's face, right now.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002566 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002567 moveTaskToFrontLocked(taskTop.task, r);
2568 }
2569 }
2570 // If the caller has requested that the target task be
2571 // reset, then do so.
2572 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2573 taskTop = resetTaskIfNeededLocked(taskTop, r);
2574 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002575 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002576 // We don't need to start a new activity, and
2577 // the client said not to do anything if that
2578 // is the case, so this is it! And for paranoia, make
2579 // sure we have correctly resumed the top activity.
2580 if (doResume) {
2581 resumeTopActivityLocked(null);
2582 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002583 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002584 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002585 if ((launchFlags &
2586 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2587 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2588 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002589 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002590 // not be too hard...
2591 reuseTask = taskTop.task;
2592 performClearTaskLocked(taskTop.task.taskId);
2593 reuseTask.setIntent(r.intent, r.info);
2594 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002595 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2596 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2597 // In this situation we want to remove all activities
2598 // from the task up to the one being started. In most
2599 // cases this means we are resetting the task to its
2600 // initial state.
2601 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002602 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002603 if (top != null) {
2604 if (top.frontOfTask) {
2605 // Activity aliases may mean we use different
2606 // intents for the top activity, so make sure
2607 // the task now has the identity of the new
2608 // intent.
2609 top.task.setIntent(r.intent, r.info);
2610 }
2611 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002612 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002613 } else {
2614 // A special case: we need to
2615 // start the activity because it is not currently
2616 // running, and the caller has asked to clear the
2617 // current task to have this activity at the top.
2618 addingToTask = true;
2619 // Now pretend like this activity is being started
2620 // by the top of its task, so it is put in the
2621 // right place.
2622 sourceRecord = taskTop;
2623 }
2624 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2625 // In this case the top activity on the task is the
2626 // same as the one being launched, so we take that
2627 // as a request to bring the task to the foreground.
2628 // If the top activity in the task is the root
2629 // activity, deliver this new intent to it if it
2630 // desires.
2631 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2632 && taskTop.realActivity.equals(r.realActivity)) {
2633 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2634 if (taskTop.frontOfTask) {
2635 taskTop.task.setIntent(r.intent, r.info);
2636 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002637 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002638 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2639 // In this case we are launching the root activity
2640 // of the task, but with a different intent. We
2641 // should start a new instance on top.
2642 addingToTask = true;
2643 sourceRecord = taskTop;
2644 }
2645 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2646 // In this case an activity is being launched in to an
2647 // existing task, without resetting that task. This
2648 // is typically the situation of launching an activity
2649 // from a notification or shortcut. We want to place
2650 // the new activity on top of the current task.
2651 addingToTask = true;
2652 sourceRecord = taskTop;
2653 } else if (!taskTop.task.rootWasReset) {
2654 // In this case we are launching in to an existing task
2655 // that has not yet been started from its front door.
2656 // The current task has been brought to the front.
2657 // Ideally, we'd probably like to place this new task
2658 // at the bottom of its stack, but that's a little hard
2659 // to do with the current organization of the code so
2660 // for now we'll just drop it.
2661 taskTop.task.setIntent(r.intent, r.info);
2662 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002663 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002664 // We didn't do anything... but it was needed (a.k.a., client
2665 // don't use that intent!) And for paranoia, make
2666 // sure we have correctly resumed the top activity.
2667 if (doResume) {
2668 resumeTopActivityLocked(null);
2669 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002670 return ActivityManager.START_TASK_TO_FRONT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002671 }
2672 }
2673 }
2674 }
2675
2676 //String uri = r.intent.toURI();
2677 //Intent intent2 = new Intent(uri);
2678 //Slog.i(TAG, "Given intent: " + r.intent);
2679 //Slog.i(TAG, "URI is: " + uri);
2680 //Slog.i(TAG, "To intent: " + intent2);
2681
2682 if (r.packageName != null) {
2683 // If the activity being launched is the same as the one currently
2684 // at the top, then we need to check if it should only be launched
2685 // once.
2686 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2687 if (top != null && r.resultTo == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002688 if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002689 if (top.app != null && top.app.thread != null) {
2690 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2691 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2692 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2693 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2694 // For paranoia, make sure we have correctly
2695 // resumed the top activity.
2696 if (doResume) {
2697 resumeTopActivityLocked(null);
2698 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002699 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002700 // We don't need to start a new activity, and
2701 // the client said not to do anything if that
2702 // is the case, so this is it!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002703 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002704 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002705 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002706 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002707 }
2708 }
2709 }
2710 }
2711
2712 } else {
2713 if (r.resultTo != null) {
2714 sendActivityResultLocked(-1,
2715 r.resultTo, r.resultWho, r.requestCode,
2716 Activity.RESULT_CANCELED, null);
2717 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002718 return ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002719 }
2720
2721 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002722 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002723
2724 // Should this be considered a new task?
2725 if (r.resultTo == null && !addingToTask
2726 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002727 if (reuseTask == null) {
2728 // todo: should do better management of integers.
2729 mService.mCurTask++;
2730 if (mService.mCurTask <= 0) {
2731 mService.mCurTask = 1;
2732 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002733 r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002734 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2735 + " in new task " + r.task);
2736 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002737 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002738 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002739 newTask = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002740 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002741
2742 } else if (sourceRecord != null) {
2743 if (!addingToTask &&
2744 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2745 // In this case, we are adding the activity to an existing
2746 // task, but the caller has asked to clear that task if the
2747 // activity is already running.
2748 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002749 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002750 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002751 if (top != null) {
2752 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002753 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002754 // For paranoia, make sure we have correctly
2755 // resumed the top activity.
2756 if (doResume) {
2757 resumeTopActivityLocked(null);
2758 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002759 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002760 }
2761 } else if (!addingToTask &&
2762 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2763 // In this case, we are launching an activity in our own task
2764 // that may already be running somewhere in the history, and
2765 // we want to shuffle it to the front of the stack if so.
2766 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2767 if (where >= 0) {
2768 ActivityRecord top = moveActivityToFrontLocked(where);
2769 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002770 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002771 if (doResume) {
2772 resumeTopActivityLocked(null);
2773 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002774 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002775 }
2776 }
2777 // An existing activity is starting this new activity, so we want
2778 // to keep the new one in the same task as the one that is starting
2779 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002780 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002781 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2782 + " in existing task " + r.task);
2783
2784 } else {
2785 // This not being started from an existing activity, and not part
2786 // of a new task... just put it in the top task, though these days
2787 // this case should never happen.
2788 final int N = mHistory.size();
2789 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002790 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002791 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002792 ? prev.task
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002793 : new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002794 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2795 + " in new guessed " + r.task);
2796 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002797
Dianne Hackborn39792d22010-08-19 18:01:52 -07002798 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002799 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002800
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002801 if (newTask) {
2802 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
2803 }
2804 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002805 startActivityLocked(r, newTask, doResume, keepCurTransition);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002806 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002807 }
2808
Dianne Hackborna4972e92012-03-14 10:38:05 -07002809 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
2810 String profileFile, ParcelFileDescriptor profileFd) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002811 // Collect information about the target of the Intent.
2812 ActivityInfo aInfo;
2813 try {
2814 ResolveInfo rInfo =
2815 AppGlobals.getPackageManager().resolveIntent(
2816 intent, resolvedType,
2817 PackageManager.MATCH_DEFAULT_ONLY
2818 | ActivityManagerService.STOCK_PM_FLAGS);
2819 aInfo = rInfo != null ? rInfo.activityInfo : null;
2820 } catch (RemoteException e) {
2821 aInfo = null;
2822 }
2823
2824 if (aInfo != null) {
2825 // Store the found target back into the intent, because now that
2826 // we have it we never want to do this again. For example, if the
2827 // user navigates back to this point in the history, we should
2828 // always restart the exact same activity.
2829 intent.setComponent(new ComponentName(
2830 aInfo.applicationInfo.packageName, aInfo.name));
2831
2832 // Don't debug things in the system process
Dianne Hackborna4972e92012-03-14 10:38:05 -07002833 if ((startFlags&ActivityManager.START_FLAG_DEBUG) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002834 if (!aInfo.processName.equals("system")) {
2835 mService.setDebugApp(aInfo.processName, true, false);
2836 }
2837 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002838
Dianne Hackborna4972e92012-03-14 10:38:05 -07002839 if ((startFlags&ActivityManager.START_FLAG_OPENGL_TRACES) != 0) {
Siva Velusamy92a8b222012-03-09 16:24:04 -08002840 if (!aInfo.processName.equals("system")) {
2841 mService.setOpenGlTraceApp(aInfo.applicationInfo, aInfo.processName);
2842 }
2843 }
2844
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002845 if (profileFile != null) {
2846 if (!aInfo.processName.equals("system")) {
2847 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002848 profileFile, profileFd,
2849 (startFlags&ActivityManager.START_FLAG_AUTO_STOP_PROFILER) != 0);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002850 }
2851 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002852 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002853 return aInfo;
2854 }
2855
2856 final int startActivityMayWait(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002857 Intent intent, String resolvedType, IBinder resultTo,
2858 String resultWho, int requestCode, int startFlags, String profileFile,
2859 ParcelFileDescriptor profileFd, WaitResult outResult, Configuration config,
2860 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002861 // Refuse possible leaked file descriptors
2862 if (intent != null && intent.hasFileDescriptors()) {
2863 throw new IllegalArgumentException("File descriptors passed in Intent");
2864 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002865 boolean componentSpecified = intent.getComponent() != null;
2866
2867 // Don't modify the client's object!
2868 intent = new Intent(intent);
2869
2870 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002871 ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,
2872 profileFile, profileFd);
Amith Yamasani742a6712011-05-04 14:49:28 -07002873 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002874
2875 synchronized (mService) {
2876 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002877 if (callingUid >= 0) {
2878 callingPid = -1;
2879 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002880 callingPid = Binder.getCallingPid();
2881 callingUid = Binder.getCallingUid();
2882 } else {
2883 callingPid = callingUid = -1;
2884 }
2885
2886 mConfigWillChange = config != null
2887 && mService.mConfiguration.diff(config) != 0;
2888 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2889 "Starting activity when config will change = " + mConfigWillChange);
2890
2891 final long origId = Binder.clearCallingIdentity();
2892
2893 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07002894 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002895 // This may be a heavy-weight process! Check to see if we already
2896 // have another, different heavy-weight process running.
2897 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
2898 if (mService.mHeavyWeightProcess != null &&
2899 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
2900 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
2901 int realCallingPid = callingPid;
2902 int realCallingUid = callingUid;
2903 if (caller != null) {
2904 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
2905 if (callerApp != null) {
2906 realCallingPid = callerApp.pid;
2907 realCallingUid = callerApp.info.uid;
2908 } else {
2909 Slog.w(TAG, "Unable to find app for caller " + caller
2910 + " (pid=" + realCallingPid + ") when starting: "
2911 + intent.toString());
Dianne Hackborna4972e92012-03-14 10:38:05 -07002912 return ActivityManager.START_PERMISSION_DENIED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002913 }
2914 }
2915
2916 IIntentSender target = mService.getIntentSenderLocked(
Dianne Hackborna4972e92012-03-14 10:38:05 -07002917 ActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002918 realCallingUid, null, null, 0, new Intent[] { intent },
2919 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002920 | PendingIntent.FLAG_ONE_SHOT);
2921
2922 Intent newIntent = new Intent();
2923 if (requestCode >= 0) {
2924 // Caller is requesting a result.
2925 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
2926 }
2927 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
2928 new IntentSender(target));
2929 if (mService.mHeavyWeightProcess.activities.size() > 0) {
2930 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
2931 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
2932 hist.packageName);
2933 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
2934 hist.task.taskId);
2935 }
2936 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
2937 aInfo.packageName);
2938 newIntent.setFlags(intent.getFlags());
2939 newIntent.setClassName("android",
2940 HeavyWeightSwitcherActivity.class.getName());
2941 intent = newIntent;
2942 resolvedType = null;
2943 caller = null;
2944 callingUid = Binder.getCallingUid();
2945 callingPid = Binder.getCallingPid();
2946 componentSpecified = true;
2947 try {
2948 ResolveInfo rInfo =
2949 AppGlobals.getPackageManager().resolveIntent(
2950 intent, null,
2951 PackageManager.MATCH_DEFAULT_ONLY
2952 | ActivityManagerService.STOCK_PM_FLAGS);
2953 aInfo = rInfo != null ? rInfo.activityInfo : null;
Amith Yamasani742a6712011-05-04 14:49:28 -07002954 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002955 } catch (RemoteException e) {
2956 aInfo = null;
2957 }
2958 }
2959 }
2960 }
2961
2962 int res = startActivityLocked(caller, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002963 aInfo, resultTo, resultWho, requestCode, callingPid, callingUid,
2964 startFlags, options, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002965
2966 if (mConfigWillChange && mMainStack) {
2967 // If the caller also wants to switch to a new configuration,
2968 // do so now. This allows a clean switch, as we are waiting
2969 // for the current activity to pause (so we will not destroy
2970 // it), and have not yet started the next activity.
2971 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
2972 "updateConfiguration()");
2973 mConfigWillChange = false;
2974 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2975 "Updating to new configuration after starting activity.");
Dianne Hackborn813075a62011-11-14 17:45:19 -08002976 mService.updateConfigurationLocked(config, null, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002977 }
2978
2979 Binder.restoreCallingIdentity(origId);
2980
2981 if (outResult != null) {
2982 outResult.result = res;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002983 if (res == ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002984 mWaitingActivityLaunched.add(outResult);
2985 do {
2986 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07002987 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002988 } catch (InterruptedException e) {
2989 }
2990 } while (!outResult.timeout && outResult.who == null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002991 } else if (res == ActivityManager.START_TASK_TO_FRONT) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002992 ActivityRecord r = this.topRunningActivityLocked(null);
2993 if (r.nowVisible) {
2994 outResult.timeout = false;
2995 outResult.who = new ComponentName(r.info.packageName, r.info.name);
2996 outResult.totalTime = 0;
2997 outResult.thisTime = 0;
2998 } else {
2999 outResult.thisTime = SystemClock.uptimeMillis();
3000 mWaitingActivityVisible.add(outResult);
3001 do {
3002 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003003 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003004 } catch (InterruptedException e) {
3005 }
3006 } while (!outResult.timeout && outResult.who == null);
3007 }
3008 }
3009 }
3010
3011 return res;
3012 }
3013 }
3014
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003015 final int startActivities(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003016 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
3017 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003018 if (intents == null) {
3019 throw new NullPointerException("intents is null");
3020 }
3021 if (resolvedTypes == null) {
3022 throw new NullPointerException("resolvedTypes is null");
3023 }
3024 if (intents.length != resolvedTypes.length) {
3025 throw new IllegalArgumentException("intents are length different than resolvedTypes");
3026 }
3027
3028 ActivityRecord[] outActivity = new ActivityRecord[1];
3029
3030 int callingPid;
3031 if (callingUid >= 0) {
3032 callingPid = -1;
3033 } else if (caller == null) {
3034 callingPid = Binder.getCallingPid();
3035 callingUid = Binder.getCallingUid();
3036 } else {
3037 callingPid = callingUid = -1;
3038 }
3039 final long origId = Binder.clearCallingIdentity();
3040 try {
3041 synchronized (mService) {
3042
3043 for (int i=0; i<intents.length; i++) {
3044 Intent intent = intents[i];
3045 if (intent == null) {
3046 continue;
3047 }
3048
3049 // Refuse possible leaked file descriptors
3050 if (intent != null && intent.hasFileDescriptors()) {
3051 throw new IllegalArgumentException("File descriptors passed in Intent");
3052 }
3053
3054 boolean componentSpecified = intent.getComponent() != null;
3055
3056 // Don't modify the client's object!
3057 intent = new Intent(intent);
3058
3059 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003060 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i],
3061 0, null, null);
Amith Yamasani742a6712011-05-04 14:49:28 -07003062 // TODO: New, check if this is correct
3063 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003064
3065 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
3066 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
3067 throw new IllegalArgumentException(
3068 "FLAG_CANT_SAVE_STATE not supported here");
3069 }
3070
3071 int res = startActivityLocked(caller, intent, resolvedTypes[i],
Dianne Hackborna4972e92012-03-14 10:38:05 -07003072 aInfo, resultTo, null, -1, callingPid, callingUid,
3073 0, options, componentSpecified, outActivity);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003074 if (res < 0) {
3075 return res;
3076 }
3077
Dianne Hackbornbe707852011-11-11 14:32:10 -08003078 resultTo = outActivity[0] != null ? outActivity[0].appToken : null;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003079 }
3080 }
3081 } finally {
3082 Binder.restoreCallingIdentity(origId);
3083 }
3084
Dianne Hackborna4972e92012-03-14 10:38:05 -07003085 return ActivityManager.START_SUCCESS;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003086 }
3087
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003088 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
3089 long thisTime, long totalTime) {
3090 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
3091 WaitResult w = mWaitingActivityLaunched.get(i);
3092 w.timeout = timeout;
3093 if (r != null) {
3094 w.who = new ComponentName(r.info.packageName, r.info.name);
3095 }
3096 w.thisTime = thisTime;
3097 w.totalTime = totalTime;
3098 }
3099 mService.notifyAll();
3100 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003101
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003102 void reportActivityVisibleLocked(ActivityRecord r) {
3103 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
3104 WaitResult w = mWaitingActivityVisible.get(i);
3105 w.timeout = false;
3106 if (r != null) {
3107 w.who = new ComponentName(r.info.packageName, r.info.name);
3108 }
3109 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
3110 w.thisTime = w.totalTime;
3111 }
3112 mService.notifyAll();
Dianne Hackborn90c52de2011-09-23 12:57:44 -07003113
3114 if (mDismissKeyguardOnNextActivity) {
3115 mDismissKeyguardOnNextActivity = false;
3116 mService.mWindowManager.dismissKeyguard();
3117 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003118 }
3119
3120 void sendActivityResultLocked(int callingUid, ActivityRecord r,
3121 String resultWho, int requestCode, int resultCode, Intent data) {
3122
3123 if (callingUid > 0) {
3124 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003125 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003126 }
3127
3128 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3129 + " : who=" + resultWho + " req=" + requestCode
3130 + " res=" + resultCode + " data=" + data);
3131 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3132 try {
3133 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3134 list.add(new ResultInfo(resultWho, requestCode,
3135 resultCode, data));
Dianne Hackbornbe707852011-11-11 14:32:10 -08003136 r.app.thread.scheduleSendResult(r.appToken, list);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003137 return;
3138 } catch (Exception e) {
3139 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3140 }
3141 }
3142
3143 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3144 }
3145
3146 private final void stopActivityLocked(ActivityRecord r) {
3147 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3148 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3149 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3150 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003151 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003152 "no-history");
3153 }
3154 } else if (r.app != null && r.app.thread != null) {
3155 if (mMainStack) {
3156 if (mService.mFocusedActivity == r) {
3157 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3158 }
3159 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003160 r.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003161 try {
3162 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003163 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3164 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003165 r.state = ActivityState.STOPPING;
3166 if (DEBUG_VISBILITY) Slog.v(
3167 TAG, "Stopping visible=" + r.visible + " for " + r);
3168 if (!r.visible) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003169 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003170 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003171 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003172 if (mService.isSleeping()) {
3173 r.setSleeping(true);
3174 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003175 } catch (Exception e) {
3176 // Maybe just ignore exceptions here... if the process
3177 // has crashed, our death notification will clean things
3178 // up.
3179 Slog.w(TAG, "Exception thrown during pause", e);
3180 // Just in case, assume it to be stopped.
3181 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003182 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003183 r.state = ActivityState.STOPPED;
3184 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003185 destroyActivityLocked(r, true, false, "stop-except");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003186 }
3187 }
3188 }
3189 }
3190
3191 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3192 boolean remove) {
3193 int N = mStoppingActivities.size();
3194 if (N <= 0) return null;
3195
3196 ArrayList<ActivityRecord> stops = null;
3197
3198 final boolean nowVisible = mResumedActivity != null
3199 && mResumedActivity.nowVisible
3200 && !mResumedActivity.waitingVisible;
3201 for (int i=0; i<N; i++) {
3202 ActivityRecord s = mStoppingActivities.get(i);
3203 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3204 + nowVisible + " waitingVisible=" + s.waitingVisible
3205 + " finishing=" + s.finishing);
3206 if (s.waitingVisible && nowVisible) {
3207 mWaitingVisibleActivities.remove(s);
3208 s.waitingVisible = false;
3209 if (s.finishing) {
3210 // If this activity is finishing, it is sitting on top of
3211 // everyone else but we now know it is no longer needed...
3212 // so get rid of it. Otherwise, we need to go through the
3213 // normal flow and hide it once we determine that it is
3214 // hidden by the activities in front of it.
3215 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003216 mService.mWindowManager.setAppVisibility(s.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003217 }
3218 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003219 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003220 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3221 if (stops == null) {
3222 stops = new ArrayList<ActivityRecord>();
3223 }
3224 stops.add(s);
3225 mStoppingActivities.remove(i);
3226 N--;
3227 i--;
3228 }
3229 }
3230
3231 return stops;
3232 }
3233
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003234 final void scheduleIdleLocked() {
3235 Message msg = Message.obtain();
3236 msg.what = IDLE_NOW_MSG;
3237 mHandler.sendMessage(msg);
3238 }
3239
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003240 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003241 Configuration config) {
3242 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3243
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003244 ActivityRecord res = null;
3245
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003246 ArrayList<ActivityRecord> stops = null;
3247 ArrayList<ActivityRecord> finishes = null;
3248 ArrayList<ActivityRecord> thumbnails = null;
3249 int NS = 0;
3250 int NF = 0;
3251 int NT = 0;
3252 IApplicationThread sendThumbnail = null;
3253 boolean booting = false;
3254 boolean enableScreen = false;
3255
3256 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003257 ActivityRecord r = ActivityRecord.forToken(token);
3258 if (r != null) {
3259 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003260 }
3261
3262 // Get the activity record.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003263 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003264 if (index >= 0) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003265 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003266
3267 if (fromTimeout) {
3268 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3269 }
3270
3271 // This is a hack to semi-deal with a race condition
3272 // in the client where it can be constructed with a
3273 // newer configuration from when we asked it to launch.
3274 // We'll update with whatever configuration it now says
3275 // it used to launch.
3276 if (config != null) {
3277 r.configuration = config;
3278 }
3279
3280 // No longer need to keep the device awake.
3281 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3282 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3283 mLaunchingActivity.release();
3284 }
3285
3286 // We are now idle. If someone is waiting for a thumbnail from
3287 // us, we can now deliver.
3288 r.idle = true;
3289 mService.scheduleAppGcsLocked();
3290 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3291 sendThumbnail = r.app.thread;
3292 r.thumbnailNeeded = false;
3293 }
3294
3295 // If this activity is fullscreen, set up to hide those under it.
3296
3297 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3298 ensureActivitiesVisibleLocked(null, 0);
3299
3300 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3301 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003302 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003303 mService.mBooted = true;
3304 enableScreen = true;
3305 }
3306 }
3307
3308 } else if (fromTimeout) {
3309 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3310 }
3311
3312 // Atomically retrieve all of the other things to do.
3313 stops = processStoppingActivitiesLocked(true);
3314 NS = stops != null ? stops.size() : 0;
3315 if ((NF=mFinishingActivities.size()) > 0) {
3316 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3317 mFinishingActivities.clear();
3318 }
3319 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3320 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3321 mService.mCancelledThumbnails.clear();
3322 }
3323
3324 if (mMainStack) {
3325 booting = mService.mBooting;
3326 mService.mBooting = false;
3327 }
3328 }
3329
3330 int i;
3331
3332 // Send thumbnail if requested.
3333 if (sendThumbnail != null) {
3334 try {
3335 sendThumbnail.requestThumbnail(token);
3336 } catch (Exception e) {
3337 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3338 mService.sendPendingThumbnail(null, token, null, null, true);
3339 }
3340 }
3341
3342 // Stop any activities that are scheduled to do so but have been
3343 // waiting for the next one to start.
3344 for (i=0; i<NS; i++) {
3345 ActivityRecord r = (ActivityRecord)stops.get(i);
3346 synchronized (mService) {
3347 if (r.finishing) {
3348 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY);
3349 } else {
3350 stopActivityLocked(r);
3351 }
3352 }
3353 }
3354
3355 // Finish any activities that are scheduled to do so but have been
3356 // waiting for the next one to start.
3357 for (i=0; i<NF; i++) {
3358 ActivityRecord r = (ActivityRecord)finishes.get(i);
3359 synchronized (mService) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003360 destroyActivityLocked(r, true, false, "finish-idle");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003361 }
3362 }
3363
3364 // Report back to any thumbnail receivers.
3365 for (i=0; i<NT; i++) {
3366 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3367 mService.sendPendingThumbnail(r, null, null, null, true);
3368 }
3369
3370 if (booting) {
3371 mService.finishBooting();
3372 }
3373
3374 mService.trimApplications();
3375 //dump();
3376 //mWindowManager.dump();
3377
3378 if (enableScreen) {
3379 mService.enableScreenAfterBoot();
3380 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003381
3382 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003383 }
3384
3385 /**
3386 * @return Returns true if the activity is being finished, false if for
3387 * some reason it is being left as-is.
3388 */
3389 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
3390 Intent resultData, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003391 int index = indexOfTokenLocked(token);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003392 if (DEBUG_RESULTS) Slog.v(
3393 TAG, "Finishing activity @" + index + ": token=" + token
3394 + ", result=" + resultCode + ", data=" + resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003395 if (index < 0) {
3396 return false;
3397 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003398 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003399
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003400 finishActivityLocked(r, index, resultCode, resultData, reason);
3401 return true;
3402 }
3403
Dianne Hackborn5c607432012-02-28 14:44:19 -08003404 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
3405 // send the result
3406 ActivityRecord resultTo = r.resultTo;
3407 if (resultTo != null) {
3408 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3409 + " who=" + r.resultWho + " req=" + r.requestCode
3410 + " res=" + resultCode + " data=" + resultData);
3411 if (r.info.applicationInfo.uid > 0) {
3412 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3413 resultTo.packageName, resultData,
3414 resultTo.getUriPermissionsLocked());
3415 }
3416 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3417 resultData);
3418 r.resultTo = null;
3419 }
3420 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3421
3422 // Make sure this HistoryRecord is not holding on to other resources,
3423 // because clients have remote IPC references to this object so we
3424 // can't assume that will go away and want to avoid circular IPC refs.
3425 r.results = null;
3426 r.pendingResults = null;
3427 r.newIntents = null;
3428 r.icicle = null;
3429 }
3430
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003431 /**
3432 * @return Returns true if this activity has been removed from the history
3433 * list, or false if it is still in the list and will be removed later.
3434 */
3435 final boolean finishActivityLocked(ActivityRecord r, int index,
3436 int resultCode, Intent resultData, String reason) {
3437 if (r.finishing) {
3438 Slog.w(TAG, "Duplicate finish request for " + r);
3439 return false;
3440 }
3441
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003442 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003443 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3444 System.identityHashCode(r),
3445 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003446 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003447 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003448 if (next.task == r.task) {
3449 if (r.frontOfTask) {
3450 // The next activity is now the front of the task.
3451 next.frontOfTask = true;
3452 }
3453 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3454 // If the caller asked that this activity (and all above it)
3455 // be cleared when the task is reset, don't lose that information,
3456 // but propagate it up to the next activity.
3457 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3458 }
3459 }
3460 }
3461
3462 r.pauseKeyDispatchingLocked();
3463 if (mMainStack) {
3464 if (mService.mFocusedActivity == r) {
3465 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3466 }
3467 }
3468
Dianne Hackborn5c607432012-02-28 14:44:19 -08003469 finishActivityResultsLocked(r, resultCode, resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003470
3471 if (mService.mPendingThumbnails.size() > 0) {
3472 // There are clients waiting to receive thumbnails so, in case
3473 // this is an activity that someone is waiting for, add it
3474 // to the pending list so we can correctly update the clients.
3475 mService.mCancelledThumbnails.add(r);
3476 }
3477
3478 if (mResumedActivity == r) {
3479 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003480 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003481 if (DEBUG_TRANSITION) Slog.v(TAG,
3482 "Prepare close transition: finishing " + r);
3483 mService.mWindowManager.prepareAppTransition(endTask
3484 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003485 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003486
3487 // Tell window manager to prepare for this one to be removed.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003488 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003489
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003490 if (mPausingActivity == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003491 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3492 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3493 startPausingLocked(false, false);
3494 }
3495
3496 } else if (r.state != ActivityState.PAUSING) {
3497 // If the activity is PAUSING, we will complete the finish once
3498 // it is done pausing; else we can just directly finish it here.
3499 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3500 return finishCurrentActivityLocked(r, index,
3501 FINISH_AFTER_PAUSE) == null;
3502 } else {
3503 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3504 }
3505
3506 return false;
3507 }
3508
3509 private static final int FINISH_IMMEDIATELY = 0;
3510 private static final int FINISH_AFTER_PAUSE = 1;
3511 private static final int FINISH_AFTER_VISIBLE = 2;
3512
3513 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3514 int mode) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003515 final int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003516 if (index < 0) {
3517 return null;
3518 }
3519
3520 return finishCurrentActivityLocked(r, index, mode);
3521 }
3522
3523 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3524 int index, int mode) {
3525 // First things first: if this activity is currently visible,
3526 // and the resumed activity is not yet visible, then hold off on
3527 // finishing until the resumed one becomes visible.
3528 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3529 if (!mStoppingActivities.contains(r)) {
3530 mStoppingActivities.add(r);
3531 if (mStoppingActivities.size() > 3) {
3532 // If we already have a few activities waiting to stop,
3533 // then give up on things going idle and start clearing
3534 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003535 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003536 } else {
3537 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003538 }
3539 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003540 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3541 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003542 r.state = ActivityState.STOPPING;
3543 mService.updateOomAdjLocked();
3544 return r;
3545 }
3546
3547 // make sure the record is cleaned out of other places.
3548 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003549 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003550 mWaitingVisibleActivities.remove(r);
3551 if (mResumedActivity == r) {
3552 mResumedActivity = null;
3553 }
3554 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003555 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003556 r.state = ActivityState.FINISHING;
3557
3558 if (mode == FINISH_IMMEDIATELY
3559 || prevState == ActivityState.STOPPED
3560 || prevState == ActivityState.INITIALIZING) {
3561 // If this activity is already stopped, we can just finish
3562 // it right now.
Dianne Hackborn28695e02011-11-02 21:59:51 -07003563 return destroyActivityLocked(r, true, true, "finish-imm") ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003564 } else {
3565 // Need to go through the full pause cycle to get this
3566 // activity into the stopped state and then finish it.
3567 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3568 mFinishingActivities.add(r);
3569 resumeTopActivityLocked(null);
3570 }
3571 return r;
3572 }
3573
3574 /**
3575 * Perform the common clean-up of an activity record. This is called both
3576 * as part of destroyActivityLocked() (when destroying the client-side
3577 * representation) and cleaning things up as a result of its hosting
3578 * processing going away, in which case there is no remaining client-side
3579 * state to destroy so only the cleanup here is needed.
3580 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003581 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3582 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003583 if (mResumedActivity == r) {
3584 mResumedActivity = null;
3585 }
3586 if (mService.mFocusedActivity == r) {
3587 mService.mFocusedActivity = null;
3588 }
3589
3590 r.configDestroy = false;
3591 r.frozenBeforeDestroy = false;
3592
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003593 if (setState) {
3594 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3595 r.state = ActivityState.DESTROYED;
3596 }
3597
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003598 // Make sure this record is no longer in the pending finishes list.
3599 // This could happen, for example, if we are trimming activities
3600 // down to the max limit while they are still waiting to finish.
3601 mFinishingActivities.remove(r);
3602 mWaitingVisibleActivities.remove(r);
3603
3604 // Remove any pending results.
3605 if (r.finishing && r.pendingResults != null) {
3606 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3607 PendingIntentRecord rec = apr.get();
3608 if (rec != null) {
3609 mService.cancelIntentSenderLocked(rec, false);
3610 }
3611 }
3612 r.pendingResults = null;
3613 }
3614
3615 if (cleanServices) {
3616 cleanUpActivityServicesLocked(r);
3617 }
3618
3619 if (mService.mPendingThumbnails.size() > 0) {
3620 // There are clients waiting to receive thumbnails so, in case
3621 // this is an activity that someone is waiting for, add it
3622 // to the pending list so we can correctly update the clients.
3623 mService.mCancelledThumbnails.add(r);
3624 }
3625
3626 // Get rid of any pending idle timeouts.
3627 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
3628 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003629 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003630 }
3631
Dianne Hackborn5c607432012-02-28 14:44:19 -08003632 final void removeActivityFromHistoryLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003633 if (r.state != ActivityState.DESTROYED) {
Dianne Hackborn5c607432012-02-28 14:44:19 -08003634 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003635 r.makeFinishing();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003636 if (DEBUG_ADD_REMOVE) {
3637 RuntimeException here = new RuntimeException("here");
3638 here.fillInStackTrace();
3639 Slog.i(TAG, "Removing activity " + r + " from stack");
3640 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003641 mHistory.remove(r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003642 r.takeFromHistory();
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003643 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3644 + " (removed from history)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003645 r.state = ActivityState.DESTROYED;
Dianne Hackbornbe707852011-11-11 14:32:10 -08003646 mService.mWindowManager.removeAppToken(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003647 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003648 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003649 }
3650 cleanUpActivityServicesLocked(r);
3651 r.removeUriPermissionsLocked();
3652 }
3653 }
3654
3655 /**
3656 * Perform clean-up of service connections in an activity record.
3657 */
3658 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3659 // Throw away any services that have been bound by this activity.
3660 if (r.connections != null) {
3661 Iterator<ConnectionRecord> it = r.connections.iterator();
3662 while (it.hasNext()) {
3663 ConnectionRecord c = it.next();
3664 mService.removeConnectionLocked(c, null, r);
3665 }
3666 r.connections = null;
3667 }
3668 }
3669
Dianne Hackborn28695e02011-11-02 21:59:51 -07003670 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003671 for (int i=mHistory.size()-1; i>=0; i--) {
3672 ActivityRecord r = mHistory.get(i);
3673 if (owner != null && r.app != owner) {
3674 continue;
3675 }
3676 // We can destroy this one if we have its icicle saved and
3677 // it is not in the process of pausing/stopping/finishing.
3678 if (r.app != null && r.haveState && !r.visible && r.stopped && !r.finishing
3679 && r.state != ActivityState.DESTROYING
3680 && r.state != ActivityState.DESTROYED) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003681 destroyActivityLocked(r, true, oomAdj, "trim");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003682 }
3683 }
3684 }
3685
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003686 /**
3687 * Destroy the current CLIENT SIDE instance of an activity. This may be
3688 * called both when actually finishing an activity, or when performing
3689 * a configuration switch where we destroy the current client-side object
3690 * but then create a new client-side object for this same HistoryRecord.
3691 */
3692 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackborn28695e02011-11-02 21:59:51 -07003693 boolean removeFromApp, boolean oomAdj, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003694 if (DEBUG_SWITCH) Slog.v(
3695 TAG, "Removing activity: token=" + r
3696 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3697 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3698 System.identityHashCode(r),
Dianne Hackborn28695e02011-11-02 21:59:51 -07003699 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003700
3701 boolean removedFromHistory = false;
3702
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003703 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003704
3705 final boolean hadApp = r.app != null;
3706
3707 if (hadApp) {
3708 if (removeFromApp) {
3709 int idx = r.app.activities.indexOf(r);
3710 if (idx >= 0) {
3711 r.app.activities.remove(idx);
3712 }
3713 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
3714 mService.mHeavyWeightProcess = null;
3715 mService.mHandler.sendEmptyMessage(
3716 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
3717 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003718 if (r.app.activities.size() == 0) {
3719 // No longer have activities, so update location in
3720 // LRU list.
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003721 mService.updateLruProcessLocked(r.app, oomAdj, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003722 }
3723 }
3724
3725 boolean skipDestroy = false;
3726
3727 try {
3728 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003729 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003730 r.configChangeFlags);
3731 } catch (Exception e) {
3732 // We can just ignore exceptions here... if the process
3733 // has crashed, our death notification will clean things
3734 // up.
3735 //Slog.w(TAG, "Exception thrown during finish", e);
3736 if (r.finishing) {
3737 removeActivityFromHistoryLocked(r);
3738 removedFromHistory = true;
3739 skipDestroy = true;
3740 }
3741 }
3742
3743 r.app = null;
3744 r.nowVisible = false;
3745
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003746 // If the activity is finishing, we need to wait on removing it
3747 // from the list to give it a chance to do its cleanup. During
3748 // that time it may make calls back with its token so we need to
3749 // be able to find it on the list and so we don't want to remove
3750 // it from the list yet. Otherwise, we can just immediately put
3751 // it in the destroyed state since we are not removing it from the
3752 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003753 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003754 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
3755 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003756 r.state = ActivityState.DESTROYING;
3757 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
3758 msg.obj = r;
3759 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
3760 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003761 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3762 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003763 r.state = ActivityState.DESTROYED;
3764 }
3765 } else {
3766 // remove this record from the history.
3767 if (r.finishing) {
3768 removeActivityFromHistoryLocked(r);
3769 removedFromHistory = true;
3770 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003771 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3772 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003773 r.state = ActivityState.DESTROYED;
3774 }
3775 }
3776
3777 r.configChangeFlags = 0;
3778
3779 if (!mLRUActivities.remove(r) && hadApp) {
3780 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
3781 }
3782
3783 return removedFromHistory;
3784 }
3785
3786 final void activityDestroyed(IBinder token) {
3787 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003788 ActivityRecord r = ActivityRecord.forToken(token);
3789 if (r != null) {
3790 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
3791 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003792
Dianne Hackbornbe707852011-11-11 14:32:10 -08003793 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003794 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003795 if (r.state == ActivityState.DESTROYING) {
3796 final long origId = Binder.clearCallingIdentity();
3797 removeActivityFromHistoryLocked(r);
3798 Binder.restoreCallingIdentity(origId);
3799 }
3800 }
3801 }
3802 }
3803
3804 private static void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
3805 int i = list.size();
3806 if (localLOGV) Slog.v(
3807 TAG, "Removing app " + app + " from list " + list
3808 + " with " + i + " entries");
3809 while (i > 0) {
3810 i--;
3811 ActivityRecord r = (ActivityRecord)list.get(i);
3812 if (localLOGV) Slog.v(
3813 TAG, "Record #" + i + " " + r + ": app=" + r.app);
3814 if (r.app == app) {
3815 if (localLOGV) Slog.v(TAG, "Removing this entry!");
3816 list.remove(i);
3817 }
3818 }
3819 }
3820
3821 void removeHistoryRecordsForAppLocked(ProcessRecord app) {
3822 removeHistoryRecordsForAppLocked(mLRUActivities, app);
3823 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003824 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003825 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
3826 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
3827 }
3828
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003829 /**
3830 * Move the current home activity's task (if one exists) to the front
3831 * of the stack.
3832 */
3833 final void moveHomeToFrontLocked() {
3834 TaskRecord homeTask = null;
3835 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003836 ActivityRecord hr = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003837 if (hr.isHomeActivity) {
3838 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003839 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003840 }
3841 }
3842 if (homeTask != null) {
3843 moveTaskToFrontLocked(homeTask, null);
3844 }
3845 }
3846
3847
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003848 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason) {
3849 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
3850
3851 final int task = tr.taskId;
3852 int top = mHistory.size()-1;
3853
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003854 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003855 // nothing to do!
3856 return;
3857 }
3858
Dianne Hackbornbe707852011-11-11 14:32:10 -08003859 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003860
3861 // Applying the affinities may have removed entries from the history,
3862 // so get the size again.
3863 top = mHistory.size()-1;
3864 int pos = top;
3865
3866 // Shift all activities with this task up to the top
3867 // of the stack, keeping them in the same internal order.
3868 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003869 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003870 if (localLOGV) Slog.v(
3871 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003872 if (r.task.taskId == task) {
3873 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003874 if (DEBUG_ADD_REMOVE) {
3875 RuntimeException here = new RuntimeException("here");
3876 here.fillInStackTrace();
3877 Slog.i(TAG, "Removing and adding activity " + r + " to stack at " + top, here);
3878 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003879 mHistory.remove(pos);
3880 mHistory.add(top, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003881 moved.add(0, r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003882 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003883 }
3884 pos--;
3885 }
3886
3887 if (DEBUG_TRANSITION) Slog.v(TAG,
3888 "Prepare to front transition: task=" + tr);
3889 if (reason != null &&
3890 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003891 mService.mWindowManager.prepareAppTransition(
3892 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003893 ActivityRecord r = topRunningActivityLocked(null);
3894 if (r != null) {
3895 mNoAnimActivities.add(r);
3896 }
3897 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003898 mService.mWindowManager.prepareAppTransition(
3899 WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003900 }
3901
3902 mService.mWindowManager.moveAppTokensToTop(moved);
3903 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003904 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003905 }
3906
3907 finishTaskMoveLocked(task);
3908 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
3909 }
3910
3911 private final void finishTaskMoveLocked(int task) {
3912 resumeTopActivityLocked(null);
3913 }
3914
3915 /**
3916 * Worker method for rearranging history stack. Implements the function of moving all
3917 * activities for a specific task (gathering them if disjoint) into a single group at the
3918 * bottom of the stack.
3919 *
3920 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
3921 * to premeptively cancel the move.
3922 *
3923 * @param task The taskId to collect and move to the bottom.
3924 * @return Returns true if the move completed, false if not.
3925 */
3926 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
3927 Slog.i(TAG, "moveTaskToBack: " + task);
3928
3929 // If we have a watcher, preflight the move before committing to it. First check
3930 // for *other* available tasks, but if none are available, then try again allowing the
3931 // current task to be selected.
3932 if (mMainStack && mService.mController != null) {
3933 ActivityRecord next = topRunningActivityLocked(null, task);
3934 if (next == null) {
3935 next = topRunningActivityLocked(null, 0);
3936 }
3937 if (next != null) {
3938 // ask watcher if this is allowed
3939 boolean moveOK = true;
3940 try {
3941 moveOK = mService.mController.activityResuming(next.packageName);
3942 } catch (RemoteException e) {
3943 mService.mController = null;
3944 }
3945 if (!moveOK) {
3946 return false;
3947 }
3948 }
3949 }
3950
Dianne Hackbornbe707852011-11-11 14:32:10 -08003951 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003952
3953 if (DEBUG_TRANSITION) Slog.v(TAG,
3954 "Prepare to back transition: task=" + task);
3955
3956 final int N = mHistory.size();
3957 int bottom = 0;
3958 int pos = 0;
3959
3960 // Shift all activities with this task down to the bottom
3961 // of the stack, keeping them in the same internal order.
3962 while (pos < N) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003963 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003964 if (localLOGV) Slog.v(
3965 TAG, "At " + pos + " ckp " + r.task + ": " + r);
3966 if (r.task.taskId == task) {
3967 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003968 if (DEBUG_ADD_REMOVE) {
3969 RuntimeException here = new RuntimeException("here");
3970 here.fillInStackTrace();
3971 Slog.i(TAG, "Removing and adding activity " + r + " to stack at "
3972 + bottom, here);
3973 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003974 mHistory.remove(pos);
3975 mHistory.add(bottom, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003976 moved.add(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003977 bottom++;
3978 }
3979 pos++;
3980 }
3981
3982 if (reason != null &&
3983 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003984 mService.mWindowManager.prepareAppTransition(
3985 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003986 ActivityRecord r = topRunningActivityLocked(null);
3987 if (r != null) {
3988 mNoAnimActivities.add(r);
3989 }
3990 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003991 mService.mWindowManager.prepareAppTransition(
3992 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003993 }
3994 mService.mWindowManager.moveAppTokensToBottom(moved);
3995 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003996 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003997 }
3998
3999 finishTaskMoveLocked(task);
4000 return true;
4001 }
4002
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004003 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
4004 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4005 ActivityRecord resumed = mResumedActivity;
4006 if (resumed != null && resumed.thumbHolder == tr) {
4007 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
4008 } else {
4009 info.mainThumbnail = tr.lastThumbnail;
4010 }
4011 return info;
4012 }
4013
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004014 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex,
4015 boolean taskRequired) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004016 TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
4017 if (info.root == null) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004018 if (taskRequired) {
4019 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
4020 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004021 return null;
4022 }
4023
4024 if (subTaskIndex < 0) {
4025 // Just remove the entire task.
4026 performClearTaskAtIndexLocked(taskId, info.rootIndex);
4027 return info.root;
4028 }
4029
4030 if (subTaskIndex >= info.subtasks.size()) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004031 if (taskRequired) {
4032 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
4033 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004034 return null;
4035 }
4036
4037 // Remove all of this task's activies starting at the sub task.
4038 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
4039 performClearTaskAtIndexLocked(taskId, subtask.index);
4040 return subtask.activity;
4041 }
4042
4043 public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
4044 ActivityRecord resumed = mResumedActivity;
4045 final TaskAccessInfo thumbs = new TaskAccessInfo();
4046 // How many different sub-thumbnails?
4047 final int NA = mHistory.size();
4048 int j = 0;
4049 ThumbnailHolder holder = null;
4050 while (j < NA) {
4051 ActivityRecord ar = mHistory.get(j);
4052 if (!ar.finishing && ar.task.taskId == taskId) {
4053 holder = ar.thumbHolder;
4054 break;
4055 }
4056 j++;
4057 }
4058
4059 if (j >= NA) {
4060 return thumbs;
4061 }
4062
4063 thumbs.root = mHistory.get(j);
4064 thumbs.rootIndex = j;
4065
4066 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
4067 thumbs.subtasks = subtasks;
4068 ActivityRecord lastActivity = null;
4069 while (j < NA) {
4070 ActivityRecord ar = mHistory.get(j);
4071 j++;
4072 if (ar.finishing) {
4073 continue;
4074 }
4075 if (ar.task.taskId != taskId) {
4076 break;
4077 }
4078 lastActivity = ar;
4079 if (ar.thumbHolder != holder && holder != null) {
4080 thumbs.numSubThumbbails++;
4081 holder = ar.thumbHolder;
4082 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
4083 sub.thumbnail = holder.lastThumbnail;
4084 sub.activity = ar;
4085 sub.index = j-1;
4086 subtasks.add(sub);
4087 }
4088 }
4089 if (lastActivity != null && subtasks.size() > 0) {
4090 if (resumed == lastActivity) {
4091 TaskAccessInfo.SubTask sub = subtasks.get(subtasks.size()-1);
4092 sub.thumbnail = lastActivity.stack.screenshotActivities(lastActivity);
4093 }
4094 }
4095 if (thumbs.numSubThumbbails > 0) {
4096 thumbs.retriever = new IThumbnailRetriever.Stub() {
4097 public Bitmap getThumbnail(int index) {
4098 if (index < 0 || index >= thumbs.subtasks.size()) {
4099 return null;
4100 }
4101 return thumbs.subtasks.get(index).thumbnail;
4102 }
4103 };
4104 }
4105 return thumbs;
4106 }
4107
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004108 private final void logStartActivity(int tag, ActivityRecord r,
4109 TaskRecord task) {
4110 EventLog.writeEvent(tag,
4111 System.identityHashCode(r), task.taskId,
4112 r.shortComponentName, r.intent.getAction(),
4113 r.intent.getType(), r.intent.getDataString(),
4114 r.intent.getFlags());
4115 }
4116
4117 /**
4118 * Make sure the given activity matches the current configuration. Returns
4119 * false if the activity had to be destroyed. Returns true if the
4120 * configuration is the same, or the activity will remain running as-is
4121 * for whatever reason. Ensures the HistoryRecord is updated with the
4122 * correct configuration and all other bookkeeping is handled.
4123 */
4124 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
4125 int globalChanges) {
4126 if (mConfigWillChange) {
4127 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4128 "Skipping config check (will change): " + r);
4129 return true;
4130 }
4131
4132 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4133 "Ensuring correct configuration: " + r);
4134
4135 // Short circuit: if the two configurations are the exact same
4136 // object (the common case), then there is nothing to do.
4137 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004138 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004139 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4140 "Configuration unchanged in " + r);
4141 return true;
4142 }
4143
4144 // We don't worry about activities that are finishing.
4145 if (r.finishing) {
4146 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4147 "Configuration doesn't matter in finishing " + r);
4148 r.stopFreezingScreenLocked(false);
4149 return true;
4150 }
4151
4152 // Okay we now are going to make this activity have the new config.
4153 // But then we need to figure out how it needs to deal with that.
4154 Configuration oldConfig = r.configuration;
4155 r.configuration = newConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004156
4157 // Determine what has changed. May be nothing, if this is a config
4158 // that has come back from the app after going idle. In that case
4159 // we just want to leave the official config object now in the
4160 // activity and do nothing else.
4161 final int changes = oldConfig.diff(newConfig);
4162 if (changes == 0 && !r.forceNewConfig) {
4163 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4164 "Configuration no differences in " + r);
4165 return true;
4166 }
4167
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004168 // If the activity isn't currently running, just leave the new
4169 // configuration and it will pick that up next time it starts.
4170 if (r.app == null || r.app.thread == null) {
4171 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4172 "Configuration doesn't matter not running " + r);
4173 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004174 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004175 return true;
4176 }
4177
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004178 // Figure out how to handle the changes between the configurations.
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004179 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4180 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
4181 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07004182 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004183 + ", newConfig=" + newConfig);
4184 }
Dianne Hackborne6676352011-06-01 16:51:20 -07004185 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004186 // Aha, the activity isn't handling the change, so DIE DIE DIE.
4187 r.configChangeFlags |= changes;
4188 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004189 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004190 if (r.app == null || r.app.thread == null) {
4191 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4192 "Switch is destroying non-running " + r);
Dianne Hackborn28695e02011-11-02 21:59:51 -07004193 destroyActivityLocked(r, true, false, "config");
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004194 } else if (r.state == ActivityState.PAUSING) {
4195 // A little annoying: we are waiting for this activity to
4196 // finish pausing. Let's not do anything now, but just
4197 // flag that it needs to be restarted when done pausing.
4198 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4199 "Switch is skipping already pausing " + r);
4200 r.configDestroy = true;
4201 return true;
4202 } else if (r.state == ActivityState.RESUMED) {
4203 // Try to optimize this case: the configuration is changing
4204 // and we need to restart the top, resumed activity.
4205 // Instead of doing the normal handshaking, just say
4206 // "restart!".
4207 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4208 "Switch is restarting resumed " + r);
4209 relaunchActivityLocked(r, r.configChangeFlags, true);
4210 r.configChangeFlags = 0;
4211 } else {
4212 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4213 "Switch is restarting non-resumed " + r);
4214 relaunchActivityLocked(r, r.configChangeFlags, false);
4215 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004216 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004217
4218 // All done... tell the caller we weren't able to keep this
4219 // activity around.
4220 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004221 }
4222
4223 // Default case: the activity can handle this new configuration, so
4224 // hand it over. Note that we don't need to give it the new
4225 // configuration, since we always send configuration changes to all
4226 // process when they happen so it can just use whatever configuration
4227 // it last got.
4228 if (r.app != null && r.app.thread != null) {
4229 try {
4230 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004231 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004232 } catch (RemoteException e) {
4233 // If process died, whatever.
4234 }
4235 }
4236 r.stopFreezingScreenLocked(false);
4237
4238 return true;
4239 }
4240
4241 private final boolean relaunchActivityLocked(ActivityRecord r,
4242 int changes, boolean andResume) {
4243 List<ResultInfo> results = null;
4244 List<Intent> newIntents = null;
4245 if (andResume) {
4246 results = r.results;
4247 newIntents = r.newIntents;
4248 }
4249 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4250 + " with results=" + results + " newIntents=" + newIntents
4251 + " andResume=" + andResume);
4252 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
4253 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
4254 r.task.taskId, r.shortComponentName);
4255
4256 r.startFreezingScreenLocked(r.app, 0);
4257
4258 try {
4259 if (DEBUG_SWITCH) Slog.i(TAG, "Switch is restarting resumed " + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004260 r.forceNewConfig = false;
Dianne Hackbornbe707852011-11-11 14:32:10 -08004261 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004262 changes, !andResume, new Configuration(mService.mConfiguration));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004263 // Note: don't need to call pauseIfSleepingLocked() here, because
4264 // the caller will only pass in 'andResume' if this activity is
4265 // currently resumed, which implies we aren't sleeping.
4266 } catch (RemoteException e) {
4267 return false;
4268 }
4269
4270 if (andResume) {
4271 r.results = null;
4272 r.newIntents = null;
4273 if (mMainStack) {
4274 mService.reportResumedActivityLocked(r);
4275 }
4276 }
4277
4278 return true;
4279 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004280
4281 public void dismissKeyguardOnNextActivityLocked() {
4282 mDismissKeyguardOnNextActivity = true;
4283 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004284}