blob: 0430c748925a0f78a17544f49a00723b7f02983f [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006-2008 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.os.BatteryStatsImpl;
Dianne Hackbornde7faf62009-06-30 13:27:30 -070020import com.android.server.AttributeCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import com.android.server.IntentResolver;
22import com.android.server.ProcessMap;
23import com.android.server.ProcessStats;
24import com.android.server.SystemServer;
25import com.android.server.Watchdog;
26import com.android.server.WindowManagerService;
27
Dianne Hackborndd71fc82009-12-16 19:24:32 -080028import dalvik.system.Zygote;
29
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.app.Activity;
31import android.app.ActivityManager;
32import android.app.ActivityManagerNative;
33import android.app.ActivityThread;
34import android.app.AlertDialog;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020035import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070037import android.app.IActivityController;
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -080038import android.app.IActivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.app.IActivityWatcher;
40import android.app.IApplicationThread;
41import android.app.IInstrumentationWatcher;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.app.IServiceConnection;
43import android.app.IThumbnailReceiver;
44import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070045import android.app.Notification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.app.PendingIntent;
47import android.app.ResultInfo;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070048import android.app.Service;
Christopher Tate45281862010-03-05 15:46:30 -080049import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020050import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080051import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.content.ComponentName;
53import android.content.ContentResolver;
54import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020055import android.content.DialogInterface;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.Intent;
57import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070058import android.content.IIntentReceiver;
59import android.content.IIntentSender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070060import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.content.pm.ActivityInfo;
62import android.content.pm.ApplicationInfo;
63import android.content.pm.ConfigurationInfo;
64import android.content.pm.IPackageDataObserver;
65import android.content.pm.IPackageManager;
66import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080067import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.content.pm.PackageManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070069import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.content.pm.ProviderInfo;
71import android.content.pm.ResolveInfo;
72import android.content.pm.ServiceInfo;
73import android.content.res.Configuration;
74import android.graphics.Bitmap;
75import android.net.Uri;
76import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080077import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080078import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070079import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080080import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080082import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import android.os.FileUtils;
84import android.os.Handler;
85import android.os.IBinder;
86import android.os.IPermissionController;
87import android.os.Looper;
88import android.os.Message;
89import android.os.Parcel;
90import android.os.ParcelFileDescriptor;
91import android.os.PowerManager;
92import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070093import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094import android.os.RemoteException;
95import android.os.ServiceManager;
96import android.os.SystemClock;
97import android.os.SystemProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099import android.util.Config;
100import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800101import android.util.Slog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800102import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import android.util.PrintWriterPrinter;
104import android.util.SparseArray;
105import android.view.Gravity;
106import android.view.LayoutInflater;
107import android.view.View;
108import android.view.WindowManager;
109import android.view.WindowManagerPolicy;
110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import java.io.File;
112import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import java.io.FileNotFoundException;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200114import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800115import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116import java.io.PrintWriter;
117import java.lang.IllegalStateException;
118import java.lang.ref.WeakReference;
119import java.util.ArrayList;
120import java.util.HashMap;
121import java.util.HashSet;
122import java.util.Iterator;
123import java.util.List;
124import java.util.Locale;
125import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700126import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700127import java.util.concurrent.atomic.AtomicBoolean;
128import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129
130public final class ActivityManagerService extends ActivityManagerNative implements Watchdog.Monitor {
131 static final String TAG = "ActivityManager";
132 static final boolean DEBUG = false;
133 static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
134 static final boolean DEBUG_SWITCH = localLOGV || false;
135 static final boolean DEBUG_TASKS = localLOGV || false;
136 static final boolean DEBUG_PAUSE = localLOGV || false;
137 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
138 static final boolean DEBUG_TRANSITION = localLOGV || false;
139 static final boolean DEBUG_BROADCAST = localLOGV || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700140 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141 static final boolean DEBUG_SERVICE = localLOGV || false;
142 static final boolean DEBUG_VISBILITY = localLOGV || false;
143 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700144 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800145 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700147 static final boolean DEBUG_RESULTS = localLOGV || false;
Christopher Tate436344a2009-09-30 16:17:37 -0700148 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700149 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150 static final boolean VALIDATE_TOKENS = false;
151 static final boolean SHOW_ACTIVITY_START_TIME = true;
152
153 // Control over CPU and battery monitoring.
154 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
155 static final boolean MONITOR_CPU_USAGE = true;
156 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
157 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
158 static final boolean MONITOR_THREAD_CPU_USAGE = false;
159
Dianne Hackborn1655be42009-05-08 14:29:01 -0700160 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700161 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 private static final String SYSTEM_SECURE = "ro.secure";
164
165 // This is the maximum number of application processes we would like
166 // to have running. Due to the asynchronous nature of things, we can
167 // temporarily go beyond this limit.
168 static final int MAX_PROCESSES = 2;
169
170 // Set to false to leave processes running indefinitely, relying on
171 // the kernel killing them as resources are required.
172 static final boolean ENFORCE_PROCESS_LIMIT = false;
173
174 // This is the maximum number of activities that we would like to have
175 // running at a given time.
176 static final int MAX_ACTIVITIES = 20;
177
178 // Maximum number of recent tasks that we can remember.
179 static final int MAX_RECENT_TASKS = 20;
180
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700181 // Amount of time after a call to stopAppSwitches() during which we will
182 // prevent further untrusted switches from happening.
183 static final long APP_SWITCH_DELAY_TIME = 5*1000;
184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 // How long until we reset a task when the user returns to it. Currently
186 // 30 minutes.
187 static final long ACTIVITY_INACTIVE_RESET_TIME = 1000*60*30;
188
189 // Set to true to disable the icon that is shown while a new activity
190 // is being started.
191 static final boolean SHOW_APP_STARTING_ICON = true;
192
193 // How long we wait until giving up on the last activity to pause. This
194 // is short because it directly impacts the responsiveness of starting the
195 // next activity.
196 static final int PAUSE_TIMEOUT = 500;
197
198 /**
199 * How long we can hold the launch wake lock before giving up.
200 */
201 static final int LAUNCH_TIMEOUT = 10*1000;
202
203 // How long we wait for a launched process to attach to the activity manager
204 // before we decide it's never going to come up for real.
205 static final int PROC_START_TIMEOUT = 10*1000;
206
207 // How long we wait until giving up on the last activity telling us it
208 // is idle.
209 static final int IDLE_TIMEOUT = 10*1000;
210
211 // How long to wait after going idle before forcing apps to GC.
212 static final int GC_TIMEOUT = 5*1000;
213
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700214 // The minimum amount of time between successive GC requests for a process.
215 static final int GC_MIN_INTERVAL = 60*1000;
216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 // How long we wait until giving up on an activity telling us it has
218 // finished destroying itself.
219 static final int DESTROY_TIMEOUT = 10*1000;
220
221 // How long we allow a receiver to run before giving up on it.
222 static final int BROADCAST_TIMEOUT = 10*1000;
223
224 // How long we wait for a service to finish executing.
225 static final int SERVICE_TIMEOUT = 20*1000;
226
227 // How long a service needs to be running until restarting its process
228 // is no longer considered to be a relaunch of the service.
229 static final int SERVICE_RESTART_DURATION = 5*1000;
230
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700231 // How long a service needs to be running until it will start back at
232 // SERVICE_RESTART_DURATION after being killed.
233 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
234
235 // Multiplying factor to increase restart duration time by, for each time
236 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
237 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
238
239 // The minimum amount of time between restarting services that we allow.
240 // That is, when multiple services are restarting, we won't allow each
241 // to restart less than this amount of time from the last one.
242 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 // Maximum amount of time for there to be no activity on a service before
245 // we consider it non-essential and allow its process to go on the
246 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700247 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248
249 // How long we wait until we timeout on key dispatching.
250 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
251
252 // The minimum time we allow between crashes, for us to consider this
253 // application to be bad and stop and its services and reject broadcasts.
254 static final int MIN_CRASH_INTERVAL = 60*1000;
255
256 // How long we wait until we timeout on key dispatching during instrumentation.
257 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
258
259 // OOM adjustments for processes in various states:
260
261 // This is a process without anything currently running in it. Definitely
262 // the first to go! Value set in system/rootdir/init.rc on startup.
263 // This value is initalized in the constructor, careful when refering to
264 // this static variable externally.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800265 static final int EMPTY_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266
267 // This is a process only hosting activities that are not visible,
268 // so it can be killed without any disruption. Value set in
269 // system/rootdir/init.rc on startup.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800270 static final int HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271 static int HIDDEN_APP_MIN_ADJ;
272
The Android Open Source Project4df24232009-03-05 14:34:35 -0800273 // This is a process holding the home application -- we want to try
274 // avoiding killing it, even if it would normally be in the background,
275 // because the user interacts with it so much.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800276 static final int HOME_APP_ADJ;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800277
Christopher Tate6fa95972009-06-05 18:43:55 -0700278 // This is a process currently hosting a backup operation. Killing it
279 // is not entirely fatal but is generally a bad idea.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800280 static final int BACKUP_APP_ADJ;
Christopher Tate6fa95972009-06-05 18:43:55 -0700281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 // This is a process holding a secondary server -- killing it will not
283 // have much of an impact as far as the user is concerned. Value set in
284 // system/rootdir/init.rc on startup.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800285 static final int SECONDARY_SERVER_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286
287 // This is a process only hosting activities that are visible to the
288 // user, so we'd prefer they don't disappear. Value set in
289 // system/rootdir/init.rc on startup.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800290 static final int VISIBLE_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291
292 // This is the process running the current foreground app. We'd really
293 // rather not kill it! Value set in system/rootdir/init.rc on startup.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800294 static final int FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295
296 // This is a process running a core server, such as telephony. Definitely
297 // don't want to kill it, but doing so is not completely fatal.
298 static final int CORE_SERVER_ADJ = -12;
299
300 // The system process runs at the default adjustment.
301 static final int SYSTEM_ADJ = -16;
302
303 // Memory pages are 4K.
304 static final int PAGE_SIZE = 4*1024;
305
306 // Corresponding memory levels for above adjustments.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800307 static final int EMPTY_APP_MEM;
308 static final int HIDDEN_APP_MEM;
309 static final int HOME_APP_MEM;
310 static final int BACKUP_APP_MEM;
311 static final int SECONDARY_SERVER_MEM;
312 static final int VISIBLE_APP_MEM;
313 static final int FOREGROUND_APP_MEM;
314
315 // The minimum number of hidden apps we want to be able to keep around,
316 // without empty apps being able to push them out of memory.
317 static final int MIN_HIDDEN_APPS = 2;
318
Dianne Hackborn8633e682010-04-22 16:03:41 -0700319 // The maximum number of hidden processes we will keep around before
320 // killing them; this is just a control to not let us go too crazy with
321 // keeping around processes on devices with large amounts of RAM.
322 static final int MAX_HIDDEN_APPS = 15;
323
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800324 // We put empty content processes after any hidden processes that have
Dianne Hackborn906497c2010-05-10 15:57:38 -0700325 // been idle for less than 15 seconds.
326 static final long CONTENT_APP_IDLE_OFFSET = 15*1000;
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800327
328 // We put empty content processes after any hidden processes that have
Dianne Hackborn906497c2010-05-10 15:57:38 -0700329 // been idle for less than 120 seconds.
330 static final long EMPTY_APP_IDLE_OFFSET = 120*1000;
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800331
332 static {
333 // These values are set in system/rootdir/init.rc on startup.
334 FOREGROUND_APP_ADJ =
335 Integer.valueOf(SystemProperties.get("ro.FOREGROUND_APP_ADJ"));
336 VISIBLE_APP_ADJ =
337 Integer.valueOf(SystemProperties.get("ro.VISIBLE_APP_ADJ"));
338 SECONDARY_SERVER_ADJ =
339 Integer.valueOf(SystemProperties.get("ro.SECONDARY_SERVER_ADJ"));
340 BACKUP_APP_ADJ =
341 Integer.valueOf(SystemProperties.get("ro.BACKUP_APP_ADJ"));
342 HOME_APP_ADJ =
343 Integer.valueOf(SystemProperties.get("ro.HOME_APP_ADJ"));
344 HIDDEN_APP_MIN_ADJ =
345 Integer.valueOf(SystemProperties.get("ro.HIDDEN_APP_MIN_ADJ"));
346 EMPTY_APP_ADJ =
347 Integer.valueOf(SystemProperties.get("ro.EMPTY_APP_ADJ"));
348 HIDDEN_APP_MAX_ADJ = EMPTY_APP_ADJ-1;
349 FOREGROUND_APP_MEM =
350 Integer.valueOf(SystemProperties.get("ro.FOREGROUND_APP_MEM"))*PAGE_SIZE;
351 VISIBLE_APP_MEM =
352 Integer.valueOf(SystemProperties.get("ro.VISIBLE_APP_MEM"))*PAGE_SIZE;
353 SECONDARY_SERVER_MEM =
354 Integer.valueOf(SystemProperties.get("ro.SECONDARY_SERVER_MEM"))*PAGE_SIZE;
355 BACKUP_APP_MEM =
356 Integer.valueOf(SystemProperties.get("ro.BACKUP_APP_MEM"))*PAGE_SIZE;
357 HOME_APP_MEM =
358 Integer.valueOf(SystemProperties.get("ro.HOME_APP_MEM"))*PAGE_SIZE;
359 HIDDEN_APP_MEM =
360 Integer.valueOf(SystemProperties.get("ro.HIDDEN_APP_MEM"))*PAGE_SIZE;
361 EMPTY_APP_MEM =
362 Integer.valueOf(SystemProperties.get("ro.EMPTY_APP_MEM"))*PAGE_SIZE;
363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364
Dan Egnor42471dd2010-01-07 17:25:22 -0800365 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366
367 static final String[] EMPTY_STRING_ARRAY = new String[0];
368
369 enum ActivityState {
370 INITIALIZING,
371 RESUMED,
372 PAUSING,
373 PAUSED,
374 STOPPING,
375 STOPPED,
376 FINISHING,
377 DESTROYING,
378 DESTROYED
379 }
380
381 /**
382 * The back history of all previous (and possibly still
383 * running) activities. It contains HistoryRecord objects.
384 */
385 final ArrayList mHistory = new ArrayList();
386
387 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700388 * Description of a request to start a new activity, which has been held
389 * due to app switches being disabled.
390 */
391 class PendingActivityLaunch {
392 HistoryRecord r;
393 HistoryRecord sourceRecord;
394 Uri[] grantedUriPermissions;
395 int grantedMode;
396 boolean onlyIfNeeded;
397 }
398
399 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
400 = new ArrayList<PendingActivityLaunch>();
401
402 /**
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -0800403 * List of people waiting to find out about the next launched activity.
404 */
405 final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched
406 = new ArrayList<IActivityManager.WaitResult>();
407
408 /**
409 * List of people waiting to find out about the next visible activity.
410 */
411 final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible
412 = new ArrayList<IActivityManager.WaitResult>();
413
414 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800415 * List of all active broadcasts that are to be executed immediately
416 * (without waiting for another broadcast to finish). Currently this only
417 * contains broadcasts to registered receivers, to avoid spinning up
418 * a bunch of processes to execute IntentReceiver components.
419 */
420 final ArrayList<BroadcastRecord> mParallelBroadcasts
421 = new ArrayList<BroadcastRecord>();
422
423 /**
424 * List of all active broadcasts that are to be executed one at a time.
425 * The object at the top of the list is the currently activity broadcasts;
426 * those after it are waiting for the top to finish..
427 */
428 final ArrayList<BroadcastRecord> mOrderedBroadcasts
429 = new ArrayList<BroadcastRecord>();
430
431 /**
Dianne Hackborn12527f92009-11-11 17:39:50 -0800432 * Historical data of past broadcasts, for debugging.
433 */
434 static final int MAX_BROADCAST_HISTORY = 100;
435 final BroadcastRecord[] mBroadcastHistory
436 = new BroadcastRecord[MAX_BROADCAST_HISTORY];
437
438 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439 * Set when we current have a BROADCAST_INTENT_MSG in flight.
440 */
441 boolean mBroadcastsScheduled = false;
442
443 /**
444 * Set to indicate whether to issue an onUserLeaving callback when a
445 * newly launched activity is being brought in front of us.
446 */
447 boolean mUserLeaving = false;
448
449 /**
450 * When we are in the process of pausing an activity, before starting the
451 * next one, this variable holds the activity that is currently being paused.
452 */
453 HistoryRecord mPausingActivity = null;
454
455 /**
456 * Current activity that is resumed, or null if there is none.
457 */
458 HistoryRecord mResumedActivity = null;
459
460 /**
461 * Activity we have told the window manager to have key focus.
462 */
463 HistoryRecord mFocusedActivity = null;
464
465 /**
466 * This is the last activity that we put into the paused state. This is
467 * used to determine if we need to do an activity transition while sleeping,
468 * when we normally hold the top activity paused.
469 */
470 HistoryRecord mLastPausedActivity = null;
471
472 /**
473 * List of activities that are waiting for a new activity
474 * to become visible before completing whatever operation they are
475 * supposed to do.
476 */
477 final ArrayList mWaitingVisibleActivities = new ArrayList();
478
479 /**
480 * List of activities that are ready to be stopped, but waiting
481 * for the next activity to settle down before doing so. It contains
482 * HistoryRecord objects.
483 */
484 final ArrayList<HistoryRecord> mStoppingActivities
485 = new ArrayList<HistoryRecord>();
486
487 /**
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700488 * Animations that for the current transition have requested not to
489 * be considered for the transition animation.
490 */
491 final ArrayList<HistoryRecord> mNoAnimActivities
492 = new ArrayList<HistoryRecord>();
493
494 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495 * List of intents that were used to start the most recent tasks.
496 */
497 final ArrayList<TaskRecord> mRecentTasks
498 = new ArrayList<TaskRecord>();
499
500 /**
501 * List of activities that are ready to be finished, but waiting
502 * for the previous activity to settle down before doing so. It contains
503 * HistoryRecord objects.
504 */
505 final ArrayList mFinishingActivities = new ArrayList();
506
507 /**
508 * All of the applications we currently have running organized by name.
509 * The keys are strings of the application package name (as
510 * returned by the package manager), and the keys are ApplicationRecord
511 * objects.
512 */
513 final ProcessMap<ProcessRecord> mProcessNames
514 = new ProcessMap<ProcessRecord>();
515
516 /**
517 * The last time that various processes have crashed.
518 */
519 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
520
521 /**
522 * Set of applications that we consider to be bad, and will reject
523 * incoming broadcasts from (which the user has no control over).
524 * Processes are added to this set when they have crashed twice within
525 * a minimum amount of time; they are removed from it when they are
526 * later restarted (hopefully due to some user action). The value is the
527 * time it was added to the list.
528 */
529 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
530
531 /**
532 * All of the processes we currently have running organized by pid.
533 * The keys are the pid running the application.
534 *
535 * <p>NOTE: This object is protected by its own lock, NOT the global
536 * activity manager lock!
537 */
538 final SparseArray<ProcessRecord> mPidsSelfLocked
539 = new SparseArray<ProcessRecord>();
540
541 /**
542 * All of the processes that have been forced to be foreground. The key
543 * is the pid of the caller who requested it (we hold a death
544 * link on it).
545 */
546 abstract class ForegroundToken implements IBinder.DeathRecipient {
547 int pid;
548 IBinder token;
549 }
550 final SparseArray<ForegroundToken> mForegroundProcesses
551 = new SparseArray<ForegroundToken>();
552
553 /**
554 * List of records for processes that someone had tried to start before the
555 * system was ready. We don't start them at that point, but ensure they
556 * are started by the time booting is complete.
557 */
558 final ArrayList<ProcessRecord> mProcessesOnHold
559 = new ArrayList<ProcessRecord>();
560
561 /**
562 * List of records for processes that we have started and are waiting
563 * for them to call back. This is really only needed when running in
564 * single processes mode, in which case we do not have a unique pid for
565 * each process.
566 */
567 final ArrayList<ProcessRecord> mStartingProcesses
568 = new ArrayList<ProcessRecord>();
569
570 /**
571 * List of persistent applications that are in the process
572 * of being started.
573 */
574 final ArrayList<ProcessRecord> mPersistentStartingProcesses
575 = new ArrayList<ProcessRecord>();
576
577 /**
578 * Processes that are being forcibly torn down.
579 */
580 final ArrayList<ProcessRecord> mRemovedProcesses
581 = new ArrayList<ProcessRecord>();
582
583 /**
584 * List of running applications, sorted by recent usage.
585 * The first entry in the list is the least recently used.
586 * It contains ApplicationRecord objects. This list does NOT include
587 * any persistent application records (since we never want to exit them).
588 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800589 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 = new ArrayList<ProcessRecord>();
591
592 /**
593 * List of processes that should gc as soon as things are idle.
594 */
595 final ArrayList<ProcessRecord> mProcessesToGc
596 = new ArrayList<ProcessRecord>();
597
598 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800599 * This is the process holding what we currently consider to be
600 * the "home" activity.
601 */
602 private ProcessRecord mHomeProcess;
603
604 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 * List of running activities, sorted by recent usage.
606 * The first entry in the list is the least recently used.
607 * It contains HistoryRecord objects.
608 */
609 private final ArrayList mLRUActivities = new ArrayList();
610
611 /**
612 * Set of PendingResultRecord objects that are currently active.
613 */
614 final HashSet mPendingResultRecords = new HashSet();
615
616 /**
617 * Set of IntentSenderRecord objects that are currently active.
618 */
619 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
620 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
621
622 /**
623 * Intent broadcast that we have tried to start, but are
624 * waiting for its application's process to be created. We only
625 * need one (instead of a list) because we always process broadcasts
626 * one at a time, so no others can be started while waiting for this
627 * one.
628 */
629 BroadcastRecord mPendingBroadcast = null;
630
631 /**
632 * Keeps track of all IIntentReceivers that have been registered for
633 * broadcasts. Hash keys are the receiver IBinder, hash value is
634 * a ReceiverList.
635 */
636 final HashMap mRegisteredReceivers = new HashMap();
637
638 /**
639 * Resolver for broadcast intents to registered receivers.
640 * Holds BroadcastFilter (subclass of IntentFilter).
641 */
642 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
643 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
644 @Override
645 protected boolean allowFilterResult(
646 BroadcastFilter filter, List<BroadcastFilter> dest) {
647 IBinder target = filter.receiverList.receiver.asBinder();
648 for (int i=dest.size()-1; i>=0; i--) {
649 if (dest.get(i).receiverList.receiver.asBinder() == target) {
650 return false;
651 }
652 }
653 return true;
654 }
655 };
656
657 /**
658 * State of all active sticky broadcasts. Keys are the action of the
659 * sticky Intent, values are an ArrayList of all broadcasted intents with
660 * that action (which should usually be one).
661 */
662 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
663 new HashMap<String, ArrayList<Intent>>();
664
665 /**
666 * All currently running services.
667 */
668 final HashMap<ComponentName, ServiceRecord> mServices =
669 new HashMap<ComponentName, ServiceRecord>();
670
671 /**
672 * All currently running services indexed by the Intent used to start them.
673 */
674 final HashMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent =
675 new HashMap<Intent.FilterComparison, ServiceRecord>();
676
677 /**
678 * All currently bound service connections. Keys are the IBinder of
679 * the client's IServiceConnection.
680 */
681 final HashMap<IBinder, ConnectionRecord> mServiceConnections
682 = new HashMap<IBinder, ConnectionRecord>();
683
684 /**
685 * List of services that we have been asked to start,
686 * but haven't yet been able to. It is used to hold start requests
687 * while waiting for their corresponding application thread to get
688 * going.
689 */
690 final ArrayList<ServiceRecord> mPendingServices
691 = new ArrayList<ServiceRecord>();
692
693 /**
694 * List of services that are scheduled to restart following a crash.
695 */
696 final ArrayList<ServiceRecord> mRestartingServices
697 = new ArrayList<ServiceRecord>();
698
699 /**
700 * List of services that are in the process of being stopped.
701 */
702 final ArrayList<ServiceRecord> mStoppingServices
703 = new ArrayList<ServiceRecord>();
704
705 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700706 * Backup/restore process management
707 */
708 String mBackupAppName = null;
709 BackupRecord mBackupTarget = null;
710
711 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 * List of PendingThumbnailsRecord objects of clients who are still
713 * waiting to receive all of the thumbnails for a task.
714 */
715 final ArrayList mPendingThumbnails = new ArrayList();
716
717 /**
718 * List of HistoryRecord objects that have been finished and must
719 * still report back to a pending thumbnail receiver.
720 */
721 final ArrayList mCancelledThumbnails = new ArrayList();
722
723 /**
724 * All of the currently running global content providers. Keys are a
725 * string containing the provider name and values are a
726 * ContentProviderRecord object containing the data about it. Note
727 * that a single provider may be published under multiple names, so
728 * there may be multiple entries here for a single one in mProvidersByClass.
729 */
730 final HashMap mProvidersByName = new HashMap();
731
732 /**
733 * All of the currently running global content providers. Keys are a
734 * string containing the provider's implementation class and values are a
735 * ContentProviderRecord object containing the data about it.
736 */
737 final HashMap mProvidersByClass = new HashMap();
738
739 /**
740 * List of content providers who have clients waiting for them. The
741 * application is currently being launched and the provider will be
742 * removed from this list once it is published.
743 */
744 final ArrayList mLaunchingProviders = new ArrayList();
745
746 /**
747 * Global set of specific Uri permissions that have been granted.
748 */
749 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
750 = new SparseArray<HashMap<Uri, UriPermission>>();
751
752 /**
753 * Thread-local storage used to carry caller permissions over through
754 * indirect content-provider access.
755 * @see #ActivityManagerService.openContentUri()
756 */
757 private class Identity {
758 public int pid;
759 public int uid;
760
761 Identity(int _pid, int _uid) {
762 pid = _pid;
763 uid = _uid;
764 }
765 }
766 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
767
768 /**
769 * All information we have collected about the runtime performance of
770 * any user id that can impact battery performance.
771 */
772 final BatteryStatsService mBatteryStatsService;
773
774 /**
775 * information about component usage
776 */
777 final UsageStatsService mUsageStatsService;
778
779 /**
780 * Current configuration information. HistoryRecord objects are given
781 * a reference to this object to indicate which configuration they are
782 * currently running in, so this object must be kept immutable.
783 */
784 Configuration mConfiguration = new Configuration();
785
786 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800787 * Current sequencing integer of the configuration, for skipping old
788 * configurations.
789 */
790 int mConfigurationSeq = 0;
791
792 /**
Dianne Hackbornd49258f2010-03-26 00:44:29 -0700793 * Set when we know we are going to be calling updateConfiguration()
794 * soon, so want to skip intermediate config checks.
795 */
796 boolean mConfigWillChange;
797
798 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700799 * Hardware-reported OpenGLES version.
800 */
801 final int GL_ES_VERSION;
802
803 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 * List of initialization arguments to pass to all processes when binding applications to them.
805 * For example, references to the commonly used services.
806 */
807 HashMap<String, IBinder> mAppBindArgs;
808
809 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700810 * Temporary to avoid allocations. Protected by main lock.
811 */
812 final StringBuilder mStringBuilder = new StringBuilder(256);
813
814 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 * Used to control how we initialize the service.
816 */
817 boolean mStartRunning = false;
818 ComponentName mTopComponent;
819 String mTopAction;
820 String mTopData;
821 boolean mSystemReady = false;
822 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700823 boolean mWaitingUpdate = false;
824 boolean mDidUpdate = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825
826 Context mContext;
827
828 int mFactoryTest;
829
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700830 boolean mCheckedForSetup;
831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700833 * The time at which we will allow normal application switches again,
834 * after a call to {@link #stopAppSwitches()}.
835 */
836 long mAppSwitchesAllowedTime;
837
838 /**
839 * This is set to true after the first switch after mAppSwitchesAllowedTime
840 * is set; any switches after that will clear the time.
841 */
842 boolean mDidAppSwitch;
843
844 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 * Set while we are wanting to sleep, to prevent any
846 * activities from being started/resumed.
847 */
848 boolean mSleeping = false;
849
850 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700851 * Set if we are shutting down the system, similar to sleeping.
852 */
853 boolean mShuttingDown = false;
854
855 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 * Set when the system is going to sleep, until we have
857 * successfully paused the current activity and released our wake lock.
858 * At that point the system is allowed to actually sleep.
859 */
860 PowerManager.WakeLock mGoingToSleep;
861
862 /**
863 * We don't want to allow the device to go to sleep while in the process
864 * of launching an activity. This is primarily to allow alarm intent
865 * receivers to launch an activity and get that to run before the device
866 * goes back to sleep.
867 */
868 PowerManager.WakeLock mLaunchingActivity;
869
870 /**
871 * Task identifier that activities are currently being started
872 * in. Incremented each time a new task is created.
873 * todo: Replace this with a TokenSpace class that generates non-repeating
874 * integers that won't wrap.
875 */
876 int mCurTask = 1;
877
878 /**
879 * Current sequence id for oom_adj computation traversal.
880 */
881 int mAdjSeq = 0;
882
883 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700884 * Current sequence id for process LRU updating.
885 */
886 int mLruSeq = 0;
887
888 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 * Set to true if the ANDROID_SIMPLE_PROCESS_MANAGEMENT envvar
890 * is set, indicating the user wants processes started in such a way
891 * that they can use ANDROID_PROCESS_WRAPPER and know what will be
892 * running in each process (thus no pre-initialized process, etc).
893 */
894 boolean mSimpleProcessManagement = false;
895
896 /**
897 * System monitoring: number of processes that died since the last
898 * N procs were started.
899 */
900 int[] mProcDeaths = new int[20];
901
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700902 /**
903 * This is set if we had to do a delayed dexopt of an app before launching
904 * it, to increasing the ANR timeouts in that case.
905 */
906 boolean mDidDexOpt;
907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 String mDebugApp = null;
909 boolean mWaitForDebugger = false;
910 boolean mDebugTransient = false;
911 String mOrigDebugApp = null;
912 boolean mOrigWaitForDebugger = false;
913 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700914 IActivityController mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700916 final RemoteCallbackList<IActivityWatcher> mWatchers
917 = new RemoteCallbackList<IActivityWatcher>();
918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 /**
920 * Callback of last caller to {@link #requestPss}.
921 */
922 Runnable mRequestPssCallback;
923
924 /**
925 * Remaining processes for which we are waiting results from the last
926 * call to {@link #requestPss}.
927 */
928 final ArrayList<ProcessRecord> mRequestPssList
929 = new ArrayList<ProcessRecord>();
930
931 /**
932 * Runtime statistics collection thread. This object's lock is used to
933 * protect all related state.
934 */
935 final Thread mProcessStatsThread;
936
937 /**
938 * Used to collect process stats when showing not responding dialog.
939 * Protected by mProcessStatsThread.
940 */
941 final ProcessStats mProcessStats = new ProcessStats(
942 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700943 final AtomicLong mLastCpuTime = new AtomicLong(0);
944 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 long mLastWriteTime = 0;
947
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700948 long mInitialStartTime = 0;
949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 /**
951 * Set to true after the system has finished booting.
952 */
953 boolean mBooted = false;
954
955 int mProcessLimit = 0;
956
957 WindowManagerService mWindowManager;
958
959 static ActivityManagerService mSelf;
960 static ActivityThread mSystemThread;
961
962 private final class AppDeathRecipient implements IBinder.DeathRecipient {
963 final ProcessRecord mApp;
964 final int mPid;
965 final IApplicationThread mAppThread;
966
967 AppDeathRecipient(ProcessRecord app, int pid,
968 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800969 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 TAG, "New death recipient " + this
971 + " for thread " + thread.asBinder());
972 mApp = app;
973 mPid = pid;
974 mAppThread = thread;
975 }
976
977 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800978 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 TAG, "Death received in " + this
980 + " for thread " + mAppThread.asBinder());
981 removeRequestedPss(mApp);
982 synchronized(ActivityManagerService.this) {
983 appDiedLocked(mApp, mPid, mAppThread);
984 }
985 }
986 }
987
988 static final int SHOW_ERROR_MSG = 1;
989 static final int SHOW_NOT_RESPONDING_MSG = 2;
990 static final int SHOW_FACTORY_ERROR_MSG = 3;
991 static final int UPDATE_CONFIGURATION_MSG = 4;
992 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
993 static final int WAIT_FOR_DEBUGGER_MSG = 6;
994 static final int BROADCAST_INTENT_MSG = 7;
995 static final int BROADCAST_TIMEOUT_MSG = 8;
996 static final int PAUSE_TIMEOUT_MSG = 9;
997 static final int IDLE_TIMEOUT_MSG = 10;
998 static final int IDLE_NOW_MSG = 11;
999 static final int SERVICE_TIMEOUT_MSG = 12;
1000 static final int UPDATE_TIME_ZONE = 13;
1001 static final int SHOW_UID_ERROR_MSG = 14;
1002 static final int IM_FEELING_LUCKY_MSG = 15;
1003 static final int LAUNCH_TIMEOUT_MSG = 16;
1004 static final int DESTROY_TIMEOUT_MSG = 17;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 static final int RESUME_TOP_ACTIVITY_MSG = 19;
1006 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001007 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001008 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001009 static final int FINALIZE_PENDING_INTENT_MSG = 23;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010
1011 AlertDialog mUidAlert;
1012
1013 final Handler mHandler = new Handler() {
1014 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001015 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 //}
1017
1018 public void handleMessage(Message msg) {
1019 switch (msg.what) {
1020 case SHOW_ERROR_MSG: {
1021 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 synchronized (ActivityManagerService.this) {
1023 ProcessRecord proc = (ProcessRecord)data.get("app");
1024 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001025 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 return;
1027 }
1028 AppErrorResult res = (AppErrorResult) data.get("result");
Dianne Hackborn55280a92009-05-07 15:53:46 -07001029 if (!mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -08001030 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 d.show();
1032 proc.crashDialog = d;
1033 } else {
1034 // The device is asleep, so just pretend that the user
1035 // saw a crash dialog and hit "force quit".
1036 res.set(0);
1037 }
1038 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001039
1040 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 } break;
1042 case SHOW_NOT_RESPONDING_MSG: {
1043 synchronized (ActivityManagerService.this) {
1044 HashMap data = (HashMap) msg.obj;
1045 ProcessRecord proc = (ProcessRecord)data.get("app");
1046 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001047 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 return;
1049 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08001050
1051 broadcastIntentLocked(null, null, new Intent("android.intent.action.ANR"),
1052 null, null, 0, null, null, null,
1053 false, false, MY_PID, Process.SYSTEM_UID);
1054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
1056 mContext, proc, (HistoryRecord)data.get("activity"));
1057 d.show();
1058 proc.anrDialog = d;
1059 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001060
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001061 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 } break;
1063 case SHOW_FACTORY_ERROR_MSG: {
1064 Dialog d = new FactoryErrorDialog(
1065 mContext, msg.getData().getCharSequence("msg"));
1066 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001067 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 } break;
1069 case UPDATE_CONFIGURATION_MSG: {
1070 final ContentResolver resolver = mContext.getContentResolver();
1071 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
1072 } break;
1073 case GC_BACKGROUND_PROCESSES_MSG: {
1074 synchronized (ActivityManagerService.this) {
1075 performAppGcsIfAppropriateLocked();
1076 }
1077 } break;
1078 case WAIT_FOR_DEBUGGER_MSG: {
1079 synchronized (ActivityManagerService.this) {
1080 ProcessRecord app = (ProcessRecord)msg.obj;
1081 if (msg.arg1 != 0) {
1082 if (!app.waitedForDebugger) {
1083 Dialog d = new AppWaitingForDebuggerDialog(
1084 ActivityManagerService.this,
1085 mContext, app);
1086 app.waitDialog = d;
1087 app.waitedForDebugger = true;
1088 d.show();
1089 }
1090 } else {
1091 if (app.waitDialog != null) {
1092 app.waitDialog.dismiss();
1093 app.waitDialog = null;
1094 }
1095 }
1096 }
1097 } break;
1098 case BROADCAST_INTENT_MSG: {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001099 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 TAG, "Received BROADCAST_INTENT_MSG");
1101 processNextBroadcast(true);
1102 } break;
1103 case BROADCAST_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001104 if (mDidDexOpt) {
1105 mDidDexOpt = false;
1106 Message nmsg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG);
1107 mHandler.sendMessageDelayed(nmsg, BROADCAST_TIMEOUT);
1108 return;
1109 }
Jeff Hamiltonacf84742010-05-25 22:10:18 -05001110 // Only process broadcast timeouts if the system is ready. That way
1111 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
1112 // to do heavy lifting for system up
1113 if (mSystemReady) {
1114 broadcastTimeout();
1115 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 } break;
1117 case PAUSE_TIMEOUT_MSG: {
1118 IBinder token = (IBinder)msg.obj;
1119 // We don't at this point know if the activity is fullscreen,
1120 // so we need to be conservative and assume it isn't.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001121 Slog.w(TAG, "Activity pause timeout for " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 activityPaused(token, null, true);
1123 } break;
1124 case IDLE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001125 if (mDidDexOpt) {
1126 mDidDexOpt = false;
1127 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1128 nmsg.obj = msg.obj;
1129 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
1130 return;
1131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132 // We don't at this point know if the activity is fullscreen,
1133 // so we need to be conservative and assume it isn't.
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001134 IBinder token = (IBinder)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001135 Slog.w(TAG, "Activity idle timeout for " + token);
Dianne Hackborne88846e2009-09-30 21:34:25 -07001136 activityIdleInternal(token, true, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 } break;
1138 case DESTROY_TIMEOUT_MSG: {
1139 IBinder token = (IBinder)msg.obj;
1140 // We don't at this point know if the activity is fullscreen,
1141 // so we need to be conservative and assume it isn't.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001142 Slog.w(TAG, "Activity destroy timeout for " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 activityDestroyed(token);
1144 } break;
1145 case IDLE_NOW_MSG: {
1146 IBinder token = (IBinder)msg.obj;
Dianne Hackborne88846e2009-09-30 21:34:25 -07001147 activityIdle(token, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148 } break;
1149 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001150 if (mDidDexOpt) {
1151 mDidDexOpt = false;
1152 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1153 nmsg.obj = msg.obj;
1154 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
1155 return;
1156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 serviceTimeout((ProcessRecord)msg.obj);
1158 } break;
1159 case UPDATE_TIME_ZONE: {
1160 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001161 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1162 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 if (r.thread != null) {
1164 try {
1165 r.thread.updateTimeZone();
1166 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001167 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 }
1169 }
1170 }
1171 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001172 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 case SHOW_UID_ERROR_MSG: {
1174 // XXX This is a temporary dialog, no need to localize.
1175 AlertDialog d = new BaseErrorDialog(mContext);
1176 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1177 d.setCancelable(false);
1178 d.setTitle("System UIDs Inconsistent");
1179 d.setMessage("UIDs on the system are inconsistent, you need to wipe your data partition or your device will be unstable.");
Christian Mehlmauer7664e202010-07-20 08:46:17 +02001180 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1182 mUidAlert = d;
1183 d.show();
1184 } break;
1185 case IM_FEELING_LUCKY_MSG: {
1186 if (mUidAlert != null) {
1187 mUidAlert.dismiss();
1188 mUidAlert = null;
1189 }
1190 } break;
1191 case LAUNCH_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001192 if (mDidDexOpt) {
1193 mDidDexOpt = false;
1194 Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
1195 mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
1196 return;
1197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 synchronized (ActivityManagerService.this) {
1199 if (mLaunchingActivity.isHeld()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001200 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201 mLaunchingActivity.release();
1202 }
1203 }
1204 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 case RESUME_TOP_ACTIVITY_MSG: {
1206 synchronized (ActivityManagerService.this) {
1207 resumeTopActivityLocked(null);
1208 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001209 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001211 if (mDidDexOpt) {
1212 mDidDexOpt = false;
1213 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1214 nmsg.obj = msg.obj;
1215 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1216 return;
1217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 ProcessRecord app = (ProcessRecord)msg.obj;
1219 synchronized (ActivityManagerService.this) {
1220 processStartTimedOutLocked(app);
1221 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001222 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001223 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1224 synchronized (ActivityManagerService.this) {
1225 doPendingActivityLaunchesLocked(true);
1226 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001227 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001228 case KILL_APPLICATION_MSG: {
1229 synchronized (ActivityManagerService.this) {
1230 int uid = msg.arg1;
1231 boolean restart = (msg.arg2 == 1);
1232 String pkg = (String) msg.obj;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001233 forceStopPackageLocked(pkg, uid, restart, false, true);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001234 }
1235 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001236 case FINALIZE_PENDING_INTENT_MSG: {
1237 ((PendingIntentRecord)msg.obj).completeFinalize();
1238 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 }
1240 }
1241 };
1242
1243 public static void setSystemProcess() {
1244 try {
1245 ActivityManagerService m = mSelf;
1246
1247 ServiceManager.addService("activity", m);
1248 ServiceManager.addService("meminfo", new MemBinder(m));
1249 if (MONITOR_CPU_USAGE) {
1250 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1251 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 ServiceManager.addService("permission", new PermissionController(m));
1253
1254 ApplicationInfo info =
1255 mSelf.mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -07001256 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001257 mSystemThread.installSystemApplicationInfo(info);
1258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 synchronized (mSelf) {
1260 ProcessRecord app = mSelf.newProcessRecordLocked(
1261 mSystemThread.getApplicationThread(), info,
1262 info.processName);
1263 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001264 app.pid = MY_PID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 app.maxAdj = SYSTEM_ADJ;
1266 mSelf.mProcessNames.put(app.processName, app.info.uid, app);
1267 synchronized (mSelf.mPidsSelfLocked) {
1268 mSelf.mPidsSelfLocked.put(app.pid, app);
1269 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001270 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 }
1272 } catch (PackageManager.NameNotFoundException e) {
1273 throw new RuntimeException(
1274 "Unable to find android system package", e);
1275 }
1276 }
1277
1278 public void setWindowManager(WindowManagerService wm) {
1279 mWindowManager = wm;
1280 }
1281
1282 public static final Context main(int factoryTest) {
1283 AThread thr = new AThread();
1284 thr.start();
1285
1286 synchronized (thr) {
1287 while (thr.mService == null) {
1288 try {
1289 thr.wait();
1290 } catch (InterruptedException e) {
1291 }
1292 }
1293 }
1294
1295 ActivityManagerService m = thr.mService;
1296 mSelf = m;
1297 ActivityThread at = ActivityThread.systemMain();
1298 mSystemThread = at;
1299 Context context = at.getSystemContext();
1300 m.mContext = context;
1301 m.mFactoryTest = factoryTest;
1302 PowerManager pm =
1303 (PowerManager)context.getSystemService(Context.POWER_SERVICE);
1304 m.mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
1305 m.mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
1306 m.mLaunchingActivity.setReferenceCounted(false);
1307
1308 m.mBatteryStatsService.publish(context);
1309 m.mUsageStatsService.publish(context);
1310
1311 synchronized (thr) {
1312 thr.mReady = true;
1313 thr.notifyAll();
1314 }
1315
1316 m.startRunning(null, null, null, null);
1317
1318 return context;
1319 }
1320
1321 public static ActivityManagerService self() {
1322 return mSelf;
1323 }
1324
1325 static class AThread extends Thread {
1326 ActivityManagerService mService;
1327 boolean mReady = false;
1328
1329 public AThread() {
1330 super("ActivityManager");
1331 }
1332
1333 public void run() {
1334 Looper.prepare();
1335
1336 android.os.Process.setThreadPriority(
1337 android.os.Process.THREAD_PRIORITY_FOREGROUND);
1338
1339 ActivityManagerService m = new ActivityManagerService();
1340
1341 synchronized (this) {
1342 mService = m;
1343 notifyAll();
1344 }
1345
1346 synchronized (this) {
1347 while (!mReady) {
1348 try {
1349 wait();
1350 } catch (InterruptedException e) {
1351 }
1352 }
1353 }
1354
1355 Looper.loop();
1356 }
1357 }
1358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359 static class MemBinder extends Binder {
1360 ActivityManagerService mActivityManagerService;
1361 MemBinder(ActivityManagerService activityManagerService) {
1362 mActivityManagerService = activityManagerService;
1363 }
1364
1365 @Override
1366 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1367 ActivityManagerService service = mActivityManagerService;
1368 ArrayList<ProcessRecord> procs;
1369 synchronized (mActivityManagerService) {
1370 if (args != null && args.length > 0
1371 && args[0].charAt(0) != '-') {
1372 procs = new ArrayList<ProcessRecord>();
1373 int pid = -1;
1374 try {
1375 pid = Integer.parseInt(args[0]);
1376 } catch (NumberFormatException e) {
1377
1378 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001379 for (int i=service.mLruProcesses.size()-1; i>=0; i--) {
1380 ProcessRecord proc = service.mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 if (proc.pid == pid) {
1382 procs.add(proc);
1383 } else if (proc.processName.equals(args[0])) {
1384 procs.add(proc);
1385 }
1386 }
1387 if (procs.size() <= 0) {
1388 pw.println("No process found for: " + args[0]);
1389 return;
1390 }
1391 } else {
Dianne Hackborn472ad872010-04-07 17:31:48 -07001392 procs = new ArrayList<ProcessRecord>(service.mLruProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 }
1394 }
1395 dumpApplicationMemoryUsage(fd, pw, procs, " ", args);
1396 }
1397 }
1398
1399 static class CpuBinder extends Binder {
1400 ActivityManagerService mActivityManagerService;
1401 CpuBinder(ActivityManagerService activityManagerService) {
1402 mActivityManagerService = activityManagerService;
1403 }
1404
1405 @Override
1406 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1407 synchronized (mActivityManagerService.mProcessStatsThread) {
1408 pw.print(mActivityManagerService.mProcessStats.printCurrentState());
1409 }
1410 }
1411 }
1412
1413 private ActivityManagerService() {
1414 String v = System.getenv("ANDROID_SIMPLE_PROCESS_MANAGEMENT");
1415 if (v != null && Integer.getInteger(v) != 0) {
1416 mSimpleProcessManagement = true;
1417 }
1418 v = System.getenv("ANDROID_DEBUG_APP");
1419 if (v != null) {
1420 mSimpleProcessManagement = true;
1421 }
1422
Joe Onorato8a9b2202010-02-26 18:56:32 -08001423 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 File dataDir = Environment.getDataDirectory();
1426 File systemDir = new File(dataDir, "system");
1427 systemDir.mkdirs();
1428 mBatteryStatsService = new BatteryStatsService(new File(
1429 systemDir, "batterystats.bin").toString());
1430 mBatteryStatsService.getActiveStatistics().readLocked();
1431 mBatteryStatsService.getActiveStatistics().writeLocked();
1432
1433 mUsageStatsService = new UsageStatsService( new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001434 systemDir, "usagestats").toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435
Jack Palevichb90d28c2009-07-22 15:35:24 -07001436 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1437 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1438
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001439 mConfiguration.setToDefaults();
1440 mConfiguration.locale = Locale.getDefault();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 mProcessStats.init();
1442
1443 // Add ourself to the Watchdog monitors.
1444 Watchdog.getInstance().addMonitor(this);
1445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 mProcessStatsThread = new Thread("ProcessStats") {
1447 public void run() {
1448 while (true) {
1449 try {
1450 try {
1451 synchronized(this) {
1452 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001453 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001455 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 // + ", write delay=" + nextWriteDelay);
1457 if (nextWriteDelay < nextCpuDelay) {
1458 nextCpuDelay = nextWriteDelay;
1459 }
1460 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001461 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 this.wait(nextCpuDelay);
1463 }
1464 }
1465 } catch (InterruptedException e) {
1466 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 updateCpuStatsNow();
1468 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001469 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 }
1471 }
1472 }
1473 };
1474 mProcessStatsThread.start();
1475 }
1476
1477 @Override
1478 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1479 throws RemoteException {
1480 try {
1481 return super.onTransact(code, data, reply, flags);
1482 } catch (RuntimeException e) {
1483 // The activity manager only throws security exceptions, so let's
1484 // log all others.
1485 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001486 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 }
1488 throw e;
1489 }
1490 }
1491
1492 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001493 final long now = SystemClock.uptimeMillis();
1494 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1495 return;
1496 }
1497 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1498 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 mProcessStatsThread.notify();
1500 }
1501 }
1502 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 void updateCpuStatsNow() {
1505 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001506 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 final long now = SystemClock.uptimeMillis();
1508 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001511 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1512 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 haveNewCpuStats = true;
1514 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001515 //Slog.i(TAG, mProcessStats.printCurrentState());
1516 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 // + mProcessStats.getTotalCpuPercent() + "%");
1518
Joe Onorato8a9b2202010-02-26 18:56:32 -08001519 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 if ("true".equals(SystemProperties.get("events.cpu"))) {
1521 int user = mProcessStats.getLastUserTime();
1522 int system = mProcessStats.getLastSystemTime();
1523 int iowait = mProcessStats.getLastIoWaitTime();
1524 int irq = mProcessStats.getLastIrqTime();
1525 int softIrq = mProcessStats.getLastSoftIrqTime();
1526 int idle = mProcessStats.getLastIdleTime();
1527
1528 int total = user + system + iowait + irq + softIrq + idle;
1529 if (total == 0) total = 1;
1530
Doug Zongker2bec3d42009-12-04 12:52:44 -08001531 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 ((user+system+iowait+irq+softIrq) * 100) / total,
1533 (user * 100) / total,
1534 (system * 100) / total,
1535 (iowait * 100) / total,
1536 (irq * 100) / total,
1537 (softIrq * 100) / total);
1538 }
1539 }
1540
Amith Yamasanie43530a2009-08-21 13:11:37 -07001541 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001542 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001543 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 synchronized(mPidsSelfLocked) {
1545 if (haveNewCpuStats) {
1546 if (mBatteryStatsService.isOnBattery()) {
1547 final int N = mProcessStats.countWorkingStats();
1548 for (int i=0; i<N; i++) {
1549 ProcessStats.Stats st
1550 = mProcessStats.getWorkingStats(i);
1551 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
1552 if (pr != null) {
1553 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
1554 ps.addCpuTimeLocked(st.rel_utime, st.rel_stime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001555 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001556 } else {
1557 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001558 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001559 if (ps != null) {
1560 ps.addCpuTimeLocked(st.rel_utime, st.rel_stime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001561 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 }
1564 }
1565 }
1566 }
1567 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1570 mLastWriteTime = now;
1571 mBatteryStatsService.getActiveStatistics().writeLocked();
1572 }
1573 }
1574 }
1575 }
1576
1577 /**
1578 * Initialize the application bind args. These are passed to each
1579 * process when the bindApplication() IPC is sent to the process. They're
1580 * lazily setup to make sure the services are running when they're asked for.
1581 */
1582 private HashMap<String, IBinder> getCommonServicesLocked() {
1583 if (mAppBindArgs == null) {
1584 mAppBindArgs = new HashMap<String, IBinder>();
1585
1586 // Setup the application init args
1587 mAppBindArgs.put("package", ServiceManager.getService("package"));
1588 mAppBindArgs.put("window", ServiceManager.getService("window"));
1589 mAppBindArgs.put(Context.ALARM_SERVICE,
1590 ServiceManager.getService(Context.ALARM_SERVICE));
1591 }
1592 return mAppBindArgs;
1593 }
1594
1595 private final void setFocusedActivityLocked(HistoryRecord r) {
1596 if (mFocusedActivity != r) {
1597 mFocusedActivity = r;
1598 mWindowManager.setFocusedApp(r, true);
1599 }
1600 }
1601
Dianne Hackborn906497c2010-05-10 15:57:38 -07001602 private final void updateLruProcessInternalLocked(ProcessRecord app,
1603 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001605 int lrui = mLruProcesses.indexOf(app);
1606 if (lrui >= 0) mLruProcesses.remove(lrui);
1607
1608 int i = mLruProcesses.size()-1;
1609 int skipTop = 0;
1610
Dianne Hackborn906497c2010-05-10 15:57:38 -07001611 app.lruSeq = mLruSeq;
1612
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001613 // compute the new weight for this process.
1614 if (updateActivityTime) {
1615 app.lastActivityTime = SystemClock.uptimeMillis();
1616 }
1617 if (app.activities.size() > 0) {
1618 // If this process has activities, we more strongly want to keep
1619 // it around.
1620 app.lruWeight = app.lastActivityTime;
1621 } else if (app.pubProviders.size() > 0) {
1622 // If this process contains content providers, we want to keep
1623 // it a little more strongly.
1624 app.lruWeight = app.lastActivityTime - CONTENT_APP_IDLE_OFFSET;
1625 // Also don't let it kick out the first few "real" hidden processes.
1626 skipTop = MIN_HIDDEN_APPS;
1627 } else {
1628 // If this process doesn't have activities, we less strongly
1629 // want to keep it around, and generally want to avoid getting
1630 // in front of any very recently used activities.
1631 app.lruWeight = app.lastActivityTime - EMPTY_APP_IDLE_OFFSET;
1632 // Also don't let it kick out the first few "real" hidden processes.
1633 skipTop = MIN_HIDDEN_APPS;
1634 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001635
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001636 while (i >= 0) {
1637 ProcessRecord p = mLruProcesses.get(i);
1638 // If this app shouldn't be in front of the first N background
1639 // apps, then skip over that many that are currently hidden.
1640 if (skipTop > 0 && p.setAdj >= HIDDEN_APP_MIN_ADJ) {
1641 skipTop--;
1642 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001643 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001644 mLruProcesses.add(i+1, app);
1645 break;
1646 }
1647 i--;
1648 }
1649 if (i < 0) {
1650 mLruProcesses.add(0, app);
1651 }
1652
Dianne Hackborn906497c2010-05-10 15:57:38 -07001653 // If the app is currently using a content provider or service,
1654 // bump those processes as well.
1655 if (app.connections.size() > 0) {
1656 for (ConnectionRecord cr : app.connections) {
1657 if (cr.binding != null && cr.binding.service != null
1658 && cr.binding.service.app != null
1659 && cr.binding.service.app.lruSeq != mLruSeq) {
1660 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1661 updateActivityTime, i+1);
1662 }
1663 }
1664 }
1665 if (app.conProviders.size() > 0) {
1666 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
1667 if (cpr.app != null && cpr.app.lruSeq != mLruSeq) {
1668 updateLruProcessInternalLocked(cpr.app, oomAdj,
1669 updateActivityTime, i+1);
1670 }
1671 }
1672 }
1673
Joe Onorato8a9b2202010-02-26 18:56:32 -08001674 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 if (oomAdj) {
1676 updateOomAdjLocked();
1677 }
1678 }
1679
Dianne Hackborn906497c2010-05-10 15:57:38 -07001680 private final void updateLruProcessLocked(ProcessRecord app,
1681 boolean oomAdj, boolean updateActivityTime) {
1682 mLruSeq++;
1683 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1684 }
1685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 private final boolean updateLRUListLocked(HistoryRecord r) {
1687 final boolean hadit = mLRUActivities.remove(r);
1688 mLRUActivities.add(r);
1689 return hadit;
1690 }
1691
1692 private final HistoryRecord topRunningActivityLocked(HistoryRecord notTop) {
1693 int i = mHistory.size()-1;
1694 while (i >= 0) {
1695 HistoryRecord r = (HistoryRecord)mHistory.get(i);
1696 if (!r.finishing && r != notTop) {
1697 return r;
1698 }
1699 i--;
1700 }
1701 return null;
1702 }
1703
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001704 private final HistoryRecord topRunningNonDelayedActivityLocked(HistoryRecord notTop) {
1705 int i = mHistory.size()-1;
1706 while (i >= 0) {
1707 HistoryRecord r = (HistoryRecord)mHistory.get(i);
1708 if (!r.finishing && !r.delayedResume && r != notTop) {
1709 return r;
1710 }
1711 i--;
1712 }
1713 return null;
1714 }
1715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 /**
1717 * This is a simplified version of topRunningActivityLocked that provides a number of
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001718 * optional skip-over modes. It is intended for use with the ActivityController hook only.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 *
1720 * @param token If non-null, any history records matching this token will be skipped.
1721 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
1722 *
1723 * @return Returns the HistoryRecord of the next activity on the stack.
1724 */
1725 private final HistoryRecord topRunningActivityLocked(IBinder token, int taskId) {
1726 int i = mHistory.size()-1;
1727 while (i >= 0) {
1728 HistoryRecord r = (HistoryRecord)mHistory.get(i);
1729 // Note: the taskId check depends on real taskId fields being non-zero
1730 if (!r.finishing && (token != r) && (taskId != r.task.taskId)) {
1731 return r;
1732 }
1733 i--;
1734 }
1735 return null;
1736 }
1737
1738 private final ProcessRecord getProcessRecordLocked(
1739 String processName, int uid) {
1740 if (uid == Process.SYSTEM_UID) {
1741 // The system gets to run in any process. If there are multiple
1742 // processes with the same uid, just pick the first (this
1743 // should never happen).
1744 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1745 processName);
1746 return procs != null ? procs.valueAt(0) : null;
1747 }
1748 ProcessRecord proc = mProcessNames.get(processName, uid);
1749 return proc;
1750 }
1751
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001752 private void ensurePackageDexOpt(String packageName) {
1753 IPackageManager pm = ActivityThread.getPackageManager();
1754 try {
1755 if (pm.performDexOpt(packageName)) {
1756 mDidDexOpt = true;
1757 }
1758 } catch (RemoteException e) {
1759 }
1760 }
1761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 private boolean isNextTransitionForward() {
1763 int transit = mWindowManager.getPendingAppTransition();
1764 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1765 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1766 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1767 }
1768
1769 private final boolean realStartActivityLocked(HistoryRecord r,
1770 ProcessRecord app, boolean andResume, boolean checkConfig)
1771 throws RemoteException {
1772
1773 r.startFreezingScreenLocked(app, 0);
1774 mWindowManager.setAppVisibility(r, true);
1775
1776 // Have the window manager re-evaluate the orientation of
1777 // the screen based on the new activity order. Note that
1778 // as a result of this, it can call back into the activity
1779 // manager with a new orientation. We don't care about that,
1780 // because the activity is not currently running so we are
1781 // just restarting it anyway.
1782 if (checkConfig) {
1783 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07001784 mConfiguration,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 r.mayFreezeScreenLocked(app) ? r : null);
1786 updateConfigurationLocked(config, r);
1787 }
1788
1789 r.app = app;
1790
Joe Onorato8a9b2202010-02-26 18:56:32 -08001791 if (localLOGV) Slog.v(TAG, "Launching: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792
1793 int idx = app.activities.indexOf(r);
1794 if (idx < 0) {
1795 app.activities.add(r);
1796 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001797 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798
1799 try {
1800 if (app.thread == null) {
1801 throw new RemoteException();
1802 }
1803 List<ResultInfo> results = null;
1804 List<Intent> newIntents = null;
1805 if (andResume) {
1806 results = r.results;
1807 newIntents = r.newIntents;
1808 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001809 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 + " icicle=" + r.icicle
1811 + " with results=" + results + " newIntents=" + newIntents
1812 + " andResume=" + andResume);
1813 if (andResume) {
Doug Zongker2bec3d42009-12-04 12:52:44 -08001814 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 System.identityHashCode(r),
1816 r.task.taskId, r.shortComponentName);
1817 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08001818 if (r.isHomeActivity) {
1819 mHomeProcess = app;
1820 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001821 ensurePackageDexOpt(r.intent.getComponent().getPackageName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 app.thread.scheduleLaunchActivity(new Intent(r.intent), r,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001823 System.identityHashCode(r),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 r.info, r.icicle, results, newIntents, !andResume,
1825 isNextTransitionForward());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 } catch (RemoteException e) {
1827 if (r.launchFailed) {
1828 // This is the second time we failed -- finish activity
1829 // and give up.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001830 Slog.e(TAG, "Second failure launching "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 + r.intent.getComponent().flattenToShortString()
1832 + ", giving up", e);
1833 appDiedLocked(app, app.pid, app.thread);
1834 requestFinishActivityLocked(r, Activity.RESULT_CANCELED, null,
1835 "2nd-crash");
1836 return false;
1837 }
1838
1839 // This is the first time we failed -- restart process and
1840 // retry.
1841 app.activities.remove(r);
1842 throw e;
1843 }
1844
1845 r.launchFailed = false;
1846 if (updateLRUListLocked(r)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001847 Slog.w(TAG, "Activity " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 + " being launched, but already in LRU list");
1849 }
1850
1851 if (andResume) {
1852 // As part of the process of launching, ActivityThread also performs
1853 // a resume.
1854 r.state = ActivityState.RESUMED;
1855 r.icicle = null;
1856 r.haveState = false;
1857 r.stopped = false;
1858 mResumedActivity = r;
1859 r.task.touchActiveTime();
1860 completeResumeLocked(r);
1861 pauseIfSleepingLocked();
1862 } else {
1863 // This activity is not starting in the resumed state... which
1864 // should look like we asked it to pause+stop (but remain visible),
1865 // and it has done so and reported back the current icicle and
1866 // other state.
1867 r.state = ActivityState.STOPPED;
1868 r.stopped = true;
1869 }
1870
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07001871 // Launch the new version setup screen if needed. We do this -after-
1872 // launching the initial activity (that is, home), so that it can have
1873 // a chance to initialize itself while in the background, making the
1874 // switch back to it faster and look better.
1875 startSetupActivityLocked();
1876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 return true;
1878 }
1879
1880 private final void startSpecificActivityLocked(HistoryRecord r,
1881 boolean andResume, boolean checkConfig) {
1882 // Is this activity's application already running?
1883 ProcessRecord app = getProcessRecordLocked(r.processName,
1884 r.info.applicationInfo.uid);
1885
1886 if (r.startTime == 0) {
1887 r.startTime = SystemClock.uptimeMillis();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07001888 if (mInitialStartTime == 0) {
1889 mInitialStartTime = r.startTime;
1890 }
1891 } else if (mInitialStartTime == 0) {
1892 mInitialStartTime = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 }
1894
1895 if (app != null && app.thread != null) {
1896 try {
1897 realStartActivityLocked(r, app, andResume, checkConfig);
1898 return;
1899 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001900 Slog.w(TAG, "Exception when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 + r.intent.getComponent().flattenToShortString(), e);
1902 }
1903
1904 // If a dead object exception was thrown -- fall through to
1905 // restart the application.
1906 }
1907
1908 startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001909 "activity", r.intent.getComponent(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 }
1911
1912 private final ProcessRecord startProcessLocked(String processName,
1913 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001914 String hostingType, ComponentName hostingName, boolean allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 ProcessRecord app = getProcessRecordLocked(processName, info.uid);
1916 // We don't have to do anything more if:
1917 // (1) There is an existing application record; and
1918 // (2) The caller doesn't think it is dead, OR there is no thread
1919 // object attached to it so we know it couldn't have crashed; and
1920 // (3) There is a pid assigned to it, so it is either starting or
1921 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001922 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 + " app=" + app + " knownToBeDead=" + knownToBeDead
1924 + " thread=" + (app != null ? app.thread : null)
1925 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001926 if (app != null && app.pid > 0) {
1927 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001928 // We already have the app running, or are waiting for it to
1929 // come up (we have a pid but not yet its thread), so keep it.
Magnus Edlund7bb25812010-02-24 15:45:06 +01001930 return app;
1931 } else {
1932 // An application record is attached to a previous process,
1933 // clean it up now.
1934 handleAppDiedLocked(app, true);
1935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 String hostingNameStr = hostingName != null
1939 ? hostingName.flattenToShortString() : null;
1940
1941 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1942 // If we are in the background, then check to see if this process
1943 // is bad. If so, we will just silently fail.
1944 if (mBadProcesses.get(info.processName, info.uid) != null) {
1945 return null;
1946 }
1947 } else {
1948 // When the user is explicitly starting a process, then clear its
1949 // crash count so that we won't make it bad until they see at
1950 // least one crash dialog again, and make the process good again
1951 // if it had been bad.
1952 mProcessCrashTimes.remove(info.processName, info.uid);
1953 if (mBadProcesses.get(info.processName, info.uid) != null) {
Doug Zongker2bec3d42009-12-04 12:52:44 -08001954 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 info.processName);
1956 mBadProcesses.remove(info.processName, info.uid);
1957 if (app != null) {
1958 app.bad = false;
1959 }
1960 }
1961 }
1962
1963 if (app == null) {
1964 app = newProcessRecordLocked(null, info, processName);
1965 mProcessNames.put(processName, info.uid, app);
1966 } else {
1967 // If this is a new package in the process, add the package to the list
1968 app.addPackage(info.packageName);
1969 }
1970
1971 // If the system is not ready yet, then hold off on starting this
1972 // process until it is.
1973 if (!mSystemReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001974 && !isAllowedWhileBooting(info)
1975 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 if (!mProcessesOnHold.contains(app)) {
1977 mProcessesOnHold.add(app);
1978 }
1979 return app;
1980 }
1981
1982 startProcessLocked(app, hostingType, hostingNameStr);
1983 return (app.pid != 0) ? app : null;
1984 }
1985
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001986 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1987 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1988 }
1989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 private final void startProcessLocked(ProcessRecord app,
1991 String hostingType, String hostingNameStr) {
1992 if (app.pid > 0 && app.pid != MY_PID) {
1993 synchronized (mPidsSelfLocked) {
1994 mPidsSelfLocked.remove(app.pid);
1995 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1996 }
1997 app.pid = 0;
1998 }
1999
2000 mProcessesOnHold.remove(app);
2001
2002 updateCpuStats();
2003
2004 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
2005 mProcDeaths[0] = 0;
2006
2007 try {
2008 int uid = app.info.uid;
2009 int[] gids = null;
2010 try {
2011 gids = mContext.getPackageManager().getPackageGids(
2012 app.info.packageName);
2013 } catch (PackageManager.NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002014 Slog.w(TAG, "Unable to retrieve gids", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002015 }
2016 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2017 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2018 && mTopComponent != null
2019 && app.processName.equals(mTopComponent.getPackageName())) {
2020 uid = 0;
2021 }
2022 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2023 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2024 uid = 0;
2025 }
2026 }
2027 int debugFlags = 0;
2028 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2029 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
2030 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002031 // Run the app in safe mode if its manifest requests so or the
2032 // system is booted in safe mode.
2033 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2034 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002035 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2036 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002037 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2038 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2039 }
2040 if ("1".equals(SystemProperties.get("debug.assert"))) {
2041 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2042 }
2043 int pid = Process.start("android.app.ActivityThread",
2044 mSimpleProcessManagement ? app.processName : null, uid, uid,
2045 gids, debugFlags, null);
2046 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2047 synchronized (bs) {
2048 if (bs.isOnBattery()) {
2049 app.batteryStats.incStartsLocked();
2050 }
2051 }
2052
Doug Zongker2bec3d42009-12-04 12:52:44 -08002053 EventLog.writeEvent(EventLogTags.AM_PROC_START, pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 app.processName, hostingType,
2055 hostingNameStr != null ? hostingNameStr : "");
2056
2057 if (app.persistent) {
2058 Watchdog.getInstance().processStarted(app, app.processName, pid);
2059 }
2060
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002061 StringBuilder buf = mStringBuilder;
2062 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 buf.append("Start proc ");
2064 buf.append(app.processName);
2065 buf.append(" for ");
2066 buf.append(hostingType);
2067 if (hostingNameStr != null) {
2068 buf.append(" ");
2069 buf.append(hostingNameStr);
2070 }
2071 buf.append(": pid=");
2072 buf.append(pid);
2073 buf.append(" uid=");
2074 buf.append(uid);
2075 buf.append(" gids={");
2076 if (gids != null) {
2077 for (int gi=0; gi<gids.length; gi++) {
2078 if (gi != 0) buf.append(", ");
2079 buf.append(gids[gi]);
2080
2081 }
2082 }
2083 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002084 Slog.i(TAG, buf.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 if (pid == 0 || pid == MY_PID) {
2086 // Processes are being emulated with threads.
2087 app.pid = MY_PID;
2088 app.removed = false;
2089 mStartingProcesses.add(app);
2090 } else if (pid > 0) {
2091 app.pid = pid;
2092 app.removed = false;
2093 synchronized (mPidsSelfLocked) {
2094 this.mPidsSelfLocked.put(pid, app);
2095 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2096 msg.obj = app;
2097 mHandler.sendMessageDelayed(msg, PROC_START_TIMEOUT);
2098 }
2099 } else {
2100 app.pid = 0;
2101 RuntimeException e = new RuntimeException(
2102 "Failure starting process " + app.processName
2103 + ": returned pid=" + pid);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002104 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 }
2106 } catch (RuntimeException e) {
2107 // XXX do better error recovery.
2108 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002109 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002110 }
2111 }
2112
2113 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
2114 if (mPausingActivity != null) {
2115 RuntimeException e = new RuntimeException();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002116 Slog.e(TAG, "Trying to pause when pause is already pending for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 + mPausingActivity, e);
2118 }
2119 HistoryRecord prev = mResumedActivity;
2120 if (prev == null) {
2121 RuntimeException e = new RuntimeException();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002122 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 resumeTopActivityLocked(null);
2124 return;
2125 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08002126 if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127 mResumedActivity = null;
2128 mPausingActivity = prev;
2129 mLastPausedActivity = prev;
2130 prev.state = ActivityState.PAUSING;
2131 prev.task.touchActiveTime();
2132
2133 updateCpuStats();
2134
2135 if (prev.app != null && prev.app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002136 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002137 try {
Doug Zongker2bec3d42009-12-04 12:52:44 -08002138 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139 System.identityHashCode(prev),
2140 prev.shortComponentName);
2141 prev.app.thread.schedulePauseActivity(prev, prev.finishing, userLeaving,
2142 prev.configChangeFlags);
2143 updateUsageStats(prev, false);
2144 } catch (Exception e) {
2145 // Ignore exception, if process died other code will cleanup.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002146 Slog.w(TAG, "Exception thrown during pause", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002147 mPausingActivity = null;
2148 mLastPausedActivity = null;
2149 }
2150 } else {
2151 mPausingActivity = null;
2152 mLastPausedActivity = null;
2153 }
2154
2155 // If we are not going to sleep, we want to ensure the device is
2156 // awake until the next activity is started.
Dianne Hackborn55280a92009-05-07 15:53:46 -07002157 if (!mSleeping && !mShuttingDown) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002158 mLaunchingActivity.acquire();
2159 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
2160 // To be safe, don't allow the wake lock to be held for too long.
2161 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
2162 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
2163 }
2164 }
2165
2166
2167 if (mPausingActivity != null) {
2168 // Have the window manager pause its key dispatching until the new
2169 // activity has started. If we're pausing the activity just because
2170 // the screen is being turned off and the UI is sleeping, don't interrupt
2171 // key dispatch; the same activity will pick it up again on wakeup.
2172 if (!uiSleeping) {
2173 prev.pauseKeyDispatchingLocked();
2174 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002175 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 }
2177
2178 // Schedule a pause timeout in case the app doesn't respond.
2179 // We don't give it much time because this directly impacts the
2180 // responsiveness seen by the user.
2181 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
2182 msg.obj = prev;
2183 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002184 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002185 } else {
2186 // This activity failed to schedule the
2187 // pause, so just treat it as being paused now.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002188 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002189 resumeTopActivityLocked(null);
2190 }
2191 }
2192
2193 private final void completePauseLocked() {
2194 HistoryRecord prev = mPausingActivity;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002195 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002196
2197 if (prev != null) {
2198 if (prev.finishing) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002199 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE);
2201 } else if (prev.app != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002202 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002203 if (prev.waitingVisible) {
2204 prev.waitingVisible = false;
2205 mWaitingVisibleActivities.remove(prev);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002206 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002207 TAG, "Complete pause, no longer waiting: " + prev);
2208 }
2209 if (prev.configDestroy) {
2210 // The previous is being paused because the configuration
2211 // is changing, which means it is actually stopping...
2212 // To juggle the fact that we are also starting a new
2213 // instance right now, we need to first completely stop
2214 // the current instance before starting the new one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002215 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002216 destroyActivityLocked(prev, true);
2217 } else {
2218 mStoppingActivities.add(prev);
2219 if (mStoppingActivities.size() > 3) {
2220 // If we already have a few activities waiting to stop,
2221 // then give up on things going idle and start clearing
2222 // them out.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002223 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002224 Message msg = Message.obtain();
2225 msg.what = ActivityManagerService.IDLE_NOW_MSG;
2226 mHandler.sendMessage(msg);
2227 }
2228 }
2229 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002230 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002231 prev = null;
2232 }
2233 mPausingActivity = null;
2234 }
2235
Dianne Hackborn55280a92009-05-07 15:53:46 -07002236 if (!mSleeping && !mShuttingDown) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002237 resumeTopActivityLocked(prev);
2238 } else {
2239 if (mGoingToSleep.isHeld()) {
2240 mGoingToSleep.release();
2241 }
Dianne Hackborn55280a92009-05-07 15:53:46 -07002242 if (mShuttingDown) {
2243 notifyAll();
2244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002245 }
2246
2247 if (prev != null) {
2248 prev.resumeKeyDispatchingLocked();
2249 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07002250
2251 if (prev.app != null && prev.cpuTimeAtResume > 0 && mBatteryStatsService.isOnBattery()) {
2252 long diff = 0;
2253 synchronized (mProcessStatsThread) {
2254 diff = mProcessStats.getCpuTimeForPid(prev.app.pid) - prev.cpuTimeAtResume;
2255 }
2256 if (diff > 0) {
2257 BatteryStatsImpl bsi = mBatteryStatsService.getActiveStatistics();
2258 synchronized (bsi) {
2259 BatteryStatsImpl.Uid.Proc ps =
2260 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
2261 prev.info.packageName);
2262 if (ps != null) {
2263 ps.addForegroundTimeLocked(diff);
2264 }
2265 }
2266 }
2267 }
2268 prev.cpuTimeAtResume = 0; // reset it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 }
2270
2271 /**
2272 * Once we know that we have asked an application to put an activity in
2273 * the resumed state (either by launching it or explicitly telling it),
2274 * this function updates the rest of our state to match that fact.
2275 */
2276 private final void completeResumeLocked(HistoryRecord next) {
2277 next.idle = false;
2278 next.results = null;
2279 next.newIntents = null;
2280
2281 // schedule an idle timeout in case the app doesn't do it for us.
2282 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
2283 msg.obj = next;
2284 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
2285
2286 if (false) {
2287 // The activity was never told to pause, so just keep
2288 // things going as-is. To maintain our own state,
2289 // we need to emulate it coming back and saying it is
2290 // idle.
2291 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
2292 msg.obj = next;
2293 mHandler.sendMessage(msg);
2294 }
2295
Dianne Hackborn1bcf5a82009-09-30 15:22:29 -07002296 reportResumedActivityLocked(next);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002298 next.thumbnail = null;
2299 setFocusedActivityLocked(next);
2300 next.resumeKeyDispatchingLocked();
2301 ensureActivitiesVisibleLocked(null, 0);
2302 mWindowManager.executeAppTransition();
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07002303 mNoAnimActivities.clear();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07002304
2305 // Mark the point when the activity is resuming
2306 // TODO: To be more accurate, the mark should be before the onCreate,
2307 // not after the onResume. But for subsequent starts, onResume is fine.
2308 if (next.app != null) {
2309 synchronized (mProcessStatsThread) {
2310 next.cpuTimeAtResume = mProcessStats.getCpuTimeForPid(next.app.pid);
2311 }
2312 } else {
2313 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
2314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002315 }
2316
2317 /**
2318 * Make sure that all activities that need to be visible (that is, they
2319 * currently can be seen by the user) actually are.
2320 */
2321 private final void ensureActivitiesVisibleLocked(HistoryRecord top,
2322 HistoryRecord starting, String onlyThisProcess, int configChanges) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002323 if (DEBUG_VISBILITY) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002324 TAG, "ensureActivitiesVisible behind " + top
2325 + " configChanges=0x" + Integer.toHexString(configChanges));
2326
2327 // If the top activity is not fullscreen, then we need to
2328 // make sure any activities under it are now visible.
2329 final int count = mHistory.size();
2330 int i = count-1;
2331 while (mHistory.get(i) != top) {
2332 i--;
2333 }
2334 HistoryRecord r;
2335 boolean behindFullscreen = false;
2336 for (; i>=0; i--) {
2337 r = (HistoryRecord)mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002338 if (DEBUG_VISBILITY) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002339 TAG, "Make visible? " + r + " finishing=" + r.finishing
2340 + " state=" + r.state);
2341 if (r.finishing) {
2342 continue;
2343 }
2344
2345 final boolean doThisProcess = onlyThisProcess == null
2346 || onlyThisProcess.equals(r.processName);
2347
2348 // First: if this is not the current activity being started, make
2349 // sure it matches the current configuration.
2350 if (r != starting && doThisProcess) {
2351 ensureActivityConfigurationLocked(r, 0);
2352 }
2353
2354 if (r.app == null || r.app.thread == null) {
2355 if (onlyThisProcess == null
2356 || onlyThisProcess.equals(r.processName)) {
2357 // This activity needs to be visible, but isn't even
2358 // running... get it started, but don't resume it
2359 // at this point.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002360 if (DEBUG_VISBILITY) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361 TAG, "Start and freeze screen for " + r);
2362 if (r != starting) {
2363 r.startFreezingScreenLocked(r.app, configChanges);
2364 }
2365 if (!r.visible) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002366 if (DEBUG_VISBILITY) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367 TAG, "Starting and making visible: " + r);
2368 mWindowManager.setAppVisibility(r, true);
2369 }
2370 if (r != starting) {
2371 startSpecificActivityLocked(r, false, false);
2372 }
2373 }
2374
2375 } else if (r.visible) {
2376 // If this activity is already visible, then there is nothing
2377 // else to do here.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002378 if (DEBUG_VISBILITY) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 TAG, "Skipping: already visible at " + r);
2380 r.stopFreezingScreenLocked(false);
2381
2382 } else if (onlyThisProcess == null) {
2383 // This activity is not currently visible, but is running.
2384 // Tell it to become visible.
2385 r.visible = true;
2386 if (r.state != ActivityState.RESUMED && r != starting) {
2387 // If this activity is paused, tell it
2388 // to now show its window.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002389 if (DEBUG_VISBILITY) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 TAG, "Making visible and scheduling visibility: " + r);
2391 try {
2392 mWindowManager.setAppVisibility(r, true);
2393 r.app.thread.scheduleWindowVisibility(r, true);
2394 r.stopFreezingScreenLocked(false);
2395 } catch (Exception e) {
2396 // Just skip on any failure; we'll make it
2397 // visible when it next restarts.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002398 Slog.w(TAG, "Exception thrown making visibile: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002399 + r.intent.getComponent(), e);
2400 }
2401 }
2402 }
2403
2404 // Aggregate current change flags.
2405 configChanges |= r.configChangeFlags;
2406
2407 if (r.fullscreen) {
2408 // At this point, nothing else needs to be shown
Joe Onorato8a9b2202010-02-26 18:56:32 -08002409 if (DEBUG_VISBILITY) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002410 TAG, "Stopping: fullscreen at " + r);
2411 behindFullscreen = true;
2412 i--;
2413 break;
2414 }
2415 }
2416
2417 // Now for any activities that aren't visible to the user, make
2418 // sure they no longer are keeping the screen frozen.
2419 while (i >= 0) {
2420 r = (HistoryRecord)mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002421 if (DEBUG_VISBILITY) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002422 TAG, "Make invisible? " + r + " finishing=" + r.finishing
2423 + " state=" + r.state
2424 + " behindFullscreen=" + behindFullscreen);
2425 if (!r.finishing) {
2426 if (behindFullscreen) {
2427 if (r.visible) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002428 if (DEBUG_VISBILITY) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002429 TAG, "Making invisible: " + r);
2430 r.visible = false;
2431 try {
2432 mWindowManager.setAppVisibility(r, false);
2433 if ((r.state == ActivityState.STOPPING
2434 || r.state == ActivityState.STOPPED)
2435 && r.app != null && r.app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002436 if (DEBUG_VISBILITY) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002437 TAG, "Scheduling invisibility: " + r);
2438 r.app.thread.scheduleWindowVisibility(r, false);
2439 }
2440 } catch (Exception e) {
2441 // Just skip on any failure; we'll make it
2442 // visible when it next restarts.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002443 Slog.w(TAG, "Exception thrown making hidden: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 + r.intent.getComponent(), e);
2445 }
2446 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002447 if (DEBUG_VISBILITY) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002448 TAG, "Already invisible: " + r);
2449 }
2450 } else if (r.fullscreen) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002451 if (DEBUG_VISBILITY) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002452 TAG, "Now behindFullscreen: " + r);
2453 behindFullscreen = true;
2454 }
2455 }
2456 i--;
2457 }
2458 }
2459
2460 /**
2461 * Version of ensureActivitiesVisible that can easily be called anywhere.
2462 */
2463 private final void ensureActivitiesVisibleLocked(HistoryRecord starting,
2464 int configChanges) {
2465 HistoryRecord r = topRunningActivityLocked(null);
2466 if (r != null) {
2467 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
2468 }
2469 }
2470
2471 private void updateUsageStats(HistoryRecord resumedComponent, boolean resumed) {
2472 if (resumed) {
2473 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2474 } else {
2475 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2476 }
2477 }
2478
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002479 private boolean startHomeActivityLocked() {
2480 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2481 && mTopAction == null) {
2482 // We are running in factory test mode, but unable to find
2483 // the factory test app, so just sit around displaying the
2484 // error message and don't try to start anything.
2485 return false;
2486 }
2487 Intent intent = new Intent(
2488 mTopAction,
2489 mTopData != null ? Uri.parse(mTopData) : null);
2490 intent.setComponent(mTopComponent);
2491 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2492 intent.addCategory(Intent.CATEGORY_HOME);
2493 }
2494 ActivityInfo aInfo =
2495 intent.resolveActivityInfo(mContext.getPackageManager(),
2496 STOCK_PM_FLAGS);
2497 if (aInfo != null) {
2498 intent.setComponent(new ComponentName(
2499 aInfo.applicationInfo.packageName, aInfo.name));
2500 // Don't do this if the home app is currently being
2501 // instrumented.
2502 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2503 aInfo.applicationInfo.uid);
2504 if (app == null || app.instrumentationClass == null) {
2505 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
2506 startActivityLocked(null, intent, null, null, 0, aInfo,
2507 null, null, 0, 0, 0, false, false);
2508 }
2509 }
2510
2511
2512 return true;
2513 }
2514
2515 /**
2516 * Starts the "new version setup screen" if appropriate.
2517 */
2518 private void startSetupActivityLocked() {
2519 // Only do this once per boot.
2520 if (mCheckedForSetup) {
2521 return;
2522 }
2523
2524 // We will show this screen if the current one is a different
2525 // version than the last one shown, and we are not running in
2526 // low-level factory test mode.
2527 final ContentResolver resolver = mContext.getContentResolver();
2528 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2529 Settings.Secure.getInt(resolver,
2530 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2531 mCheckedForSetup = true;
2532
2533 // See if we should be showing the platform update setup UI.
2534 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2535 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2536 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2537
2538 // We don't allow third party apps to replace this.
2539 ResolveInfo ri = null;
2540 for (int i=0; ris != null && i<ris.size(); i++) {
2541 if ((ris.get(i).activityInfo.applicationInfo.flags
2542 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2543 ri = ris.get(i);
2544 break;
2545 }
2546 }
2547
2548 if (ri != null) {
2549 String vers = ri.activityInfo.metaData != null
2550 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2551 : null;
2552 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2553 vers = ri.activityInfo.applicationInfo.metaData.getString(
2554 Intent.METADATA_SETUP_VERSION);
2555 }
2556 String lastVers = Settings.Secure.getString(
2557 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2558 if (vers != null && !vers.equals(lastVers)) {
2559 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2560 intent.setComponent(new ComponentName(
2561 ri.activityInfo.packageName, ri.activityInfo.name));
2562 startActivityLocked(null, intent, null, null, 0, ri.activityInfo,
2563 null, null, 0, 0, 0, false, false);
2564 }
2565 }
2566 }
2567 }
2568
Dianne Hackborn1bcf5a82009-09-30 15:22:29 -07002569 private void reportResumedActivityLocked(HistoryRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002570 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002571
2572 final int identHash = System.identityHashCode(r);
2573 updateUsageStats(r, true);
2574
2575 int i = mWatchers.beginBroadcast();
2576 while (i > 0) {
2577 i--;
2578 IActivityWatcher w = mWatchers.getBroadcastItem(i);
2579 if (w != null) {
2580 try {
2581 w.activityResuming(identHash);
2582 } catch (RemoteException e) {
2583 }
2584 }
2585 }
2586 mWatchers.finishBroadcast();
2587 }
2588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 /**
2590 * Ensure that the top activity in the stack is resumed.
2591 *
2592 * @param prev The previously resumed activity, for when in the process
2593 * of pausing; can be null to call from elsewhere.
2594 *
2595 * @return Returns true if something is being resumed, or false if
2596 * nothing happened.
2597 */
2598 private final boolean resumeTopActivityLocked(HistoryRecord prev) {
2599 // Find the first activity that is not finishing.
2600 HistoryRecord next = topRunningActivityLocked(null);
2601
2602 // Remember how we'll process this pause/resume situation, and ensure
2603 // that the state is reset however we wind up proceeding.
2604 final boolean userLeaving = mUserLeaving;
2605 mUserLeaving = false;
2606
2607 if (next == null) {
2608 // There are no more activities! Let's just start up the
2609 // Launcher...
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002610 return startHomeActivityLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002611 }
2612
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002613 next.delayedResume = false;
2614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 // If the top activity is the resumed one, nothing to do.
2616 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
2617 // Make sure we have executed any pending transitions, since there
2618 // should be nothing left to do at this point.
2619 mWindowManager.executeAppTransition();
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07002620 mNoAnimActivities.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 return false;
2622 }
2623
2624 // If we are sleeping, and there is no resumed activity, and the top
2625 // activity is paused, well that is the state we want.
Dianne Hackborn55280a92009-05-07 15:53:46 -07002626 if ((mSleeping || mShuttingDown)
2627 && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628 // Make sure we have executed any pending transitions, since there
2629 // should be nothing left to do at this point.
2630 mWindowManager.executeAppTransition();
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07002631 mNoAnimActivities.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002632 return false;
2633 }
2634
2635 // The activity may be waiting for stop, but that is no longer
2636 // appropriate for it.
2637 mStoppingActivities.remove(next);
2638 mWaitingVisibleActivities.remove(next);
2639
Joe Onorato8a9b2202010-02-26 18:56:32 -08002640 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641
2642 // If we are currently pausing an activity, then don't do anything
2643 // until that is done.
2644 if (mPausingActivity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002645 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002646 return false;
2647 }
2648
2649 // We need to start pausing the current activity so the top one
2650 // can be resumed...
2651 if (mResumedActivity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002652 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653 startPausingLocked(userLeaving, false);
2654 return true;
2655 }
2656
2657 if (prev != null && prev != next) {
2658 if (!prev.waitingVisible && next != null && !next.nowVisible) {
2659 prev.waitingVisible = true;
2660 mWaitingVisibleActivities.add(prev);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002661 if (DEBUG_SWITCH) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662 TAG, "Resuming top, waiting visible to hide: " + prev);
2663 } else {
2664 // The next activity is already visible, so hide the previous
2665 // activity's windows right now so we can show the new one ASAP.
2666 // We only do this if the previous is finishing, which should mean
2667 // it is on top of the one being resumed so hiding it quickly
2668 // is good. Otherwise, we want to do the normal route of allowing
2669 // the resumed activity to be shown so we can decide if the
2670 // previous should actually be hidden depending on whether the
2671 // new one is found to be full-screen or not.
2672 if (prev.finishing) {
2673 mWindowManager.setAppVisibility(prev, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002674 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 + prev + ", waitingVisible="
2676 + (prev != null ? prev.waitingVisible : null)
2677 + ", nowVisible=" + next.nowVisible);
2678 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002679 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002680 + prev + ", waitingVisible="
2681 + (prev != null ? prev.waitingVisible : null)
2682 + ", nowVisible=" + next.nowVisible);
2683 }
2684 }
2685 }
2686
2687 // We are starting up the next activity, so tell the window manager
2688 // that the previous one will be hidden soon. This way it can know
2689 // to ignore it when computing the desired screen orientation.
2690 if (prev != null) {
2691 if (prev.finishing) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002692 if (DEBUG_TRANSITION) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693 "Prepare close transition: prev=" + prev);
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07002694 if (mNoAnimActivities.contains(prev)) {
2695 mWindowManager.prepareAppTransition(WindowManagerPolicy.TRANSIT_NONE);
2696 } else {
2697 mWindowManager.prepareAppTransition(prev.task == next.task
2698 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
2699 : WindowManagerPolicy.TRANSIT_TASK_CLOSE);
2700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002701 mWindowManager.setAppWillBeHidden(prev);
2702 mWindowManager.setAppVisibility(prev, false);
2703 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002704 if (DEBUG_TRANSITION) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002705 "Prepare open transition: prev=" + prev);
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07002706 if (mNoAnimActivities.contains(next)) {
2707 mWindowManager.prepareAppTransition(WindowManagerPolicy.TRANSIT_NONE);
2708 } else {
2709 mWindowManager.prepareAppTransition(prev.task == next.task
2710 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
2711 : WindowManagerPolicy.TRANSIT_TASK_OPEN);
2712 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002713 }
2714 if (false) {
2715 mWindowManager.setAppWillBeHidden(prev);
2716 mWindowManager.setAppVisibility(prev, false);
2717 }
2718 } else if (mHistory.size() > 1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002719 if (DEBUG_TRANSITION) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 "Prepare open transition: no previous");
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07002721 if (mNoAnimActivities.contains(next)) {
2722 mWindowManager.prepareAppTransition(WindowManagerPolicy.TRANSIT_NONE);
2723 } else {
2724 mWindowManager.prepareAppTransition(WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN);
2725 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002726 }
2727
2728 if (next.app != null && next.app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002729 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002730
2731 // This activity is now becoming visible.
2732 mWindowManager.setAppVisibility(next, true);
2733
2734 HistoryRecord lastResumedActivity = mResumedActivity;
2735 ActivityState lastState = next.state;
2736
2737 updateCpuStats();
2738
2739 next.state = ActivityState.RESUMED;
2740 mResumedActivity = next;
2741 next.task.touchActiveTime();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002742 updateLruProcessLocked(next.app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002743 updateLRUListLocked(next);
2744
2745 // Have the window manager re-evaluate the orientation of
2746 // the screen based on the new activity order.
Eric Fischerd4d04de2009-10-27 18:55:57 -07002747 boolean updated;
2748 synchronized (this) {
2749 Configuration config = mWindowManager.updateOrientationFromAppTokens(
2750 mConfiguration,
2751 next.mayFreezeScreenLocked(next.app) ? next : null);
2752 if (config != null) {
Eric Fischerd4d04de2009-10-27 18:55:57 -07002753 next.frozenBeforeDestroy = true;
2754 }
2755 updated = updateConfigurationLocked(config, next);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002756 }
Eric Fischerd4d04de2009-10-27 18:55:57 -07002757 if (!updated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758 // The configuration update wasn't able to keep the existing
2759 // instance of the activity, and instead started a new one.
2760 // We should be all done, but let's just make sure our activity
2761 // is still at the top and schedule another run if something
2762 // weird happened.
2763 HistoryRecord nextNext = topRunningActivityLocked(null);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002764 if (DEBUG_SWITCH) Slog.i(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765 "Activity config changed during resume: " + next
2766 + ", new next: " + nextNext);
2767 if (nextNext != next) {
2768 // Do over!
2769 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
2770 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002771 setFocusedActivityLocked(next);
2772 ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002773 mWindowManager.executeAppTransition();
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07002774 mNoAnimActivities.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775 return true;
2776 }
2777
2778 try {
2779 // Deliver all pending results.
2780 ArrayList a = next.results;
2781 if (a != null) {
2782 final int N = a.size();
2783 if (!next.finishing && N > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002784 if (DEBUG_RESULTS) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002785 TAG, "Delivering results to " + next
2786 + ": " + a);
2787 next.app.thread.scheduleSendResult(next, a);
2788 }
2789 }
2790
2791 if (next.newIntents != null) {
2792 next.app.thread.scheduleNewIntent(next.newIntents, next);
2793 }
2794
Doug Zongker2bec3d42009-12-04 12:52:44 -08002795 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 System.identityHashCode(next),
2797 next.task.taskId, next.shortComponentName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002798
2799 next.app.thread.scheduleResumeActivity(next,
2800 isNextTransitionForward());
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002802 pauseIfSleepingLocked();
2803
2804 } catch (Exception e) {
2805 // Whoops, need to restart this activity!
2806 next.state = lastState;
2807 mResumedActivity = lastResumedActivity;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002808 Slog.i(TAG, "Restarting because process died: " + next);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002809 if (!next.hasBeenLaunched) {
2810 next.hasBeenLaunched = true;
2811 } else {
2812 if (SHOW_APP_STARTING_ICON) {
2813 mWindowManager.setAppStartingWindow(
2814 next, next.packageName, next.theme,
2815 next.nonLocalizedLabel,
2816 next.labelRes, next.icon, null, true);
2817 }
2818 }
2819 startSpecificActivityLocked(next, true, false);
2820 return true;
2821 }
2822
2823 // From this point on, if something goes wrong there is no way
2824 // to recover the activity.
2825 try {
2826 next.visible = true;
2827 completeResumeLocked(next);
2828 } catch (Exception e) {
2829 // If any exception gets thrown, toss away this
2830 // activity and try the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002831 Slog.w(TAG, "Exception thrown during resume of " + next, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 requestFinishActivityLocked(next, Activity.RESULT_CANCELED, null,
2833 "resume-exception");
2834 return true;
2835 }
2836
2837 // Didn't need to use the icicle, and it is now out of date.
2838 next.icicle = null;
2839 next.haveState = false;
2840 next.stopped = false;
2841
2842 } else {
2843 // Whoops, need to restart this activity!
2844 if (!next.hasBeenLaunched) {
2845 next.hasBeenLaunched = true;
2846 } else {
2847 if (SHOW_APP_STARTING_ICON) {
2848 mWindowManager.setAppStartingWindow(
2849 next, next.packageName, next.theme,
2850 next.nonLocalizedLabel,
2851 next.labelRes, next.icon, null, true);
2852 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08002853 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002854 }
2855 startSpecificActivityLocked(next, true, true);
2856 }
2857
2858 return true;
2859 }
2860
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002861 private final void startActivityLocked(HistoryRecord r, boolean newTask,
2862 boolean doResume) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 final int NH = mHistory.size();
2864
2865 int addPos = -1;
2866
2867 if (!newTask) {
2868 // If starting in an existing task, find where that is...
2869 HistoryRecord next = null;
2870 boolean startIt = true;
2871 for (int i = NH-1; i >= 0; i--) {
2872 HistoryRecord p = (HistoryRecord)mHistory.get(i);
2873 if (p.finishing) {
2874 continue;
2875 }
2876 if (p.task == r.task) {
2877 // Here it is! Now, if this is not yet visible to the
2878 // user, then just add it without starting; it will
2879 // get started when the user navigates back to it.
2880 addPos = i+1;
2881 if (!startIt) {
2882 mHistory.add(addPos, r);
2883 r.inHistory = true;
2884 r.task.numActivities++;
2885 mWindowManager.addAppToken(addPos, r, r.task.taskId,
2886 r.info.screenOrientation, r.fullscreen);
2887 if (VALIDATE_TOKENS) {
2888 mWindowManager.validateAppTokens(mHistory);
2889 }
2890 return;
2891 }
2892 break;
2893 }
2894 if (p.fullscreen) {
2895 startIt = false;
2896 }
2897 next = p;
2898 }
2899 }
2900
2901 // Place a new activity at top of stack, so it is next to interact
2902 // with the user.
2903 if (addPos < 0) {
2904 addPos = mHistory.size();
2905 }
2906
2907 // If we are not placing the new activity frontmost, we do not want
2908 // to deliver the onUserLeaving callback to the actual frontmost
2909 // activity
2910 if (addPos < NH) {
2911 mUserLeaving = false;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002912 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 }
2914
2915 // Slot the activity into the history stack and proceed
2916 mHistory.add(addPos, r);
2917 r.inHistory = true;
2918 r.frontOfTask = newTask;
2919 r.task.numActivities++;
2920 if (NH > 0) {
2921 // We want to show the starting preview window if we are
2922 // switching to a new task, or the next activity's process is
2923 // not currently running.
2924 boolean showStartingIcon = newTask;
2925 ProcessRecord proc = r.app;
2926 if (proc == null) {
2927 proc = mProcessNames.get(r.processName, r.info.applicationInfo.uid);
2928 }
2929 if (proc == null || proc.thread == null) {
2930 showStartingIcon = true;
2931 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08002932 if (DEBUG_TRANSITION) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002933 "Prepare open transition: starting " + r);
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07002934 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
2935 mWindowManager.prepareAppTransition(WindowManagerPolicy.TRANSIT_NONE);
2936 mNoAnimActivities.add(r);
2937 } else if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
2938 mWindowManager.prepareAppTransition(WindowManagerPolicy.TRANSIT_TASK_OPEN);
2939 mNoAnimActivities.remove(r);
2940 } else {
2941 mWindowManager.prepareAppTransition(newTask
2942 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
2943 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN);
2944 mNoAnimActivities.remove(r);
2945 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002946 mWindowManager.addAppToken(
2947 addPos, r, r.task.taskId, r.info.screenOrientation, r.fullscreen);
2948 boolean doShow = true;
2949 if (newTask) {
2950 // Even though this activity is starting fresh, we still need
2951 // to reset it to make sure we apply affinities to move any
2952 // existing activities from other tasks in to it.
2953 // If the caller has requested that the target task be
2954 // reset, then do so.
2955 if ((r.intent.getFlags()
2956 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2957 resetTaskIfNeededLocked(r, r);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002958 doShow = topRunningNonDelayedActivityLocked(null) == r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002959 }
2960 }
2961 if (SHOW_APP_STARTING_ICON && doShow) {
2962 // Figure out if we are transitioning from another activity that is
2963 // "has the same starting icon" as the next one. This allows the
2964 // window manager to keep the previous window it had previously
2965 // created, if it still had one.
2966 HistoryRecord prev = mResumedActivity;
2967 if (prev != null) {
2968 // We don't want to reuse the previous starting preview if:
2969 // (1) The current activity is in a different task.
2970 if (prev.task != r.task) prev = null;
2971 // (2) The current activity is already displayed.
2972 else if (prev.nowVisible) prev = null;
2973 }
2974 mWindowManager.setAppStartingWindow(
2975 r, r.packageName, r.theme, r.nonLocalizedLabel,
2976 r.labelRes, r.icon, prev, showStartingIcon);
2977 }
2978 } else {
2979 // If this is the first activity, don't do any fancy animations,
2980 // because there is nothing for it to animate on top of.
2981 mWindowManager.addAppToken(addPos, r, r.task.taskId,
2982 r.info.screenOrientation, r.fullscreen);
2983 }
2984 if (VALIDATE_TOKENS) {
2985 mWindowManager.validateAppTokens(mHistory);
2986 }
2987
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002988 if (doResume) {
2989 resumeTopActivityLocked(null);
2990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002991 }
2992
2993 /**
2994 * Perform clear operation as requested by
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002995 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2996 * stack to the given task, then look for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002997 * an instance of that activity in the stack and, if found, finish all
2998 * activities on top of it and return the instance.
2999 *
3000 * @param newR Description of the new activity being started.
3001 * @return Returns the old activity that should be continue to be used,
3002 * or null if none was found.
3003 */
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003004 private final HistoryRecord performClearTaskLocked(int taskId,
Dianne Hackbornaa52f9a2009-08-25 16:01:15 -07003005 HistoryRecord newR, int launchFlags, boolean doClear) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003006 int i = mHistory.size();
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003007
3008 // First find the requested task.
3009 while (i > 0) {
3010 i--;
3011 HistoryRecord r = (HistoryRecord)mHistory.get(i);
3012 if (r.task.taskId == taskId) {
3013 i++;
3014 break;
3015 }
3016 }
3017
3018 // Now clear it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003019 while (i > 0) {
3020 i--;
3021 HistoryRecord r = (HistoryRecord)mHistory.get(i);
3022 if (r.finishing) {
3023 continue;
3024 }
3025 if (r.task.taskId != taskId) {
3026 return null;
3027 }
3028 if (r.realActivity.equals(newR.realActivity)) {
3029 // Here it is! Now finish everything in front...
3030 HistoryRecord ret = r;
3031 if (doClear) {
3032 while (i < (mHistory.size()-1)) {
3033 i++;
3034 r = (HistoryRecord)mHistory.get(i);
3035 if (r.finishing) {
3036 continue;
3037 }
3038 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
3039 null, "clear")) {
3040 i--;
3041 }
3042 }
3043 }
3044
3045 // Finally, if this is a normal launch mode (that is, not
3046 // expecting onNewIntent()), then we will finish the current
3047 // instance of the activity so a new fresh one can be started.
Dianne Hackbornaa52f9a2009-08-25 16:01:15 -07003048 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
3049 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003050 if (!ret.finishing) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07003051 int index = indexOfTokenLocked(ret);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003052 if (index >= 0) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07003053 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003054 null, "clear");
3055 }
3056 return null;
3057 }
3058 }
3059
3060 return ret;
3061 }
3062 }
3063
3064 return null;
3065 }
3066
3067 /**
3068 * Find the activity in the history stack within the given task. Returns
3069 * the index within the history at which it's found, or < 0 if not found.
3070 */
3071 private final int findActivityInHistoryLocked(HistoryRecord r, int task) {
3072 int i = mHistory.size();
3073 while (i > 0) {
3074 i--;
3075 HistoryRecord candidate = (HistoryRecord)mHistory.get(i);
3076 if (candidate.task.taskId != task) {
3077 break;
3078 }
3079 if (candidate.realActivity.equals(r.realActivity)) {
3080 return i;
3081 }
3082 }
3083
3084 return -1;
3085 }
3086
3087 /**
3088 * Reorder the history stack so that the activity at the given index is
3089 * brought to the front.
3090 */
3091 private final HistoryRecord moveActivityToFrontLocked(int where) {
3092 HistoryRecord newTop = (HistoryRecord)mHistory.remove(where);
3093 int top = mHistory.size();
3094 HistoryRecord oldTop = (HistoryRecord)mHistory.get(top-1);
3095 mHistory.add(top, newTop);
3096 oldTop.frontOfTask = false;
3097 newTop.frontOfTask = true;
3098 return newTop;
3099 }
3100
3101 /**
3102 * Deliver a new Intent to an existing activity, so that its onNewIntent()
3103 * method will be called at the proper time.
3104 */
3105 private final void deliverNewIntentLocked(HistoryRecord r, Intent intent) {
3106 boolean sent = false;
3107 if (r.state == ActivityState.RESUMED
3108 && r.app != null && r.app.thread != null) {
3109 try {
3110 ArrayList<Intent> ar = new ArrayList<Intent>();
3111 ar.add(new Intent(intent));
3112 r.app.thread.scheduleNewIntent(ar, r);
3113 sent = true;
3114 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003115 Slog.w(TAG, "Exception thrown sending new intent to " + r, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003116 }
3117 }
3118 if (!sent) {
3119 r.addNewIntentLocked(new Intent(intent));
3120 }
3121 }
3122
3123 private final void logStartActivity(int tag, HistoryRecord r,
3124 TaskRecord task) {
3125 EventLog.writeEvent(tag,
3126 System.identityHashCode(r), task.taskId,
3127 r.shortComponentName, r.intent.getAction(),
3128 r.intent.getType(), r.intent.getDataString(),
3129 r.intent.getFlags());
3130 }
3131
3132 private final int startActivityLocked(IApplicationThread caller,
3133 Intent intent, String resolvedType,
3134 Uri[] grantedUriPermissions,
3135 int grantedMode, ActivityInfo aInfo, IBinder resultTo,
3136 String resultWho, int requestCode,
The Android Open Source Project4df24232009-03-05 14:34:35 -08003137 int callingPid, int callingUid, boolean onlyIfNeeded,
3138 boolean componentSpecified) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003139 Slog.i(TAG, "Starting activity: " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003140
3141 HistoryRecord sourceRecord = null;
3142 HistoryRecord resultRecord = null;
3143 if (resultTo != null) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07003144 int index = indexOfTokenLocked(resultTo);
Joe Onorato8a9b2202010-02-26 18:56:32 -08003145 if (DEBUG_RESULTS) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003146 TAG, "Sending result to " + resultTo + " (index " + index + ")");
3147 if (index >= 0) {
3148 sourceRecord = (HistoryRecord)mHistory.get(index);
3149 if (requestCode >= 0 && !sourceRecord.finishing) {
3150 resultRecord = sourceRecord;
3151 }
3152 }
3153 }
3154
3155 int launchFlags = intent.getFlags();
3156
3157 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
3158 && sourceRecord != null) {
3159 // Transfer the result target from the source activity to the new
3160 // one being started, including any failures.
3161 if (requestCode >= 0) {
3162 return START_FORWARD_AND_REQUEST_CONFLICT;
3163 }
3164 resultRecord = sourceRecord.resultTo;
3165 resultWho = sourceRecord.resultWho;
3166 requestCode = sourceRecord.requestCode;
3167 sourceRecord.resultTo = null;
3168 if (resultRecord != null) {
3169 resultRecord.removeResultsLocked(
3170 sourceRecord, resultWho, requestCode);
3171 }
3172 }
3173
3174 int err = START_SUCCESS;
3175
3176 if (intent.getComponent() == null) {
3177 // We couldn't find a class that can handle the given Intent.
3178 // That's the end of that!
3179 err = START_INTENT_NOT_RESOLVED;
3180 }
3181
3182 if (err == START_SUCCESS && aInfo == null) {
3183 // We couldn't find the specific class specified in the Intent.
3184 // Also the end of the line.
3185 err = START_CLASS_NOT_FOUND;
3186 }
3187
3188 ProcessRecord callerApp = null;
3189 if (err == START_SUCCESS && caller != null) {
3190 callerApp = getRecordForAppLocked(caller);
3191 if (callerApp != null) {
3192 callingPid = callerApp.pid;
3193 callingUid = callerApp.info.uid;
3194 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003195 Slog.w(TAG, "Unable to find app for caller " + caller
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003196 + " (pid=" + callingPid + ") when starting: "
3197 + intent.toString());
3198 err = START_PERMISSION_DENIED;
3199 }
3200 }
3201
3202 if (err != START_SUCCESS) {
3203 if (resultRecord != null) {
3204 sendActivityResultLocked(-1,
3205 resultRecord, resultWho, requestCode,
3206 Activity.RESULT_CANCELED, null);
3207 }
3208 return err;
3209 }
3210
3211 final int perm = checkComponentPermission(aInfo.permission, callingPid,
3212 callingUid, aInfo.exported ? -1 : aInfo.applicationInfo.uid);
3213 if (perm != PackageManager.PERMISSION_GRANTED) {
3214 if (resultRecord != null) {
3215 sendActivityResultLocked(-1,
3216 resultRecord, resultWho, requestCode,
3217 Activity.RESULT_CANCELED, null);
3218 }
3219 String msg = "Permission Denial: starting " + intent.toString()
3220 + " from " + callerApp + " (pid=" + callingPid
3221 + ", uid=" + callingUid + ")"
3222 + " requires " + aInfo.permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003223 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003224 throw new SecurityException(msg);
3225 }
3226
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003227 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003228 boolean abort = false;
3229 try {
3230 // The Intent we give to the watcher has the extra data
3231 // stripped off, since it can contain private information.
3232 Intent watchIntent = intent.cloneFilter();
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003233 abort = !mController.activityStarting(watchIntent,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003234 aInfo.applicationInfo.packageName);
3235 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003236 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003237 }
3238
3239 if (abort) {
3240 if (resultRecord != null) {
3241 sendActivityResultLocked(-1,
3242 resultRecord, resultWho, requestCode,
3243 Activity.RESULT_CANCELED, null);
3244 }
3245 // We pretend to the caller that it was really started, but
3246 // they will just get a cancel result.
3247 return START_SUCCESS;
3248 }
3249 }
3250
3251 HistoryRecord r = new HistoryRecord(this, callerApp, callingUid,
3252 intent, resolvedType, aInfo, mConfiguration,
The Android Open Source Project4df24232009-03-05 14:34:35 -08003253 resultRecord, resultWho, requestCode, componentSpecified);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003255 if (mResumedActivity == null
3256 || mResumedActivity.info.applicationInfo.uid != callingUid) {
3257 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
3258 PendingActivityLaunch pal = new PendingActivityLaunch();
3259 pal.r = r;
3260 pal.sourceRecord = sourceRecord;
3261 pal.grantedUriPermissions = grantedUriPermissions;
3262 pal.grantedMode = grantedMode;
3263 pal.onlyIfNeeded = onlyIfNeeded;
3264 mPendingActivityLaunches.add(pal);
3265 return START_SWITCHES_CANCELED;
3266 }
3267 }
3268
3269 if (mDidAppSwitch) {
3270 // This is the second allowed switch since we stopped switches,
3271 // so now just generally allow switches. Use case: user presses
3272 // home (switches disabled, switch to home, mDidAppSwitch now true);
3273 // user taps a home icon (coming from home so allowed, we hit here
3274 // and now allow anyone to switch again).
3275 mAppSwitchesAllowedTime = 0;
3276 } else {
3277 mDidAppSwitch = true;
3278 }
3279
3280 doPendingActivityLaunchesLocked(false);
3281
3282 return startActivityUncheckedLocked(r, sourceRecord,
3283 grantedUriPermissions, grantedMode, onlyIfNeeded, true);
3284 }
3285
3286 private final void doPendingActivityLaunchesLocked(boolean doResume) {
3287 final int N = mPendingActivityLaunches.size();
3288 if (N <= 0) {
3289 return;
3290 }
3291 for (int i=0; i<N; i++) {
3292 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
3293 startActivityUncheckedLocked(pal.r, pal.sourceRecord,
3294 pal.grantedUriPermissions, pal.grantedMode, pal.onlyIfNeeded,
3295 doResume && i == (N-1));
3296 }
3297 mPendingActivityLaunches.clear();
3298 }
3299
3300 private final int startActivityUncheckedLocked(HistoryRecord r,
3301 HistoryRecord sourceRecord, Uri[] grantedUriPermissions,
3302 int grantedMode, boolean onlyIfNeeded, boolean doResume) {
3303 final Intent intent = r.intent;
3304 final int callingUid = r.launchedFromUid;
3305
3306 int launchFlags = intent.getFlags();
3307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003308 // We'll invoke onUserLeaving before onPause only if the launching
3309 // activity did not explicitly state that this is an automated launch.
3310 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003311 if (DEBUG_USER_LEAVING) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 "startActivity() => mUserLeaving=" + mUserLeaving);
3313
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003314 // If the caller has asked not to resume at this point, we make note
3315 // of this in the record so that we can skip it when trying to find
3316 // the top running activity.
3317 if (!doResume) {
3318 r.delayedResume = true;
3319 }
3320
3321 HistoryRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
3322 != 0 ? r : null;
3323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003324 // If the onlyIfNeeded flag is set, then we can do this if the activity
3325 // being launched is the same as the one making the call... or, as
3326 // a special case, if we do not know the caller then we count the
3327 // current top activity as the caller.
3328 if (onlyIfNeeded) {
3329 HistoryRecord checkedCaller = sourceRecord;
3330 if (checkedCaller == null) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003331 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003332 }
3333 if (!checkedCaller.realActivity.equals(r.realActivity)) {
3334 // Caller is not the same as launcher, so always needed.
3335 onlyIfNeeded = false;
3336 }
3337 }
3338
3339 if (grantedUriPermissions != null && callingUid > 0) {
3340 for (int i=0; i<grantedUriPermissions.length; i++) {
3341 grantUriPermissionLocked(callingUid, r.packageName,
3342 grantedUriPermissions[i], grantedMode, r);
3343 }
3344 }
3345
3346 grantUriPermissionFromIntentLocked(callingUid, r.packageName,
3347 intent, r);
3348
3349 if (sourceRecord == null) {
3350 // This activity is not being started from another... in this
3351 // case we -always- start a new task.
3352 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003353 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003354 + intent);
3355 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
3356 }
3357 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
3358 // The original activity who is starting us is running as a single
3359 // instance... this new activity it is starting must go on its
3360 // own task.
3361 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
3362 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
3363 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
3364 // The activity being started is a single instance... it always
3365 // gets launched into its own task.
3366 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
3367 }
3368
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003369 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370 // For whatever reason this activity is being launched into a new
3371 // task... yet the caller has requested a result back. Well, that
3372 // is pretty messed up, so instead immediately send back a cancel
3373 // and let the new task continue launched as normal without a
3374 // dependency on its originator.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003375 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003376 sendActivityResultLocked(-1,
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003377 r.resultTo, r.resultWho, r.requestCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003378 Activity.RESULT_CANCELED, null);
3379 r.resultTo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 }
3381
3382 boolean addingToTask = false;
3383 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
3384 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
3385 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
3386 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
3387 // If bring to front is requested, and no result is requested, and
3388 // we can find a task that was started with this same
3389 // component, then instead of launching bring that one to the front.
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003390 if (r.resultTo == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003391 // See if there is a task to bring to the front. If this is
3392 // a SINGLE_INSTANCE activity, there can be one and only one
3393 // instance of it in the history, and it is always in its own
3394 // unique task, so we do a special search.
3395 HistoryRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
3396 ? findTaskLocked(intent, r.info)
3397 : findActivityLocked(intent, r.info);
3398 if (taskTop != null) {
3399 if (taskTop.task.intent == null) {
3400 // This task was started because of movement of
3401 // the activity based on affinity... now that we
3402 // are actually launching it, we can assign the
3403 // base intent.
3404 taskTop.task.setIntent(intent, r.info);
3405 }
3406 // If the target task is not in the front, then we need
3407 // to bring it to the front... except... well, with
3408 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
3409 // to have the same behavior as if a new instance was
3410 // being started, which means not bringing it to the front
3411 // if the caller is not itself in the front.
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003412 HistoryRecord curTop = topRunningNonDelayedActivityLocked(notTop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003413 if (curTop.task != taskTop.task) {
3414 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
3415 boolean callerAtFront = sourceRecord == null
3416 || curTop.task == sourceRecord.task;
3417 if (callerAtFront) {
3418 // We really do want to push this one into the
3419 // user's face, right now.
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07003420 moveTaskToFrontLocked(taskTop.task, r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003421 }
3422 }
3423 // If the caller has requested that the target task be
3424 // reset, then do so.
3425 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
3426 taskTop = resetTaskIfNeededLocked(taskTop, r);
3427 }
3428 if (onlyIfNeeded) {
3429 // We don't need to start a new activity, and
3430 // the client said not to do anything if that
3431 // is the case, so this is it! And for paranoia, make
3432 // sure we have correctly resumed the top activity.
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003433 if (doResume) {
3434 resumeTopActivityLocked(null);
3435 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003436 return START_RETURN_INTENT_TO_CALLER;
3437 }
3438 if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
3439 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
3440 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
3441 // In this situation we want to remove all activities
3442 // from the task up to the one being started. In most
3443 // cases this means we are resetting the task to its
3444 // initial state.
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003445 HistoryRecord top = performClearTaskLocked(
Dianne Hackbornaa52f9a2009-08-25 16:01:15 -07003446 taskTop.task.taskId, r, launchFlags, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003447 if (top != null) {
3448 if (top.frontOfTask) {
3449 // Activity aliases may mean we use different
3450 // intents for the top activity, so make sure
3451 // the task now has the identity of the new
3452 // intent.
3453 top.task.setIntent(r.intent, r.info);
3454 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08003455 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003456 deliverNewIntentLocked(top, r.intent);
3457 } else {
3458 // A special case: we need to
3459 // start the activity because it is not currently
3460 // running, and the caller has asked to clear the
3461 // current task to have this activity at the top.
3462 addingToTask = true;
3463 // Now pretend like this activity is being started
3464 // by the top of its task, so it is put in the
3465 // right place.
3466 sourceRecord = taskTop;
3467 }
3468 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
3469 // In this case the top activity on the task is the
3470 // same as the one being launched, so we take that
3471 // as a request to bring the task to the foreground.
3472 // If the top activity in the task is the root
3473 // activity, deliver this new intent to it if it
3474 // desires.
3475 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
3476 && taskTop.realActivity.equals(r.realActivity)) {
Doug Zongker2bec3d42009-12-04 12:52:44 -08003477 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003478 if (taskTop.frontOfTask) {
3479 taskTop.task.setIntent(r.intent, r.info);
3480 }
3481 deliverNewIntentLocked(taskTop, r.intent);
3482 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
3483 // In this case we are launching the root activity
3484 // of the task, but with a different intent. We
3485 // should start a new instance on top.
3486 addingToTask = true;
3487 sourceRecord = taskTop;
3488 }
3489 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
3490 // In this case an activity is being launched in to an
3491 // existing task, without resetting that task. This
3492 // is typically the situation of launching an activity
3493 // from a notification or shortcut. We want to place
3494 // the new activity on top of the current task.
3495 addingToTask = true;
3496 sourceRecord = taskTop;
3497 } else if (!taskTop.task.rootWasReset) {
3498 // In this case we are launching in to an existing task
3499 // that has not yet been started from its front door.
3500 // The current task has been brought to the front.
3501 // Ideally, we'd probably like to place this new task
3502 // at the bottom of its stack, but that's a little hard
3503 // to do with the current organization of the code so
3504 // for now we'll just drop it.
3505 taskTop.task.setIntent(r.intent, r.info);
3506 }
3507 if (!addingToTask) {
3508 // We didn't do anything... but it was needed (a.k.a., client
3509 // don't use that intent!) And for paranoia, make
3510 // sure we have correctly resumed the top activity.
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003511 if (doResume) {
3512 resumeTopActivityLocked(null);
3513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003514 return START_TASK_TO_FRONT;
3515 }
3516 }
3517 }
3518 }
3519
3520 //String uri = r.intent.toURI();
3521 //Intent intent2 = new Intent(uri);
Joe Onorato8a9b2202010-02-26 18:56:32 -08003522 //Slog.i(TAG, "Given intent: " + r.intent);
3523 //Slog.i(TAG, "URI is: " + uri);
3524 //Slog.i(TAG, "To intent: " + intent2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003525
3526 if (r.packageName != null) {
3527 // If the activity being launched is the same as the one currently
3528 // at the top, then we need to check if it should only be launched
3529 // once.
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003530 HistoryRecord top = topRunningNonDelayedActivityLocked(notTop);
3531 if (top != null && r.resultTo == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003532 if (top.realActivity.equals(r.realActivity)) {
3533 if (top.app != null && top.app.thread != null) {
3534 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
3535 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
3536 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
Doug Zongker2bec3d42009-12-04 12:52:44 -08003537 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003538 // For paranoia, make sure we have correctly
3539 // resumed the top activity.
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003540 if (doResume) {
3541 resumeTopActivityLocked(null);
3542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003543 if (onlyIfNeeded) {
3544 // We don't need to start a new activity, and
3545 // the client said not to do anything if that
3546 // is the case, so this is it!
3547 return START_RETURN_INTENT_TO_CALLER;
3548 }
3549 deliverNewIntentLocked(top, r.intent);
3550 return START_DELIVERED_TO_TOP;
3551 }
3552 }
3553 }
3554 }
3555
3556 } else {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003557 if (r.resultTo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003558 sendActivityResultLocked(-1,
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003559 r.resultTo, r.resultWho, r.requestCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003560 Activity.RESULT_CANCELED, null);
3561 }
3562 return START_CLASS_NOT_FOUND;
3563 }
3564
3565 boolean newTask = false;
3566
3567 // Should this be considered a new task?
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003568 if (r.resultTo == null && !addingToTask
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003569 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
3570 // todo: should do better management of integers.
3571 mCurTask++;
3572 if (mCurTask <= 0) {
3573 mCurTask = 1;
3574 }
3575 r.task = new TaskRecord(mCurTask, r.info, intent,
3576 (r.info.flags&ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08003577 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003578 + " in new task " + r.task);
3579 newTask = true;
Josh Bartel7f208742010-02-25 11:01:44 -06003580 addRecentTaskLocked(r.task);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003581
3582 } else if (sourceRecord != null) {
3583 if (!addingToTask &&
3584 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
3585 // In this case, we are adding the activity to an existing
3586 // task, but the caller has asked to clear that task if the
3587 // activity is already running.
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003588 HistoryRecord top = performClearTaskLocked(
Dianne Hackbornaa52f9a2009-08-25 16:01:15 -07003589 sourceRecord.task.taskId, r, launchFlags, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003590 if (top != null) {
Doug Zongker2bec3d42009-12-04 12:52:44 -08003591 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003592 deliverNewIntentLocked(top, r.intent);
3593 // For paranoia, make sure we have correctly
3594 // resumed the top activity.
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003595 if (doResume) {
3596 resumeTopActivityLocked(null);
3597 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003598 return START_DELIVERED_TO_TOP;
3599 }
3600 } else if (!addingToTask &&
3601 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
3602 // In this case, we are launching an activity in our own task
3603 // that may already be running somewhere in the history, and
3604 // we want to shuffle it to the front of the stack if so.
3605 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
3606 if (where >= 0) {
3607 HistoryRecord top = moveActivityToFrontLocked(where);
Doug Zongker2bec3d42009-12-04 12:52:44 -08003608 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003609 deliverNewIntentLocked(top, r.intent);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003610 if (doResume) {
3611 resumeTopActivityLocked(null);
3612 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003613 return START_DELIVERED_TO_TOP;
3614 }
3615 }
3616 // An existing activity is starting this new activity, so we want
3617 // to keep the new one in the same task as the one that is starting
3618 // it.
3619 r.task = sourceRecord.task;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003620 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003621 + " in existing task " + r.task);
3622
3623 } else {
3624 // This not being started from an existing activity, and not part
3625 // of a new task... just put it in the top task, though these days
3626 // this case should never happen.
3627 final int N = mHistory.size();
3628 HistoryRecord prev =
3629 N > 0 ? (HistoryRecord)mHistory.get(N-1) : null;
3630 r.task = prev != null
3631 ? prev.task
3632 : new TaskRecord(mCurTask, r.info, intent,
3633 (r.info.flags&ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08003634 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 + " in new guessed " + r.task);
3636 }
3637 if (newTask) {
Doug Zongker2bec3d42009-12-04 12:52:44 -08003638 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003639 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08003640 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003641 startActivityLocked(r, newTask, doResume);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003642 return START_SUCCESS;
3643 }
3644
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08003645 void reportActivityLaunchedLocked(boolean timeout, HistoryRecord r,
3646 long thisTime, long totalTime) {
3647 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
3648 WaitResult w = mWaitingActivityLaunched.get(i);
3649 w.timeout = timeout;
3650 if (r != null) {
3651 w.who = new ComponentName(r.info.packageName, r.info.name);
3652 }
3653 w.thisTime = thisTime;
3654 w.totalTime = totalTime;
3655 }
3656 notify();
3657 }
3658
3659 void reportActivityVisibleLocked(HistoryRecord r) {
3660 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
3661 WaitResult w = mWaitingActivityVisible.get(i);
3662 w.timeout = false;
3663 if (r != null) {
3664 w.who = new ComponentName(r.info.packageName, r.info.name);
3665 }
3666 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
3667 w.thisTime = w.totalTime;
3668 }
3669 notify();
3670 }
3671
3672 private final int startActivityMayWait(IApplicationThread caller,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003673 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
3674 int grantedMode, IBinder resultTo,
3675 String resultWho, int requestCode, boolean onlyIfNeeded,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07003676 boolean debug, WaitResult outResult, Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003677 // Refuse possible leaked file descriptors
3678 if (intent != null && intent.hasFileDescriptors()) {
3679 throw new IllegalArgumentException("File descriptors passed in Intent");
3680 }
3681
The Android Open Source Project4df24232009-03-05 14:34:35 -08003682 final boolean componentSpecified = intent.getComponent() != null;
3683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003684 // Don't modify the client's object!
3685 intent = new Intent(intent);
3686
3687 // Collect information about the target of the Intent.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003688 ActivityInfo aInfo;
3689 try {
3690 ResolveInfo rInfo =
3691 ActivityThread.getPackageManager().resolveIntent(
3692 intent, resolvedType,
3693 PackageManager.MATCH_DEFAULT_ONLY
Dianne Hackborn1655be42009-05-08 14:29:01 -07003694 | STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003695 aInfo = rInfo != null ? rInfo.activityInfo : null;
3696 } catch (RemoteException e) {
3697 aInfo = null;
3698 }
3699
3700 if (aInfo != null) {
3701 // Store the found target back into the intent, because now that
3702 // we have it we never want to do this again. For example, if the
3703 // user navigates back to this point in the history, we should
3704 // always restart the exact same activity.
3705 intent.setComponent(new ComponentName(
3706 aInfo.applicationInfo.packageName, aInfo.name));
3707
3708 // Don't debug things in the system process
3709 if (debug) {
3710 if (!aInfo.processName.equals("system")) {
3711 setDebugApp(aInfo.processName, true, false);
3712 }
3713 }
3714 }
3715
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08003716 synchronized (this) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08003717 int callingPid;
3718 int callingUid;
3719 if (caller == null) {
3720 callingPid = Binder.getCallingPid();
3721 callingUid = Binder.getCallingUid();
3722 } else {
3723 callingPid = callingUid = -1;
3724 }
Dianne Hackbornd49258f2010-03-26 00:44:29 -07003725
3726 mConfigWillChange = config != null && mConfiguration.diff(config) != 0;
Dianne Hackborne2522462010-03-29 18:41:30 -07003727 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3728 "Starting activity when config will change = " + mConfigWillChange);
Dianne Hackbornd49258f2010-03-26 00:44:29 -07003729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003730 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornd49258f2010-03-26 00:44:29 -07003731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003732 int res = startActivityLocked(caller, intent, resolvedType,
3733 grantedUriPermissions, grantedMode, aInfo,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08003734 resultTo, resultWho, requestCode, callingPid, callingUid,
The Android Open Source Project4df24232009-03-05 14:34:35 -08003735 onlyIfNeeded, componentSpecified);
Dianne Hackbornd49258f2010-03-26 00:44:29 -07003736
Dianne Hackborne2522462010-03-29 18:41:30 -07003737 if (mConfigWillChange) {
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07003738 // If the caller also wants to switch to a new configuration,
3739 // do so now. This allows a clean switch, as we are waiting
3740 // for the current activity to pause (so we will not destroy
3741 // it), and have not yet started the next activity.
3742 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
3743 "updateConfiguration()");
Dianne Hackborne2522462010-03-29 18:41:30 -07003744 mConfigWillChange = false;
3745 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3746 "Updating to new configuration after starting activity.");
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07003747 updateConfigurationLocked(config, null);
3748 }
Dianne Hackbornd49258f2010-03-26 00:44:29 -07003749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003750 Binder.restoreCallingIdentity(origId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08003751
3752 if (outResult != null) {
3753 outResult.result = res;
3754 if (res == IActivityManager.START_SUCCESS) {
3755 mWaitingActivityLaunched.add(outResult);
3756 do {
3757 try {
3758 wait();
3759 } catch (InterruptedException e) {
3760 }
3761 } while (!outResult.timeout && outResult.who == null);
3762 } else if (res == IActivityManager.START_TASK_TO_FRONT) {
3763 HistoryRecord r = this.topRunningActivityLocked(null);
3764 if (r.nowVisible) {
3765 outResult.timeout = false;
3766 outResult.who = new ComponentName(r.info.packageName, r.info.name);
3767 outResult.totalTime = 0;
3768 outResult.thisTime = 0;
3769 } else {
3770 outResult.thisTime = SystemClock.uptimeMillis();
3771 mWaitingActivityVisible.add(outResult);
3772 do {
3773 try {
3774 wait();
3775 } catch (InterruptedException e) {
3776 }
3777 } while (!outResult.timeout && outResult.who == null);
3778 }
3779 }
3780 }
3781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003782 return res;
3783 }
3784 }
3785
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08003786 public final int startActivity(IApplicationThread caller,
3787 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
3788 int grantedMode, IBinder resultTo,
3789 String resultWho, int requestCode, boolean onlyIfNeeded,
3790 boolean debug) {
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07003791 return startActivityMayWait(caller, intent, resolvedType,
3792 grantedUriPermissions, grantedMode, resultTo, resultWho,
3793 requestCode, onlyIfNeeded, debug, null, null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08003794 }
3795
3796 public final WaitResult startActivityAndWait(IApplicationThread caller,
3797 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
3798 int grantedMode, IBinder resultTo,
3799 String resultWho, int requestCode, boolean onlyIfNeeded,
3800 boolean debug) {
3801 WaitResult res = new WaitResult();
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07003802 startActivityMayWait(caller, intent, resolvedType,
3803 grantedUriPermissions, grantedMode, resultTo, resultWho,
3804 requestCode, onlyIfNeeded, debug, res, null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08003805 return res;
3806 }
3807
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07003808 public final int startActivityWithConfig(IApplicationThread caller,
3809 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
3810 int grantedMode, IBinder resultTo,
3811 String resultWho, int requestCode, boolean onlyIfNeeded,
3812 boolean debug, Configuration config) {
3813 return startActivityMayWait(caller, intent, resolvedType,
3814 grantedUriPermissions, grantedMode, resultTo, resultWho,
3815 requestCode, onlyIfNeeded, debug, null, config);
3816 }
3817
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08003818 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003819 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003820 IBinder resultTo, String resultWho, int requestCode,
3821 int flagsMask, int flagsValues) {
3822 // Refuse possible leaked file descriptors
3823 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
3824 throw new IllegalArgumentException("File descriptors passed in Intent");
3825 }
3826
3827 IIntentSender sender = intent.getTarget();
3828 if (!(sender instanceof PendingIntentRecord)) {
3829 throw new IllegalArgumentException("Bad PendingIntent object");
3830 }
3831
3832 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003833
3834 synchronized (this) {
3835 // If this is coming from the currently resumed activity, it is
3836 // effectively saying that app switches are allowed at this point.
3837 if (mResumedActivity != null
3838 && mResumedActivity.info.applicationInfo.uid ==
3839 Binder.getCallingUid()) {
3840 mAppSwitchesAllowedTime = 0;
3841 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003842 }
3843
3844 return pir.sendInner(0, fillInIntent, resolvedType,
3845 null, resultTo, resultWho, requestCode, flagsMask, flagsValues);
3846 }
3847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003848 public boolean startNextMatchingActivity(IBinder callingActivity,
3849 Intent intent) {
3850 // Refuse possible leaked file descriptors
3851 if (intent != null && intent.hasFileDescriptors() == true) {
3852 throw new IllegalArgumentException("File descriptors passed in Intent");
3853 }
3854
3855 synchronized (this) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07003856 int index = indexOfTokenLocked(callingActivity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003857 if (index < 0) {
3858 return false;
3859 }
3860 HistoryRecord r = (HistoryRecord)mHistory.get(index);
3861 if (r.app == null || r.app.thread == null) {
3862 // The caller is not running... d'oh!
3863 return false;
3864 }
3865 intent = new Intent(intent);
3866 // The caller is not allowed to change the data.
3867 intent.setDataAndType(r.intent.getData(), r.intent.getType());
3868 // And we are resetting to find the next component...
3869 intent.setComponent(null);
3870
3871 ActivityInfo aInfo = null;
3872 try {
3873 List<ResolveInfo> resolves =
3874 ActivityThread.getPackageManager().queryIntentActivities(
3875 intent, r.resolvedType,
Dianne Hackborn1655be42009-05-08 14:29:01 -07003876 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003877
3878 // Look for the original activity in the list...
3879 final int N = resolves != null ? resolves.size() : 0;
3880 for (int i=0; i<N; i++) {
3881 ResolveInfo rInfo = resolves.get(i);
3882 if (rInfo.activityInfo.packageName.equals(r.packageName)
3883 && rInfo.activityInfo.name.equals(r.info.name)) {
3884 // We found the current one... the next matching is
3885 // after it.
3886 i++;
3887 if (i<N) {
3888 aInfo = resolves.get(i).activityInfo;
3889 }
3890 break;
3891 }
3892 }
3893 } catch (RemoteException e) {
3894 }
3895
3896 if (aInfo == null) {
3897 // Nobody who is next!
3898 return false;
3899 }
3900
3901 intent.setComponent(new ComponentName(
3902 aInfo.applicationInfo.packageName, aInfo.name));
3903 intent.setFlags(intent.getFlags()&~(
3904 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
3905 Intent.FLAG_ACTIVITY_CLEAR_TOP|
3906 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
3907 Intent.FLAG_ACTIVITY_NEW_TASK));
3908
3909 // Okay now we need to start the new activity, replacing the
3910 // currently running activity. This is a little tricky because
3911 // we want to start the new one as if the current one is finished,
3912 // but not finish the current one first so that there is no flicker.
3913 // And thus...
3914 final boolean wasFinishing = r.finishing;
3915 r.finishing = true;
3916
3917 // Propagate reply information over to the new activity.
3918 final HistoryRecord resultTo = r.resultTo;
3919 final String resultWho = r.resultWho;
3920 final int requestCode = r.requestCode;
3921 r.resultTo = null;
3922 if (resultTo != null) {
3923 resultTo.removeResultsLocked(r, resultWho, requestCode);
3924 }
3925
3926 final long origId = Binder.clearCallingIdentity();
3927 // XXX we are not dealing with propagating grantedUriPermissions...
3928 // those are not yet exposed to user code, so there is no need.
3929 int res = startActivityLocked(r.app.thread, intent,
3930 r.resolvedType, null, 0, aInfo, resultTo, resultWho,
The Android Open Source Project4df24232009-03-05 14:34:35 -08003931 requestCode, -1, r.launchedFromUid, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003932 Binder.restoreCallingIdentity(origId);
3933
3934 r.finishing = wasFinishing;
3935 if (res != START_SUCCESS) {
3936 return false;
3937 }
3938 return true;
3939 }
3940 }
3941
Dianne Hackborn2d91af02009-07-16 13:34:33 -07003942 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003943 Intent intent, String resolvedType, IBinder resultTo,
3944 String resultWho, int requestCode, boolean onlyIfNeeded) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07003945
3946 // This is so super not safe, that only the system (or okay root)
3947 // can do it.
3948 final int callingUid = Binder.getCallingUid();
3949 if (callingUid != 0 && callingUid != Process.myUid()) {
3950 throw new SecurityException(
3951 "startActivityInPackage only available to the system");
3952 }
3953
The Android Open Source Project4df24232009-03-05 14:34:35 -08003954 final boolean componentSpecified = intent.getComponent() != null;
3955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003956 // Don't modify the client's object!
3957 intent = new Intent(intent);
3958
3959 // Collect information about the target of the Intent.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003960 ActivityInfo aInfo;
3961 try {
3962 ResolveInfo rInfo =
3963 ActivityThread.getPackageManager().resolveIntent(
3964 intent, resolvedType,
Dianne Hackborn1655be42009-05-08 14:29:01 -07003965 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003966 aInfo = rInfo != null ? rInfo.activityInfo : null;
3967 } catch (RemoteException e) {
3968 aInfo = null;
3969 }
3970
3971 if (aInfo != null) {
3972 // Store the found target back into the intent, because now that
3973 // we have it we never want to do this again. For example, if the
3974 // user navigates back to this point in the history, we should
3975 // always restart the exact same activity.
3976 intent.setComponent(new ComponentName(
3977 aInfo.applicationInfo.packageName, aInfo.name));
3978 }
3979
3980 synchronized(this) {
3981 return startActivityLocked(null, intent, resolvedType,
3982 null, 0, aInfo, resultTo, resultWho, requestCode, -1, uid,
The Android Open Source Project4df24232009-03-05 14:34:35 -08003983 onlyIfNeeded, componentSpecified);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003984 }
3985 }
3986
Josh Bartel7f208742010-02-25 11:01:44 -06003987 private final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003988 // Remove any existing entries that are the same kind of task.
3989 int N = mRecentTasks.size();
3990 for (int i=0; i<N; i++) {
3991 TaskRecord tr = mRecentTasks.get(i);
3992 if ((task.affinity != null && task.affinity.equals(tr.affinity))
3993 || (task.intent != null && task.intent.filterEquals(tr.intent))) {
3994 mRecentTasks.remove(i);
3995 i--;
3996 N--;
3997 if (task.intent == null) {
3998 // If the new recent task we are adding is not fully
3999 // specified, then replace it with the existing recent task.
4000 task = tr;
4001 }
4002 }
4003 }
4004 if (N >= MAX_RECENT_TASKS) {
4005 mRecentTasks.remove(N-1);
4006 }
4007 mRecentTasks.add(0, task);
4008 }
4009
4010 public void setRequestedOrientation(IBinder token,
4011 int requestedOrientation) {
4012 synchronized (this) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07004013 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004014 if (index < 0) {
4015 return;
4016 }
4017 HistoryRecord r = (HistoryRecord)mHistory.get(index);
4018 final long origId = Binder.clearCallingIdentity();
4019 mWindowManager.setAppOrientation(r, requestedOrientation);
4020 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07004021 mConfiguration,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004022 r.mayFreezeScreenLocked(r.app) ? r : null);
4023 if (config != null) {
4024 r.frozenBeforeDestroy = true;
4025 if (!updateConfigurationLocked(config, r)) {
4026 resumeTopActivityLocked(null);
4027 }
4028 }
4029 Binder.restoreCallingIdentity(origId);
4030 }
4031 }
4032
4033 public int getRequestedOrientation(IBinder token) {
4034 synchronized (this) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07004035 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004036 if (index < 0) {
4037 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
4038 }
4039 HistoryRecord r = (HistoryRecord)mHistory.get(index);
4040 return mWindowManager.getAppOrientation(r);
4041 }
4042 }
4043
4044 private final void stopActivityLocked(HistoryRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004045 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
4047 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
4048 if (!r.finishing) {
4049 requestFinishActivityLocked(r, Activity.RESULT_CANCELED, null,
4050 "no-history");
4051 }
4052 } else if (r.app != null && r.app.thread != null) {
4053 if (mFocusedActivity == r) {
4054 setFocusedActivityLocked(topRunningActivityLocked(null));
4055 }
4056 r.resumeKeyDispatchingLocked();
4057 try {
4058 r.stopped = false;
4059 r.state = ActivityState.STOPPING;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004060 if (DEBUG_VISBILITY) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004061 TAG, "Stopping visible=" + r.visible + " for " + r);
4062 if (!r.visible) {
4063 mWindowManager.setAppVisibility(r, false);
4064 }
4065 r.app.thread.scheduleStopActivity(r, r.visible, r.configChangeFlags);
4066 } catch (Exception e) {
4067 // Maybe just ignore exceptions here... if the process
4068 // has crashed, our death notification will clean things
4069 // up.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004070 Slog.w(TAG, "Exception thrown during pause", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004071 // Just in case, assume it to be stopped.
4072 r.stopped = true;
4073 r.state = ActivityState.STOPPED;
4074 if (r.configDestroy) {
4075 destroyActivityLocked(r, true);
4076 }
4077 }
4078 }
4079 }
4080
4081 /**
4082 * @return Returns true if the activity is being finished, false if for
4083 * some reason it is being left as-is.
4084 */
4085 private final boolean requestFinishActivityLocked(IBinder token, int resultCode,
4086 Intent resultData, String reason) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004087 if (DEBUG_RESULTS) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004088 TAG, "Finishing activity: token=" + token
4089 + ", result=" + resultCode + ", data=" + resultData);
4090
Dianne Hackborn75b03852009-06-12 15:43:26 -07004091 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004092 if (index < 0) {
4093 return false;
4094 }
4095 HistoryRecord r = (HistoryRecord)mHistory.get(index);
4096
4097 // Is this the last activity left?
4098 boolean lastActivity = true;
4099 for (int i=mHistory.size()-1; i>=0; i--) {
4100 HistoryRecord p = (HistoryRecord)mHistory.get(i);
4101 if (!p.finishing && p != r) {
4102 lastActivity = false;
4103 break;
4104 }
4105 }
4106
4107 // If this is the last activity, but it is the home activity, then
4108 // just don't finish it.
4109 if (lastActivity) {
4110 if (r.intent.hasCategory(Intent.CATEGORY_HOME)) {
4111 return false;
4112 }
4113 }
4114
4115 finishActivityLocked(r, index, resultCode, resultData, reason);
4116 return true;
4117 }
4118
4119 /**
4120 * @return Returns true if this activity has been removed from the history
4121 * list, or false if it is still in the list and will be removed later.
4122 */
4123 private final boolean finishActivityLocked(HistoryRecord r, int index,
4124 int resultCode, Intent resultData, String reason) {
4125 if (r.finishing) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004126 Slog.w(TAG, "Duplicate finish request for " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004127 return false;
4128 }
4129
4130 r.finishing = true;
Doug Zongker2bec3d42009-12-04 12:52:44 -08004131 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004132 System.identityHashCode(r),
4133 r.task.taskId, r.shortComponentName, reason);
4134 r.task.numActivities--;
Dianne Hackbornb67fa452010-04-14 18:01:43 -07004135 if (index < (mHistory.size()-1)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004136 HistoryRecord next = (HistoryRecord)mHistory.get(index+1);
4137 if (next.task == r.task) {
Dianne Hackbornb67fa452010-04-14 18:01:43 -07004138 if (r.frontOfTask) {
4139 // The next activity is now the front of the task.
4140 next.frontOfTask = true;
4141 }
4142 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
4143 // If the caller asked that this activity (and all above it)
4144 // be cleared when the task is reset, don't lose that information,
4145 // but propagate it up to the next activity.
4146 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
4147 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004148 }
4149 }
4150
4151 r.pauseKeyDispatchingLocked();
4152 if (mFocusedActivity == r) {
4153 setFocusedActivityLocked(topRunningActivityLocked(null));
4154 }
4155
4156 // send the result
4157 HistoryRecord resultTo = r.resultTo;
4158 if (resultTo != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004159 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
Chris Tate8a7dc172009-03-24 20:11:42 -07004160 + " who=" + r.resultWho + " req=" + r.requestCode
4161 + " res=" + resultCode + " data=" + resultData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004162 if (r.info.applicationInfo.uid > 0) {
4163 grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
4164 r.packageName, resultData, r);
4165 }
4166 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
4167 resultData);
4168 r.resultTo = null;
4169 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004170 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004171
4172 // Make sure this HistoryRecord is not holding on to other resources,
4173 // because clients have remote IPC references to this object so we
4174 // can't assume that will go away and want to avoid circular IPC refs.
4175 r.results = null;
4176 r.pendingResults = null;
4177 r.newIntents = null;
4178 r.icicle = null;
4179
4180 if (mPendingThumbnails.size() > 0) {
4181 // There are clients waiting to receive thumbnails so, in case
4182 // this is an activity that someone is waiting for, add it
4183 // to the pending list so we can correctly update the clients.
4184 mCancelledThumbnails.add(r);
4185 }
4186
4187 if (mResumedActivity == r) {
4188 boolean endTask = index <= 0
4189 || ((HistoryRecord)mHistory.get(index-1)).task != r.task;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004190 if (DEBUG_TRANSITION) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004191 "Prepare close transition: finishing " + r);
4192 mWindowManager.prepareAppTransition(endTask
4193 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
4194 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE);
4195
4196 // Tell window manager to prepare for this one to be removed.
4197 mWindowManager.setAppVisibility(r, false);
4198
4199 if (mPausingActivity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004200 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
4201 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004202 startPausingLocked(false, false);
4203 }
4204
4205 } else if (r.state != ActivityState.PAUSING) {
4206 // If the activity is PAUSING, we will complete the finish once
4207 // it is done pausing; else we can just directly finish it here.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004208 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004209 return finishCurrentActivityLocked(r, index,
4210 FINISH_AFTER_PAUSE) == null;
4211 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004212 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004213 }
4214
4215 return false;
4216 }
4217
4218 private static final int FINISH_IMMEDIATELY = 0;
4219 private static final int FINISH_AFTER_PAUSE = 1;
4220 private static final int FINISH_AFTER_VISIBLE = 2;
4221
4222 private final HistoryRecord finishCurrentActivityLocked(HistoryRecord r,
4223 int mode) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07004224 final int index = indexOfTokenLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004225 if (index < 0) {
4226 return null;
4227 }
4228
4229 return finishCurrentActivityLocked(r, index, mode);
4230 }
4231
4232 private final HistoryRecord finishCurrentActivityLocked(HistoryRecord r,
4233 int index, int mode) {
4234 // First things first: if this activity is currently visible,
4235 // and the resumed activity is not yet visible, then hold off on
4236 // finishing until the resumed one becomes visible.
4237 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
4238 if (!mStoppingActivities.contains(r)) {
4239 mStoppingActivities.add(r);
4240 if (mStoppingActivities.size() > 3) {
4241 // If we already have a few activities waiting to stop,
4242 // then give up on things going idle and start clearing
4243 // them out.
4244 Message msg = Message.obtain();
4245 msg.what = ActivityManagerService.IDLE_NOW_MSG;
4246 mHandler.sendMessage(msg);
4247 }
4248 }
4249 r.state = ActivityState.STOPPING;
4250 updateOomAdjLocked();
4251 return r;
4252 }
4253
4254 // make sure the record is cleaned out of other places.
4255 mStoppingActivities.remove(r);
4256 mWaitingVisibleActivities.remove(r);
4257 if (mResumedActivity == r) {
4258 mResumedActivity = null;
4259 }
4260 final ActivityState prevState = r.state;
4261 r.state = ActivityState.FINISHING;
4262
4263 if (mode == FINISH_IMMEDIATELY
4264 || prevState == ActivityState.STOPPED
4265 || prevState == ActivityState.INITIALIZING) {
4266 // If this activity is already stopped, we can just finish
4267 // it right now.
4268 return destroyActivityLocked(r, true) ? null : r;
4269 } else {
4270 // Need to go through the full pause cycle to get this
4271 // activity into the stopped state and then finish it.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004272 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004273 mFinishingActivities.add(r);
4274 resumeTopActivityLocked(null);
4275 }
4276 return r;
4277 }
4278
4279 /**
4280 * This is the internal entry point for handling Activity.finish().
4281 *
4282 * @param token The Binder token referencing the Activity we want to finish.
4283 * @param resultCode Result code, if any, from this Activity.
4284 * @param resultData Result data (Intent), if any, from this Activity.
4285 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11004286 * @return Returns true if the activity successfully finished, or false if it is still running.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004287 */
4288 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
4289 // Refuse possible leaked file descriptors
4290 if (resultData != null && resultData.hasFileDescriptors() == true) {
4291 throw new IllegalArgumentException("File descriptors passed in Intent");
4292 }
4293
4294 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004295 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004296 // Find the first activity that is not finishing.
4297 HistoryRecord next = topRunningActivityLocked(token, 0);
4298 if (next != null) {
4299 // ask watcher if this is allowed
4300 boolean resumeOK = true;
4301 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004302 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004303 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004304 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004305 }
4306
4307 if (!resumeOK) {
4308 return false;
4309 }
4310 }
4311 }
4312 final long origId = Binder.clearCallingIdentity();
4313 boolean res = requestFinishActivityLocked(token, resultCode,
4314 resultData, "app-request");
4315 Binder.restoreCallingIdentity(origId);
4316 return res;
4317 }
4318 }
4319
4320 void sendActivityResultLocked(int callingUid, HistoryRecord r,
4321 String resultWho, int requestCode, int resultCode, Intent data) {
4322
4323 if (callingUid > 0) {
4324 grantUriPermissionFromIntentLocked(callingUid, r.packageName,
4325 data, r);
4326 }
4327
Joe Onorato8a9b2202010-02-26 18:56:32 -08004328 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
The Android Open Source Project10592532009-03-18 17:39:46 -07004329 + " : who=" + resultWho + " req=" + requestCode
4330 + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004331 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
4332 try {
4333 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
4334 list.add(new ResultInfo(resultWho, requestCode,
4335 resultCode, data));
4336 r.app.thread.scheduleSendResult(r, list);
4337 return;
4338 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004339 Slog.w(TAG, "Exception thrown sending result to " + r, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004340 }
4341 }
4342
4343 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
4344 }
4345
4346 public final void finishSubActivity(IBinder token, String resultWho,
4347 int requestCode) {
4348 synchronized(this) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07004349 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004350 if (index < 0) {
4351 return;
4352 }
4353 HistoryRecord self = (HistoryRecord)mHistory.get(index);
4354
4355 final long origId = Binder.clearCallingIdentity();
4356
4357 int i;
4358 for (i=mHistory.size()-1; i>=0; i--) {
4359 HistoryRecord r = (HistoryRecord)mHistory.get(i);
4360 if (r.resultTo == self && r.requestCode == requestCode) {
4361 if ((r.resultWho == null && resultWho == null) ||
4362 (r.resultWho != null && r.resultWho.equals(resultWho))) {
4363 finishActivityLocked(r, i,
4364 Activity.RESULT_CANCELED, null, "request-sub");
4365 }
4366 }
4367 }
4368
4369 Binder.restoreCallingIdentity(origId);
4370 }
4371 }
4372
Dianne Hackborn061d58a2010-03-12 15:07:06 -08004373 public boolean willActivityBeVisible(IBinder token) {
4374 synchronized(this) {
4375 int i;
4376 for (i=mHistory.size()-1; i>=0; i--) {
4377 HistoryRecord r = (HistoryRecord)mHistory.get(i);
4378 if (r == token) {
4379 return true;
4380 }
4381 if (r.fullscreen && !r.finishing) {
4382 return false;
4383 }
4384 }
4385 return true;
4386 }
4387 }
4388
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07004389 public void overridePendingTransition(IBinder token, String packageName,
4390 int enterAnim, int exitAnim) {
4391 synchronized(this) {
4392 int index = indexOfTokenLocked(token);
4393 if (index < 0) {
4394 return;
4395 }
4396 HistoryRecord self = (HistoryRecord)mHistory.get(index);
4397
4398 final long origId = Binder.clearCallingIdentity();
4399
4400 if (self.state == ActivityState.RESUMED
4401 || self.state == ActivityState.PAUSING) {
4402 mWindowManager.overridePendingAppTransition(packageName,
4403 enterAnim, exitAnim);
4404 }
4405
4406 Binder.restoreCallingIdentity(origId);
4407 }
4408 }
4409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004410 /**
4411 * Perform clean-up of service connections in an activity record.
4412 */
4413 private final void cleanUpActivityServicesLocked(HistoryRecord r) {
4414 // Throw away any services that have been bound by this activity.
4415 if (r.connections != null) {
4416 Iterator<ConnectionRecord> it = r.connections.iterator();
4417 while (it.hasNext()) {
4418 ConnectionRecord c = it.next();
4419 removeConnectionLocked(c, null, r);
4420 }
4421 r.connections = null;
4422 }
4423 }
4424
4425 /**
4426 * Perform the common clean-up of an activity record. This is called both
4427 * as part of destroyActivityLocked() (when destroying the client-side
4428 * representation) and cleaning things up as a result of its hosting
4429 * processing going away, in which case there is no remaining client-side
4430 * state to destroy so only the cleanup here is needed.
4431 */
4432 private final void cleanUpActivityLocked(HistoryRecord r, boolean cleanServices) {
4433 if (mResumedActivity == r) {
4434 mResumedActivity = null;
4435 }
4436 if (mFocusedActivity == r) {
4437 mFocusedActivity = null;
4438 }
4439
4440 r.configDestroy = false;
4441 r.frozenBeforeDestroy = false;
4442
4443 // Make sure this record is no longer in the pending finishes list.
4444 // This could happen, for example, if we are trimming activities
4445 // down to the max limit while they are still waiting to finish.
4446 mFinishingActivities.remove(r);
4447 mWaitingVisibleActivities.remove(r);
4448
4449 // Remove any pending results.
4450 if (r.finishing && r.pendingResults != null) {
4451 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
4452 PendingIntentRecord rec = apr.get();
4453 if (rec != null) {
4454 cancelIntentSenderLocked(rec, false);
4455 }
4456 }
4457 r.pendingResults = null;
4458 }
4459
4460 if (cleanServices) {
4461 cleanUpActivityServicesLocked(r);
4462 }
4463
4464 if (mPendingThumbnails.size() > 0) {
4465 // There are clients waiting to receive thumbnails so, in case
4466 // this is an activity that someone is waiting for, add it
4467 // to the pending list so we can correctly update the clients.
4468 mCancelledThumbnails.add(r);
4469 }
4470
4471 // Get rid of any pending idle timeouts.
4472 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
4473 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
4474 }
4475
4476 private final void removeActivityFromHistoryLocked(HistoryRecord r) {
4477 if (r.state != ActivityState.DESTROYED) {
4478 mHistory.remove(r);
4479 r.inHistory = false;
4480 r.state = ActivityState.DESTROYED;
4481 mWindowManager.removeAppToken(r);
4482 if (VALIDATE_TOKENS) {
4483 mWindowManager.validateAppTokens(mHistory);
4484 }
4485 cleanUpActivityServicesLocked(r);
4486 removeActivityUriPermissionsLocked(r);
4487 }
4488 }
4489
4490 /**
4491 * Destroy the current CLIENT SIDE instance of an activity. This may be
4492 * called both when actually finishing an activity, or when performing
4493 * a configuration switch where we destroy the current client-side object
4494 * but then create a new client-side object for this same HistoryRecord.
4495 */
4496 private final boolean destroyActivityLocked(HistoryRecord r,
4497 boolean removeFromApp) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004498 if (DEBUG_SWITCH) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004499 TAG, "Removing activity: token=" + r
4500 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
Doug Zongker2bec3d42009-12-04 12:52:44 -08004501 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004502 System.identityHashCode(r),
4503 r.task.taskId, r.shortComponentName);
4504
4505 boolean removedFromHistory = false;
4506
4507 cleanUpActivityLocked(r, false);
4508
Dianne Hackborn03abb812010-01-04 18:43:19 -08004509 final boolean hadApp = r.app != null;
4510
4511 if (hadApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004512 if (removeFromApp) {
4513 int idx = r.app.activities.indexOf(r);
4514 if (idx >= 0) {
4515 r.app.activities.remove(idx);
4516 }
4517 if (r.persistent) {
4518 decPersistentCountLocked(r.app);
4519 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004520 if (r.app.activities.size() == 0) {
4521 // No longer have activities, so update location in
4522 // LRU list.
4523 updateLruProcessLocked(r.app, true, false);
4524 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004525 }
4526
4527 boolean skipDestroy = false;
4528
4529 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004530 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004531 r.app.thread.scheduleDestroyActivity(r, r.finishing,
4532 r.configChangeFlags);
4533 } catch (Exception e) {
4534 // We can just ignore exceptions here... if the process
4535 // has crashed, our death notification will clean things
4536 // up.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004537 //Slog.w(TAG, "Exception thrown during finish", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004538 if (r.finishing) {
4539 removeActivityFromHistoryLocked(r);
4540 removedFromHistory = true;
4541 skipDestroy = true;
4542 }
4543 }
4544
4545 r.app = null;
4546 r.nowVisible = false;
4547
4548 if (r.finishing && !skipDestroy) {
4549 r.state = ActivityState.DESTROYING;
4550 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
4551 msg.obj = r;
4552 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
4553 } else {
4554 r.state = ActivityState.DESTROYED;
4555 }
4556 } else {
4557 // remove this record from the history.
4558 if (r.finishing) {
4559 removeActivityFromHistoryLocked(r);
4560 removedFromHistory = true;
4561 } else {
4562 r.state = ActivityState.DESTROYED;
4563 }
4564 }
4565
4566 r.configChangeFlags = 0;
4567
Dianne Hackborn03abb812010-01-04 18:43:19 -08004568 if (!mLRUActivities.remove(r) && hadApp) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004569 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004570 }
4571
4572 return removedFromHistory;
4573 }
4574
Dianne Hackborn03abb812010-01-04 18:43:19 -08004575 private static void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004576 int i = list.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004577 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004578 TAG, "Removing app " + app + " from list " + list
4579 + " with " + i + " entries");
4580 while (i > 0) {
4581 i--;
4582 HistoryRecord r = (HistoryRecord)list.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08004583 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004584 TAG, "Record #" + i + " " + r + ": app=" + r.app);
4585 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004586 if (localLOGV) Slog.v(TAG, "Removing this entry!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004587 list.remove(i);
4588 }
4589 }
4590 }
4591
4592 /**
4593 * Main function for removing an existing process from the activity manager
4594 * as a result of that process going away. Clears out all connections
4595 * to the process.
4596 */
4597 private final void handleAppDiedLocked(ProcessRecord app,
4598 boolean restarting) {
4599 cleanUpApplicationRecordLocked(app, restarting, -1);
4600 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004601 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004602 }
4603
4604 // Just in case...
4605 if (mPausingActivity != null && mPausingActivity.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004606 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " + mPausingActivity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004607 mPausingActivity = null;
4608 }
4609 if (mLastPausedActivity != null && mLastPausedActivity.app == app) {
4610 mLastPausedActivity = null;
4611 }
4612
4613 // Remove this application's activities from active lists.
4614 removeHistoryRecordsForAppLocked(mLRUActivities, app);
4615 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
4616 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
4617 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
4618
4619 boolean atTop = true;
4620 boolean hasVisibleActivities = false;
4621
4622 // Clean out the history list.
4623 int i = mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08004624 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004625 TAG, "Removing app " + app + " from history with " + i + " entries");
4626 while (i > 0) {
4627 i--;
4628 HistoryRecord r = (HistoryRecord)mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08004629 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004630 TAG, "Record #" + i + " " + r + ": app=" + r.app);
4631 if (r.app == app) {
4632 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004633 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004634 TAG, "Removing this entry! frozen=" + r.haveState
4635 + " finishing=" + r.finishing);
4636 mHistory.remove(i);
4637
4638 r.inHistory = false;
4639 mWindowManager.removeAppToken(r);
4640 if (VALIDATE_TOKENS) {
4641 mWindowManager.validateAppTokens(mHistory);
4642 }
4643 removeActivityUriPermissionsLocked(r);
4644
4645 } else {
4646 // We have the current state for this activity, so
4647 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004648 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004649 TAG, "Keeping entry, setting app to null");
4650 if (r.visible) {
4651 hasVisibleActivities = true;
4652 }
4653 r.app = null;
4654 r.nowVisible = false;
4655 if (!r.haveState) {
4656 r.icicle = null;
4657 }
4658 }
4659
4660 cleanUpActivityLocked(r, true);
4661 r.state = ActivityState.STOPPED;
4662 }
4663 atTop = false;
4664 }
4665
4666 app.activities.clear();
4667
4668 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004669 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004670 + " running instrumentation " + app.instrumentationClass);
4671 Bundle info = new Bundle();
4672 info.putString("shortMsg", "Process crashed.");
4673 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
4674 }
4675
4676 if (!restarting) {
4677 if (!resumeTopActivityLocked(null)) {
4678 // If there was nothing to resume, and we are not already
4679 // restarting this process, but there is a visible activity that
4680 // is hosted by the process... then make sure all visible
4681 // activities are running, taking care of restarting this
4682 // process.
4683 if (hasVisibleActivities) {
4684 ensureActivitiesVisibleLocked(null, 0);
4685 }
4686 }
4687 }
4688 }
4689
4690 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
4691 IBinder threadBinder = thread.asBinder();
4692
4693 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004694 for (int i=mLruProcesses.size()-1; i>=0; i--) {
4695 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004696 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
4697 return i;
4698 }
4699 }
4700 return -1;
4701 }
4702
4703 private final ProcessRecord getRecordForAppLocked(
4704 IApplicationThread thread) {
4705 if (thread == null) {
4706 return null;
4707 }
4708
4709 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004710 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004711 }
4712
4713 private final void appDiedLocked(ProcessRecord app, int pid,
4714 IApplicationThread thread) {
4715
4716 mProcDeaths[0]++;
4717
Magnus Edlund7bb25812010-02-24 15:45:06 +01004718 // Clean up already done if the process has been re-started.
4719 if (app.pid == pid && app.thread != null &&
4720 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07004721 if (!app.killedBackground) {
4722 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
4723 + ") has died.");
4724 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08004725 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08004726 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004727 TAG, "Dying app: " + app + ", pid: " + pid
4728 + ", thread: " + thread.asBinder());
4729 boolean doLowMem = app.instrumentationClass == null;
4730 handleAppDiedLocked(app, false);
4731
4732 if (doLowMem) {
4733 // If there are no longer any background processes running,
4734 // and the app that died was not running instrumentation,
4735 // then tell everyone we are now low on memory.
4736 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004737 for (int i=mLruProcesses.size()-1; i>=0; i--) {
4738 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004739 if (rec.thread != null && rec.setAdj >= HIDDEN_APP_MIN_ADJ) {
4740 haveBg = true;
4741 break;
4742 }
4743 }
4744
4745 if (!haveBg) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004746 Slog.i(TAG, "Low Memory: No more background processes.");
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004747 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004748 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004749 for (int i=mLruProcesses.size()-1; i>=0; i--) {
4750 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07004751 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004752 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
4753 // The low memory report is overriding any current
4754 // state for a GC request. Make sure to do
4755 // visible/foreground processes first.
4756 if (rec.setAdj <= VISIBLE_APP_ADJ) {
4757 rec.lastRequestedGc = 0;
4758 } else {
4759 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004760 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004761 rec.reportLowMemory = true;
4762 rec.lastLowMemory = now;
4763 mProcessesToGc.remove(rec);
4764 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004765 }
4766 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004767 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004768 }
4769 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01004770 } else if (app.pid != pid) {
4771 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08004772 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01004773 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08004774 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08004775 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004776 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004777 + thread.asBinder());
4778 }
4779 }
4780
Dan Egnor42471dd2010-01-07 17:25:22 -08004781 /**
4782 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07004783 * @param clearTraces causes the dump file to be erased prior to the new
4784 * traces being written, if true; when false, the new traces will be
4785 * appended to any existing file content.
Dan Egnor42471dd2010-01-07 17:25:22 -08004786 * @param pids of dalvik VM processes to dump stack traces for
4787 * @return file containing stack traces, or null if no dump file is configured
4788 */
Christopher Tate6ee412d2010-05-28 12:01:56 -07004789 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> pids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08004790 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
4791 if (tracesPath == null || tracesPath.length() == 0) {
4792 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004793 }
Dan Egnor42471dd2010-01-07 17:25:22 -08004794
4795 File tracesFile = new File(tracesPath);
4796 try {
4797 File tracesDir = tracesFile.getParentFile();
4798 if (!tracesDir.exists()) tracesFile.mkdirs();
4799 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
4800
Christopher Tate6ee412d2010-05-28 12:01:56 -07004801 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08004802 tracesFile.createNewFile();
4803 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
4804 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004805 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08004806 return null;
4807 }
4808
4809 // Use a FileObserver to detect when traces finish writing.
4810 // The order of traces is considered important to maintain for legibility.
4811 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
4812 public synchronized void onEvent(int event, String path) { notify(); }
4813 };
4814
4815 try {
4816 observer.startWatching();
4817 int num = pids.size();
4818 for (int i = 0; i < num; i++) {
4819 synchronized (observer) {
4820 Process.sendSignal(pids.get(i), Process.SIGNAL_QUIT);
4821 observer.wait(200); // Wait for write-close, give up after 200msec
4822 }
4823 }
4824 } catch (InterruptedException e) {
Joe Onorato5d3bea62010-03-01 13:44:29 -08004825 Log.wtf(TAG, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08004826 } finally {
4827 observer.stopWatching();
4828 }
4829
4830 return tracesFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004831 }
4832
Dianne Hackbornad5499d2010-03-29 18:08:45 -07004833 final void appNotResponding(ProcessRecord app, HistoryRecord activity,
Dan Egnor42471dd2010-01-07 17:25:22 -08004834 HistoryRecord parent, final String annotation) {
Dan Egnor42471dd2010-01-07 17:25:22 -08004835 ArrayList<Integer> pids = new ArrayList<Integer>(20);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07004836
4837 synchronized (this) {
4838 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
4839 if (mShuttingDown) {
4840 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
4841 return;
4842 } else if (app.notResponding) {
4843 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
4844 return;
4845 } else if (app.crashing) {
4846 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
4847 return;
4848 }
4849
4850 // In case we come through here for the same app before completing
4851 // this one, mark as anring now so we will bail out.
4852 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08004853
Dianne Hackbornad5499d2010-03-29 18:08:45 -07004854 // Log the ANR to the event log.
4855 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
4856 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08004857
Dianne Hackbornad5499d2010-03-29 18:08:45 -07004858 // Dump thread traces as quickly as we can, starting with "interesting" processes.
4859 pids.add(app.pid);
4860
4861 int parentPid = app.pid;
4862 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
4863 if (parentPid != app.pid) pids.add(parentPid);
4864
4865 if (MY_PID != app.pid && MY_PID != parentPid) pids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08004866
Dianne Hackbornad5499d2010-03-29 18:08:45 -07004867 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
4868 ProcessRecord r = mLruProcesses.get(i);
4869 if (r != null && r.thread != null) {
4870 int pid = r.pid;
4871 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) pids.add(pid);
4872 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004873 }
4874 }
4875
Christopher Tate6ee412d2010-05-28 12:01:56 -07004876 File tracesFile = dumpStackTraces(true, pids);
Dan Egnor42471dd2010-01-07 17:25:22 -08004877
4878 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07004879 StringBuilder info = mStringBuilder;
4880 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08004881 info.append("ANR in ").append(app.processName);
4882 if (activity != null && activity.shortComponentName != null) {
4883 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07004884 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08004885 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004886 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08004887 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004888 }
Dan Egnor42471dd2010-01-07 17:25:22 -08004889 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08004890 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004892
Dan Egnor42471dd2010-01-07 17:25:22 -08004893 String cpuInfo = null;
4894 if (MONITOR_CPU_USAGE) {
4895 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07004896 synchronized (mProcessStatsThread) {
4897 cpuInfo = mProcessStats.printCurrentState();
4898 }
Dan Egnor42471dd2010-01-07 17:25:22 -08004899 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004900 }
4901
Joe Onorato8a9b2202010-02-26 18:56:32 -08004902 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08004903 if (tracesFile == null) {
4904 // There is no trace file, so dump (only) the alleged culprit's threads to the log
4905 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
4906 }
4907
4908 addErrorToDropBox("anr", app, activity, parent, annotation, cpuInfo, tracesFile, null);
4909
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004910 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004911 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08004912 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
4913 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004914 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08004915 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
4916 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004917 }
4918 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004919 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004920 }
4921 }
4922
Dan Egnor42471dd2010-01-07 17:25:22 -08004923 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
4924 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
4925 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07004926
4927 synchronized (this) {
4928 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
4929 Process.killProcess(app.pid);
4930 return;
4931 }
4932
4933 // Set the app's notResponding state, and look up the errorReportReceiver
4934 makeAppNotRespondingLocked(app,
4935 activity != null ? activity.shortComponentName : null,
4936 annotation != null ? "ANR " + annotation : "ANR",
4937 info.toString());
4938
4939 // Bring up the infamous App Not Responding dialog
4940 Message msg = Message.obtain();
4941 HashMap map = new HashMap();
4942 msg.what = SHOW_NOT_RESPONDING_MSG;
4943 msg.obj = map;
4944 map.put("app", app);
4945 if (activity != null) {
4946 map.put("activity", activity);
4947 }
4948
4949 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08004950 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004951 }
4952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004953 private final void decPersistentCountLocked(ProcessRecord app)
4954 {
4955 app.persistentActivities--;
4956 if (app.persistentActivities > 0) {
4957 // Still more of 'em...
4958 return;
4959 }
4960 if (app.persistent) {
4961 // Ah, but the application itself is persistent. Whatever!
4962 return;
4963 }
4964
4965 // App is no longer persistent... make sure it and the ones
4966 // following it in the LRU list have the correc oom_adj.
4967 updateOomAdjLocked();
4968 }
4969
4970 public void setPersistent(IBinder token, boolean isPersistent) {
4971 if (checkCallingPermission(android.Manifest.permission.PERSISTENT_ACTIVITY)
4972 != PackageManager.PERMISSION_GRANTED) {
4973 String msg = "Permission Denial: setPersistent() from pid="
4974 + Binder.getCallingPid()
4975 + ", uid=" + Binder.getCallingUid()
4976 + " requires " + android.Manifest.permission.PERSISTENT_ACTIVITY;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004977 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004978 throw new SecurityException(msg);
4979 }
4980
4981 synchronized(this) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07004982 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004983 if (index < 0) {
4984 return;
4985 }
4986 HistoryRecord r = (HistoryRecord)mHistory.get(index);
4987 ProcessRecord app = r.app;
4988
Joe Onorato8a9b2202010-02-26 18:56:32 -08004989 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004990 TAG, "Setting persistence " + isPersistent + ": " + r);
4991
4992 if (isPersistent) {
4993 if (r.persistent) {
4994 // Okay okay, I heard you already!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004995 if (localLOGV) Slog.v(TAG, "Already persistent!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004996 return;
4997 }
4998 r.persistent = true;
4999 app.persistentActivities++;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005000 if (localLOGV) Slog.v(TAG, "Num persistent now: " + app.persistentActivities);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005001 if (app.persistentActivities > 1) {
5002 // We aren't the first...
Joe Onorato8a9b2202010-02-26 18:56:32 -08005003 if (localLOGV) Slog.v(TAG, "Not the first!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005004 return;
5005 }
5006 if (app.persistent) {
5007 // This would be redundant.
Joe Onorato8a9b2202010-02-26 18:56:32 -08005008 if (localLOGV) Slog.v(TAG, "App is persistent!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005009 return;
5010 }
5011
5012 // App is now persistent... make sure it and the ones
5013 // following it now have the correct oom_adj.
5014 final long origId = Binder.clearCallingIdentity();
5015 updateOomAdjLocked();
5016 Binder.restoreCallingIdentity(origId);
5017
5018 } else {
5019 if (!r.persistent) {
5020 // Okay okay, I heard you already!
5021 return;
5022 }
5023 r.persistent = false;
5024 final long origId = Binder.clearCallingIdentity();
5025 decPersistentCountLocked(app);
5026 Binder.restoreCallingIdentity(origId);
5027
5028 }
5029 }
5030 }
5031
5032 public boolean clearApplicationUserData(final String packageName,
5033 final IPackageDataObserver observer) {
5034 int uid = Binder.getCallingUid();
5035 int pid = Binder.getCallingPid();
5036 long callingId = Binder.clearCallingIdentity();
5037 try {
5038 IPackageManager pm = ActivityThread.getPackageManager();
5039 int pkgUid = -1;
5040 synchronized(this) {
5041 try {
5042 pkgUid = pm.getPackageUid(packageName);
5043 } catch (RemoteException e) {
5044 }
5045 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005046 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005047 return false;
5048 }
5049 if (uid == pkgUid || checkComponentPermission(
5050 android.Manifest.permission.CLEAR_APP_USER_DATA,
5051 pid, uid, -1)
5052 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08005053 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005054 } else {
5055 throw new SecurityException(pid+" does not have permission:"+
5056 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
5057 "for process:"+packageName);
5058 }
5059 }
5060
5061 try {
5062 //clear application user data
5063 pm.clearApplicationUserData(packageName, observer);
5064 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
5065 Uri.fromParts("package", packageName, null));
5066 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Josh Bartel2ecce342010-02-25 10:55:48 -06005067 synchronized (this) {
5068 broadcastIntentLocked(null, null, intent,
5069 null, null, 0, null, null, null,
5070 false, false, MY_PID, Process.SYSTEM_UID);
5071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005072 } catch (RemoteException e) {
5073 }
5074 } finally {
5075 Binder.restoreCallingIdentity(callingId);
5076 }
5077 return true;
5078 }
5079
Dianne Hackborn03abb812010-01-04 18:43:19 -08005080 public void killBackgroundProcesses(final String packageName) {
5081 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
5082 != PackageManager.PERMISSION_GRANTED &&
5083 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
5084 != PackageManager.PERMISSION_GRANTED) {
5085 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005086 + Binder.getCallingPid()
5087 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08005088 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005089 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005090 throw new SecurityException(msg);
5091 }
5092
5093 long callingId = Binder.clearCallingIdentity();
5094 try {
5095 IPackageManager pm = ActivityThread.getPackageManager();
5096 int pkgUid = -1;
5097 synchronized(this) {
5098 try {
5099 pkgUid = pm.getPackageUid(packageName);
5100 } catch (RemoteException e) {
5101 }
5102 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005103 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005104 return;
5105 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08005106 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005107 SECONDARY_SERVER_ADJ, false, true);
Dianne Hackborn03abb812010-01-04 18:43:19 -08005108 }
5109 } finally {
5110 Binder.restoreCallingIdentity(callingId);
5111 }
5112 }
5113
5114 public void forceStopPackage(final String packageName) {
5115 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
5116 != PackageManager.PERMISSION_GRANTED) {
5117 String msg = "Permission Denial: forceStopPackage() from pid="
5118 + Binder.getCallingPid()
5119 + ", uid=" + Binder.getCallingUid()
5120 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005121 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08005122 throw new SecurityException(msg);
5123 }
5124
5125 long callingId = Binder.clearCallingIdentity();
5126 try {
5127 IPackageManager pm = ActivityThread.getPackageManager();
5128 int pkgUid = -1;
5129 synchronized(this) {
5130 try {
5131 pkgUid = pm.getPackageUid(packageName);
5132 } catch (RemoteException e) {
5133 }
5134 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005135 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08005136 return;
5137 }
5138 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005139 }
5140 } finally {
5141 Binder.restoreCallingIdentity(callingId);
5142 }
5143 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005144
5145 /*
5146 * The pkg name and uid have to be specified.
5147 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
5148 */
5149 public void killApplicationWithUid(String pkg, int uid) {
5150 if (pkg == null) {
5151 return;
5152 }
5153 // Make sure the uid is valid.
5154 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005155 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005156 return;
5157 }
5158 int callerUid = Binder.getCallingUid();
5159 // Only the system server can kill an application
5160 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07005161 // Post an aysnc message to kill the application
5162 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
5163 msg.arg1 = uid;
5164 msg.arg2 = 0;
5165 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07005166 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005167 } else {
5168 throw new SecurityException(callerUid + " cannot kill pkg: " +
5169 pkg);
5170 }
5171 }
5172
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07005173 public void closeSystemDialogs(String reason) {
5174 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
5175 if (reason != null) {
5176 intent.putExtra("reason", reason);
5177 }
5178
5179 final int uid = Binder.getCallingUid();
5180 final long origId = Binder.clearCallingIdentity();
5181 synchronized (this) {
5182 int i = mWatchers.beginBroadcast();
5183 while (i > 0) {
5184 i--;
5185 IActivityWatcher w = mWatchers.getBroadcastItem(i);
5186 if (w != null) {
5187 try {
5188 w.closingSystemDialogs(reason);
5189 } catch (RemoteException e) {
5190 }
5191 }
5192 }
5193 mWatchers.finishBroadcast();
5194
Dianne Hackbornffa42482009-09-23 22:20:11 -07005195 mWindowManager.closeSystemDialogs(reason);
5196
5197 for (i=mHistory.size()-1; i>=0; i--) {
5198 HistoryRecord r = (HistoryRecord)mHistory.get(i);
5199 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
5200 finishActivityLocked(r, i,
5201 Activity.RESULT_CANCELED, null, "close-sys");
5202 }
5203 }
5204
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07005205 broadcastIntentLocked(null, null, intent, null,
5206 null, 0, null, null, null, false, false, -1, uid);
5207 }
5208 Binder.restoreCallingIdentity(origId);
5209 }
5210
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07005211 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07005212 throws RemoteException {
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07005213 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
5214 for (int i=pids.length-1; i>=0; i--) {
5215 infos[i] = new Debug.MemoryInfo();
5216 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07005217 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07005218 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07005219 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07005220
5221 public void killApplicationProcess(String processName, int uid) {
5222 if (processName == null) {
5223 return;
5224 }
5225
5226 int callerUid = Binder.getCallingUid();
5227 // Only the system server can kill an application
5228 if (callerUid == Process.SYSTEM_UID) {
5229 synchronized (this) {
5230 ProcessRecord app = getProcessRecordLocked(processName, uid);
5231 if (app != null) {
5232 try {
5233 app.thread.scheduleSuicide();
5234 } catch (RemoteException e) {
5235 // If the other end already died, then our work here is done.
5236 }
5237 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005238 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07005239 + processName + " / " + uid);
5240 }
5241 }
5242 } else {
5243 throw new SecurityException(callerUid + " cannot kill app process: " +
5244 processName);
5245 }
5246 }
5247
Dianne Hackborn03abb812010-01-04 18:43:19 -08005248 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005249 forceStopPackageLocked(packageName, uid, false, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005250 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
5251 Uri.fromParts("package", packageName, null));
5252 intent.putExtra(Intent.EXTRA_UID, uid);
5253 broadcastIntentLocked(null, null, intent,
5254 null, null, 0, null, null, null,
5255 false, false, MY_PID, Process.SYSTEM_UID);
5256 }
5257
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005258 private final boolean killPackageProcessesLocked(String packageName, int uid,
5259 int minOomAdj, boolean callerWillRestart, boolean doit) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08005260 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005261
Dianne Hackborn03abb812010-01-04 18:43:19 -08005262 // Remove all processes this package may have touched: all with the
5263 // same UID (except for the system or root user), and all whose name
5264 // matches the package name.
5265 final String procNamePrefix = packageName + ":";
5266 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
5267 final int NA = apps.size();
5268 for (int ia=0; ia<NA; ia++) {
5269 ProcessRecord app = apps.valueAt(ia);
5270 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005271 if (doit) {
5272 procs.add(app);
5273 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08005274 } else if ((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
5275 || app.processName.equals(packageName)
5276 || app.processName.startsWith(procNamePrefix)) {
5277 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005278 if (!doit) {
5279 return true;
5280 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08005281 app.removed = true;
5282 procs.add(app);
5283 }
5284 }
5285 }
5286 }
5287
5288 int N = procs.size();
5289 for (int i=0; i<N; i++) {
5290 removeProcessLocked(procs.get(i), callerWillRestart);
5291 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005292 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08005293 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005294
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005295 private final boolean forceStopPackageLocked(String name, int uid,
5296 boolean callerWillRestart, boolean purgeCache, boolean doit) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005297 int i, N;
5298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005299 if (uid < 0) {
5300 try {
5301 uid = ActivityThread.getPackageManager().getPackageUid(name);
5302 } catch (RemoteException e) {
5303 }
5304 }
5305
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005306 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005307 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08005308
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005309 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
5310 while (badApps.hasNext()) {
5311 SparseArray<Long> ba = badApps.next();
5312 if (ba.get(uid) != null) {
5313 badApps.remove();
5314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005315 }
5316 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005317
5318 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
5319 callerWillRestart, doit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005320
5321 for (i=mHistory.size()-1; i>=0; i--) {
5322 HistoryRecord r = (HistoryRecord)mHistory.get(i);
5323 if (r.packageName.equals(name)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005324 if (!doit) {
5325 return true;
5326 }
5327 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005328 Slog.i(TAG, " Force finishing activity " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005329 if (r.app != null) {
5330 r.app.removed = true;
5331 }
5332 r.app = null;
5333 finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "uninstall");
5334 }
5335 }
5336
5337 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
5338 for (ServiceRecord service : mServices.values()) {
5339 if (service.packageName.equals(name)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005340 if (!doit) {
5341 return true;
5342 }
5343 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005344 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005345 if (service.app != null) {
5346 service.app.removed = true;
5347 }
5348 service.app = null;
5349 services.add(service);
5350 }
5351 }
5352
5353 N = services.size();
5354 for (i=0; i<N; i++) {
5355 bringDownServiceLocked(services.get(i), true);
5356 }
5357
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005358 if (doit) {
5359 if (purgeCache) {
5360 AttributeCache ac = AttributeCache.instance();
5361 if (ac != null) {
5362 ac.removePackage(name);
5363 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005364 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005365 resumeTopActivityLocked(null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005366 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005367
5368 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005369 }
5370
5371 private final boolean removeProcessLocked(ProcessRecord app, boolean callerWillRestart) {
5372 final String name = app.processName;
5373 final int uid = app.info.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005374 if (DEBUG_PROCESSES) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005375 TAG, "Force removing process " + app + " (" + name
5376 + "/" + uid + ")");
5377
5378 mProcessNames.remove(name, uid);
5379 boolean needRestart = false;
5380 if (app.pid > 0 && app.pid != MY_PID) {
5381 int pid = app.pid;
5382 synchronized (mPidsSelfLocked) {
5383 mPidsSelfLocked.remove(pid);
5384 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
5385 }
5386 handleAppDiedLocked(app, true);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08005387 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005388 Process.killProcess(pid);
5389
5390 if (app.persistent) {
5391 if (!callerWillRestart) {
5392 addAppLocked(app.info);
5393 } else {
5394 needRestart = true;
5395 }
5396 }
5397 } else {
5398 mRemovedProcesses.add(app);
5399 }
5400
5401 return needRestart;
5402 }
5403
5404 private final void processStartTimedOutLocked(ProcessRecord app) {
5405 final int pid = app.pid;
5406 boolean gone = false;
5407 synchronized (mPidsSelfLocked) {
5408 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
5409 if (knownApp != null && knownApp.thread == null) {
5410 mPidsSelfLocked.remove(pid);
5411 gone = true;
5412 }
5413 }
5414
5415 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005416 Slog.w(TAG, "Process " + app + " failed to attach");
Doug Zongker2bec3d42009-12-04 12:52:44 -08005417 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.info.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08005418 app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005419 mProcessNames.remove(app.processName, app.info.uid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08005420 // Take care of any launching providers waiting for this process.
5421 checkAppInLaunchingProvidersLocked(app, true);
5422 // Take care of any services that are waiting for the process.
5423 for (int i=0; i<mPendingServices.size(); i++) {
5424 ServiceRecord sr = mPendingServices.get(i);
5425 if (app.info.uid == sr.appInfo.uid
5426 && app.processName.equals(sr.processName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005427 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08005428 mPendingServices.remove(i);
5429 i--;
5430 bringDownServiceLocked(sr, true);
5431 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005432 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08005433 Process.killProcess(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07005434 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005435 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07005436 try {
5437 IBackupManager bm = IBackupManager.Stub.asInterface(
5438 ServiceManager.getService(Context.BACKUP_SERVICE));
5439 bm.agentDisconnected(app.info.packageName);
5440 } catch (RemoteException e) {
5441 // Can't happen; the backup manager is local
5442 }
5443 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08005444 if (mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005445 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Dianne Hackbornf670ef72009-11-16 13:59:16 -08005446 mPendingBroadcast = null;
5447 scheduleBroadcastsLocked();
5448 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005449 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005450 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005451 }
5452 }
5453
5454 private final boolean attachApplicationLocked(IApplicationThread thread,
5455 int pid) {
5456
5457 // Find the application record that is being attached... either via
5458 // the pid if we are running in multiple processes, or just pull the
5459 // next app record if we are emulating process with anonymous threads.
5460 ProcessRecord app;
5461 if (pid != MY_PID && pid >= 0) {
5462 synchronized (mPidsSelfLocked) {
5463 app = mPidsSelfLocked.get(pid);
5464 }
5465 } else if (mStartingProcesses.size() > 0) {
5466 app = mStartingProcesses.remove(0);
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07005467 app.setPid(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005468 } else {
5469 app = null;
5470 }
5471
5472 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005473 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005474 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08005475 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005476 if (pid > 0 && pid != MY_PID) {
5477 Process.killProcess(pid);
5478 } else {
5479 try {
5480 thread.scheduleExit();
5481 } catch (Exception e) {
5482 // Ignore exceptions.
5483 }
5484 }
5485 return false;
5486 }
5487
5488 // If this application record is still attached to a previous
5489 // process, clean it up now.
5490 if (app.thread != null) {
5491 handleAppDiedLocked(app, true);
5492 }
5493
5494 // Tell the process all about itself.
5495
Joe Onorato8a9b2202010-02-26 18:56:32 -08005496 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005497 TAG, "Binding process pid " + pid + " to record " + app);
5498
5499 String processName = app.processName;
5500 try {
5501 thread.asBinder().linkToDeath(new AppDeathRecipient(
5502 app, pid, thread), 0);
5503 } catch (RemoteException e) {
5504 app.resetPackageList();
5505 startProcessLocked(app, "link fail", processName);
5506 return false;
5507 }
5508
Doug Zongker2bec3d42009-12-04 12:52:44 -08005509 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005510
5511 app.thread = thread;
5512 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08005513 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
5514 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005515 app.forcingToForeground = null;
5516 app.foregroundServices = false;
5517 app.debugging = false;
5518
5519 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
5520
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005521 boolean normalMode = mSystemReady || isAllowedWhileBooting(app.info);
5522 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005523
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005524 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005525 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005526 }
5527
Joe Onorato8a9b2202010-02-26 18:56:32 -08005528 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005529 TAG, "New app record " + app
5530 + " thread=" + thread.asBinder() + " pid=" + pid);
5531 try {
5532 int testMode = IApplicationThread.DEBUG_OFF;
5533 if (mDebugApp != null && mDebugApp.equals(processName)) {
5534 testMode = mWaitForDebugger
5535 ? IApplicationThread.DEBUG_WAIT
5536 : IApplicationThread.DEBUG_ON;
5537 app.debugging = true;
5538 if (mDebugTransient) {
5539 mDebugApp = mOrigDebugApp;
5540 mWaitForDebugger = mOrigWaitForDebugger;
5541 }
5542 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005543
Christopher Tate181fafa2009-05-14 11:12:14 -07005544 // If the app is being launched for restore or full backup, set it up specially
5545 boolean isRestrictedBackupMode = false;
5546 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
5547 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
5548 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
5549 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005550
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07005551 ensurePackageDexOpt(app.instrumentationInfo != null
5552 ? app.instrumentationInfo.packageName
5553 : app.info.packageName);
5554 if (app.instrumentationClass != null) {
5555 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005556 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005557 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07005558 + processName + " with config " + mConfiguration);
Dianne Hackborn1655be42009-05-08 14:29:01 -07005559 thread.bindApplication(processName, app.instrumentationInfo != null
5560 ? app.instrumentationInfo : app.info, providers,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005561 app.instrumentationClass, app.instrumentationProfileFile,
5562 app.instrumentationArguments, app.instrumentationWatcher, testMode,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005563 isRestrictedBackupMode || !normalMode,
5564 mConfiguration, getCommonServicesLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08005565 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07005566 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005567 } catch (Exception e) {
5568 // todo: Yikes! What should we do? For now we will try to
5569 // start another process, but that could easily get us in
5570 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08005571 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005572
5573 app.resetPackageList();
5574 startProcessLocked(app, "bind fail", processName);
5575 return false;
5576 }
5577
5578 // Remove this record from the list of starting applications.
5579 mPersistentStartingProcesses.remove(app);
5580 mProcessesOnHold.remove(app);
5581
5582 boolean badApp = false;
5583 boolean didSomething = false;
5584
5585 // See if the top visible activity is waiting to run in this process...
5586 HistoryRecord hr = topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07005587 if (hr != null && normalMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005588 if (hr.app == null && app.info.uid == hr.info.applicationInfo.uid
5589 && processName.equals(hr.processName)) {
5590 try {
5591 if (realStartActivityLocked(hr, app, true, true)) {
5592 didSomething = true;
5593 }
5594 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005595 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005596 + hr.intent.getComponent().flattenToShortString(), e);
5597 badApp = true;
5598 }
5599 } else {
5600 ensureActivitiesVisibleLocked(hr, null, processName, 0);
5601 }
5602 }
5603
5604 // Find any services that should be running in this process...
5605 if (!badApp && mPendingServices.size() > 0) {
5606 ServiceRecord sr = null;
5607 try {
5608 for (int i=0; i<mPendingServices.size(); i++) {
5609 sr = mPendingServices.get(i);
5610 if (app.info.uid != sr.appInfo.uid
5611 || !processName.equals(sr.processName)) {
5612 continue;
5613 }
5614
5615 mPendingServices.remove(i);
5616 i--;
5617 realStartServiceLocked(sr, app);
5618 didSomething = true;
5619 }
5620 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005621 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005622 + sr.shortName, e);
5623 badApp = true;
5624 }
5625 }
5626
5627 // Check if the next broadcast receiver is in this process...
5628 BroadcastRecord br = mPendingBroadcast;
5629 if (!badApp && br != null && br.curApp == app) {
5630 try {
5631 mPendingBroadcast = null;
5632 processCurBroadcastLocked(br, app);
5633 didSomething = true;
5634 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005635 Slog.w(TAG, "Exception in new application when starting receiver "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005636 + br.curComponent.flattenToShortString(), e);
5637 badApp = true;
5638 logBroadcastReceiverDiscard(br);
5639 finishReceiverLocked(br.receiver, br.resultCode, br.resultData,
5640 br.resultExtras, br.resultAbort, true);
5641 scheduleBroadcastsLocked();
Magnus Edlund7bb25812010-02-24 15:45:06 +01005642 // We need to reset the state if we fails to start the receiver.
5643 br.state = BroadcastRecord.IDLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005644 }
5645 }
5646
Christopher Tate181fafa2009-05-14 11:12:14 -07005647 // Check whether the next backup agent is in this process...
5648 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.info.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005649 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005650 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07005651 try {
5652 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo, mBackupTarget.backupMode);
5653 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005654 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07005655 e.printStackTrace();
5656 }
5657 }
5658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005659 if (badApp) {
5660 // todo: Also need to kill application to deal with all
5661 // kinds of exceptions.
5662 handleAppDiedLocked(app, false);
5663 return false;
5664 }
5665
5666 if (!didSomething) {
5667 updateOomAdjLocked();
5668 }
5669
5670 return true;
5671 }
5672
5673 public final void attachApplication(IApplicationThread thread) {
5674 synchronized (this) {
5675 int callingPid = Binder.getCallingPid();
5676 final long origId = Binder.clearCallingIdentity();
5677 attachApplicationLocked(thread, callingPid);
5678 Binder.restoreCallingIdentity(origId);
5679 }
5680 }
5681
Dianne Hackborne88846e2009-09-30 21:34:25 -07005682 public final void activityIdle(IBinder token, Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005683 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne88846e2009-09-30 21:34:25 -07005684 activityIdleInternal(token, false, config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005685 Binder.restoreCallingIdentity(origId);
5686 }
5687
5688 final ArrayList<HistoryRecord> processStoppingActivitiesLocked(
5689 boolean remove) {
5690 int N = mStoppingActivities.size();
5691 if (N <= 0) return null;
5692
5693 ArrayList<HistoryRecord> stops = null;
5694
5695 final boolean nowVisible = mResumedActivity != null
5696 && mResumedActivity.nowVisible
5697 && !mResumedActivity.waitingVisible;
5698 for (int i=0; i<N; i++) {
5699 HistoryRecord s = mStoppingActivities.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08005700 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005701 + nowVisible + " waitingVisible=" + s.waitingVisible
5702 + " finishing=" + s.finishing);
5703 if (s.waitingVisible && nowVisible) {
5704 mWaitingVisibleActivities.remove(s);
5705 s.waitingVisible = false;
5706 if (s.finishing) {
5707 // If this activity is finishing, it is sitting on top of
5708 // everyone else but we now know it is no longer needed...
5709 // so get rid of it. Otherwise, we need to go through the
5710 // normal flow and hide it once we determine that it is
5711 // hidden by the activities in front of it.
Joe Onorato8a9b2202010-02-26 18:56:32 -08005712 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005713 mWindowManager.setAppVisibility(s, false);
5714 }
5715 }
5716 if (!s.waitingVisible && remove) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005717 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005718 if (stops == null) {
5719 stops = new ArrayList<HistoryRecord>();
5720 }
5721 stops.add(s);
5722 mStoppingActivities.remove(i);
5723 N--;
5724 i--;
5725 }
5726 }
5727
5728 return stops;
5729 }
5730
5731 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08005732 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005733 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005734 mWindowManager.enableScreenAfterBoot();
5735 }
5736
Dianne Hackborne88846e2009-09-30 21:34:25 -07005737 final void activityIdleInternal(IBinder token, boolean fromTimeout,
5738 Configuration config) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005739 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005740
5741 ArrayList<HistoryRecord> stops = null;
5742 ArrayList<HistoryRecord> finishes = null;
5743 ArrayList<HistoryRecord> thumbnails = null;
5744 int NS = 0;
5745 int NF = 0;
5746 int NT = 0;
5747 IApplicationThread sendThumbnail = null;
5748 boolean booting = false;
5749 boolean enableScreen = false;
5750
5751 synchronized (this) {
5752 if (token != null) {
5753 mHandler.removeMessages(IDLE_TIMEOUT_MSG, token);
5754 }
5755
5756 // Get the activity record.
Dianne Hackborn75b03852009-06-12 15:43:26 -07005757 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005758 if (index >= 0) {
5759 HistoryRecord r = (HistoryRecord)mHistory.get(index);
5760
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08005761 if (fromTimeout) {
5762 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
5763 }
5764
Dianne Hackborne88846e2009-09-30 21:34:25 -07005765 // This is a hack to semi-deal with a race condition
5766 // in the client where it can be constructed with a
5767 // newer configuration from when we asked it to launch.
5768 // We'll update with whatever configuration it now says
5769 // it used to launch.
5770 if (config != null) {
5771 r.configuration = config;
5772 }
5773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005774 // No longer need to keep the device awake.
5775 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
5776 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
5777 mLaunchingActivity.release();
5778 }
5779
5780 // We are now idle. If someone is waiting for a thumbnail from
5781 // us, we can now deliver.
5782 r.idle = true;
5783 scheduleAppGcsLocked();
5784 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
5785 sendThumbnail = r.app.thread;
5786 r.thumbnailNeeded = false;
5787 }
5788
5789 // If this activity is fullscreen, set up to hide those under it.
5790
Joe Onorato8a9b2202010-02-26 18:56:32 -08005791 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005792 ensureActivitiesVisibleLocked(null, 0);
5793
Joe Onorato8a9b2202010-02-26 18:56:32 -08005794 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005795 if (!mBooted && !fromTimeout) {
5796 mBooted = true;
5797 enableScreen = true;
5798 }
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08005799
5800 } else if (fromTimeout) {
5801 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005802 }
5803
5804 // Atomically retrieve all of the other things to do.
5805 stops = processStoppingActivitiesLocked(true);
5806 NS = stops != null ? stops.size() : 0;
5807 if ((NF=mFinishingActivities.size()) > 0) {
5808 finishes = new ArrayList<HistoryRecord>(mFinishingActivities);
5809 mFinishingActivities.clear();
5810 }
5811 if ((NT=mCancelledThumbnails.size()) > 0) {
5812 thumbnails = new ArrayList<HistoryRecord>(mCancelledThumbnails);
5813 mCancelledThumbnails.clear();
5814 }
5815
5816 booting = mBooting;
5817 mBooting = false;
5818 }
5819
5820 int i;
5821
5822 // Send thumbnail if requested.
5823 if (sendThumbnail != null) {
5824 try {
5825 sendThumbnail.requestThumbnail(token);
5826 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005827 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005828 sendPendingThumbnail(null, token, null, null, true);
5829 }
5830 }
5831
5832 // Stop any activities that are scheduled to do so but have been
5833 // waiting for the next one to start.
5834 for (i=0; i<NS; i++) {
5835 HistoryRecord r = (HistoryRecord)stops.get(i);
5836 synchronized (this) {
5837 if (r.finishing) {
5838 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY);
5839 } else {
5840 stopActivityLocked(r);
5841 }
5842 }
5843 }
5844
5845 // Finish any activities that are scheduled to do so but have been
5846 // waiting for the next one to start.
5847 for (i=0; i<NF; i++) {
5848 HistoryRecord r = (HistoryRecord)finishes.get(i);
5849 synchronized (this) {
5850 destroyActivityLocked(r, true);
5851 }
5852 }
5853
5854 // Report back to any thumbnail receivers.
5855 for (i=0; i<NT; i++) {
5856 HistoryRecord r = (HistoryRecord)thumbnails.get(i);
5857 sendPendingThumbnail(r, null, null, null, true);
5858 }
5859
5860 if (booting) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005861 finishBooting();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005862 }
5863
5864 trimApplications();
5865 //dump();
5866 //mWindowManager.dump();
5867
5868 if (enableScreen) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005869 enableScreenAfterBoot();
5870 }
5871 }
5872
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005873 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005874 IntentFilter pkgFilter = new IntentFilter();
5875 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
5876 pkgFilter.addDataScheme("package");
5877 mContext.registerReceiver(new BroadcastReceiver() {
5878 @Override
5879 public void onReceive(Context context, Intent intent) {
5880 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
5881 if (pkgs != null) {
5882 for (String pkg : pkgs) {
5883 if (forceStopPackageLocked(pkg, -1, false, false, false)) {
5884 setResultCode(Activity.RESULT_OK);
5885 return;
5886 }
5887 }
5888 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005889 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005890 }, pkgFilter);
5891
5892 synchronized (this) {
5893 // Ensure that any processes we had put on hold are now started
5894 // up.
5895 final int NP = mProcessesOnHold.size();
5896 if (NP > 0) {
5897 ArrayList<ProcessRecord> procs =
5898 new ArrayList<ProcessRecord>(mProcessesOnHold);
5899 for (int ip=0; ip<NP; ip++) {
5900 this.startProcessLocked(procs.get(ip), "on-hold", null);
5901 }
5902 }
5903
5904 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
5905 // Tell anyone interested that we are done booting!
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005906 broadcastIntentLocked(null, null,
5907 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
5908 null, null, 0, null, null,
5909 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
5910 false, false, MY_PID, Process.SYSTEM_UID);
5911 }
5912 }
5913 }
5914
5915 final void ensureBootCompleted() {
5916 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005917 boolean enableScreen;
5918 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005919 booting = mBooting;
5920 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005921 enableScreen = !mBooted;
5922 mBooted = true;
5923 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005924
5925 if (booting) {
5926 finishBooting();
5927 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005928
5929 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005930 enableScreenAfterBoot();
5931 }
5932 }
5933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005934 public final void activityPaused(IBinder token, Bundle icicle) {
5935 // Refuse possible leaked file descriptors
5936 if (icicle != null && icicle.hasFileDescriptors()) {
5937 throw new IllegalArgumentException("File descriptors passed in Bundle");
5938 }
5939
5940 final long origId = Binder.clearCallingIdentity();
5941 activityPaused(token, icicle, false);
5942 Binder.restoreCallingIdentity(origId);
5943 }
5944
5945 final void activityPaused(IBinder token, Bundle icicle, boolean timeout) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005946 if (DEBUG_PAUSE) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005947 TAG, "Activity paused: token=" + token + ", icicle=" + icicle
5948 + ", timeout=" + timeout);
5949
5950 HistoryRecord r = null;
5951
5952 synchronized (this) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07005953 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005954 if (index >= 0) {
5955 r = (HistoryRecord)mHistory.get(index);
5956 if (!timeout) {
5957 r.icicle = icicle;
5958 r.haveState = true;
5959 }
5960 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
5961 if (mPausingActivity == r) {
5962 r.state = ActivityState.PAUSED;
5963 completePauseLocked();
5964 } else {
Doug Zongker2bec3d42009-12-04 12:52:44 -08005965 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005966 System.identityHashCode(r), r.shortComponentName,
5967 mPausingActivity != null
5968 ? mPausingActivity.shortComponentName : "(none)");
5969 }
5970 }
5971 }
5972 }
5973
5974 public final void activityStopped(IBinder token, Bitmap thumbnail,
5975 CharSequence description) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005976 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005977 TAG, "Activity stopped: token=" + token);
5978
5979 HistoryRecord r = null;
5980
5981 final long origId = Binder.clearCallingIdentity();
5982
5983 synchronized (this) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07005984 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005985 if (index >= 0) {
5986 r = (HistoryRecord)mHistory.get(index);
5987 r.thumbnail = thumbnail;
5988 r.description = description;
5989 r.stopped = true;
5990 r.state = ActivityState.STOPPED;
5991 if (!r.finishing) {
5992 if (r.configDestroy) {
5993 destroyActivityLocked(r, true);
5994 resumeTopActivityLocked(null);
5995 }
5996 }
5997 }
5998 }
5999
6000 if (r != null) {
6001 sendPendingThumbnail(r, null, null, null, false);
6002 }
6003
6004 trimApplications();
6005
6006 Binder.restoreCallingIdentity(origId);
6007 }
6008
6009 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006010 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006011 synchronized (this) {
6012 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, token);
6013
Dianne Hackborn75b03852009-06-12 15:43:26 -07006014 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006015 if (index >= 0) {
6016 HistoryRecord r = (HistoryRecord)mHistory.get(index);
6017 if (r.state == ActivityState.DESTROYING) {
6018 final long origId = Binder.clearCallingIdentity();
6019 removeActivityFromHistoryLocked(r);
6020 Binder.restoreCallingIdentity(origId);
6021 }
6022 }
6023 }
6024 }
6025
6026 public String getCallingPackage(IBinder token) {
6027 synchronized (this) {
6028 HistoryRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07006029 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006030 }
6031 }
6032
6033 public ComponentName getCallingActivity(IBinder token) {
6034 synchronized (this) {
6035 HistoryRecord r = getCallingRecordLocked(token);
6036 return r != null ? r.intent.getComponent() : null;
6037 }
6038 }
6039
6040 private HistoryRecord getCallingRecordLocked(IBinder token) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07006041 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006042 if (index >= 0) {
6043 HistoryRecord r = (HistoryRecord)mHistory.get(index);
6044 if (r != null) {
6045 return r.resultTo;
6046 }
6047 }
6048 return null;
6049 }
6050
6051 public ComponentName getActivityClassForToken(IBinder token) {
6052 synchronized(this) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07006053 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006054 if (index >= 0) {
6055 HistoryRecord r = (HistoryRecord)mHistory.get(index);
6056 return r.intent.getComponent();
6057 }
6058 return null;
6059 }
6060 }
6061
6062 public String getPackageForToken(IBinder token) {
6063 synchronized(this) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07006064 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006065 if (index >= 0) {
6066 HistoryRecord r = (HistoryRecord)mHistory.get(index);
6067 return r.packageName;
6068 }
6069 return null;
6070 }
6071 }
6072
6073 public IIntentSender getIntentSender(int type,
6074 String packageName, IBinder token, String resultWho,
6075 int requestCode, Intent intent, String resolvedType, int flags) {
6076 // Refuse possible leaked file descriptors
6077 if (intent != null && intent.hasFileDescriptors() == true) {
6078 throw new IllegalArgumentException("File descriptors passed in Intent");
6079 }
6080
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006081 if (type == INTENT_SENDER_BROADCAST) {
6082 if ((intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
6083 throw new IllegalArgumentException(
6084 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
6085 }
6086 }
6087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006088 synchronized(this) {
6089 int callingUid = Binder.getCallingUid();
6090 try {
6091 if (callingUid != 0 && callingUid != Process.SYSTEM_UID &&
6092 Process.supportsProcesses()) {
6093 int uid = ActivityThread.getPackageManager()
6094 .getPackageUid(packageName);
6095 if (uid != Binder.getCallingUid()) {
6096 String msg = "Permission Denial: getIntentSender() from pid="
6097 + Binder.getCallingPid()
6098 + ", uid=" + Binder.getCallingUid()
6099 + ", (need uid=" + uid + ")"
6100 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006101 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006102 throw new SecurityException(msg);
6103 }
6104 }
6105 } catch (RemoteException e) {
6106 throw new SecurityException(e);
6107 }
6108 HistoryRecord activity = null;
6109 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07006110 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006111 if (index < 0) {
6112 return null;
6113 }
6114 activity = (HistoryRecord)mHistory.get(index);
6115 if (activity.finishing) {
6116 return null;
6117 }
6118 }
6119
6120 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
6121 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
6122 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
6123 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
6124 |PendingIntent.FLAG_UPDATE_CURRENT);
6125
6126 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
6127 type, packageName, activity, resultWho,
6128 requestCode, intent, resolvedType, flags);
6129 WeakReference<PendingIntentRecord> ref;
6130 ref = mIntentSenderRecords.get(key);
6131 PendingIntentRecord rec = ref != null ? ref.get() : null;
6132 if (rec != null) {
6133 if (!cancelCurrent) {
6134 if (updateCurrent) {
6135 rec.key.requestIntent.replaceExtras(intent);
6136 }
6137 return rec;
6138 }
6139 rec.canceled = true;
6140 mIntentSenderRecords.remove(key);
6141 }
6142 if (noCreate) {
6143 return rec;
6144 }
6145 rec = new PendingIntentRecord(this, key, callingUid);
6146 mIntentSenderRecords.put(key, rec.ref);
6147 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
6148 if (activity.pendingResults == null) {
6149 activity.pendingResults
6150 = new HashSet<WeakReference<PendingIntentRecord>>();
6151 }
6152 activity.pendingResults.add(rec.ref);
6153 }
6154 return rec;
6155 }
6156 }
6157
6158 public void cancelIntentSender(IIntentSender sender) {
6159 if (!(sender instanceof PendingIntentRecord)) {
6160 return;
6161 }
6162 synchronized(this) {
6163 PendingIntentRecord rec = (PendingIntentRecord)sender;
6164 try {
6165 int uid = ActivityThread.getPackageManager()
6166 .getPackageUid(rec.key.packageName);
6167 if (uid != Binder.getCallingUid()) {
6168 String msg = "Permission Denial: cancelIntentSender() from pid="
6169 + Binder.getCallingPid()
6170 + ", uid=" + Binder.getCallingUid()
6171 + " is not allowed to cancel packges "
6172 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006173 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006174 throw new SecurityException(msg);
6175 }
6176 } catch (RemoteException e) {
6177 throw new SecurityException(e);
6178 }
6179 cancelIntentSenderLocked(rec, true);
6180 }
6181 }
6182
6183 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
6184 rec.canceled = true;
6185 mIntentSenderRecords.remove(rec.key);
6186 if (cleanActivity && rec.key.activity != null) {
6187 rec.key.activity.pendingResults.remove(rec.ref);
6188 }
6189 }
6190
6191 public String getPackageForIntentSender(IIntentSender pendingResult) {
6192 if (!(pendingResult instanceof PendingIntentRecord)) {
6193 return null;
6194 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07006195 try {
6196 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
6197 return res.key.packageName;
6198 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006199 }
6200 return null;
6201 }
6202
6203 public void setProcessLimit(int max) {
6204 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
6205 "setProcessLimit()");
6206 mProcessLimit = max;
6207 }
6208
6209 public int getProcessLimit() {
6210 return mProcessLimit;
6211 }
6212
6213 void foregroundTokenDied(ForegroundToken token) {
6214 synchronized (ActivityManagerService.this) {
6215 synchronized (mPidsSelfLocked) {
6216 ForegroundToken cur
6217 = mForegroundProcesses.get(token.pid);
6218 if (cur != token) {
6219 return;
6220 }
6221 mForegroundProcesses.remove(token.pid);
6222 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
6223 if (pr == null) {
6224 return;
6225 }
6226 pr.forcingToForeground = null;
6227 pr.foregroundServices = false;
6228 }
6229 updateOomAdjLocked();
6230 }
6231 }
6232
6233 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
6234 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
6235 "setProcessForeground()");
6236 synchronized(this) {
6237 boolean changed = false;
6238
6239 synchronized (mPidsSelfLocked) {
6240 ProcessRecord pr = mPidsSelfLocked.get(pid);
6241 if (pr == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006242 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006243 return;
6244 }
6245 ForegroundToken oldToken = mForegroundProcesses.get(pid);
6246 if (oldToken != null) {
6247 oldToken.token.unlinkToDeath(oldToken, 0);
6248 mForegroundProcesses.remove(pid);
6249 pr.forcingToForeground = null;
6250 changed = true;
6251 }
6252 if (isForeground && token != null) {
6253 ForegroundToken newToken = new ForegroundToken() {
6254 public void binderDied() {
6255 foregroundTokenDied(this);
6256 }
6257 };
6258 newToken.pid = pid;
6259 newToken.token = token;
6260 try {
6261 token.linkToDeath(newToken, 0);
6262 mForegroundProcesses.put(pid, newToken);
6263 pr.forcingToForeground = token;
6264 changed = true;
6265 } catch (RemoteException e) {
6266 // If the process died while doing this, we will later
6267 // do the cleanup with the process death link.
6268 }
6269 }
6270 }
6271
6272 if (changed) {
6273 updateOomAdjLocked();
6274 }
6275 }
6276 }
6277
6278 // =========================================================
6279 // PERMISSIONS
6280 // =========================================================
6281
6282 static class PermissionController extends IPermissionController.Stub {
6283 ActivityManagerService mActivityManagerService;
6284 PermissionController(ActivityManagerService activityManagerService) {
6285 mActivityManagerService = activityManagerService;
6286 }
6287
6288 public boolean checkPermission(String permission, int pid, int uid) {
6289 return mActivityManagerService.checkPermission(permission, pid,
6290 uid) == PackageManager.PERMISSION_GRANTED;
6291 }
6292 }
6293
6294 /**
6295 * This can be called with or without the global lock held.
6296 */
6297 int checkComponentPermission(String permission, int pid, int uid,
6298 int reqUid) {
6299 // We might be performing an operation on behalf of an indirect binder
6300 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
6301 // client identity accordingly before proceeding.
6302 Identity tlsIdentity = sCallerIdentity.get();
6303 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006304 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006305 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
6306 uid = tlsIdentity.uid;
6307 pid = tlsIdentity.pid;
6308 }
6309
6310 // Root, system server and our own process get to do everything.
6311 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID ||
6312 !Process.supportsProcesses()) {
6313 return PackageManager.PERMISSION_GRANTED;
6314 }
6315 // If the target requires a specific UID, always fail for others.
6316 if (reqUid >= 0 && uid != reqUid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006317 Slog.w(TAG, "Permission denied: checkComponentPermission() reqUid=" + reqUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006318 return PackageManager.PERMISSION_DENIED;
6319 }
6320 if (permission == null) {
6321 return PackageManager.PERMISSION_GRANTED;
6322 }
6323 try {
6324 return ActivityThread.getPackageManager()
6325 .checkUidPermission(permission, uid);
6326 } catch (RemoteException e) {
6327 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08006328 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006329 }
6330 return PackageManager.PERMISSION_DENIED;
6331 }
6332
6333 /**
6334 * As the only public entry point for permissions checking, this method
6335 * can enforce the semantic that requesting a check on a null global
6336 * permission is automatically denied. (Internally a null permission
6337 * string is used when calling {@link #checkComponentPermission} in cases
6338 * when only uid-based security is needed.)
6339 *
6340 * This can be called with or without the global lock held.
6341 */
6342 public int checkPermission(String permission, int pid, int uid) {
6343 if (permission == null) {
6344 return PackageManager.PERMISSION_DENIED;
6345 }
6346 return checkComponentPermission(permission, pid, uid, -1);
6347 }
6348
6349 /**
6350 * Binder IPC calls go through the public entry point.
6351 * This can be called with or without the global lock held.
6352 */
6353 int checkCallingPermission(String permission) {
6354 return checkPermission(permission,
6355 Binder.getCallingPid(),
6356 Binder.getCallingUid());
6357 }
6358
6359 /**
6360 * This can be called with or without the global lock held.
6361 */
6362 void enforceCallingPermission(String permission, String func) {
6363 if (checkCallingPermission(permission)
6364 == PackageManager.PERMISSION_GRANTED) {
6365 return;
6366 }
6367
6368 String msg = "Permission Denial: " + func + " from pid="
6369 + Binder.getCallingPid()
6370 + ", uid=" + Binder.getCallingUid()
6371 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006372 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006373 throw new SecurityException(msg);
6374 }
6375
6376 private final boolean checkHoldingPermissionsLocked(IPackageManager pm,
6377 ProviderInfo pi, int uid, int modeFlags) {
6378 try {
6379 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
6380 if ((pi.readPermission != null) &&
6381 (pm.checkUidPermission(pi.readPermission, uid)
6382 != PackageManager.PERMISSION_GRANTED)) {
6383 return false;
6384 }
6385 }
6386 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
6387 if ((pi.writePermission != null) &&
6388 (pm.checkUidPermission(pi.writePermission, uid)
6389 != PackageManager.PERMISSION_GRANTED)) {
6390 return false;
6391 }
6392 }
6393 return true;
6394 } catch (RemoteException e) {
6395 return false;
6396 }
6397 }
6398
6399 private final boolean checkUriPermissionLocked(Uri uri, int uid,
6400 int modeFlags) {
6401 // Root gets to do everything.
6402 if (uid == 0 || !Process.supportsProcesses()) {
6403 return true;
6404 }
6405 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
6406 if (perms == null) return false;
6407 UriPermission perm = perms.get(uri);
6408 if (perm == null) return false;
6409 return (modeFlags&perm.modeFlags) == modeFlags;
6410 }
6411
6412 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
6413 // Another redirected-binder-call permissions check as in
6414 // {@link checkComponentPermission}.
6415 Identity tlsIdentity = sCallerIdentity.get();
6416 if (tlsIdentity != null) {
6417 uid = tlsIdentity.uid;
6418 pid = tlsIdentity.pid;
6419 }
6420
6421 // Our own process gets to do everything.
6422 if (pid == MY_PID) {
6423 return PackageManager.PERMISSION_GRANTED;
6424 }
6425 synchronized(this) {
6426 return checkUriPermissionLocked(uri, uid, modeFlags)
6427 ? PackageManager.PERMISSION_GRANTED
6428 : PackageManager.PERMISSION_DENIED;
6429 }
6430 }
6431
6432 private void grantUriPermissionLocked(int callingUid,
6433 String targetPkg, Uri uri, int modeFlags, HistoryRecord activity) {
6434 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
6435 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
6436 if (modeFlags == 0) {
6437 return;
6438 }
6439
Joe Onorato8a9b2202010-02-26 18:56:32 -08006440 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006441 "Requested grant " + targetPkg + " permission to " + uri);
6442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006443 final IPackageManager pm = ActivityThread.getPackageManager();
6444
6445 // If this is not a content: uri, we can't do anything with it.
6446 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006447 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006448 "Can't grant URI permission for non-content URI: " + uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006449 return;
6450 }
6451
6452 String name = uri.getAuthority();
6453 ProviderInfo pi = null;
6454 ContentProviderRecord cpr
6455 = (ContentProviderRecord)mProvidersByName.get(name);
6456 if (cpr != null) {
6457 pi = cpr.info;
6458 } else {
6459 try {
6460 pi = pm.resolveContentProvider(name,
6461 PackageManager.GET_URI_PERMISSION_PATTERNS);
6462 } catch (RemoteException ex) {
6463 }
6464 }
6465 if (pi == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006466 Slog.w(TAG, "No content provider found for: " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006467 return;
6468 }
6469
6470 int targetUid;
6471 try {
6472 targetUid = pm.getPackageUid(targetPkg);
6473 if (targetUid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006474 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006475 "Can't grant URI permission no uid for: " + targetPkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006476 return;
6477 }
6478 } catch (RemoteException ex) {
6479 return;
6480 }
6481
6482 // First... does the target actually need this permission?
6483 if (checkHoldingPermissionsLocked(pm, pi, targetUid, modeFlags)) {
6484 // No need to grant the target this permission.
Joe Onorato8a9b2202010-02-26 18:56:32 -08006485 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006486 "Target " + targetPkg + " already has full permission to " + uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487 return;
6488 }
6489
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006490 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006491 if (!pi.grantUriPermissions) {
6492 throw new SecurityException("Provider " + pi.packageName
6493 + "/" + pi.name
6494 + " does not allow granting of Uri permissions (uri "
6495 + uri + ")");
6496 }
6497 if (pi.uriPermissionPatterns != null) {
6498 final int N = pi.uriPermissionPatterns.length;
6499 boolean allowed = false;
6500 for (int i=0; i<N; i++) {
6501 if (pi.uriPermissionPatterns[i] != null
6502 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
6503 allowed = true;
6504 break;
6505 }
6506 }
6507 if (!allowed) {
6508 throw new SecurityException("Provider " + pi.packageName
6509 + "/" + pi.name
6510 + " does not allow granting of permission to path of Uri "
6511 + uri);
6512 }
6513 }
6514
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006515 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006516 // this uri?
6517 if (!checkHoldingPermissionsLocked(pm, pi, callingUid, modeFlags)) {
6518 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
6519 throw new SecurityException("Uid " + callingUid
6520 + " does not have permission to uri " + uri);
6521 }
6522 }
6523
6524 // Okay! So here we are: the caller has the assumed permission
6525 // to the uri, and the target doesn't. Let's now give this to
6526 // the target.
6527
Joe Onorato8a9b2202010-02-26 18:56:32 -08006528 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006529 "Granting " + targetPkg + " permission to " + uri);
6530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006531 HashMap<Uri, UriPermission> targetUris
6532 = mGrantedUriPermissions.get(targetUid);
6533 if (targetUris == null) {
6534 targetUris = new HashMap<Uri, UriPermission>();
6535 mGrantedUriPermissions.put(targetUid, targetUris);
6536 }
6537
6538 UriPermission perm = targetUris.get(uri);
6539 if (perm == null) {
6540 perm = new UriPermission(targetUid, uri);
6541 targetUris.put(uri, perm);
6542
6543 }
6544 perm.modeFlags |= modeFlags;
6545 if (activity == null) {
6546 perm.globalModeFlags |= modeFlags;
6547 } else if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
6548 perm.readActivities.add(activity);
6549 if (activity.readUriPermissions == null) {
6550 activity.readUriPermissions = new HashSet<UriPermission>();
6551 }
6552 activity.readUriPermissions.add(perm);
6553 } else if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
6554 perm.writeActivities.add(activity);
6555 if (activity.writeUriPermissions == null) {
6556 activity.writeUriPermissions = new HashSet<UriPermission>();
6557 }
6558 activity.writeUriPermissions.add(perm);
6559 }
6560 }
6561
6562 private void grantUriPermissionFromIntentLocked(int callingUid,
6563 String targetPkg, Intent intent, HistoryRecord activity) {
6564 if (intent == null) {
6565 return;
6566 }
6567 Uri data = intent.getData();
6568 if (data == null) {
6569 return;
6570 }
6571 grantUriPermissionLocked(callingUid, targetPkg, data,
6572 intent.getFlags(), activity);
6573 }
6574
6575 public void grantUriPermission(IApplicationThread caller, String targetPkg,
6576 Uri uri, int modeFlags) {
6577 synchronized(this) {
6578 final ProcessRecord r = getRecordForAppLocked(caller);
6579 if (r == null) {
6580 throw new SecurityException("Unable to find app for caller "
6581 + caller
6582 + " when granting permission to uri " + uri);
6583 }
6584 if (targetPkg == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006585 Slog.w(TAG, "grantUriPermission: null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006586 return;
6587 }
6588 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006589 Slog.w(TAG, "grantUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006590 return;
6591 }
6592
6593 grantUriPermissionLocked(r.info.uid, targetPkg, uri, modeFlags,
6594 null);
6595 }
6596 }
6597
6598 private void removeUriPermissionIfNeededLocked(UriPermission perm) {
6599 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
6600 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
6601 HashMap<Uri, UriPermission> perms
6602 = mGrantedUriPermissions.get(perm.uid);
6603 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006604 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006605 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006606 perms.remove(perm.uri);
6607 if (perms.size() == 0) {
6608 mGrantedUriPermissions.remove(perm.uid);
6609 }
6610 }
6611 }
6612 }
6613
6614 private void removeActivityUriPermissionsLocked(HistoryRecord activity) {
6615 if (activity.readUriPermissions != null) {
6616 for (UriPermission perm : activity.readUriPermissions) {
6617 perm.readActivities.remove(activity);
6618 if (perm.readActivities.size() == 0 && (perm.globalModeFlags
6619 &Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0) {
6620 perm.modeFlags &= ~Intent.FLAG_GRANT_READ_URI_PERMISSION;
6621 removeUriPermissionIfNeededLocked(perm);
6622 }
6623 }
6624 }
6625 if (activity.writeUriPermissions != null) {
6626 for (UriPermission perm : activity.writeUriPermissions) {
6627 perm.writeActivities.remove(activity);
6628 if (perm.writeActivities.size() == 0 && (perm.globalModeFlags
6629 &Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0) {
6630 perm.modeFlags &= ~Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
6631 removeUriPermissionIfNeededLocked(perm);
6632 }
6633 }
6634 }
6635 }
6636
6637 private void revokeUriPermissionLocked(int callingUid, Uri uri,
6638 int modeFlags) {
6639 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
6640 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
6641 if (modeFlags == 0) {
6642 return;
6643 }
6644
Joe Onorato8a9b2202010-02-26 18:56:32 -08006645 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006646 "Revoking all granted permissions to " + uri);
6647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006648 final IPackageManager pm = ActivityThread.getPackageManager();
6649
6650 final String authority = uri.getAuthority();
6651 ProviderInfo pi = null;
6652 ContentProviderRecord cpr
6653 = (ContentProviderRecord)mProvidersByName.get(authority);
6654 if (cpr != null) {
6655 pi = cpr.info;
6656 } else {
6657 try {
6658 pi = pm.resolveContentProvider(authority,
6659 PackageManager.GET_URI_PERMISSION_PATTERNS);
6660 } catch (RemoteException ex) {
6661 }
6662 }
6663 if (pi == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006664 Slog.w(TAG, "No content provider found for: " + authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006665 return;
6666 }
6667
6668 // Does the caller have this permission on the URI?
6669 if (!checkHoldingPermissionsLocked(pm, pi, callingUid, modeFlags)) {
6670 // Right now, if you are not the original owner of the permission,
6671 // you are not allowed to revoke it.
6672 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
6673 throw new SecurityException("Uid " + callingUid
6674 + " does not have permission to uri " + uri);
6675 //}
6676 }
6677
6678 // Go through all of the permissions and remove any that match.
6679 final List<String> SEGMENTS = uri.getPathSegments();
6680 if (SEGMENTS != null) {
6681 final int NS = SEGMENTS.size();
6682 int N = mGrantedUriPermissions.size();
6683 for (int i=0; i<N; i++) {
6684 HashMap<Uri, UriPermission> perms
6685 = mGrantedUriPermissions.valueAt(i);
6686 Iterator<UriPermission> it = perms.values().iterator();
6687 toploop:
6688 while (it.hasNext()) {
6689 UriPermission perm = it.next();
6690 Uri targetUri = perm.uri;
6691 if (!authority.equals(targetUri.getAuthority())) {
6692 continue;
6693 }
6694 List<String> targetSegments = targetUri.getPathSegments();
6695 if (targetSegments == null) {
6696 continue;
6697 }
6698 if (targetSegments.size() < NS) {
6699 continue;
6700 }
6701 for (int j=0; j<NS; j++) {
6702 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
6703 continue toploop;
6704 }
6705 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006706 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006707 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006708 perm.clearModes(modeFlags);
6709 if (perm.modeFlags == 0) {
6710 it.remove();
6711 }
6712 }
6713 if (perms.size() == 0) {
6714 mGrantedUriPermissions.remove(
6715 mGrantedUriPermissions.keyAt(i));
6716 N--;
6717 i--;
6718 }
6719 }
6720 }
6721 }
6722
6723 public void revokeUriPermission(IApplicationThread caller, Uri uri,
6724 int modeFlags) {
6725 synchronized(this) {
6726 final ProcessRecord r = getRecordForAppLocked(caller);
6727 if (r == null) {
6728 throw new SecurityException("Unable to find app for caller "
6729 + caller
6730 + " when revoking permission to uri " + uri);
6731 }
6732 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006733 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006734 return;
6735 }
6736
6737 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
6738 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
6739 if (modeFlags == 0) {
6740 return;
6741 }
6742
6743 final IPackageManager pm = ActivityThread.getPackageManager();
6744
6745 final String authority = uri.getAuthority();
6746 ProviderInfo pi = null;
6747 ContentProviderRecord cpr
6748 = (ContentProviderRecord)mProvidersByName.get(authority);
6749 if (cpr != null) {
6750 pi = cpr.info;
6751 } else {
6752 try {
6753 pi = pm.resolveContentProvider(authority,
6754 PackageManager.GET_URI_PERMISSION_PATTERNS);
6755 } catch (RemoteException ex) {
6756 }
6757 }
6758 if (pi == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006759 Slog.w(TAG, "No content provider found for: " + authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006760 return;
6761 }
6762
6763 revokeUriPermissionLocked(r.info.uid, uri, modeFlags);
6764 }
6765 }
6766
6767 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
6768 synchronized (this) {
6769 ProcessRecord app =
6770 who != null ? getRecordForAppLocked(who) : null;
6771 if (app == null) return;
6772
6773 Message msg = Message.obtain();
6774 msg.what = WAIT_FOR_DEBUGGER_MSG;
6775 msg.obj = app;
6776 msg.arg1 = waiting ? 1 : 0;
6777 mHandler.sendMessage(msg);
6778 }
6779 }
6780
6781 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
6782 outInfo.availMem = Process.getFreeMemory();
The Android Open Source Project4df24232009-03-05 14:34:35 -08006783 outInfo.threshold = HOME_APP_MEM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006784 outInfo.lowMemory = outInfo.availMem <
The Android Open Source Project4df24232009-03-05 14:34:35 -08006785 (HOME_APP_MEM + ((HIDDEN_APP_MEM-HOME_APP_MEM)/2));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006786 }
6787
6788 // =========================================================
6789 // TASK MANAGEMENT
6790 // =========================================================
6791
6792 public List getTasks(int maxNum, int flags,
6793 IThumbnailReceiver receiver) {
6794 ArrayList list = new ArrayList();
6795
6796 PendingThumbnailsRecord pending = null;
6797 IApplicationThread topThumbnail = null;
6798 HistoryRecord topRecord = null;
6799
6800 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006801 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006802 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
6803 + ", receiver=" + receiver);
6804
6805 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
6806 != PackageManager.PERMISSION_GRANTED) {
6807 if (receiver != null) {
6808 // If the caller wants to wait for pending thumbnails,
6809 // it ain't gonna get them.
6810 try {
6811 receiver.finished();
6812 } catch (RemoteException ex) {
6813 }
6814 }
6815 String msg = "Permission Denial: getTasks() from pid="
6816 + Binder.getCallingPid()
6817 + ", uid=" + Binder.getCallingUid()
6818 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006819 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006820 throw new SecurityException(msg);
6821 }
6822
6823 int pos = mHistory.size()-1;
6824 HistoryRecord next =
6825 pos >= 0 ? (HistoryRecord)mHistory.get(pos) : null;
6826 HistoryRecord top = null;
6827 CharSequence topDescription = null;
6828 TaskRecord curTask = null;
6829 int numActivities = 0;
6830 int numRunning = 0;
6831 while (pos >= 0 && maxNum > 0) {
6832 final HistoryRecord r = next;
6833 pos--;
6834 next = pos >= 0 ? (HistoryRecord)mHistory.get(pos) : null;
6835
6836 // Initialize state for next task if needed.
6837 if (top == null ||
6838 (top.state == ActivityState.INITIALIZING
6839 && top.task == r.task)) {
6840 top = r;
6841 topDescription = r.description;
6842 curTask = r.task;
6843 numActivities = numRunning = 0;
6844 }
6845
6846 // Add 'r' into the current task.
6847 numActivities++;
6848 if (r.app != null && r.app.thread != null) {
6849 numRunning++;
6850 }
6851 if (topDescription == null) {
6852 topDescription = r.description;
6853 }
6854
Joe Onorato8a9b2202010-02-26 18:56:32 -08006855 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006856 TAG, r.intent.getComponent().flattenToShortString()
6857 + ": task=" + r.task);
6858
6859 // If the next one is a different task, generate a new
6860 // TaskInfo entry for what we have.
6861 if (next == null || next.task != curTask) {
6862 ActivityManager.RunningTaskInfo ci
6863 = new ActivityManager.RunningTaskInfo();
6864 ci.id = curTask.taskId;
6865 ci.baseActivity = r.intent.getComponent();
6866 ci.topActivity = top.intent.getComponent();
6867 ci.thumbnail = top.thumbnail;
6868 ci.description = topDescription;
6869 ci.numActivities = numActivities;
6870 ci.numRunning = numRunning;
6871 //System.out.println(
6872 // "#" + maxNum + ": " + " descr=" + ci.description);
6873 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006874 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006875 TAG, "State=" + top.state + "Idle=" + top.idle
6876 + " app=" + top.app
6877 + " thr=" + (top.app != null ? top.app.thread : null));
6878 if (top.state == ActivityState.RESUMED
6879 || top.state == ActivityState.PAUSING) {
6880 if (top.idle && top.app != null
6881 && top.app.thread != null) {
6882 topRecord = top;
6883 topThumbnail = top.app.thread;
6884 } else {
6885 top.thumbnailNeeded = true;
6886 }
6887 }
6888 if (pending == null) {
6889 pending = new PendingThumbnailsRecord(receiver);
6890 }
6891 pending.pendingRecords.add(top);
6892 }
6893 list.add(ci);
6894 maxNum--;
6895 top = null;
6896 }
6897 }
6898
6899 if (pending != null) {
6900 mPendingThumbnails.add(pending);
6901 }
6902 }
6903
Joe Onorato8a9b2202010-02-26 18:56:32 -08006904 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006905
6906 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006907 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006908 try {
6909 topThumbnail.requestThumbnail(topRecord);
6910 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006911 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006912 sendPendingThumbnail(null, topRecord, null, null, true);
6913 }
6914 }
6915
6916 if (pending == null && receiver != null) {
6917 // In this case all thumbnails were available and the client
6918 // is being asked to be told when the remaining ones come in...
6919 // which is unusually, since the top-most currently running
6920 // activity should never have a canned thumbnail! Oh well.
6921 try {
6922 receiver.finished();
6923 } catch (RemoteException ex) {
6924 }
6925 }
6926
6927 return list;
6928 }
6929
6930 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
6931 int flags) {
6932 synchronized (this) {
6933 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
6934 "getRecentTasks()");
6935
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07006936 IPackageManager pm = ActivityThread.getPackageManager();
6937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006938 final int N = mRecentTasks.size();
6939 ArrayList<ActivityManager.RecentTaskInfo> res
6940 = new ArrayList<ActivityManager.RecentTaskInfo>(
6941 maxNum < N ? maxNum : N);
6942 for (int i=0; i<N && maxNum > 0; i++) {
6943 TaskRecord tr = mRecentTasks.get(i);
6944 if (((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
6945 || (tr.intent == null)
6946 || ((tr.intent.getFlags()
6947 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
6948 ActivityManager.RecentTaskInfo rti
6949 = new ActivityManager.RecentTaskInfo();
6950 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
6951 rti.baseIntent = new Intent(
6952 tr.intent != null ? tr.intent : tr.affinityIntent);
6953 rti.origActivity = tr.origActivity;
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07006954
6955 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
6956 // Check whether this activity is currently available.
6957 try {
6958 if (rti.origActivity != null) {
6959 if (pm.getActivityInfo(rti.origActivity, 0) == null) {
6960 continue;
6961 }
6962 } else if (rti.baseIntent != null) {
6963 if (pm.queryIntentActivities(rti.baseIntent,
6964 null, 0) == null) {
6965 continue;
6966 }
6967 }
6968 } catch (RemoteException e) {
6969 // Will never happen.
6970 }
6971 }
6972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006973 res.add(rti);
6974 maxNum--;
6975 }
6976 }
6977 return res;
6978 }
6979 }
6980
6981 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
6982 int j;
6983 TaskRecord startTask = ((HistoryRecord)mHistory.get(startIndex)).task;
6984 TaskRecord jt = startTask;
6985
6986 // First look backwards
6987 for (j=startIndex-1; j>=0; j--) {
6988 HistoryRecord r = (HistoryRecord)mHistory.get(j);
6989 if (r.task != jt) {
6990 jt = r.task;
6991 if (affinity.equals(jt.affinity)) {
6992 return j;
6993 }
6994 }
6995 }
6996
6997 // Now look forwards
6998 final int N = mHistory.size();
6999 jt = startTask;
7000 for (j=startIndex+1; j<N; j++) {
7001 HistoryRecord r = (HistoryRecord)mHistory.get(j);
7002 if (r.task != jt) {
7003 if (affinity.equals(jt.affinity)) {
7004 return j;
7005 }
7006 jt = r.task;
7007 }
7008 }
7009
7010 // Might it be at the top?
7011 if (affinity.equals(((HistoryRecord)mHistory.get(N-1)).task.affinity)) {
7012 return N-1;
7013 }
7014
7015 return -1;
7016 }
7017
7018 /**
7019 * Perform a reset of the given task, if needed as part of launching it.
7020 * Returns the new HistoryRecord at the top of the task.
7021 */
7022 private final HistoryRecord resetTaskIfNeededLocked(HistoryRecord taskTop,
7023 HistoryRecord newActivity) {
7024 boolean forceReset = (newActivity.info.flags
7025 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
7026 if (taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
7027 if ((newActivity.info.flags
7028 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
7029 forceReset = true;
7030 }
7031 }
7032
7033 final TaskRecord task = taskTop.task;
7034
7035 // We are going to move through the history list so that we can look
7036 // at each activity 'target' with 'below' either the interesting
7037 // activity immediately below it in the stack or null.
7038 HistoryRecord target = null;
7039 int targetI = 0;
7040 int taskTopI = -1;
7041 int replyChainEnd = -1;
7042 int lastReparentPos = -1;
7043 for (int i=mHistory.size()-1; i>=-1; i--) {
7044 HistoryRecord below = i >= 0 ? (HistoryRecord)mHistory.get(i) : null;
7045
7046 if (below != null && below.finishing) {
7047 continue;
7048 }
7049 if (target == null) {
7050 target = below;
7051 targetI = i;
7052 // If we were in the middle of a reply chain before this
7053 // task, it doesn't appear like the root of the chain wants
7054 // anything interesting, so drop it.
7055 replyChainEnd = -1;
7056 continue;
7057 }
7058
7059 final int flags = target.info.flags;
7060
7061 final boolean finishOnTaskLaunch =
7062 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
7063 final boolean allowTaskReparenting =
7064 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
7065
7066 if (target.task == task) {
7067 // We are inside of the task being reset... we'll either
7068 // finish this activity, push it out for another task,
7069 // or leave it as-is. We only do this
7070 // for activities that are not the root of the task (since
7071 // if we finish the root, we may no longer have the task!).
7072 if (taskTopI < 0) {
7073 taskTopI = targetI;
7074 }
7075 if (below != null && below.task == task) {
7076 final boolean clearWhenTaskReset =
7077 (target.intent.getFlags()
7078 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
Ed Heyl73798232009-03-24 21:32:21 -07007079 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007080 // If this activity is sending a reply to a previous
7081 // activity, we can't do anything with it now until
7082 // we reach the start of the reply chain.
7083 // XXX note that we are assuming the result is always
7084 // to the previous activity, which is almost always
7085 // the case but we really shouldn't count on.
7086 if (replyChainEnd < 0) {
7087 replyChainEnd = targetI;
7088 }
Ed Heyl73798232009-03-24 21:32:21 -07007089 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007090 && target.taskAffinity != null
7091 && !target.taskAffinity.equals(task.affinity)) {
7092 // If this activity has an affinity for another
7093 // task, then we need to move it out of here. We will
7094 // move it as far out of the way as possible, to the
7095 // bottom of the activity stack. This also keeps it
7096 // correctly ordered with any activities we previously
7097 // moved.
7098 HistoryRecord p = (HistoryRecord)mHistory.get(0);
7099 if (target.taskAffinity != null
7100 && target.taskAffinity.equals(p.task.affinity)) {
7101 // If the activity currently at the bottom has the
7102 // same task affinity as the one we are moving,
7103 // then merge it into the same task.
7104 target.task = p.task;
Joe Onorato8a9b2202010-02-26 18:56:32 -08007105 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007106 + " out to bottom task " + p.task);
7107 } else {
7108 mCurTask++;
7109 if (mCurTask <= 0) {
7110 mCurTask = 1;
7111 }
7112 target.task = new TaskRecord(mCurTask, target.info, null,
7113 (target.info.flags&ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0);
7114 target.task.affinityIntent = target.intent;
Joe Onorato8a9b2202010-02-26 18:56:32 -08007115 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007116 + " out to new task " + target.task);
7117 }
7118 mWindowManager.setAppGroupId(target, task.taskId);
7119 if (replyChainEnd < 0) {
7120 replyChainEnd = targetI;
7121 }
7122 int dstPos = 0;
7123 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
7124 p = (HistoryRecord)mHistory.get(srcPos);
7125 if (p.finishing) {
7126 continue;
7127 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007128 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007129 + " out to target's task " + target.task);
7130 task.numActivities--;
7131 p.task = target.task;
7132 target.task.numActivities++;
7133 mHistory.remove(srcPos);
7134 mHistory.add(dstPos, p);
7135 mWindowManager.moveAppToken(dstPos, p);
7136 mWindowManager.setAppGroupId(p, p.task.taskId);
7137 dstPos++;
7138 if (VALIDATE_TOKENS) {
7139 mWindowManager.validateAppTokens(mHistory);
7140 }
7141 i++;
7142 }
7143 if (taskTop == p) {
7144 taskTop = below;
7145 }
7146 if (taskTopI == replyChainEnd) {
7147 taskTopI = -1;
7148 }
7149 replyChainEnd = -1;
Josh Bartel7f208742010-02-25 11:01:44 -06007150 addRecentTaskLocked(target.task);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007151 } else if (forceReset || finishOnTaskLaunch
7152 || clearWhenTaskReset) {
7153 // If the activity should just be removed -- either
7154 // because it asks for it, or the task should be
7155 // cleared -- then finish it and anything that is
7156 // part of its reply chain.
7157 if (clearWhenTaskReset) {
7158 // In this case, we want to finish this activity
7159 // and everything above it, so be sneaky and pretend
7160 // like these are all in the reply chain.
7161 replyChainEnd = targetI+1;
7162 while (replyChainEnd < mHistory.size() &&
7163 ((HistoryRecord)mHistory.get(
7164 replyChainEnd)).task == task) {
7165 replyChainEnd++;
7166 }
7167 replyChainEnd--;
7168 } else if (replyChainEnd < 0) {
7169 replyChainEnd = targetI;
7170 }
7171 HistoryRecord p = null;
7172 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
7173 p = (HistoryRecord)mHistory.get(srcPos);
7174 if (p.finishing) {
7175 continue;
7176 }
7177 if (finishActivityLocked(p, srcPos,
7178 Activity.RESULT_CANCELED, null, "reset")) {
7179 replyChainEnd--;
7180 srcPos--;
7181 }
7182 }
7183 if (taskTop == p) {
7184 taskTop = below;
7185 }
7186 if (taskTopI == replyChainEnd) {
7187 taskTopI = -1;
7188 }
7189 replyChainEnd = -1;
7190 } else {
7191 // If we were in the middle of a chain, well the
7192 // activity that started it all doesn't want anything
7193 // special, so leave it all as-is.
7194 replyChainEnd = -1;
7195 }
7196 } else {
7197 // Reached the bottom of the task -- any reply chain
7198 // should be left as-is.
7199 replyChainEnd = -1;
7200 }
7201
7202 } else if (target.resultTo != null) {
7203 // If this activity is sending a reply to a previous
7204 // activity, we can't do anything with it now until
7205 // we reach the start of the reply chain.
7206 // XXX note that we are assuming the result is always
7207 // to the previous activity, which is almost always
7208 // the case but we really shouldn't count on.
7209 if (replyChainEnd < 0) {
7210 replyChainEnd = targetI;
7211 }
7212
7213 } else if (taskTopI >= 0 && allowTaskReparenting
7214 && task.affinity != null
7215 && task.affinity.equals(target.taskAffinity)) {
7216 // We are inside of another task... if this activity has
7217 // an affinity for our task, then either remove it if we are
7218 // clearing or move it over to our task. Note that
7219 // we currently punt on the case where we are resetting a
7220 // task that is not at the top but who has activities above
7221 // with an affinity to it... this is really not a normal
7222 // case, and we will need to later pull that task to the front
7223 // and usually at that point we will do the reset and pick
7224 // up those remaining activities. (This only happens if
7225 // someone starts an activity in a new task from an activity
7226 // in a task that is not currently on top.)
7227 if (forceReset || finishOnTaskLaunch) {
7228 if (replyChainEnd < 0) {
7229 replyChainEnd = targetI;
7230 }
7231 HistoryRecord p = null;
7232 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
7233 p = (HistoryRecord)mHistory.get(srcPos);
7234 if (p.finishing) {
7235 continue;
7236 }
7237 if (finishActivityLocked(p, srcPos,
7238 Activity.RESULT_CANCELED, null, "reset")) {
7239 taskTopI--;
7240 lastReparentPos--;
7241 replyChainEnd--;
7242 srcPos--;
7243 }
7244 }
7245 replyChainEnd = -1;
7246 } else {
7247 if (replyChainEnd < 0) {
7248 replyChainEnd = targetI;
7249 }
7250 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
7251 HistoryRecord p = (HistoryRecord)mHistory.get(srcPos);
7252 if (p.finishing) {
7253 continue;
7254 }
7255 if (lastReparentPos < 0) {
7256 lastReparentPos = taskTopI;
7257 taskTop = p;
7258 } else {
7259 lastReparentPos--;
7260 }
7261 mHistory.remove(srcPos);
7262 p.task.numActivities--;
7263 p.task = task;
7264 mHistory.add(lastReparentPos, p);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007265 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007266 + " in to resetting task " + task);
7267 task.numActivities++;
7268 mWindowManager.moveAppToken(lastReparentPos, p);
7269 mWindowManager.setAppGroupId(p, p.task.taskId);
7270 if (VALIDATE_TOKENS) {
7271 mWindowManager.validateAppTokens(mHistory);
7272 }
7273 }
7274 replyChainEnd = -1;
7275
7276 // Now we've moved it in to place... but what if this is
7277 // a singleTop activity and we have put it on top of another
7278 // instance of the same activity? Then we drop the instance
7279 // below so it remains singleTop.
7280 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
7281 for (int j=lastReparentPos-1; j>=0; j--) {
7282 HistoryRecord p = (HistoryRecord)mHistory.get(j);
7283 if (p.finishing) {
7284 continue;
7285 }
7286 if (p.intent.getComponent().equals(target.intent.getComponent())) {
7287 if (finishActivityLocked(p, j,
7288 Activity.RESULT_CANCELED, null, "replace")) {
7289 taskTopI--;
7290 lastReparentPos--;
7291 }
7292 }
7293 }
7294 }
7295 }
7296 }
7297
7298 target = below;
7299 targetI = i;
7300 }
7301
7302 return taskTop;
7303 }
7304
7305 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007306 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007307 */
7308 public void moveTaskToFront(int task) {
7309 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
7310 "moveTaskToFront()");
7311
7312 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007313 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
7314 Binder.getCallingUid(), "Task to front")) {
7315 return;
7316 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007317 final long origId = Binder.clearCallingIdentity();
7318 try {
7319 int N = mRecentTasks.size();
7320 for (int i=0; i<N; i++) {
7321 TaskRecord tr = mRecentTasks.get(i);
7322 if (tr.taskId == task) {
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07007323 moveTaskToFrontLocked(tr, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007324 return;
7325 }
7326 }
7327 for (int i=mHistory.size()-1; i>=0; i--) {
7328 HistoryRecord hr = (HistoryRecord)mHistory.get(i);
7329 if (hr.task.taskId == task) {
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07007330 moveTaskToFrontLocked(hr.task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007331 return;
7332 }
7333 }
7334 } finally {
7335 Binder.restoreCallingIdentity(origId);
7336 }
7337 }
7338 }
7339
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07007340 private final void moveTaskToFrontLocked(TaskRecord tr, HistoryRecord reason) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007341 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007342
7343 final int task = tr.taskId;
7344 int top = mHistory.size()-1;
7345
7346 if (top < 0 || ((HistoryRecord)mHistory.get(top)).task.taskId == task) {
7347 // nothing to do!
7348 return;
7349 }
7350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007351 ArrayList moved = new ArrayList();
7352
7353 // Applying the affinities may have removed entries from the history,
7354 // so get the size again.
7355 top = mHistory.size()-1;
7356 int pos = top;
7357
7358 // Shift all activities with this task up to the top
7359 // of the stack, keeping them in the same internal order.
7360 while (pos >= 0) {
7361 HistoryRecord r = (HistoryRecord)mHistory.get(pos);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007362 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007363 TAG, "At " + pos + " ckp " + r.task + ": " + r);
7364 boolean first = true;
7365 if (r.task.taskId == task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007366 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007367 mHistory.remove(pos);
7368 mHistory.add(top, r);
7369 moved.add(0, r);
7370 top--;
7371 if (first) {
Josh Bartel7f208742010-02-25 11:01:44 -06007372 addRecentTaskLocked(r.task);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007373 first = false;
7374 }
7375 }
7376 pos--;
7377 }
7378
Joe Onorato8a9b2202010-02-26 18:56:32 -08007379 if (DEBUG_TRANSITION) Slog.v(TAG,
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07007380 "Prepare to front transition: task=" + tr);
7381 if (reason != null &&
7382 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
7383 mWindowManager.prepareAppTransition(WindowManagerPolicy.TRANSIT_NONE);
7384 HistoryRecord r = topRunningActivityLocked(null);
7385 if (r != null) {
7386 mNoAnimActivities.add(r);
7387 }
7388 } else {
7389 mWindowManager.prepareAppTransition(WindowManagerPolicy.TRANSIT_TASK_TO_FRONT);
7390 }
7391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007392 mWindowManager.moveAppTokensToTop(moved);
7393 if (VALIDATE_TOKENS) {
7394 mWindowManager.validateAppTokens(mHistory);
7395 }
7396
Josh Bartel7f208742010-02-25 11:01:44 -06007397 finishTaskMoveLocked(task);
Doug Zongker2bec3d42009-12-04 12:52:44 -08007398 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007399 }
7400
Josh Bartel7f208742010-02-25 11:01:44 -06007401 private final void finishTaskMoveLocked(int task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007402 resumeTopActivityLocked(null);
7403 }
7404
7405 public void moveTaskToBack(int task) {
7406 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
7407 "moveTaskToBack()");
7408
7409 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007410 if (mResumedActivity != null && mResumedActivity.task.taskId == task) {
7411 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
7412 Binder.getCallingUid(), "Task to back")) {
7413 return;
7414 }
7415 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007416 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07007417 moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007418 Binder.restoreCallingIdentity(origId);
7419 }
7420 }
7421
7422 /**
7423 * Moves an activity, and all of the other activities within the same task, to the bottom
7424 * of the history stack. The activity's order within the task is unchanged.
7425 *
7426 * @param token A reference to the activity we wish to move
7427 * @param nonRoot If false then this only works if the activity is the root
7428 * of a task; if true it will work for any activity in a task.
7429 * @return Returns true if the move completed, false if not.
7430 */
7431 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
7432 synchronized(this) {
7433 final long origId = Binder.clearCallingIdentity();
7434 int taskId = getTaskForActivityLocked(token, !nonRoot);
7435 if (taskId >= 0) {
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07007436 return moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007437 }
7438 Binder.restoreCallingIdentity(origId);
7439 }
7440 return false;
7441 }
7442
7443 /**
7444 * Worker method for rearranging history stack. Implements the function of moving all
7445 * activities for a specific task (gathering them if disjoint) into a single group at the
7446 * bottom of the stack.
7447 *
7448 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
7449 * to premeptively cancel the move.
7450 *
7451 * @param task The taskId to collect and move to the bottom.
7452 * @return Returns true if the move completed, false if not.
7453 */
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07007454 private final boolean moveTaskToBackLocked(int task, HistoryRecord reason) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007455 Slog.i(TAG, "moveTaskToBack: " + task);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007456
7457 // If we have a watcher, preflight the move before committing to it. First check
7458 // for *other* available tasks, but if none are available, then try again allowing the
7459 // current task to be selected.
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007460 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007461 HistoryRecord next = topRunningActivityLocked(null, task);
7462 if (next == null) {
7463 next = topRunningActivityLocked(null, 0);
7464 }
7465 if (next != null) {
7466 // ask watcher if this is allowed
7467 boolean moveOK = true;
7468 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007469 moveOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007470 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007471 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007472 }
7473 if (!moveOK) {
7474 return false;
7475 }
7476 }
7477 }
7478
7479 ArrayList moved = new ArrayList();
7480
Joe Onorato8a9b2202010-02-26 18:56:32 -08007481 if (DEBUG_TRANSITION) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007482 "Prepare to back transition: task=" + task);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007483
7484 final int N = mHistory.size();
7485 int bottom = 0;
7486 int pos = 0;
7487
7488 // Shift all activities with this task down to the bottom
7489 // of the stack, keeping them in the same internal order.
7490 while (pos < N) {
7491 HistoryRecord r = (HistoryRecord)mHistory.get(pos);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007492 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007493 TAG, "At " + pos + " ckp " + r.task + ": " + r);
7494 if (r.task.taskId == task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007495 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007496 mHistory.remove(pos);
7497 mHistory.add(bottom, r);
7498 moved.add(r);
7499 bottom++;
7500 }
7501 pos++;
7502 }
7503
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07007504 if (reason != null &&
7505 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
7506 mWindowManager.prepareAppTransition(WindowManagerPolicy.TRANSIT_NONE);
7507 HistoryRecord r = topRunningActivityLocked(null);
7508 if (r != null) {
7509 mNoAnimActivities.add(r);
7510 }
7511 } else {
Suchi Amalapurapuc9568e32009-11-05 18:51:16 -08007512 mWindowManager.prepareAppTransition(WindowManagerPolicy.TRANSIT_TASK_TO_BACK);
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07007513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007514 mWindowManager.moveAppTokensToBottom(moved);
7515 if (VALIDATE_TOKENS) {
7516 mWindowManager.validateAppTokens(mHistory);
7517 }
7518
Josh Bartel7f208742010-02-25 11:01:44 -06007519 finishTaskMoveLocked(task);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007520 return true;
7521 }
7522
7523 public void moveTaskBackwards(int task) {
7524 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
7525 "moveTaskBackwards()");
7526
7527 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007528 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
7529 Binder.getCallingUid(), "Task backwards")) {
7530 return;
7531 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007532 final long origId = Binder.clearCallingIdentity();
7533 moveTaskBackwardsLocked(task);
7534 Binder.restoreCallingIdentity(origId);
7535 }
7536 }
7537
7538 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007539 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007540 }
7541
7542 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
7543 synchronized(this) {
7544 return getTaskForActivityLocked(token, onlyRoot);
7545 }
7546 }
7547
7548 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
7549 final int N = mHistory.size();
7550 TaskRecord lastTask = null;
7551 for (int i=0; i<N; i++) {
7552 HistoryRecord r = (HistoryRecord)mHistory.get(i);
7553 if (r == token) {
7554 if (!onlyRoot || lastTask != r.task) {
7555 return r.task.taskId;
7556 }
7557 return -1;
7558 }
7559 lastTask = r.task;
7560 }
7561
7562 return -1;
7563 }
7564
7565 /**
7566 * Returns the top activity in any existing task matching the given
7567 * Intent. Returns null if no such task is found.
7568 */
7569 private HistoryRecord findTaskLocked(Intent intent, ActivityInfo info) {
7570 ComponentName cls = intent.getComponent();
7571 if (info.targetActivity != null) {
7572 cls = new ComponentName(info.packageName, info.targetActivity);
7573 }
7574
7575 TaskRecord cp = null;
7576
7577 final int N = mHistory.size();
7578 for (int i=(N-1); i>=0; i--) {
7579 HistoryRecord r = (HistoryRecord)mHistory.get(i);
7580 if (!r.finishing && r.task != cp
7581 && r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
7582 cp = r.task;
Joe Onorato8a9b2202010-02-26 18:56:32 -08007583 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007584 // + "/aff=" + r.task.affinity + " to new cls="
7585 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
7586 if (r.task.affinity != null) {
7587 if (r.task.affinity.equals(info.taskAffinity)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007588 //Slog.i(TAG, "Found matching affinity!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007589 return r;
7590 }
7591 } else if (r.task.intent != null
7592 && r.task.intent.getComponent().equals(cls)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007593 //Slog.i(TAG, "Found matching class!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007594 //dump();
Joe Onorato8a9b2202010-02-26 18:56:32 -08007595 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007596 return r;
7597 } else if (r.task.affinityIntent != null
7598 && r.task.affinityIntent.getComponent().equals(cls)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007599 //Slog.i(TAG, "Found matching class!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007600 //dump();
Joe Onorato8a9b2202010-02-26 18:56:32 -08007601 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007602 return r;
7603 }
7604 }
7605 }
7606
7607 return null;
7608 }
7609
7610 /**
7611 * Returns the first activity (starting from the top of the stack) that
7612 * is the same as the given activity. Returns null if no such activity
7613 * is found.
7614 */
7615 private HistoryRecord findActivityLocked(Intent intent, ActivityInfo info) {
7616 ComponentName cls = intent.getComponent();
7617 if (info.targetActivity != null) {
7618 cls = new ComponentName(info.packageName, info.targetActivity);
7619 }
7620
7621 final int N = mHistory.size();
7622 for (int i=(N-1); i>=0; i--) {
7623 HistoryRecord r = (HistoryRecord)mHistory.get(i);
7624 if (!r.finishing) {
7625 if (r.intent.getComponent().equals(cls)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007626 //Slog.i(TAG, "Found matching class!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007627 //dump();
Joe Onorato8a9b2202010-02-26 18:56:32 -08007628 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007629 return r;
7630 }
7631 }
7632 }
7633
7634 return null;
7635 }
7636
7637 public void finishOtherInstances(IBinder token, ComponentName className) {
7638 synchronized(this) {
7639 final long origId = Binder.clearCallingIdentity();
7640
7641 int N = mHistory.size();
7642 TaskRecord lastTask = null;
7643 for (int i=0; i<N; i++) {
7644 HistoryRecord r = (HistoryRecord)mHistory.get(i);
7645 if (r.realActivity.equals(className)
7646 && r != token && lastTask != r.task) {
7647 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
7648 null, "others")) {
7649 i--;
7650 N--;
7651 }
7652 }
7653 lastTask = r.task;
7654 }
7655
7656 Binder.restoreCallingIdentity(origId);
7657 }
7658 }
7659
7660 // =========================================================
7661 // THUMBNAILS
7662 // =========================================================
7663
7664 public void reportThumbnail(IBinder token,
7665 Bitmap thumbnail, CharSequence description) {
7666 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
7667 final long origId = Binder.clearCallingIdentity();
7668 sendPendingThumbnail(null, token, thumbnail, description, true);
7669 Binder.restoreCallingIdentity(origId);
7670 }
7671
7672 final void sendPendingThumbnail(HistoryRecord r, IBinder token,
7673 Bitmap thumbnail, CharSequence description, boolean always) {
7674 TaskRecord task = null;
7675 ArrayList receivers = null;
7676
7677 //System.out.println("Send pending thumbnail: " + r);
7678
7679 synchronized(this) {
7680 if (r == null) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07007681 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007682 if (index < 0) {
7683 return;
7684 }
7685 r = (HistoryRecord)mHistory.get(index);
7686 }
7687 if (thumbnail == null) {
7688 thumbnail = r.thumbnail;
7689 description = r.description;
7690 }
7691 if (thumbnail == null && !always) {
7692 // If there is no thumbnail, and this entry is not actually
7693 // going away, then abort for now and pick up the next
7694 // thumbnail we get.
7695 return;
7696 }
7697 task = r.task;
7698
7699 int N = mPendingThumbnails.size();
7700 int i=0;
7701 while (i<N) {
7702 PendingThumbnailsRecord pr =
7703 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
7704 //System.out.println("Looking in " + pr.pendingRecords);
7705 if (pr.pendingRecords.remove(r)) {
7706 if (receivers == null) {
7707 receivers = new ArrayList();
7708 }
7709 receivers.add(pr);
7710 if (pr.pendingRecords.size() == 0) {
7711 pr.finished = true;
7712 mPendingThumbnails.remove(i);
7713 N--;
7714 continue;
7715 }
7716 }
7717 i++;
7718 }
7719 }
7720
7721 if (receivers != null) {
7722 final int N = receivers.size();
7723 for (int i=0; i<N; i++) {
7724 try {
7725 PendingThumbnailsRecord pr =
7726 (PendingThumbnailsRecord)receivers.get(i);
7727 pr.receiver.newThumbnail(
7728 task != null ? task.taskId : -1, thumbnail, description);
7729 if (pr.finished) {
7730 pr.receiver.finished();
7731 }
7732 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007733 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007734 }
7735 }
7736 }
7737 }
7738
7739 // =========================================================
7740 // CONTENT PROVIDERS
7741 // =========================================================
7742
7743 private final List generateApplicationProvidersLocked(ProcessRecord app) {
7744 List providers = null;
7745 try {
7746 providers = ActivityThread.getPackageManager().
7747 queryContentProviders(app.processName, app.info.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07007748 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007749 } catch (RemoteException ex) {
7750 }
7751 if (providers != null) {
7752 final int N = providers.size();
7753 for (int i=0; i<N; i++) {
7754 ProviderInfo cpi =
7755 (ProviderInfo)providers.get(i);
7756 ContentProviderRecord cpr =
7757 (ContentProviderRecord)mProvidersByClass.get(cpi.name);
7758 if (cpr == null) {
7759 cpr = new ContentProviderRecord(cpi, app.info);
7760 mProvidersByClass.put(cpi.name, cpr);
7761 }
7762 app.pubProviders.put(cpi.name, cpr);
7763 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07007764 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007765 }
7766 }
7767 return providers;
7768 }
7769
7770 private final String checkContentProviderPermissionLocked(
7771 ProviderInfo cpi, ProcessRecord r, int mode) {
7772 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
7773 final int callingUid = (r != null) ? r.info.uid : Binder.getCallingUid();
7774 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
7775 cpi.exported ? -1 : cpi.applicationInfo.uid)
7776 == PackageManager.PERMISSION_GRANTED
7777 && mode == ParcelFileDescriptor.MODE_READ_ONLY || mode == -1) {
7778 return null;
7779 }
7780 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
7781 cpi.exported ? -1 : cpi.applicationInfo.uid)
7782 == PackageManager.PERMISSION_GRANTED) {
7783 return null;
7784 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07007785
7786 PathPermission[] pps = cpi.pathPermissions;
7787 if (pps != null) {
7788 int i = pps.length;
7789 while (i > 0) {
7790 i--;
7791 PathPermission pp = pps[i];
7792 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
7793 cpi.exported ? -1 : cpi.applicationInfo.uid)
7794 == PackageManager.PERMISSION_GRANTED
7795 && mode == ParcelFileDescriptor.MODE_READ_ONLY || mode == -1) {
7796 return null;
7797 }
7798 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
7799 cpi.exported ? -1 : cpi.applicationInfo.uid)
7800 == PackageManager.PERMISSION_GRANTED) {
7801 return null;
7802 }
7803 }
7804 }
7805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007806 String msg = "Permission Denial: opening provider " + cpi.name
7807 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
7808 + ", uid=" + callingUid + ") requires "
7809 + cpi.readPermission + " or " + cpi.writePermission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08007810 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007811 return msg;
7812 }
7813
7814 private final ContentProviderHolder getContentProviderImpl(
7815 IApplicationThread caller, String name) {
7816 ContentProviderRecord cpr;
7817 ProviderInfo cpi = null;
7818
7819 synchronized(this) {
7820 ProcessRecord r = null;
7821 if (caller != null) {
7822 r = getRecordForAppLocked(caller);
7823 if (r == null) {
7824 throw new SecurityException(
7825 "Unable to find app for caller " + caller
7826 + " (pid=" + Binder.getCallingPid()
7827 + ") when getting content provider " + name);
7828 }
7829 }
7830
7831 // First check if this content provider has been published...
7832 cpr = (ContentProviderRecord)mProvidersByName.get(name);
7833 if (cpr != null) {
7834 cpi = cpr.info;
7835 if (checkContentProviderPermissionLocked(cpi, r, -1) != null) {
7836 return new ContentProviderHolder(cpi,
7837 cpi.readPermission != null
7838 ? cpi.readPermission : cpi.writePermission);
7839 }
7840
7841 if (r != null && cpr.canRunHere(r)) {
7842 // This provider has been published or is in the process
7843 // of being published... but it is also allowed to run
7844 // in the caller's process, so don't make a connection
7845 // and just let the caller instantiate its own instance.
7846 if (cpr.provider != null) {
7847 // don't give caller the provider object, it needs
7848 // to make its own.
7849 cpr = new ContentProviderRecord(cpr);
7850 }
7851 return cpr;
7852 }
7853
7854 final long origId = Binder.clearCallingIdentity();
7855
Dianne Hackborna1e989b2009-09-01 19:54:29 -07007856 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007857 // return it right away.
7858 if (r != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007859 if (DEBUG_PROVIDER) Slog.v(TAG,
Dianne Hackborna1e989b2009-09-01 19:54:29 -07007860 "Adding provider requested by "
7861 + r.processName + " from process "
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07007862 + cpr.info.processName);
7863 Integer cnt = r.conProviders.get(cpr);
7864 if (cnt == null) {
7865 r.conProviders.put(cpr, new Integer(1));
7866 } else {
7867 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
7868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007869 cpr.clients.add(r);
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07007870 if (cpr.app != null && r.setAdj >= VISIBLE_APP_ADJ) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07007871 // If this is a visible app accessing the provider,
7872 // make sure to count it as being accessed and thus
7873 // back up on the LRU list. This is good because
7874 // content providers are often expensive to start.
7875 updateLruProcessLocked(cpr.app, false, true);
7876 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07007877 } else {
7878 cpr.externals++;
7879 }
7880
7881 if (cpr.app != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007882 updateOomAdjLocked(cpr.app);
7883 }
7884
7885 Binder.restoreCallingIdentity(origId);
7886
7887 } else {
7888 try {
7889 cpi = ActivityThread.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007890 resolveContentProvider(name,
7891 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007892 } catch (RemoteException ex) {
7893 }
7894 if (cpi == null) {
7895 return null;
7896 }
7897
7898 if (checkContentProviderPermissionLocked(cpi, r, -1) != null) {
7899 return new ContentProviderHolder(cpi,
7900 cpi.readPermission != null
7901 ? cpi.readPermission : cpi.writePermission);
7902 }
7903
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08007904 if (!mSystemReady && !mDidUpdate && !mWaitingUpdate
7905 && !cpi.processName.equals("system")) {
7906 // If this content provider does not run in the system
7907 // process, and the system is not yet ready to run other
7908 // processes, then fail fast instead of hanging.
7909 throw new IllegalArgumentException(
7910 "Attempt to launch content provider before system ready");
7911 }
7912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007913 cpr = (ContentProviderRecord)mProvidersByClass.get(cpi.name);
7914 final boolean firstClass = cpr == null;
7915 if (firstClass) {
7916 try {
7917 ApplicationInfo ai =
7918 ActivityThread.getPackageManager().
7919 getApplicationInfo(
7920 cpi.applicationInfo.packageName,
Dianne Hackborn1655be42009-05-08 14:29:01 -07007921 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007922 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007923 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007924 + cpi.name);
7925 return null;
7926 }
7927 cpr = new ContentProviderRecord(cpi, ai);
7928 } catch (RemoteException ex) {
7929 // pm is in same process, this will never happen.
7930 }
7931 }
7932
7933 if (r != null && cpr.canRunHere(r)) {
7934 // If this is a multiprocess provider, then just return its
7935 // info and allow the caller to instantiate it. Only do
7936 // this if the provider is the same user as the caller's
7937 // process, or can run as root (so can be in any process).
7938 return cpr;
7939 }
7940
Dianne Hackborna1e989b2009-09-01 19:54:29 -07007941 if (DEBUG_PROVIDER) {
7942 RuntimeException e = new RuntimeException("here");
Joe Onorato8a9b2202010-02-26 18:56:32 -08007943 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.info.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07007944 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007945 }
7946
7947 // This is single process, and our app is now connecting to it.
7948 // See if we are already in the process of launching this
7949 // provider.
7950 final int N = mLaunchingProviders.size();
7951 int i;
7952 for (i=0; i<N; i++) {
7953 if (mLaunchingProviders.get(i) == cpr) {
7954 break;
7955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007956 }
7957
7958 // If the provider is not already being launched, then get it
7959 // started.
7960 if (i >= N) {
7961 final long origId = Binder.clearCallingIdentity();
7962 ProcessRecord proc = startProcessLocked(cpi.processName,
7963 cpr.appInfo, false, 0, "content provider",
7964 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007965 cpi.name), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007966 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007967 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007968 + cpi.applicationInfo.packageName + "/"
7969 + cpi.applicationInfo.uid + " for provider "
7970 + name + ": process is bad");
7971 return null;
7972 }
7973 cpr.launchingApp = proc;
7974 mLaunchingProviders.add(cpr);
7975 Binder.restoreCallingIdentity(origId);
7976 }
7977
7978 // Make sure the provider is published (the same provider class
7979 // may be published under multiple names).
7980 if (firstClass) {
7981 mProvidersByClass.put(cpi.name, cpr);
7982 }
7983 mProvidersByName.put(name, cpr);
7984
7985 if (r != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007986 if (DEBUG_PROVIDER) Slog.v(TAG,
Dianne Hackborna1e989b2009-09-01 19:54:29 -07007987 "Adding provider requested by "
7988 + r.processName + " from process "
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07007989 + cpr.info.processName);
7990 Integer cnt = r.conProviders.get(cpr);
7991 if (cnt == null) {
7992 r.conProviders.put(cpr, new Integer(1));
7993 } else {
7994 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
7995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007996 cpr.clients.add(r);
7997 } else {
7998 cpr.externals++;
7999 }
8000 }
8001 }
8002
8003 // Wait for the provider to be published...
8004 synchronized (cpr) {
8005 while (cpr.provider == null) {
8006 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008007 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008008 + cpi.applicationInfo.packageName + "/"
8009 + cpi.applicationInfo.uid + " for provider "
8010 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08008011 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008012 cpi.applicationInfo.packageName,
8013 cpi.applicationInfo.uid, name);
8014 return null;
8015 }
8016 try {
8017 cpr.wait();
8018 } catch (InterruptedException ex) {
8019 }
8020 }
8021 }
8022 return cpr;
8023 }
8024
8025 public final ContentProviderHolder getContentProvider(
8026 IApplicationThread caller, String name) {
8027 if (caller == null) {
8028 String msg = "null IApplicationThread when getting content provider "
8029 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08008030 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008031 throw new SecurityException(msg);
8032 }
8033
8034 return getContentProviderImpl(caller, name);
8035 }
8036
8037 private ContentProviderHolder getContentProviderExternal(String name) {
8038 return getContentProviderImpl(null, name);
8039 }
8040
8041 /**
8042 * Drop a content provider from a ProcessRecord's bookkeeping
8043 * @param cpr
8044 */
8045 public void removeContentProvider(IApplicationThread caller, String name) {
8046 synchronized (this) {
8047 ContentProviderRecord cpr = (ContentProviderRecord)mProvidersByName.get(name);
8048 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07008049 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08008050 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07008051 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008052 return;
8053 }
8054 final ProcessRecord r = getRecordForAppLocked(caller);
8055 if (r == null) {
8056 throw new SecurityException(
8057 "Unable to find app for caller " + caller +
8058 " when removing content provider " + name);
8059 }
8060 //update content provider record entry info
Dianne Hackborna1e989b2009-09-01 19:54:29 -07008061 ContentProviderRecord localCpr = (ContentProviderRecord)
8062 mProvidersByClass.get(cpr.info.name);
Joe Onorato8a9b2202010-02-26 18:56:32 -08008063 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07008064 + r.info.processName + " from process "
8065 + localCpr.appInfo.processName);
8066 if (localCpr.app == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008067 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08008068 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07008069 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008070 return;
8071 } else {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07008072 Integer cnt = r.conProviders.get(localCpr);
8073 if (cnt == null || cnt.intValue() <= 1) {
8074 localCpr.clients.remove(r);
8075 r.conProviders.remove(localCpr);
8076 } else {
8077 r.conProviders.put(localCpr, new Integer(cnt.intValue()-1));
8078 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008079 }
8080 updateOomAdjLocked();
8081 }
8082 }
8083
8084 private void removeContentProviderExternal(String name) {
8085 synchronized (this) {
8086 ContentProviderRecord cpr = (ContentProviderRecord)mProvidersByName.get(name);
8087 if(cpr == null) {
8088 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08008089 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008090 return;
8091 }
8092
8093 //update content provider record entry info
8094 ContentProviderRecord localCpr = (ContentProviderRecord) mProvidersByClass.get(cpr.info.name);
8095 localCpr.externals--;
8096 if (localCpr.externals < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008097 Slog.e(TAG, "Externals < 0 for content provider " + localCpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008098 }
8099 updateOomAdjLocked();
8100 }
8101 }
8102
8103 public final void publishContentProviders(IApplicationThread caller,
8104 List<ContentProviderHolder> providers) {
8105 if (providers == null) {
8106 return;
8107 }
8108
8109 synchronized(this) {
8110 final ProcessRecord r = getRecordForAppLocked(caller);
8111 if (r == null) {
8112 throw new SecurityException(
8113 "Unable to find app for caller " + caller
8114 + " (pid=" + Binder.getCallingPid()
8115 + ") when publishing content providers");
8116 }
8117
8118 final long origId = Binder.clearCallingIdentity();
8119
8120 final int N = providers.size();
8121 for (int i=0; i<N; i++) {
8122 ContentProviderHolder src = providers.get(i);
8123 if (src == null || src.info == null || src.provider == null) {
8124 continue;
8125 }
8126 ContentProviderRecord dst =
8127 (ContentProviderRecord)r.pubProviders.get(src.info.name);
8128 if (dst != null) {
8129 mProvidersByClass.put(dst.info.name, dst);
8130 String names[] = dst.info.authority.split(";");
8131 for (int j = 0; j < names.length; j++) {
8132 mProvidersByName.put(names[j], dst);
8133 }
8134
8135 int NL = mLaunchingProviders.size();
8136 int j;
8137 for (j=0; j<NL; j++) {
8138 if (mLaunchingProviders.get(j) == dst) {
8139 mLaunchingProviders.remove(j);
8140 j--;
8141 NL--;
8142 }
8143 }
8144 synchronized (dst) {
8145 dst.provider = src.provider;
8146 dst.app = r;
8147 dst.notifyAll();
8148 }
8149 updateOomAdjLocked(r);
8150 }
8151 }
8152
8153 Binder.restoreCallingIdentity(origId);
8154 }
8155 }
8156
8157 public static final void installSystemProviders() {
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08008158 List providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06008159 synchronized (mSelf) {
8160 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
8161 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08008162 if (providers != null) {
8163 for (int i=providers.size()-1; i>=0; i--) {
8164 ProviderInfo pi = (ProviderInfo)providers.get(i);
8165 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8166 Slog.w(TAG, "Not installing system proc provider " + pi.name
8167 + ": not system .apk");
8168 providers.remove(i);
8169 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08008170 }
8171 }
8172 }
Josh Bartel2ecce342010-02-25 10:55:48 -06008173 if (providers != null) {
8174 mSystemThread.installSystemProviders(providers);
8175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008176 }
8177
8178 // =========================================================
8179 // GLOBAL MANAGEMENT
8180 // =========================================================
8181
8182 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
8183 ApplicationInfo info, String customProcess) {
8184 String proc = customProcess != null ? customProcess : info.processName;
8185 BatteryStatsImpl.Uid.Proc ps = null;
8186 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
8187 synchronized (stats) {
8188 ps = stats.getProcessStatsLocked(info.uid, proc);
8189 }
8190 return new ProcessRecord(ps, thread, info, proc);
8191 }
8192
8193 final ProcessRecord addAppLocked(ApplicationInfo info) {
8194 ProcessRecord app = getProcessRecordLocked(info.processName, info.uid);
8195
8196 if (app == null) {
8197 app = newProcessRecordLocked(null, info, null);
8198 mProcessNames.put(info.processName, info.uid, app);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008199 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008200 }
8201
8202 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
8203 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
8204 app.persistent = true;
8205 app.maxAdj = CORE_SERVER_ADJ;
8206 }
8207 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
8208 mPersistentStartingProcesses.add(app);
8209 startProcessLocked(app, "added application", app.processName);
8210 }
8211
8212 return app;
8213 }
8214
8215 public void unhandledBack() {
8216 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
8217 "unhandledBack()");
8218
8219 synchronized(this) {
8220 int count = mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08008221 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008222 TAG, "Performing unhandledBack(): stack size = " + count);
8223 if (count > 1) {
8224 final long origId = Binder.clearCallingIdentity();
8225 finishActivityLocked((HistoryRecord)mHistory.get(count-1),
8226 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
8227 Binder.restoreCallingIdentity(origId);
8228 }
8229 }
8230 }
8231
8232 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
8233 String name = uri.getAuthority();
8234 ContentProviderHolder cph = getContentProviderExternal(name);
8235 ParcelFileDescriptor pfd = null;
8236 if (cph != null) {
8237 // We record the binder invoker's uid in thread-local storage before
8238 // going to the content provider to open the file. Later, in the code
8239 // that handles all permissions checks, we look for this uid and use
8240 // that rather than the Activity Manager's own uid. The effect is that
8241 // we do the check against the caller's permissions even though it looks
8242 // to the content provider like the Activity Manager itself is making
8243 // the request.
8244 sCallerIdentity.set(new Identity(
8245 Binder.getCallingPid(), Binder.getCallingUid()));
8246 try {
8247 pfd = cph.provider.openFile(uri, "r");
8248 } catch (FileNotFoundException e) {
8249 // do nothing; pfd will be returned null
8250 } finally {
8251 // Ensure that whatever happens, we clean up the identity state
8252 sCallerIdentity.remove();
8253 }
8254
8255 // We've got the fd now, so we're done with the provider.
8256 removeContentProviderExternal(name);
8257 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008258 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008259 }
8260 return pfd;
8261 }
8262
8263 public void goingToSleep() {
8264 synchronized(this) {
8265 mSleeping = true;
8266 mWindowManager.setEventDispatching(false);
8267
8268 if (mResumedActivity != null) {
8269 pauseIfSleepingLocked();
8270 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008271 Slog.w(TAG, "goingToSleep with no resumed activity!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008272 }
8273 }
8274 }
8275
Dianne Hackborn55280a92009-05-07 15:53:46 -07008276 public boolean shutdown(int timeout) {
8277 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
8278 != PackageManager.PERMISSION_GRANTED) {
8279 throw new SecurityException("Requires permission "
8280 + android.Manifest.permission.SHUTDOWN);
8281 }
8282
8283 boolean timedout = false;
8284
8285 synchronized(this) {
8286 mShuttingDown = true;
8287 mWindowManager.setEventDispatching(false);
8288
8289 if (mResumedActivity != null) {
8290 pauseIfSleepingLocked();
8291 final long endTime = System.currentTimeMillis() + timeout;
8292 while (mResumedActivity != null || mPausingActivity != null) {
8293 long delay = endTime - System.currentTimeMillis();
8294 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008295 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07008296 timedout = true;
8297 break;
8298 }
8299 try {
8300 this.wait();
8301 } catch (InterruptedException e) {
8302 }
8303 }
8304 }
8305 }
8306
8307 mUsageStatsService.shutdown();
8308 mBatteryStatsService.shutdown();
8309
8310 return timedout;
8311 }
8312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008313 void pauseIfSleepingLocked() {
Dianne Hackborn55280a92009-05-07 15:53:46 -07008314 if (mSleeping || mShuttingDown) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008315 if (!mGoingToSleep.isHeld()) {
8316 mGoingToSleep.acquire();
8317 if (mLaunchingActivity.isHeld()) {
8318 mLaunchingActivity.release();
8319 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
8320 }
8321 }
8322
8323 // If we are not currently pausing an activity, get the current
8324 // one to pause. If we are pausing one, we will just let that stuff
8325 // run and release the wake lock when all done.
8326 if (mPausingActivity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008327 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause...");
8328 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008329 startPausingLocked(false, true);
8330 }
8331 }
8332 }
8333
8334 public void wakingUp() {
8335 synchronized(this) {
8336 if (mGoingToSleep.isHeld()) {
8337 mGoingToSleep.release();
8338 }
8339 mWindowManager.setEventDispatching(true);
8340 mSleeping = false;
8341 resumeTopActivityLocked(null);
8342 }
8343 }
8344
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07008345 public void stopAppSwitches() {
8346 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
8347 != PackageManager.PERMISSION_GRANTED) {
8348 throw new SecurityException("Requires permission "
8349 + android.Manifest.permission.STOP_APP_SWITCHES);
8350 }
8351
8352 synchronized(this) {
8353 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
8354 + APP_SWITCH_DELAY_TIME;
8355 mDidAppSwitch = false;
8356 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
8357 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
8358 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
8359 }
8360 }
8361
8362 public void resumeAppSwitches() {
8363 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
8364 != PackageManager.PERMISSION_GRANTED) {
8365 throw new SecurityException("Requires permission "
8366 + android.Manifest.permission.STOP_APP_SWITCHES);
8367 }
8368
8369 synchronized(this) {
8370 // Note that we don't execute any pending app switches... we will
8371 // let those wait until either the timeout, or the next start
8372 // activity request.
8373 mAppSwitchesAllowedTime = 0;
8374 }
8375 }
8376
8377 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
8378 String name) {
8379 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
8380 return true;
8381 }
8382
8383 final int perm = checkComponentPermission(
8384 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
8385 callingUid, -1);
8386 if (perm == PackageManager.PERMISSION_GRANTED) {
8387 return true;
8388 }
8389
Joe Onorato8a9b2202010-02-26 18:56:32 -08008390 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07008391 return false;
8392 }
8393
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008394 public void setDebugApp(String packageName, boolean waitForDebugger,
8395 boolean persistent) {
8396 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
8397 "setDebugApp()");
8398
8399 // Note that this is not really thread safe if there are multiple
8400 // callers into it at the same time, but that's not a situation we
8401 // care about.
8402 if (persistent) {
8403 final ContentResolver resolver = mContext.getContentResolver();
8404 Settings.System.putString(
8405 resolver, Settings.System.DEBUG_APP,
8406 packageName);
8407 Settings.System.putInt(
8408 resolver, Settings.System.WAIT_FOR_DEBUGGER,
8409 waitForDebugger ? 1 : 0);
8410 }
8411
8412 synchronized (this) {
8413 if (!persistent) {
8414 mOrigDebugApp = mDebugApp;
8415 mOrigWaitForDebugger = mWaitForDebugger;
8416 }
8417 mDebugApp = packageName;
8418 mWaitForDebugger = waitForDebugger;
8419 mDebugTransient = !persistent;
8420 if (packageName != null) {
8421 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08008422 forceStopPackageLocked(packageName, -1, false, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008423 Binder.restoreCallingIdentity(origId);
8424 }
8425 }
8426 }
8427
8428 public void setAlwaysFinish(boolean enabled) {
8429 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
8430 "setAlwaysFinish()");
8431
8432 Settings.System.putInt(
8433 mContext.getContentResolver(),
8434 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
8435
8436 synchronized (this) {
8437 mAlwaysFinishActivities = enabled;
8438 }
8439 }
8440
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008441 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008442 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008443 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008444 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008445 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008446 }
8447 }
8448
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08008449 public boolean isUserAMonkey() {
8450 // For now the fact that there is a controller implies
8451 // we have a monkey.
8452 synchronized (this) {
8453 return mController != null;
8454 }
8455 }
8456
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008457 public void registerActivityWatcher(IActivityWatcher watcher) {
Josh Bartel2ecce342010-02-25 10:55:48 -06008458 synchronized (this) {
8459 mWatchers.register(watcher);
8460 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008461 }
8462
8463 public void unregisterActivityWatcher(IActivityWatcher watcher) {
Josh Bartel2ecce342010-02-25 10:55:48 -06008464 synchronized (this) {
8465 mWatchers.unregister(watcher);
8466 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008467 }
8468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008469 public final void enterSafeMode() {
8470 synchronized(this) {
8471 // It only makes sense to do this before the system is ready
8472 // and started launching other packages.
8473 if (!mSystemReady) {
8474 try {
8475 ActivityThread.getPackageManager().enterSafeMode();
8476 } catch (RemoteException e) {
8477 }
8478
8479 View v = LayoutInflater.from(mContext).inflate(
8480 com.android.internal.R.layout.safe_mode, null);
8481 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
8482 lp.type = WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;
8483 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
8484 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
8485 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
8486 lp.format = v.getBackground().getOpacity();
8487 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
8488 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
8489 ((WindowManager)mContext.getSystemService(
8490 Context.WINDOW_SERVICE)).addView(v, lp);
8491 }
8492 }
8493 }
8494
8495 public void noteWakeupAlarm(IIntentSender sender) {
8496 if (!(sender instanceof PendingIntentRecord)) {
8497 return;
8498 }
8499 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
8500 synchronized (stats) {
8501 if (mBatteryStatsService.isOnBattery()) {
8502 mBatteryStatsService.enforceCallingPermission();
8503 PendingIntentRecord rec = (PendingIntentRecord)sender;
8504 int MY_UID = Binder.getCallingUid();
8505 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
8506 BatteryStatsImpl.Uid.Pkg pkg =
8507 stats.getPackageStatsLocked(uid, rec.key.packageName);
8508 pkg.incWakeupsLocked();
8509 }
8510 }
8511 }
8512
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07008513 public boolean killPids(int[] pids, String pReason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008514 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07008515 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008516 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07008517 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008518 // XXX Note: don't acquire main activity lock here, because the window
8519 // manager calls in with its locks held.
8520
8521 boolean killed = false;
8522 synchronized (mPidsSelfLocked) {
8523 int[] types = new int[pids.length];
8524 int worstType = 0;
8525 for (int i=0; i<pids.length; i++) {
8526 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
8527 if (proc != null) {
8528 int type = proc.setAdj;
8529 types[i] = type;
8530 if (type > worstType) {
8531 worstType = type;
8532 }
8533 }
8534 }
8535
8536 // If the worse oom_adj is somewhere in the hidden proc LRU range,
8537 // then constrain it so we will kill all hidden procs.
8538 if (worstType < EMPTY_APP_ADJ && worstType > HIDDEN_APP_MIN_ADJ) {
8539 worstType = HIDDEN_APP_MIN_ADJ;
8540 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07008541 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008542 for (int i=0; i<pids.length; i++) {
8543 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
8544 if (proc == null) {
8545 continue;
8546 }
8547 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07008548 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07008549 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07008550 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
8551 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008552 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07008553 proc.killedBackground = true;
8554 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008555 }
8556 }
8557 }
8558 return killed;
8559 }
8560
8561 public void reportPss(IApplicationThread caller, int pss) {
8562 Watchdog.PssRequestor req;
8563 String name;
8564 ProcessRecord callerApp;
8565 synchronized (this) {
8566 if (caller == null) {
8567 return;
8568 }
8569 callerApp = getRecordForAppLocked(caller);
8570 if (callerApp == null) {
8571 return;
8572 }
8573 callerApp.lastPss = pss;
8574 req = callerApp;
8575 name = callerApp.processName;
8576 }
8577 Watchdog.getInstance().reportPss(req, name, pss);
8578 if (!callerApp.persistent) {
8579 removeRequestedPss(callerApp);
8580 }
8581 }
8582
8583 public void requestPss(Runnable completeCallback) {
8584 ArrayList<ProcessRecord> procs;
8585 synchronized (this) {
8586 mRequestPssCallback = completeCallback;
8587 mRequestPssList.clear();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008588 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8589 ProcessRecord proc = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008590 if (!proc.persistent) {
8591 mRequestPssList.add(proc);
8592 }
8593 }
8594 procs = new ArrayList<ProcessRecord>(mRequestPssList);
8595 }
8596
8597 int oldPri = Process.getThreadPriority(Process.myTid());
8598 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
8599 for (int i=procs.size()-1; i>=0; i--) {
8600 ProcessRecord proc = procs.get(i);
8601 proc.lastPss = 0;
8602 proc.requestPss();
8603 }
8604 Process.setThreadPriority(oldPri);
8605 }
8606
8607 void removeRequestedPss(ProcessRecord proc) {
8608 Runnable callback = null;
8609 synchronized (this) {
8610 if (mRequestPssList.remove(proc)) {
8611 if (mRequestPssList.size() == 0) {
8612 callback = mRequestPssCallback;
8613 mRequestPssCallback = null;
8614 }
8615 }
8616 }
8617
8618 if (callback != null) {
8619 callback.run();
8620 }
8621 }
8622
8623 public void collectPss(Watchdog.PssStats stats) {
8624 stats.mEmptyPss = 0;
8625 stats.mEmptyCount = 0;
8626 stats.mBackgroundPss = 0;
8627 stats.mBackgroundCount = 0;
8628 stats.mServicePss = 0;
8629 stats.mServiceCount = 0;
8630 stats.mVisiblePss = 0;
8631 stats.mVisibleCount = 0;
8632 stats.mForegroundPss = 0;
8633 stats.mForegroundCount = 0;
8634 stats.mNoPssCount = 0;
8635 synchronized (this) {
8636 int i;
8637 int NPD = mProcDeaths.length < stats.mProcDeaths.length
8638 ? mProcDeaths.length : stats.mProcDeaths.length;
8639 int aggr = 0;
8640 for (i=0; i<NPD; i++) {
8641 aggr += mProcDeaths[i];
8642 stats.mProcDeaths[i] = aggr;
8643 }
8644 while (i<stats.mProcDeaths.length) {
8645 stats.mProcDeaths[i] = 0;
8646 i++;
8647 }
8648
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008649 for (i=mLruProcesses.size()-1; i>=0; i--) {
8650 ProcessRecord proc = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008651 if (proc.persistent) {
8652 continue;
8653 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008654 //Slog.i(TAG, "Proc " + proc + ": pss=" + proc.lastPss);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008655 if (proc.lastPss == 0) {
8656 stats.mNoPssCount++;
8657 continue;
8658 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008659 if (proc.setAdj >= HIDDEN_APP_MIN_ADJ) {
8660 if (proc.empty) {
8661 stats.mEmptyPss += proc.lastPss;
8662 stats.mEmptyCount++;
8663 } else {
8664 stats.mBackgroundPss += proc.lastPss;
8665 stats.mBackgroundCount++;
8666 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008667 } else if (proc.setAdj >= VISIBLE_APP_ADJ) {
8668 stats.mVisiblePss += proc.lastPss;
8669 stats.mVisibleCount++;
8670 } else {
8671 stats.mForegroundPss += proc.lastPss;
8672 stats.mForegroundCount++;
8673 }
8674 }
8675 }
8676 }
8677
8678 public final void startRunning(String pkg, String cls, String action,
8679 String data) {
8680 synchronized(this) {
8681 if (mStartRunning) {
8682 return;
8683 }
8684 mStartRunning = true;
8685 mTopComponent = pkg != null && cls != null
8686 ? new ComponentName(pkg, cls) : null;
8687 mTopAction = action != null ? action : Intent.ACTION_MAIN;
8688 mTopData = data;
8689 if (!mSystemReady) {
8690 return;
8691 }
8692 }
8693
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07008694 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008695 }
8696
8697 private void retrieveSettings() {
8698 final ContentResolver resolver = mContext.getContentResolver();
8699 String debugApp = Settings.System.getString(
8700 resolver, Settings.System.DEBUG_APP);
8701 boolean waitForDebugger = Settings.System.getInt(
8702 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
8703 boolean alwaysFinishActivities = Settings.System.getInt(
8704 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
8705
8706 Configuration configuration = new Configuration();
8707 Settings.System.getConfiguration(resolver, configuration);
8708
8709 synchronized (this) {
8710 mDebugApp = mOrigDebugApp = debugApp;
8711 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
8712 mAlwaysFinishActivities = alwaysFinishActivities;
8713 // This happens before any activities are started, so we can
8714 // change mConfiguration in-place.
8715 mConfiguration.updateFrom(configuration);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08008716 mConfigurationSeq = mConfiguration.seq = 1;
Joe Onorato8a9b2202010-02-26 18:56:32 -08008717 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008718 }
8719 }
8720
8721 public boolean testIsSystemReady() {
8722 // no need to synchronize(this) just to read & return the value
8723 return mSystemReady;
8724 }
8725
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07008726 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008727 // In the simulator, startRunning will never have been called, which
8728 // normally sets a few crucial variables. Do it here instead.
8729 if (!Process.supportsProcesses()) {
8730 mStartRunning = true;
8731 mTopAction = Intent.ACTION_MAIN;
8732 }
8733
8734 synchronized(this) {
8735 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07008736 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008737 return;
8738 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008739
8740 // Check to see if there are any update receivers to run.
8741 if (!mDidUpdate) {
8742 if (mWaitingUpdate) {
8743 return;
8744 }
8745 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
8746 List<ResolveInfo> ris = null;
8747 try {
8748 ris = ActivityThread.getPackageManager().queryIntentReceivers(
8749 intent, null, 0);
8750 } catch (RemoteException e) {
8751 }
8752 if (ris != null) {
8753 for (int i=ris.size()-1; i>=0; i--) {
8754 if ((ris.get(i).activityInfo.applicationInfo.flags
8755 &ApplicationInfo.FLAG_SYSTEM) == 0) {
8756 ris.remove(i);
8757 }
8758 }
8759 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
8760 for (int i=0; i<ris.size(); i++) {
8761 ActivityInfo ai = ris.get(i).activityInfo;
8762 intent.setComponent(new ComponentName(ai.packageName, ai.name));
8763 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08008764 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008765 finisher = new IIntentReceiver.Stub() {
8766 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07008767 String data, Bundle extras, boolean ordered,
8768 boolean sticky)
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008769 throws RemoteException {
8770 synchronized (ActivityManagerService.this) {
8771 mDidUpdate = true;
8772 }
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07008773 systemReady(goingCallback);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008774 }
8775 };
8776 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008777 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008778 broadcastIntentLocked(null, null, intent, null, finisher,
8779 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID);
Dianne Hackbornd6847842010-01-12 18:14:19 -08008780 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008781 mWaitingUpdate = true;
8782 }
8783 }
8784 }
8785 if (mWaitingUpdate) {
8786 return;
8787 }
8788 mDidUpdate = true;
8789 }
8790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008791 mSystemReady = true;
8792 if (!mStartRunning) {
8793 return;
8794 }
8795 }
8796
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008797 ArrayList<ProcessRecord> procsToKill = null;
8798 synchronized(mPidsSelfLocked) {
8799 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
8800 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
8801 if (!isAllowedWhileBooting(proc.info)){
8802 if (procsToKill == null) {
8803 procsToKill = new ArrayList<ProcessRecord>();
8804 }
8805 procsToKill.add(proc);
8806 }
8807 }
8808 }
8809
8810 if (procsToKill != null) {
8811 synchronized(this) {
8812 for (int i=procsToKill.size()-1; i>=0; i--) {
8813 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08008814 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008815 removeProcessLocked(proc, true);
8816 }
8817 }
8818 }
8819
Joe Onorato8a9b2202010-02-26 18:56:32 -08008820 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08008821 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008822 SystemClock.uptimeMillis());
8823
8824 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008825 // Make sure we have no pre-ready processes sitting around.
8826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008827 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
8828 ResolveInfo ri = mContext.getPackageManager()
8829 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07008830 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008831 CharSequence errorMsg = null;
8832 if (ri != null) {
8833 ActivityInfo ai = ri.activityInfo;
8834 ApplicationInfo app = ai.applicationInfo;
8835 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8836 mTopAction = Intent.ACTION_FACTORY_TEST;
8837 mTopData = null;
8838 mTopComponent = new ComponentName(app.packageName,
8839 ai.name);
8840 } else {
8841 errorMsg = mContext.getResources().getText(
8842 com.android.internal.R.string.factorytest_not_system);
8843 }
8844 } else {
8845 errorMsg = mContext.getResources().getText(
8846 com.android.internal.R.string.factorytest_no_action);
8847 }
8848 if (errorMsg != null) {
8849 mTopAction = null;
8850 mTopData = null;
8851 mTopComponent = null;
8852 Message msg = Message.obtain();
8853 msg.what = SHOW_FACTORY_ERROR_MSG;
8854 msg.getData().putCharSequence("msg", errorMsg);
8855 mHandler.sendMessage(msg);
8856 }
8857 }
8858 }
8859
8860 retrieveSettings();
8861
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07008862 if (goingCallback != null) goingCallback.run();
8863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008864 synchronized (this) {
8865 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
8866 try {
8867 List apps = ActivityThread.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07008868 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008869 if (apps != null) {
8870 int N = apps.size();
8871 int i;
8872 for (i=0; i<N; i++) {
8873 ApplicationInfo info
8874 = (ApplicationInfo)apps.get(i);
8875 if (info != null &&
8876 !info.packageName.equals("android")) {
8877 addAppLocked(info);
8878 }
8879 }
8880 }
8881 } catch (RemoteException ex) {
8882 // pm is in same process, this will never happen.
8883 }
8884 }
8885
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008886 // Start up initial activity.
8887 mBooting = true;
8888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008889 try {
8890 if (ActivityThread.getPackageManager().hasSystemUidErrors()) {
8891 Message msg = Message.obtain();
8892 msg.what = SHOW_UID_ERROR_MSG;
8893 mHandler.sendMessage(msg);
8894 }
8895 } catch (RemoteException e) {
8896 }
8897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008898 resumeTopActivityLocked(null);
8899 }
8900 }
8901
Dan Egnorb7f03672009-12-09 16:22:32 -08008902 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008903 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008904 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08008905 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08008906 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008907 startAppProblemLocked(app);
8908 app.stopFreezingAllLocked();
8909 return handleAppCrashLocked(app);
8910 }
8911
Dan Egnorb7f03672009-12-09 16:22:32 -08008912 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008913 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008914 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08008915 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08008916 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
8917 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008918 startAppProblemLocked(app);
8919 app.stopFreezingAllLocked();
8920 }
8921
8922 /**
8923 * Generate a process error record, suitable for attachment to a ProcessRecord.
8924 *
8925 * @param app The ProcessRecord in which the error occurred.
8926 * @param condition Crashing, Application Not Responding, etc. Values are defined in
8927 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08008928 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008929 * @param shortMsg Short message describing the crash.
8930 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08008931 * @param stackTrace Full crash stack trace, may be null.
8932 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008933 * @return Returns a fully-formed AppErrorStateInfo record.
8934 */
8935 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008936 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008937 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08008938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008939 report.condition = condition;
8940 report.processName = app.processName;
8941 report.pid = app.pid;
8942 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08008943 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008944 report.shortMsg = shortMsg;
8945 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08008946 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008947
8948 return report;
8949 }
8950
Dan Egnor42471dd2010-01-07 17:25:22 -08008951 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008952 synchronized (this) {
8953 app.crashing = false;
8954 app.crashingReport = null;
8955 app.notResponding = false;
8956 app.notRespondingReport = null;
8957 if (app.anrDialog == fromDialog) {
8958 app.anrDialog = null;
8959 }
8960 if (app.waitDialog == fromDialog) {
8961 app.waitDialog = null;
8962 }
8963 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08008964 handleAppCrashLocked(app);
Dianne Hackborn8633e682010-04-22 16:03:41 -07008965 Slog.i(ActivityManagerService.TAG, "Killing "
8966 + app.processName + " (pid=" + app.pid + "): user's request");
8967 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
8968 app.processName, app.setAdj, "user's request after error");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008969 Process.killProcess(app.pid);
8970 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008971 }
8972 }
Dan Egnor42471dd2010-01-07 17:25:22 -08008973
Dan Egnorb7f03672009-12-09 16:22:32 -08008974 private boolean handleAppCrashLocked(ProcessRecord app) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008975 long now = SystemClock.uptimeMillis();
8976
8977 Long crashTime = mProcessCrashTimes.get(app.info.processName,
8978 app.info.uid);
8979 if (crashTime != null && now < crashTime+MIN_CRASH_INTERVAL) {
8980 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08008981 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008982 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08008983 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008984 app.info.processName, app.info.uid);
8985 killServicesLocked(app, false);
8986 for (int i=mHistory.size()-1; i>=0; i--) {
8987 HistoryRecord r = (HistoryRecord)mHistory.get(i);
8988 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008989 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008990 + r.intent.getComponent().flattenToShortString());
8991 finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
8992 }
8993 }
8994 if (!app.persistent) {
8995 // We don't want to start this process again until the user
8996 // explicitly does so... but for persistent process, we really
8997 // need to keep it running. If a persistent process is actually
8998 // repeatedly crashing, then badness for everyone.
Doug Zongker2bec3d42009-12-04 12:52:44 -08008999 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.info.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009000 app.info.processName);
9001 mBadProcesses.put(app.info.processName, app.info.uid, now);
9002 app.bad = true;
9003 mProcessCrashTimes.remove(app.info.processName, app.info.uid);
9004 app.removed = true;
9005 removeProcessLocked(app, false);
9006 return false;
9007 }
Dianne Hackbornf83c5552010-03-31 22:19:32 -07009008 } else {
9009 HistoryRecord r = topRunningActivityLocked(null);
9010 if (r.app == app) {
9011 // If the top running activity is from this crashing
9012 // process, then terminate it to avoid getting in a loop.
9013 Slog.w(TAG, " Force finishing activity "
9014 + r.intent.getComponent().flattenToShortString());
9015 int index = indexOfTokenLocked(r);
9016 finishActivityLocked(r, index,
9017 Activity.RESULT_CANCELED, null, "crashed");
9018 // Also terminate an activities below it that aren't yet
9019 // stopped, to avoid a situation where one will get
9020 // re-start our crashing activity once it gets resumed again.
9021 index--;
9022 if (index >= 0) {
9023 r = (HistoryRecord)mHistory.get(index);
9024 if (r.state == ActivityState.RESUMED
9025 || r.state == ActivityState.PAUSING
9026 || r.state == ActivityState.PAUSED) {
9027 if (!r.isHomeActivity) {
9028 Slog.w(TAG, " Force finishing activity "
9029 + r.intent.getComponent().flattenToShortString());
9030 finishActivityLocked(r, index,
9031 Activity.RESULT_CANCELED, null, "crashed");
9032 }
9033 }
9034 }
9035 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009036 }
9037
9038 // Bump up the crash count of any services currently running in the proc.
9039 if (app.services.size() != 0) {
9040 // Any services running in the application need to be placed
9041 // back in the pending list.
9042 Iterator it = app.services.iterator();
9043 while (it.hasNext()) {
9044 ServiceRecord sr = (ServiceRecord)it.next();
9045 sr.crashCount++;
9046 }
9047 }
9048
9049 mProcessCrashTimes.put(app.info.processName, app.info.uid, now);
9050 return true;
9051 }
9052
9053 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08009054 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
9055 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009056 skipCurrentReceiverLocked(app);
9057 }
9058
9059 void skipCurrentReceiverLocked(ProcessRecord app) {
9060 boolean reschedule = false;
9061 BroadcastRecord r = app.curReceiver;
9062 if (r != null) {
9063 // The current broadcast is waiting for this app's receiver
9064 // to be finished. Looks like that's not going to happen, so
9065 // let the broadcast continue.
9066 logBroadcastReceiverDiscard(r);
9067 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
9068 r.resultExtras, r.resultAbort, true);
9069 reschedule = true;
9070 }
9071 r = mPendingBroadcast;
9072 if (r != null && r.curApp == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009073 if (DEBUG_BROADCAST) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009074 "skip & discard pending app " + r);
9075 logBroadcastReceiverDiscard(r);
9076 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
9077 r.resultExtras, r.resultAbort, true);
9078 reschedule = true;
9079 }
9080 if (reschedule) {
9081 scheduleBroadcastsLocked();
9082 }
9083 }
9084
Dan Egnor60d87622009-12-16 16:32:58 -08009085 /**
9086 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
9087 * The application process will exit immediately after this call returns.
9088 * @param app object of the crashing app, null for the system server
9089 * @param crashInfo describing the exception
9090 */
9091 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
9092 ProcessRecord r = findAppProcess(app);
9093
9094 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
9095 app == null ? "system" : (r == null ? "unknown" : r.processName),
Dan Egnor2780e732010-01-22 14:47:35 -08009096 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08009097 crashInfo.exceptionClassName,
9098 crashInfo.exceptionMessage,
9099 crashInfo.throwFileName,
9100 crashInfo.throwLineNumber);
9101
Dan Egnor42471dd2010-01-07 17:25:22 -08009102 addErrorToDropBox("crash", r, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08009103
9104 crashApplication(r, crashInfo);
9105 }
9106
9107 /**
9108 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
9109 * @param app object of the crashing app, null for the system server
9110 * @param tag reported by the caller
9111 * @param crashInfo describing the context of the error
9112 * @return true if the process should exit immediately (WTF is fatal)
9113 */
9114 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08009115 ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnor60d87622009-12-16 16:32:58 -08009116 ProcessRecord r = findAppProcess(app);
9117
9118 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
9119 app == null ? "system" : (r == null ? "unknown" : r.processName),
Dan Egnor2780e732010-01-22 14:47:35 -08009120 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08009121 tag, crashInfo.exceptionMessage);
9122
Dan Egnor42471dd2010-01-07 17:25:22 -08009123 addErrorToDropBox("wtf", r, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08009124
Doug Zongker43866e02010-01-07 12:09:54 -08009125 if (Settings.Secure.getInt(mContext.getContentResolver(),
9126 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08009127 crashApplication(r, crashInfo);
9128 return true;
9129 } else {
9130 return false;
9131 }
9132 }
9133
9134 /**
9135 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
9136 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
9137 */
9138 private ProcessRecord findAppProcess(IBinder app) {
9139 if (app == null) {
9140 return null;
9141 }
9142
9143 synchronized (this) {
9144 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
9145 final int NA = apps.size();
9146 for (int ia=0; ia<NA; ia++) {
9147 ProcessRecord p = apps.valueAt(ia);
9148 if (p.thread != null && p.thread.asBinder() == app) {
9149 return p;
9150 }
9151 }
9152 }
9153
Joe Onorato8a9b2202010-02-26 18:56:32 -08009154 Slog.w(TAG, "Can't find mystery application: " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08009155 return null;
9156 }
9157 }
9158
9159 /**
Dan Egnor42471dd2010-01-07 17:25:22 -08009160 * Write a description of an error (crash, WTF, ANR) to the drop box.
Dan Egnor60d87622009-12-16 16:32:58 -08009161 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
Dan Egnor42471dd2010-01-07 17:25:22 -08009162 * @param process which caused the error, null means the system server
9163 * @param activity which triggered the error, null if unknown
9164 * @param parent activity related to the error, null if unknown
9165 * @param subject line related to the error, null if absent
9166 * @param report in long form describing the error, null if absent
9167 * @param logFile to include in the report, null if none
9168 * @param crashInfo giving an application stack trace, null if absent
Dan Egnor60d87622009-12-16 16:32:58 -08009169 */
Dan Egnor9bdc94b2010-03-04 14:20:31 -08009170 public void addErrorToDropBox(String eventType,
Dan Egnora455d192010-03-12 08:52:28 -08009171 ProcessRecord process, HistoryRecord activity, HistoryRecord parent, String subject,
9172 final String report, final File logFile,
9173 final ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnor9bdc94b2010-03-04 14:20:31 -08009174 // NOTE -- this must never acquire the ActivityManagerService lock,
9175 // otherwise the watchdog may be prevented from resetting the system.
9176
Dan Egnora455d192010-03-12 08:52:28 -08009177 String prefix;
Dan Egnor42471dd2010-01-07 17:25:22 -08009178 if (process == null || process.pid == MY_PID) {
Dan Egnora455d192010-03-12 08:52:28 -08009179 prefix = "system_server_";
Dan Egnor42471dd2010-01-07 17:25:22 -08009180 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Dan Egnora455d192010-03-12 08:52:28 -08009181 prefix = "system_app_";
Dan Egnor60d87622009-12-16 16:32:58 -08009182 } else {
Dan Egnora455d192010-03-12 08:52:28 -08009183 prefix = "data_app_";
Dan Egnor60d87622009-12-16 16:32:58 -08009184 }
9185
Dan Egnora455d192010-03-12 08:52:28 -08009186 final String dropboxTag = prefix + eventType;
9187 final DropBoxManager dbox = (DropBoxManager)
9188 mContext.getSystemService(Context.DROPBOX_SERVICE);
9189
9190 // Exit early if the dropbox isn't configured to accept this report type.
9191 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
9192
9193 final StringBuilder sb = new StringBuilder(1024);
9194 if (process == null || process.pid == MY_PID) {
9195 sb.append("Process: system_server\n");
9196 } else {
9197 sb.append("Process: ").append(process.processName).append("\n");
9198 }
9199 if (process != null) {
9200 int flags = process.info.flags;
9201 IPackageManager pm = ActivityThread.getPackageManager();
9202 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
9203 for (String pkg : process.pkgList) {
9204 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08009205 try {
Dan Egnora455d192010-03-12 08:52:28 -08009206 PackageInfo pi = pm.getPackageInfo(pkg, 0);
9207 if (pi != null) {
9208 sb.append(" v").append(pi.versionCode);
9209 if (pi.versionName != null) {
9210 sb.append(" (").append(pi.versionName).append(")");
9211 }
9212 }
9213 } catch (RemoteException e) {
9214 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08009215 }
Dan Egnora455d192010-03-12 08:52:28 -08009216 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08009217 }
Dan Egnora455d192010-03-12 08:52:28 -08009218 }
9219 if (activity != null) {
9220 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
9221 }
9222 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
9223 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
9224 }
9225 if (parent != null && parent != activity) {
9226 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
9227 }
9228 if (subject != null) {
9229 sb.append("Subject: ").append(subject).append("\n");
9230 }
9231 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
9232 sb.append("\n");
9233
9234 // Do the rest in a worker thread to avoid blocking the caller on I/O
9235 // (After this point, we shouldn't access AMS internal data structures.)
9236 Thread worker = new Thread("Error dump: " + dropboxTag) {
9237 @Override
9238 public void run() {
9239 if (report != null) {
9240 sb.append(report);
9241 }
9242 if (logFile != null) {
9243 try {
9244 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
9245 } catch (IOException e) {
9246 Slog.e(TAG, "Error reading " + logFile, e);
9247 }
9248 }
9249 if (crashInfo != null && crashInfo.stackTrace != null) {
9250 sb.append(crashInfo.stackTrace);
9251 }
9252
9253 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
9254 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
9255 if (lines > 0) {
9256 sb.append("\n");
9257
9258 // Merge several logcat streams, and take the last N lines
9259 InputStreamReader input = null;
9260 try {
9261 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
9262 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
9263 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
9264
9265 try { logcat.getOutputStream().close(); } catch (IOException e) {}
9266 try { logcat.getErrorStream().close(); } catch (IOException e) {}
9267 input = new InputStreamReader(logcat.getInputStream());
9268
9269 int num;
9270 char[] buf = new char[8192];
9271 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
9272 } catch (IOException e) {
9273 Slog.e(TAG, "Error running logcat", e);
9274 } finally {
9275 if (input != null) try { input.close(); } catch (IOException e) {}
9276 }
9277 }
9278
9279 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08009280 }
Dan Egnora455d192010-03-12 08:52:28 -08009281 };
9282
9283 if (process == null || process.pid == MY_PID) {
9284 worker.run(); // We may be about to die -- need to run this synchronously
9285 } else {
9286 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08009287 }
9288 }
9289
9290 /**
9291 * Bring up the "unexpected error" dialog box for a crashing app.
9292 * Deal with edge cases (intercepts from instrumented applications,
9293 * ActivityController, error intent receivers, that sort of thing).
9294 * @param r the application crashing
9295 * @param crashInfo describing the failure
9296 */
9297 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08009298 long timeMillis = System.currentTimeMillis();
9299 String shortMsg = crashInfo.exceptionClassName;
9300 String longMsg = crashInfo.exceptionMessage;
9301 String stackTrace = crashInfo.stackTrace;
9302 if (shortMsg != null && longMsg != null) {
9303 longMsg = shortMsg + ": " + longMsg;
9304 } else if (shortMsg != null) {
9305 longMsg = shortMsg;
9306 }
9307
Dan Egnor60d87622009-12-16 16:32:58 -08009308 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009309 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07009310 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009311 try {
9312 String name = r != null ? r.processName : null;
9313 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08009314 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08009315 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009316 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009317 + " at watcher's request");
9318 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08009319 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009320 }
9321 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07009322 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009323 }
9324 }
9325
9326 final long origId = Binder.clearCallingIdentity();
9327
9328 // If this process is running instrumentation, finish it.
9329 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009330 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009331 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08009332 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
9333 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009334 Bundle info = new Bundle();
9335 info.putString("shortMsg", shortMsg);
9336 info.putString("longMsg", longMsg);
9337 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
9338 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08009339 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009340 }
9341
Dan Egnor60d87622009-12-16 16:32:58 -08009342 // If we can't identify the process or it's already exceeded its crash quota,
9343 // quit right away without showing a crash dialog.
9344 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009345 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08009346 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009347 }
9348
9349 Message msg = Message.obtain();
9350 msg.what = SHOW_ERROR_MSG;
9351 HashMap data = new HashMap();
9352 data.put("result", result);
9353 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009354 msg.obj = data;
9355 mHandler.sendMessage(msg);
9356
9357 Binder.restoreCallingIdentity(origId);
9358 }
9359
9360 int res = result.get();
9361
Jacek Surazskif5b9c722009-05-18 12:09:59 +02009362 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009363 synchronized (this) {
9364 if (r != null) {
9365 mProcessCrashTimes.put(r.info.processName, r.info.uid,
9366 SystemClock.uptimeMillis());
9367 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02009368 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08009369 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02009370 }
9371 }
9372
9373 if (appErrorIntent != null) {
9374 try {
9375 mContext.startActivity(appErrorIntent);
9376 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009377 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02009378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009380 }
Dan Egnorb7f03672009-12-09 16:22:32 -08009381
9382 Intent createAppErrorIntentLocked(ProcessRecord r,
9383 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
9384 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02009385 if (report == null) {
9386 return null;
9387 }
9388 Intent result = new Intent(Intent.ACTION_APP_ERROR);
9389 result.setComponent(r.errorReportReceiver);
9390 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
9391 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
9392 return result;
9393 }
9394
Dan Egnorb7f03672009-12-09 16:22:32 -08009395 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
9396 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02009397 if (r.errorReportReceiver == null) {
9398 return null;
9399 }
9400
9401 if (!r.crashing && !r.notResponding) {
9402 return null;
9403 }
9404
Dan Egnorb7f03672009-12-09 16:22:32 -08009405 ApplicationErrorReport report = new ApplicationErrorReport();
9406 report.packageName = r.info.packageName;
9407 report.installerPackageName = r.errorReportReceiver.getPackageName();
9408 report.processName = r.processName;
9409 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01009410 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02009411
Dan Egnorb7f03672009-12-09 16:22:32 -08009412 if (r.crashing) {
9413 report.type = ApplicationErrorReport.TYPE_CRASH;
9414 report.crashInfo = crashInfo;
9415 } else if (r.notResponding) {
9416 report.type = ApplicationErrorReport.TYPE_ANR;
9417 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02009418
Dan Egnorb7f03672009-12-09 16:22:32 -08009419 report.anrInfo.activity = r.notRespondingReport.tag;
9420 report.anrInfo.cause = r.notRespondingReport.shortMsg;
9421 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02009422 }
9423
Dan Egnorb7f03672009-12-09 16:22:32 -08009424 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02009425 }
9426
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009427 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
9428 // assume our apps are happy - lazy create the list
9429 List<ActivityManager.ProcessErrorStateInfo> errList = null;
9430
9431 synchronized (this) {
9432
9433 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08009434 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9435 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009436 if ((app.thread != null) && (app.crashing || app.notResponding)) {
9437 // This one's in trouble, so we'll generate a report for it
9438 // crashes are higher priority (in case there's a crash *and* an anr)
9439 ActivityManager.ProcessErrorStateInfo report = null;
9440 if (app.crashing) {
9441 report = app.crashingReport;
9442 } else if (app.notResponding) {
9443 report = app.notRespondingReport;
9444 }
9445
9446 if (report != null) {
9447 if (errList == null) {
9448 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
9449 }
9450 errList.add(report);
9451 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009452 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009453 " crashing = " + app.crashing +
9454 " notResponding = " + app.notResponding);
9455 }
9456 }
9457 }
9458 }
9459
9460 return errList;
9461 }
9462
9463 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
9464 // Lazy instantiation of list
9465 List<ActivityManager.RunningAppProcessInfo> runList = null;
9466 synchronized (this) {
9467 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08009468 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9469 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009470 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
9471 // Generate process state info for running application
9472 ActivityManager.RunningAppProcessInfo currApp =
9473 new ActivityManager.RunningAppProcessInfo(app.processName,
9474 app.pid, app.getPackageList());
Dianne Hackborneb034652009-09-07 00:49:58 -07009475 currApp.uid = app.info.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009476 int adj = app.curAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08009477 if (adj >= EMPTY_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009478 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_EMPTY;
9479 } else if (adj >= HIDDEN_APP_MIN_ADJ) {
9480 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
The Android Open Source Project4df24232009-03-05 14:34:35 -08009481 currApp.lru = adj - HIDDEN_APP_MIN_ADJ + 1;
9482 } else if (adj >= HOME_APP_ADJ) {
9483 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
9484 currApp.lru = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009485 } else if (adj >= SECONDARY_SERVER_ADJ) {
9486 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
9487 } else if (adj >= VISIBLE_APP_ADJ) {
9488 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
9489 } else {
9490 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
9491 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07009492 currApp.importanceReasonCode = app.adjTypeCode;
9493 if (app.adjSource instanceof ProcessRecord) {
9494 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
9495 } else if (app.adjSource instanceof HistoryRecord) {
9496 HistoryRecord r = (HistoryRecord)app.adjSource;
9497 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
9498 }
9499 if (app.adjTarget instanceof ComponentName) {
9500 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
9501 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08009502 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009503 // + " lru=" + currApp.lru);
9504 if (runList == null) {
9505 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
9506 }
9507 runList.add(currApp);
9508 }
9509 }
9510 }
9511 return runList;
9512 }
9513
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07009514 public List<ApplicationInfo> getRunningExternalApplications() {
9515 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
9516 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
9517 if (runningApps != null && runningApps.size() > 0) {
9518 Set<String> extList = new HashSet<String>();
9519 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
9520 if (app.pkgList != null) {
9521 for (String pkg : app.pkgList) {
9522 extList.add(pkg);
9523 }
9524 }
9525 }
9526 IPackageManager pm = ActivityThread.getPackageManager();
9527 for (String pkg : extList) {
9528 try {
9529 ApplicationInfo info = pm.getApplicationInfo(pkg, 0);
9530 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
9531 retList.add(info);
9532 }
9533 } catch (RemoteException e) {
9534 }
9535 }
9536 }
9537 return retList;
9538 }
9539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009540 @Override
9541 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009542 if (checkCallingPermission(android.Manifest.permission.DUMP)
9543 != PackageManager.PERMISSION_GRANTED) {
9544 pw.println("Permission Denial: can't dump ActivityManager from from pid="
9545 + Binder.getCallingPid()
9546 + ", uid=" + Binder.getCallingUid()
9547 + " without permission "
9548 + android.Manifest.permission.DUMP);
9549 return;
9550 }
9551
9552 boolean dumpAll = false;
9553
9554 int opti = 0;
9555 while (opti < args.length) {
9556 String opt = args[opti];
9557 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9558 break;
9559 }
9560 opti++;
9561 if ("-a".equals(opt)) {
9562 dumpAll = true;
9563 } else if ("-h".equals(opt)) {
9564 pw.println("Activity manager dump options:");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009565 pw.println(" [-a] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009566 pw.println(" cmd may be one of:");
9567 pw.println(" activities: activity stack state");
9568 pw.println(" broadcasts: broadcast state");
9569 pw.println(" intents: pending intent state");
9570 pw.println(" processes: process state");
9571 pw.println(" providers: content provider state");
9572 pw.println(" services: service state");
9573 pw.println(" service [name]: service client-side state");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009574 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009575 } else {
9576 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009577 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009578 }
9579
9580 // Is the caller requesting to dump a particular piece of data?
9581 if (opti < args.length) {
9582 String cmd = args[opti];
9583 opti++;
9584 if ("activities".equals(cmd) || "a".equals(cmd)) {
9585 synchronized (this) {
9586 dumpActivitiesLocked(fd, pw, args, opti, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009587 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009588 return;
9589 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
9590 synchronized (this) {
9591 dumpBroadcastsLocked(fd, pw, args, opti, true);
9592 }
9593 return;
9594 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
9595 synchronized (this) {
9596 dumpPendingIntentsLocked(fd, pw, args, opti, true);
9597 }
9598 return;
9599 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
9600 synchronized (this) {
9601 dumpProcessesLocked(fd, pw, args, opti, true);
9602 }
9603 return;
9604 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
9605 synchronized (this) {
9606 dumpProvidersLocked(fd, pw, args, opti, true);
9607 }
9608 return;
9609 } else if ("service".equals(cmd)) {
9610 dumpService(fd, pw, args, opti, true);
9611 return;
9612 } else if ("services".equals(cmd) || "s".equals(cmd)) {
9613 synchronized (this) {
9614 dumpServicesLocked(fd, pw, args, opti, true);
9615 }
9616 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009617 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009618 }
9619
9620 // No piece of data specified, dump everything.
9621 synchronized (this) {
9622 boolean needSep;
9623 if (dumpAll) {
9624 pw.println("Providers in Current Activity Manager State:");
9625 }
9626 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll);
9627 if (needSep) {
9628 pw.println(" ");
9629 }
9630 if (dumpAll) {
9631 pw.println("-------------------------------------------------------------------------------");
9632 pw.println("Broadcasts in Current Activity Manager State:");
9633 }
9634 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll);
9635 if (needSep) {
9636 pw.println(" ");
9637 }
9638 if (dumpAll) {
9639 pw.println("-------------------------------------------------------------------------------");
9640 pw.println("Services in Current Activity Manager State:");
9641 }
9642 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll);
9643 if (needSep) {
9644 pw.println(" ");
9645 }
9646 if (dumpAll) {
9647 pw.println("-------------------------------------------------------------------------------");
9648 pw.println("PendingIntents in Current Activity Manager State:");
9649 }
9650 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll);
9651 if (needSep) {
9652 pw.println(" ");
9653 }
9654 if (dumpAll) {
9655 pw.println("-------------------------------------------------------------------------------");
9656 pw.println("Activities in Current Activity Manager State:");
9657 }
9658 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, !dumpAll);
9659 if (needSep) {
9660 pw.println(" ");
9661 }
9662 if (dumpAll) {
9663 pw.println("-------------------------------------------------------------------------------");
9664 pw.println("Processes in Current Activity Manager State:");
9665 }
9666 dumpProcessesLocked(fd, pw, args, opti, dumpAll);
9667 }
9668 }
9669
9670 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9671 int opti, boolean dumpAll, boolean needHeader) {
9672 if (needHeader) {
9673 pw.println(" Activity stack:");
9674 }
9675 dumpHistoryList(pw, mHistory, " ", "Hist", true);
9676 pw.println(" ");
9677 pw.println(" Running activities (most recent first):");
9678 dumpHistoryList(pw, mLRUActivities, " ", "Run", false);
9679 if (mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009680 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009681 pw.println(" Activities waiting for another to become visible:");
9682 dumpHistoryList(pw, mWaitingVisibleActivities, " ", "Wait", false);
9683 }
9684 if (mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009685 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009686 pw.println(" Activities waiting to stop:");
9687 dumpHistoryList(pw, mStoppingActivities, " ", "Stop", false);
9688 }
9689 if (mFinishingActivities.size() > 0) {
9690 pw.println(" ");
9691 pw.println(" Activities waiting to finish:");
9692 dumpHistoryList(pw, mFinishingActivities, " ", "Fin", false);
9693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009694
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009695 pw.println(" ");
9696 pw.println(" mPausingActivity: " + mPausingActivity);
9697 pw.println(" mResumedActivity: " + mResumedActivity);
9698 pw.println(" mFocusedActivity: " + mFocusedActivity);
9699 pw.println(" mLastPausedActivity: " + mLastPausedActivity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009700
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009701 if (dumpAll && mRecentTasks.size() > 0) {
9702 pw.println(" ");
9703 pw.println("Recent tasks in Current Activity Manager State:");
9704
9705 final int N = mRecentTasks.size();
9706 for (int i=0; i<N; i++) {
9707 TaskRecord tr = mRecentTasks.get(i);
9708 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9709 pw.println(tr);
9710 mRecentTasks.get(i).dump(pw, " ");
9711 }
9712 }
9713
9714 pw.println(" ");
9715 pw.println(" mCurTask: " + mCurTask);
9716
9717 return true;
9718 }
9719
9720 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9721 int opti, boolean dumpAll) {
9722 boolean needSep = false;
9723 int numPers = 0;
9724
9725 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009726 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9727 final int NA = procs.size();
9728 for (int ia=0; ia<NA; ia++) {
9729 if (!needSep) {
9730 pw.println(" All known processes:");
9731 needSep = true;
9732 }
9733 ProcessRecord r = procs.valueAt(ia);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009734 pw.print(r.persistent ? " *PERS*" : " *APP*");
9735 pw.print(" UID "); pw.print(procs.keyAt(ia));
9736 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009737 r.dump(pw, " ");
9738 if (r.persistent) {
9739 numPers++;
9740 }
9741 }
9742 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009743 }
9744
9745 if (mLruProcesses.size() > 0) {
9746 if (needSep) pw.println(" ");
9747 needSep = true;
9748 pw.println(" Running processes (most recent first):");
9749 dumpProcessList(pw, this, mLruProcesses, " ",
9750 "App ", "PERS", true);
9751 needSep = true;
9752 }
9753
9754 synchronized (mPidsSelfLocked) {
9755 if (mPidsSelfLocked.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009756 if (needSep) pw.println(" ");
9757 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009758 pw.println(" PID mappings:");
9759 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9760 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9761 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009762 }
9763 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009764 }
9765
9766 if (mForegroundProcesses.size() > 0) {
9767 if (needSep) pw.println(" ");
9768 needSep = true;
9769 pw.println(" Foreground Processes:");
9770 for (int i=0; i<mForegroundProcesses.size(); i++) {
9771 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9772 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009773 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009774 }
9775
9776 if (mPersistentStartingProcesses.size() > 0) {
9777 if (needSep) pw.println(" ");
9778 needSep = true;
9779 pw.println(" Persisent processes that are starting:");
9780 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
9781 "Starting Norm", "Restarting PERS", false);
9782 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009783
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009784 if (mStartingProcesses.size() > 0) {
9785 if (needSep) pw.println(" ");
9786 needSep = true;
9787 pw.println(" Processes that are starting:");
9788 dumpProcessList(pw, this, mStartingProcesses, " ",
9789 "Starting Norm", "Starting PERS", false);
9790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009791
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009792 if (mRemovedProcesses.size() > 0) {
9793 if (needSep) pw.println(" ");
9794 needSep = true;
9795 pw.println(" Processes that are being removed:");
9796 dumpProcessList(pw, this, mRemovedProcesses, " ",
9797 "Removed Norm", "Removed PERS", false);
9798 }
9799
9800 if (mProcessesOnHold.size() > 0) {
9801 if (needSep) pw.println(" ");
9802 needSep = true;
9803 pw.println(" Processes that are on old until the system is ready:");
9804 dumpProcessList(pw, this, mProcessesOnHold, " ",
9805 "OnHold Norm", "OnHold PERS", false);
9806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009807
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009808 if (mProcessesToGc.size() > 0) {
9809 if (needSep) pw.println(" ");
9810 needSep = true;
9811 pw.println(" Processes that are waiting to GC:");
9812 long now = SystemClock.uptimeMillis();
9813 for (int i=0; i<mProcessesToGc.size(); i++) {
9814 ProcessRecord proc = mProcessesToGc.get(i);
9815 pw.print(" Process "); pw.println(proc);
9816 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9817 pw.print(", last gced=");
9818 pw.print(now-proc.lastRequestedGc);
9819 pw.print(" ms ago, last lowMem=");
9820 pw.print(now-proc.lastLowMemory);
9821 pw.println(" ms ago");
9822
9823 }
9824 }
9825
9826 if (mProcessCrashTimes.getMap().size() > 0) {
9827 if (needSep) pw.println(" ");
9828 needSep = true;
9829 pw.println(" Time since processes crashed:");
9830 long now = SystemClock.uptimeMillis();
9831 for (Map.Entry<String, SparseArray<Long>> procs
9832 : mProcessCrashTimes.getMap().entrySet()) {
9833 SparseArray<Long> uids = procs.getValue();
9834 final int N = uids.size();
9835 for (int i=0; i<N; i++) {
9836 pw.print(" Process "); pw.print(procs.getKey());
9837 pw.print(" uid "); pw.print(uids.keyAt(i));
9838 pw.print(": last crashed ");
9839 pw.print((now-uids.valueAt(i)));
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009840 pw.println(" ms ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009841 }
9842 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009844
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009845 if (mBadProcesses.getMap().size() > 0) {
9846 if (needSep) pw.println(" ");
9847 needSep = true;
9848 pw.println(" Bad processes:");
9849 for (Map.Entry<String, SparseArray<Long>> procs
9850 : mBadProcesses.getMap().entrySet()) {
9851 SparseArray<Long> uids = procs.getValue();
9852 final int N = uids.size();
9853 for (int i=0; i<N; i++) {
9854 pw.print(" Bad process "); pw.print(procs.getKey());
9855 pw.print(" uid "); pw.print(uids.keyAt(i));
9856 pw.print(": crashed at time ");
9857 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009858 }
9859 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009860 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009861
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009862 pw.println(" ");
9863 pw.println(" mHomeProcess: " + mHomeProcess);
9864 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackbornd49258f2010-03-26 00:44:29 -07009865 pw.println(" mConfigWillChange: " + mConfigWillChange);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009866 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
9867 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9868 || mOrigWaitForDebugger) {
9869 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9870 + " mDebugTransient=" + mDebugTransient
9871 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9872 }
9873 if (mAlwaysFinishActivities || mController != null) {
9874 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9875 + " mController=" + mController);
9876 }
9877 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009878 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009879 pw.println(" mStartRunning=" + mStartRunning
9880 + " mSystemReady=" + mSystemReady
9881 + " mBooting=" + mBooting
9882 + " mBooted=" + mBooted
9883 + " mFactoryTest=" + mFactoryTest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009884 pw.println(" mGoingToSleep=" + mGoingToSleep);
9885 pw.println(" mLaunchingActivity=" + mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009886 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009887 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009888
9889 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009890 }
9891
9892 /**
9893 * There are three ways to call this:
9894 * - no service specified: dump all the services
9895 * - a flattened component name that matched an existing service was specified as the
9896 * first arg: dump that one service
9897 * - the first arg isn't the flattened component name of an existing service:
9898 * dump all services whose component contains the first arg as a substring
9899 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009900 protected void dumpService(FileDescriptor fd, PrintWriter pw, String[] args,
9901 int opti, boolean dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009902 String[] newArgs;
9903 String componentNameString;
9904 ServiceRecord r;
Kenny Root3619b9ab2010-02-13 10:05:42 -08009905 if (opti >= args.length) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009906 componentNameString = null;
9907 newArgs = EMPTY_STRING_ARRAY;
9908 r = null;
9909 } else {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009910 componentNameString = args[opti];
9911 opti++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009912 ComponentName componentName = ComponentName.unflattenFromString(componentNameString);
9913 r = componentName != null ? mServices.get(componentName) : null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009914 newArgs = new String[args.length - opti];
9915 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009916 }
9917
9918 if (r != null) {
9919 dumpService(fd, pw, r, newArgs);
9920 } else {
9921 for (ServiceRecord r1 : mServices.values()) {
9922 if (componentNameString == null
9923 || r1.name.flattenToString().contains(componentNameString)) {
9924 dumpService(fd, pw, r1, newArgs);
9925 }
9926 }
9927 }
9928 }
9929
9930 /**
9931 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
9932 * there is a thread associated with the service.
9933 */
9934 private void dumpService(FileDescriptor fd, PrintWriter pw, ServiceRecord r, String[] args) {
9935 pw.println(" Service " + r.name.flattenToString());
9936 if (r.app != null && r.app.thread != null) {
9937 try {
9938 // flush anything that is already in the PrintWriter since the thread is going
9939 // to write to the file descriptor directly
9940 pw.flush();
9941 r.app.thread.dumpService(fd, r, args);
9942 pw.print("\n");
9943 } catch (RemoteException e) {
9944 pw.println("got a RemoteException while dumping the service");
9945 }
9946 }
9947 }
9948
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009949 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9950 int opti, boolean dumpAll) {
9951 boolean needSep = false;
9952
9953 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009954 if (mRegisteredReceivers.size() > 0) {
9955 pw.println(" ");
9956 pw.println(" Registered Receivers:");
9957 Iterator it = mRegisteredReceivers.values().iterator();
9958 while (it.hasNext()) {
9959 ReceiverList r = (ReceiverList)it.next();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009960 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009961 r.dump(pw, " ");
9962 }
9963 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009965 pw.println(" ");
9966 pw.println("Receiver Resolver Table:");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009967 mReceiverResolver.dump(pw, null, " ", null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009968 needSep = true;
9969 }
9970
9971 if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
9972 || mPendingBroadcast != null) {
9973 if (mParallelBroadcasts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009974 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009975 pw.println(" Active broadcasts:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009976 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009977 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
9978 pw.println(" Broadcast #" + i + ":");
9979 mParallelBroadcasts.get(i).dump(pw, " ");
9980 }
9981 if (mOrderedBroadcasts.size() > 0) {
9982 pw.println(" ");
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009983 pw.println(" Active ordered broadcasts:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009984 }
9985 for (int i=mOrderedBroadcasts.size()-1; i>=0; i--) {
9986 pw.println(" Serialized Broadcast #" + i + ":");
9987 mOrderedBroadcasts.get(i).dump(pw, " ");
9988 }
9989 pw.println(" ");
9990 pw.println(" Pending broadcast:");
9991 if (mPendingBroadcast != null) {
9992 mPendingBroadcast.dump(pw, " ");
9993 } else {
9994 pw.println(" (null)");
9995 }
9996 needSep = true;
9997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009998
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009999 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010000 pw.println(" ");
Dianne Hackborn12527f92009-11-11 17:39:50 -080010001 pw.println(" Historical broadcasts:");
10002 for (int i=0; i<MAX_BROADCAST_HISTORY; i++) {
10003 BroadcastRecord r = mBroadcastHistory[i];
10004 if (r == null) {
10005 break;
10006 }
10007 pw.println(" Historical Broadcast #" + i + ":");
10008 r.dump(pw, " ");
10009 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010010 needSep = true;
10011 }
10012
10013 if (mStickyBroadcasts != null) {
Dianne Hackborn12527f92009-11-11 17:39:50 -080010014 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010015 pw.println(" Sticky broadcasts:");
10016 StringBuilder sb = new StringBuilder(128);
10017 for (Map.Entry<String, ArrayList<Intent>> ent
10018 : mStickyBroadcasts.entrySet()) {
10019 pw.print(" * Sticky action "); pw.print(ent.getKey());
10020 pw.println(":");
10021 ArrayList<Intent> intents = ent.getValue();
10022 final int N = intents.size();
10023 for (int i=0; i<N; i++) {
10024 sb.setLength(0);
10025 sb.append(" Intent: ");
10026 intents.get(i).toShortString(sb, true, false);
10027 pw.println(sb.toString());
10028 Bundle bundle = intents.get(i).getExtras();
10029 if (bundle != null) {
10030 pw.print(" ");
10031 pw.println(bundle.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010032 }
10033 }
10034 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010035 needSep = true;
10036 }
10037
10038 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010039 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010040 pw.println(" mBroadcastsScheduled=" + mBroadcastsScheduled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010041 pw.println(" mHandler:");
10042 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010043 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010044 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010045
10046 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010047 }
10048
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010049 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
10050 int opti, boolean dumpAll) {
10051 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010052
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010053 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010054 if (mServices.size() > 0) {
10055 pw.println(" Active services:");
10056 Iterator<ServiceRecord> it = mServices.values().iterator();
10057 while (it.hasNext()) {
10058 ServiceRecord r = it.next();
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010059 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010060 r.dump(pw, " ");
10061 }
10062 needSep = true;
10063 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010065
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010066 if (mPendingServices.size() > 0) {
10067 if (needSep) pw.println(" ");
10068 pw.println(" Pending services:");
10069 for (int i=0; i<mPendingServices.size(); i++) {
10070 ServiceRecord r = mPendingServices.get(i);
10071 pw.print(" * Pending "); pw.println(r);
10072 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010073 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010074 needSep = true;
10075 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010076
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010077 if (mRestartingServices.size() > 0) {
10078 if (needSep) pw.println(" ");
10079 pw.println(" Restarting services:");
10080 for (int i=0; i<mRestartingServices.size(); i++) {
10081 ServiceRecord r = mRestartingServices.get(i);
10082 pw.print(" * Restarting "); pw.println(r);
10083 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010084 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010085 needSep = true;
10086 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010087
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010088 if (mStoppingServices.size() > 0) {
10089 if (needSep) pw.println(" ");
10090 pw.println(" Stopping services:");
10091 for (int i=0; i<mStoppingServices.size(); i++) {
10092 ServiceRecord r = mStoppingServices.get(i);
10093 pw.print(" * Stopping "); pw.println(r);
10094 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010095 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010096 needSep = true;
10097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010098
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010099 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010100 if (mServiceConnections.size() > 0) {
10101 if (needSep) pw.println(" ");
10102 pw.println(" Connection bindings to services:");
10103 Iterator<ConnectionRecord> it
10104 = mServiceConnections.values().iterator();
10105 while (it.hasNext()) {
10106 ConnectionRecord r = it.next();
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010107 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010108 r.dump(pw, " ");
10109 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010110 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010111 }
10112 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010113
10114 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010115 }
10116
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010117 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
10118 int opti, boolean dumpAll) {
10119 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010120
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010121 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010122 if (mProvidersByClass.size() > 0) {
10123 if (needSep) pw.println(" ");
10124 pw.println(" Published content providers (by class):");
10125 Iterator it = mProvidersByClass.entrySet().iterator();
10126 while (it.hasNext()) {
10127 Map.Entry e = (Map.Entry)it.next();
10128 ContentProviderRecord r = (ContentProviderRecord)e.getValue();
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010129 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010130 r.dump(pw, " ");
10131 }
10132 needSep = true;
10133 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010134
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010135 if (mProvidersByName.size() > 0) {
10136 pw.println(" ");
10137 pw.println(" Authority to provider mappings:");
10138 Iterator it = mProvidersByName.entrySet().iterator();
10139 while (it.hasNext()) {
10140 Map.Entry e = (Map.Entry)it.next();
10141 ContentProviderRecord r = (ContentProviderRecord)e.getValue();
10142 pw.print(" "); pw.print(e.getKey()); pw.print(": ");
10143 pw.println(r);
10144 }
10145 needSep = true;
10146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010147 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010148
10149 if (mLaunchingProviders.size() > 0) {
10150 if (needSep) pw.println(" ");
10151 pw.println(" Launching content providers:");
10152 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
10153 pw.print(" Launching #"); pw.print(i); pw.print(": ");
10154 pw.println(mLaunchingProviders.get(i));
10155 }
10156 needSep = true;
10157 }
10158
10159 if (mGrantedUriPermissions.size() > 0) {
10160 pw.println();
10161 pw.println("Granted Uri Permissions:");
10162 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
10163 int uid = mGrantedUriPermissions.keyAt(i);
10164 HashMap<Uri, UriPermission> perms
10165 = mGrantedUriPermissions.valueAt(i);
10166 pw.print(" * UID "); pw.print(uid);
10167 pw.println(" holds:");
10168 for (UriPermission perm : perms.values()) {
10169 pw.print(" "); pw.println(perm);
10170 perm.dump(pw, " ");
10171 }
10172 }
10173 needSep = true;
10174 }
10175
10176 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010177 }
10178
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010179 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
10180 int opti, boolean dumpAll) {
10181 boolean needSep = false;
10182
10183 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010184 if (this.mIntentSenderRecords.size() > 0) {
10185 Iterator<WeakReference<PendingIntentRecord>> it
10186 = mIntentSenderRecords.values().iterator();
10187 while (it.hasNext()) {
10188 WeakReference<PendingIntentRecord> ref = it.next();
10189 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010190 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010191 if (rec != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010192 pw.print(" * "); pw.println(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010193 rec.dump(pw, " ");
10194 } else {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010195 pw.print(" * "); pw.print(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010196 }
10197 }
10198 }
10199 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010200
10201 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010202 }
10203
10204 private static final void dumpHistoryList(PrintWriter pw, List list,
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010205 String prefix, String label, boolean complete) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010206 TaskRecord lastTask = null;
10207 for (int i=list.size()-1; i>=0; i--) {
10208 HistoryRecord r = (HistoryRecord)list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010209 final boolean full = complete || !r.inHistory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010210 if (lastTask != r.task) {
10211 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010212 pw.print(prefix);
10213 pw.print(full ? "* " : " ");
10214 pw.println(lastTask);
10215 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010216 lastTask.dump(pw, prefix + " ");
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010218 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010219 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
10220 pw.print(" #"); pw.print(i); pw.print(": ");
10221 pw.println(r);
10222 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010223 r.dump(pw, prefix + " ");
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010224 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010225 }
10226 }
10227
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010228 private static String buildOomTag(String prefix, String space, int val, int base) {
10229 if (val == base) {
10230 if (space == null) return prefix;
10231 return prefix + " ";
10232 }
10233 return prefix + "+" + Integer.toString(val-base);
10234 }
10235
10236 private static final int dumpProcessList(PrintWriter pw,
10237 ActivityManagerService service, List list,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010238 String prefix, String normalLabel, String persistentLabel,
10239 boolean inclOomAdj) {
10240 int numPers = 0;
10241 for (int i=list.size()-1; i>=0; i--) {
10242 ProcessRecord r = (ProcessRecord)list.get(i);
10243 if (false) {
10244 pw.println(prefix + (r.persistent ? persistentLabel : normalLabel)
10245 + " #" + i + ":");
10246 r.dump(pw, prefix + " ");
10247 } else if (inclOomAdj) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010248 String oomAdj;
10249 if (r.setAdj >= EMPTY_APP_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010250 oomAdj = buildOomTag("empty", null, r.setAdj, EMPTY_APP_ADJ);
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010251 } else if (r.setAdj >= HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010252 oomAdj = buildOomTag("bak", " ", r.setAdj, HIDDEN_APP_MIN_ADJ);
10253 } else if (r.setAdj >= HOME_APP_ADJ) {
10254 oomAdj = buildOomTag("home ", null, r.setAdj, HOME_APP_ADJ);
10255 } else if (r.setAdj >= SECONDARY_SERVER_ADJ) {
10256 oomAdj = buildOomTag("svc", " ", r.setAdj, SECONDARY_SERVER_ADJ);
10257 } else if (r.setAdj >= BACKUP_APP_ADJ) {
10258 oomAdj = buildOomTag("bckup", null, r.setAdj, BACKUP_APP_ADJ);
10259 } else if (r.setAdj >= VISIBLE_APP_ADJ) {
10260 oomAdj = buildOomTag("vis ", null, r.setAdj, VISIBLE_APP_ADJ);
10261 } else if (r.setAdj >= FOREGROUND_APP_ADJ) {
10262 oomAdj = buildOomTag("fore ", null, r.setAdj, FOREGROUND_APP_ADJ);
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010263 } else if (r.setAdj >= CORE_SERVER_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010264 oomAdj = buildOomTag("core ", null, r.setAdj, CORE_SERVER_ADJ);
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010265 } else if (r.setAdj >= SYSTEM_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010266 oomAdj = buildOomTag("sys ", null, r.setAdj, SYSTEM_ADJ);
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010267 } else {
10268 oomAdj = Integer.toString(r.setAdj);
10269 }
10270 String schedGroup;
10271 switch (r.setSchedGroup) {
10272 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
10273 schedGroup = "B";
10274 break;
10275 case Process.THREAD_GROUP_DEFAULT:
10276 schedGroup = "F";
10277 break;
10278 default:
10279 schedGroup = Integer.toString(r.setSchedGroup);
10280 break;
10281 }
10282 pw.println(String.format("%s%s #%2d: adj=%s/%s %s (%s)",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010283 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010284 i, oomAdj, schedGroup, r.toShortString(), r.adjType));
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010285 if (r.adjSource != null || r.adjTarget != null) {
10286 pw.println(prefix + " " + r.adjTarget
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010287 + "<=" + r.adjSource);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010289 } else {
10290 pw.println(String.format("%s%s #%2d: %s",
10291 prefix, (r.persistent ? persistentLabel : normalLabel),
10292 i, r.toString()));
10293 }
10294 if (r.persistent) {
10295 numPers++;
10296 }
10297 }
10298 return numPers;
10299 }
10300
Dianne Hackborn472ad872010-04-07 17:31:48 -070010301 static final void dumpApplicationMemoryUsage(FileDescriptor fd,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010302 PrintWriter pw, List list, String prefix, String[] args) {
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010303 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010304 long uptime = SystemClock.uptimeMillis();
10305 long realtime = SystemClock.elapsedRealtime();
10306
10307 if (isCheckinRequest) {
10308 // short checkin version
10309 pw.println(uptime + "," + realtime);
10310 pw.flush();
10311 } else {
10312 pw.println("Applications Memory Usage (kB):");
10313 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10314 }
10315 for (int i = list.size() - 1 ; i >= 0 ; i--) {
10316 ProcessRecord r = (ProcessRecord)list.get(i);
10317 if (r.thread != null) {
10318 if (!isCheckinRequest) {
10319 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10320 pw.flush();
10321 }
10322 try {
10323 r.thread.asBinder().dump(fd, args);
10324 } catch (RemoteException e) {
10325 if (!isCheckinRequest) {
10326 pw.println("Got RemoteException!");
10327 pw.flush();
10328 }
10329 }
10330 }
10331 }
10332 }
10333
10334 /**
10335 * Searches array of arguments for the specified string
10336 * @param args array of argument strings
10337 * @param value value to search for
10338 * @return true if the value is contained in the array
10339 */
10340 private static boolean scanArgs(String[] args, String value) {
10341 if (args != null) {
10342 for (String arg : args) {
10343 if (value.equals(arg)) {
10344 return true;
10345 }
10346 }
10347 }
10348 return false;
10349 }
10350
Dianne Hackborn75b03852009-06-12 15:43:26 -070010351 private final int indexOfTokenLocked(IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010352 int count = mHistory.size();
10353
10354 // convert the token to an entry in the history.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010355 int index = -1;
10356 for (int i=count-1; i>=0; i--) {
10357 Object o = mHistory.get(i);
10358 if (o == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010359 index = i;
10360 break;
10361 }
10362 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010363
10364 return index;
10365 }
10366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010367 private final void killServicesLocked(ProcessRecord app,
10368 boolean allowRestart) {
10369 // Report disconnected services.
10370 if (false) {
10371 // XXX we are letting the client link to the service for
10372 // death notifications.
10373 if (app.services.size() > 0) {
10374 Iterator it = app.services.iterator();
10375 while (it.hasNext()) {
10376 ServiceRecord r = (ServiceRecord)it.next();
10377 if (r.connections.size() > 0) {
10378 Iterator<ConnectionRecord> jt
10379 = r.connections.values().iterator();
10380 while (jt.hasNext()) {
10381 ConnectionRecord c = jt.next();
10382 if (c.binding.client != app) {
10383 try {
10384 //c.conn.connected(r.className, null);
10385 } catch (Exception e) {
10386 // todo: this should be asynchronous!
Joe Onorato8a9b2202010-02-26 18:56:32 -080010387 Slog.w(TAG, "Exception thrown disconnected servce "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010388 + r.shortName
10389 + " from app " + app.processName, e);
10390 }
10391 }
10392 }
10393 }
10394 }
10395 }
10396 }
10397
10398 // Clean up any connections this application has to other services.
10399 if (app.connections.size() > 0) {
10400 Iterator<ConnectionRecord> it = app.connections.iterator();
10401 while (it.hasNext()) {
10402 ConnectionRecord r = it.next();
10403 removeConnectionLocked(r, app, null);
10404 }
10405 }
10406 app.connections.clear();
10407
10408 if (app.services.size() != 0) {
10409 // Any services running in the application need to be placed
10410 // back in the pending list.
10411 Iterator it = app.services.iterator();
10412 while (it.hasNext()) {
10413 ServiceRecord sr = (ServiceRecord)it.next();
10414 synchronized (sr.stats.getBatteryStats()) {
10415 sr.stats.stopLaunchedLocked();
10416 }
10417 sr.app = null;
10418 sr.executeNesting = 0;
10419 mStoppingServices.remove(sr);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010420
10421 boolean hasClients = sr.bindings.size() > 0;
10422 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010423 Iterator<IntentBindRecord> bindings
10424 = sr.bindings.values().iterator();
10425 while (bindings.hasNext()) {
10426 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010427 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010428 + ": shouldUnbind=" + b.hasBound);
10429 b.binder = null;
10430 b.requested = b.received = b.hasBound = false;
10431 }
10432 }
10433
10434 if (sr.crashCount >= 2) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010435 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010436 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010437 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010438 sr.crashCount, sr.shortName, app.pid);
10439 bringDownServiceLocked(sr, true);
10440 } else if (!allowRestart) {
10441 bringDownServiceLocked(sr, true);
10442 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010443 boolean canceled = scheduleServiceRestartLocked(sr, true);
10444
10445 // Should the service remain running? Note that in the
10446 // extreme case of so many attempts to deliver a command
10447 // that it failed, that we also will stop it here.
10448 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10449 if (sr.pendingStarts.size() == 0) {
10450 sr.startRequested = false;
10451 if (!hasClients) {
10452 // Whoops, no reason to restart!
10453 bringDownServiceLocked(sr, true);
10454 }
10455 }
10456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010457 }
10458 }
10459
10460 if (!allowRestart) {
10461 app.services.clear();
10462 }
10463 }
10464
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010465 // Make sure we have no more records on the stopping list.
10466 int i = mStoppingServices.size();
10467 while (i > 0) {
10468 i--;
10469 ServiceRecord sr = mStoppingServices.get(i);
10470 if (sr.app == app) {
10471 mStoppingServices.remove(i);
10472 }
10473 }
10474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010475 app.executingServices.clear();
10476 }
10477
10478 private final void removeDyingProviderLocked(ProcessRecord proc,
10479 ContentProviderRecord cpr) {
10480 synchronized (cpr) {
10481 cpr.launchingApp = null;
10482 cpr.notifyAll();
10483 }
10484
10485 mProvidersByClass.remove(cpr.info.name);
10486 String names[] = cpr.info.authority.split(";");
10487 for (int j = 0; j < names.length; j++) {
10488 mProvidersByName.remove(names[j]);
10489 }
10490
10491 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10492 while (cit.hasNext()) {
10493 ProcessRecord capp = cit.next();
10494 if (!capp.persistent && capp.thread != null
10495 && capp.pid != 0
10496 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010497 Slog.i(TAG, "Kill " + capp.processName
10498 + " (pid " + capp.pid + "): provider " + cpr.info.name
10499 + " in dying process " + proc.processName);
10500 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
10501 capp.processName, capp.setAdj, "dying provider " + proc.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010502 Process.killProcess(capp.pid);
10503 }
10504 }
10505
10506 mLaunchingProviders.remove(cpr);
10507 }
10508
10509 /**
10510 * Main code for cleaning up a process when it has gone away. This is
10511 * called both as a result of the process dying, or directly when stopping
10512 * a process when running in single process mode.
10513 */
10514 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
10515 boolean restarting, int index) {
10516 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010517 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010518 }
10519
Dianne Hackborn36124872009-10-08 16:22:03 -070010520 mProcessesToGc.remove(app);
10521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010522 // Dismiss any open dialogs.
10523 if (app.crashDialog != null) {
10524 app.crashDialog.dismiss();
10525 app.crashDialog = null;
10526 }
10527 if (app.anrDialog != null) {
10528 app.anrDialog.dismiss();
10529 app.anrDialog = null;
10530 }
10531 if (app.waitDialog != null) {
10532 app.waitDialog.dismiss();
10533 app.waitDialog = null;
10534 }
10535
10536 app.crashing = false;
10537 app.notResponding = false;
10538
10539 app.resetPackageList();
10540 app.thread = null;
10541 app.forcingToForeground = null;
10542 app.foregroundServices = false;
10543
10544 killServicesLocked(app, true);
10545
10546 boolean restart = false;
10547
10548 int NL = mLaunchingProviders.size();
10549
10550 // Remove published content providers.
10551 if (!app.pubProviders.isEmpty()) {
10552 Iterator it = app.pubProviders.values().iterator();
10553 while (it.hasNext()) {
10554 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10555 cpr.provider = null;
10556 cpr.app = null;
10557
10558 // See if someone is waiting for this provider... in which
10559 // case we don't remove it, but just let it restart.
10560 int i = 0;
10561 if (!app.bad) {
10562 for (; i<NL; i++) {
10563 if (mLaunchingProviders.get(i) == cpr) {
10564 restart = true;
10565 break;
10566 }
10567 }
10568 } else {
10569 i = NL;
10570 }
10571
10572 if (i >= NL) {
10573 removeDyingProviderLocked(app, cpr);
10574 NL = mLaunchingProviders.size();
10575 }
10576 }
10577 app.pubProviders.clear();
10578 }
10579
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010580 // Take care of any launching providers waiting for this process.
10581 if (checkAppInLaunchingProvidersLocked(app, false)) {
10582 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010583 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010585 // Unregister from connected content providers.
10586 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010587 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010588 while (it.hasNext()) {
10589 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10590 cpr.clients.remove(app);
10591 }
10592 app.conProviders.clear();
10593 }
10594
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010595 // At this point there may be remaining entries in mLaunchingProviders
10596 // where we were the only one waiting, so they are no longer of use.
10597 // Look for these and clean up if found.
10598 // XXX Commented out for now. Trying to figure out a way to reproduce
10599 // the actual situation to identify what is actually going on.
10600 if (false) {
10601 for (int i=0; i<NL; i++) {
10602 ContentProviderRecord cpr = (ContentProviderRecord)
10603 mLaunchingProviders.get(i);
10604 if (cpr.clients.size() <= 0 && cpr.externals <= 0) {
10605 synchronized (cpr) {
10606 cpr.launchingApp = null;
10607 cpr.notifyAll();
10608 }
10609 }
10610 }
10611 }
10612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010613 skipCurrentReceiverLocked(app);
10614
10615 // Unregister any receivers.
10616 if (app.receivers.size() > 0) {
10617 Iterator<ReceiverList> it = app.receivers.iterator();
10618 while (it.hasNext()) {
10619 removeReceiverLocked(it.next());
10620 }
10621 app.receivers.clear();
10622 }
10623
Christopher Tate181fafa2009-05-14 11:12:14 -070010624 // If the app is undergoing backup, tell the backup manager about it
10625 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010626 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010627 try {
10628 IBackupManager bm = IBackupManager.Stub.asInterface(
10629 ServiceManager.getService(Context.BACKUP_SERVICE));
10630 bm.agentDisconnected(app.info.packageName);
10631 } catch (RemoteException e) {
10632 // can't happen; backup manager is local
10633 }
10634 }
10635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010636 // If the caller is restarting this app, then leave it in its
10637 // current lists and let the caller take care of it.
10638 if (restarting) {
10639 return;
10640 }
10641
10642 if (!app.persistent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010643 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010644 "Removing non-persistent process during cleanup: " + app);
10645 mProcessNames.remove(app.processName, app.info.uid);
10646 } else if (!app.removed) {
10647 // This app is persistent, so we need to keep its record around.
10648 // If it is not already on the pending app list, add it there
10649 // and start a new process for it.
10650 app.thread = null;
10651 app.forcingToForeground = null;
10652 app.foregroundServices = false;
10653 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10654 mPersistentStartingProcesses.add(app);
10655 restart = true;
10656 }
10657 }
10658 mProcessesOnHold.remove(app);
10659
The Android Open Source Project4df24232009-03-05 14:34:35 -080010660 if (app == mHomeProcess) {
10661 mHomeProcess = null;
10662 }
10663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010664 if (restart) {
10665 // We have components that still need to be running in the
10666 // process, so re-launch it.
10667 mProcessNames.put(app.processName, app.info.uid, app);
10668 startProcessLocked(app, "restart", app.processName);
10669 } else if (app.pid > 0 && app.pid != MY_PID) {
10670 // Goodbye!
10671 synchronized (mPidsSelfLocked) {
10672 mPidsSelfLocked.remove(app.pid);
10673 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10674 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010675 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010676 }
10677 }
10678
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010679 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10680 // Look through the content providers we are waiting to have launched,
10681 // and if any run in this process then either schedule a restart of
10682 // the process or kill the client waiting for it if this process has
10683 // gone bad.
10684 int NL = mLaunchingProviders.size();
10685 boolean restart = false;
10686 for (int i=0; i<NL; i++) {
10687 ContentProviderRecord cpr = (ContentProviderRecord)
10688 mLaunchingProviders.get(i);
10689 if (cpr.launchingApp == app) {
10690 if (!alwaysBad && !app.bad) {
10691 restart = true;
10692 } else {
10693 removeDyingProviderLocked(app, cpr);
10694 NL = mLaunchingProviders.size();
10695 }
10696 }
10697 }
10698 return restart;
10699 }
10700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010701 // =========================================================
10702 // SERVICES
10703 // =========================================================
10704
10705 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10706 ActivityManager.RunningServiceInfo info =
10707 new ActivityManager.RunningServiceInfo();
10708 info.service = r.name;
10709 if (r.app != null) {
10710 info.pid = r.app.pid;
10711 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010712 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010713 info.process = r.processName;
10714 info.foreground = r.isForeground;
10715 info.activeSince = r.createTime;
10716 info.started = r.startRequested;
10717 info.clientCount = r.connections.size();
10718 info.crashCount = r.crashCount;
10719 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010720 if (r.isForeground) {
10721 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10722 }
10723 if (r.startRequested) {
10724 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10725 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010726 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010727 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10728 }
10729 if (r.app != null && r.app.persistent) {
10730 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10731 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010732 for (ConnectionRecord conn : r.connections.values()) {
10733 if (conn.clientLabel != 0) {
10734 info.clientPackage = conn.binding.client.info.packageName;
10735 info.clientLabel = conn.clientLabel;
10736 break;
10737 }
10738 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010739 return info;
10740 }
10741
10742 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10743 int flags) {
10744 synchronized (this) {
10745 ArrayList<ActivityManager.RunningServiceInfo> res
10746 = new ArrayList<ActivityManager.RunningServiceInfo>();
10747
10748 if (mServices.size() > 0) {
10749 Iterator<ServiceRecord> it = mServices.values().iterator();
10750 while (it.hasNext() && res.size() < maxNum) {
10751 res.add(makeRunningServiceInfoLocked(it.next()));
10752 }
10753 }
10754
10755 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10756 ServiceRecord r = mRestartingServices.get(i);
10757 ActivityManager.RunningServiceInfo info =
10758 makeRunningServiceInfoLocked(r);
10759 info.restarting = r.nextRestartTime;
10760 res.add(info);
10761 }
10762
10763 return res;
10764 }
10765 }
10766
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010767 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
10768 synchronized (this) {
10769 ServiceRecord r = mServices.get(name);
10770 if (r != null) {
10771 for (ConnectionRecord conn : r.connections.values()) {
10772 if (conn.clientIntent != null) {
10773 return conn.clientIntent;
10774 }
10775 }
10776 }
10777 }
10778 return null;
10779 }
10780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010781 private final ServiceRecord findServiceLocked(ComponentName name,
10782 IBinder token) {
10783 ServiceRecord r = mServices.get(name);
10784 return r == token ? r : null;
10785 }
10786
10787 private final class ServiceLookupResult {
10788 final ServiceRecord record;
10789 final String permission;
10790
10791 ServiceLookupResult(ServiceRecord _record, String _permission) {
10792 record = _record;
10793 permission = _permission;
10794 }
10795 };
10796
10797 private ServiceLookupResult findServiceLocked(Intent service,
10798 String resolvedType) {
10799 ServiceRecord r = null;
10800 if (service.getComponent() != null) {
10801 r = mServices.get(service.getComponent());
10802 }
10803 if (r == null) {
10804 Intent.FilterComparison filter = new Intent.FilterComparison(service);
10805 r = mServicesByIntent.get(filter);
10806 }
10807
10808 if (r == null) {
10809 try {
10810 ResolveInfo rInfo =
10811 ActivityThread.getPackageManager().resolveService(
10812 service, resolvedType, 0);
10813 ServiceInfo sInfo =
10814 rInfo != null ? rInfo.serviceInfo : null;
10815 if (sInfo == null) {
10816 return null;
10817 }
10818
10819 ComponentName name = new ComponentName(
10820 sInfo.applicationInfo.packageName, sInfo.name);
10821 r = mServices.get(name);
10822 } catch (RemoteException ex) {
10823 // pm is in same process, this will never happen.
10824 }
10825 }
10826 if (r != null) {
10827 int callingPid = Binder.getCallingPid();
10828 int callingUid = Binder.getCallingUid();
10829 if (checkComponentPermission(r.permission,
10830 callingPid, callingUid, r.exported ? -1 : r.appInfo.uid)
10831 != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010832 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010833 + " from pid=" + callingPid
10834 + ", uid=" + callingUid
10835 + " requires " + r.permission);
10836 return new ServiceLookupResult(null, r.permission);
10837 }
10838 return new ServiceLookupResult(r, null);
10839 }
10840 return null;
10841 }
10842
10843 private class ServiceRestarter implements Runnable {
10844 private ServiceRecord mService;
10845
10846 void setService(ServiceRecord service) {
10847 mService = service;
10848 }
10849
10850 public void run() {
10851 synchronized(ActivityManagerService.this) {
10852 performServiceRestartLocked(mService);
10853 }
10854 }
10855 }
10856
10857 private ServiceLookupResult retrieveServiceLocked(Intent service,
10858 String resolvedType, int callingPid, int callingUid) {
10859 ServiceRecord r = null;
10860 if (service.getComponent() != null) {
10861 r = mServices.get(service.getComponent());
10862 }
10863 Intent.FilterComparison filter = new Intent.FilterComparison(service);
10864 r = mServicesByIntent.get(filter);
10865 if (r == null) {
10866 try {
10867 ResolveInfo rInfo =
10868 ActivityThread.getPackageManager().resolveService(
Dianne Hackborn1655be42009-05-08 14:29:01 -070010869 service, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010870 ServiceInfo sInfo =
10871 rInfo != null ? rInfo.serviceInfo : null;
10872 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010873 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010874 ": not found");
10875 return null;
10876 }
10877
10878 ComponentName name = new ComponentName(
10879 sInfo.applicationInfo.packageName, sInfo.name);
10880 r = mServices.get(name);
10881 if (r == null) {
10882 filter = new Intent.FilterComparison(service.cloneFilter());
10883 ServiceRestarter res = new ServiceRestarter();
10884 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10885 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10886 synchronized (stats) {
10887 ss = stats.getServiceStatsLocked(
10888 sInfo.applicationInfo.uid, sInfo.packageName,
10889 sInfo.name);
10890 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010891 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010892 res.setService(r);
10893 mServices.put(name, r);
10894 mServicesByIntent.put(filter, r);
10895
10896 // Make sure this component isn't in the pending list.
10897 int N = mPendingServices.size();
10898 for (int i=0; i<N; i++) {
10899 ServiceRecord pr = mPendingServices.get(i);
10900 if (pr.name.equals(name)) {
10901 mPendingServices.remove(i);
10902 i--;
10903 N--;
10904 }
10905 }
10906 }
10907 } catch (RemoteException ex) {
10908 // pm is in same process, this will never happen.
10909 }
10910 }
10911 if (r != null) {
10912 if (checkComponentPermission(r.permission,
10913 callingPid, callingUid, r.exported ? -1 : r.appInfo.uid)
10914 != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010915 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010916 + " from pid=" + Binder.getCallingPid()
10917 + ", uid=" + Binder.getCallingUid()
10918 + " requires " + r.permission);
10919 return new ServiceLookupResult(null, r.permission);
10920 }
10921 return new ServiceLookupResult(r, null);
10922 }
10923 return null;
10924 }
10925
10926 private final void bumpServiceExecutingLocked(ServiceRecord r) {
10927 long now = SystemClock.uptimeMillis();
10928 if (r.executeNesting == 0 && r.app != null) {
10929 if (r.app.executingServices.size() == 0) {
10930 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10931 msg.obj = r.app;
10932 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
10933 }
10934 r.app.executingServices.add(r);
10935 }
10936 r.executeNesting++;
10937 r.executingStart = now;
10938 }
10939
10940 private final void sendServiceArgsLocked(ServiceRecord r,
10941 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010942 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010943 if (N == 0) {
10944 return;
10945 }
10946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010947 int i = 0;
10948 while (i < N) {
10949 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010950 ServiceRecord.StartItem si = r.pendingStarts.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080010951 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to service: "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010952 + r.name + " " + r.intent + " args=" + si.intent);
Dianne Hackbornfed534e2009-09-23 00:42:12 -070010953 if (si.intent == null && N > 1) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010954 // If somehow we got a dummy start at the front, then
10955 // just drop it here.
10956 i++;
10957 continue;
10958 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010959 bumpServiceExecutingLocked(r);
10960 if (!oomAdjusted) {
10961 oomAdjusted = true;
10962 updateOomAdjLocked(r.app);
10963 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010964 int flags = 0;
10965 if (si.deliveryCount > 0) {
10966 flags |= Service.START_FLAG_RETRY;
10967 }
10968 if (si.doneExecutingCount > 0) {
10969 flags |= Service.START_FLAG_REDELIVERY;
10970 }
10971 r.app.thread.scheduleServiceArgs(r, si.id, flags, si.intent);
10972 si.deliveredTime = SystemClock.uptimeMillis();
10973 r.deliveredStarts.add(si);
10974 si.deliveryCount++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010975 i++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010976 } catch (RemoteException e) {
10977 // Remote process gone... we'll let the normal cleanup take
10978 // care of this.
10979 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010980 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010981 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010982 break;
10983 }
10984 }
10985 if (i == N) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010986 r.pendingStarts.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010987 } else {
10988 while (i > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010989 i--;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010990 r.pendingStarts.remove(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010991 }
10992 }
10993 }
10994
10995 private final boolean requestServiceBindingLocked(ServiceRecord r,
10996 IntentBindRecord i, boolean rebind) {
10997 if (r.app == null || r.app.thread == null) {
10998 // If service is not currently running, can't yet bind.
10999 return false;
11000 }
11001 if ((!i.requested || rebind) && i.apps.size() > 0) {
11002 try {
11003 bumpServiceExecutingLocked(r);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011004 if (DEBUG_SERVICE) Slog.v(TAG, "Connecting binding " + i
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011005 + ": shouldUnbind=" + i.hasBound);
11006 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
11007 if (!rebind) {
11008 i.requested = true;
11009 }
11010 i.hasBound = true;
11011 i.doRebind = false;
11012 } catch (RemoteException e) {
11013 return false;
11014 }
11015 }
11016 return true;
11017 }
11018
11019 private final void requestServiceBindingsLocked(ServiceRecord r) {
11020 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
11021 while (bindings.hasNext()) {
11022 IntentBindRecord i = bindings.next();
11023 if (!requestServiceBindingLocked(r, i, false)) {
11024 break;
11025 }
11026 }
11027 }
11028
11029 private final void realStartServiceLocked(ServiceRecord r,
11030 ProcessRecord app) throws RemoteException {
11031 if (app.thread == null) {
11032 throw new RemoteException();
11033 }
11034
11035 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070011036 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011037
11038 app.services.add(r);
11039 bumpServiceExecutingLocked(r);
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011040 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011041
11042 boolean created = false;
11043 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011044 if (DEBUG_SERVICE) Slog.v(TAG, "Scheduling start service: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011045 + r.name + " " + r.intent);
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011046 mStringBuilder.setLength(0);
11047 r.intent.getIntent().toShortString(mStringBuilder, false, true);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011048 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011049 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011050 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011051 synchronized (r.stats.getBatteryStats()) {
11052 r.stats.startLaunchedLocked();
11053 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011054 ensurePackageDexOpt(r.serviceInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011055 app.thread.scheduleCreateService(r, r.serviceInfo);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011056 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011057 created = true;
11058 } finally {
11059 if (!created) {
11060 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011061 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011062 }
11063 }
11064
11065 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011066
11067 // If the service is in the started state, and there are no
11068 // pending arguments, then fake up one so its onStartCommand() will
11069 // be called.
11070 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
11071 r.lastStartId++;
11072 if (r.lastStartId < 1) {
11073 r.lastStartId = 1;
11074 }
11075 r.pendingStarts.add(new ServiceRecord.StartItem(r.lastStartId, null));
11076 }
11077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011078 sendServiceArgsLocked(r, true);
11079 }
11080
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011081 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
11082 boolean allowCancel) {
11083 boolean canceled = false;
11084
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011085 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011086 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011087 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011088
11089 // Any delivered but not yet finished starts should be put back
11090 // on the pending list.
11091 final int N = r.deliveredStarts.size();
11092 if (N > 0) {
11093 for (int i=N-1; i>=0; i--) {
11094 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
11095 if (si.intent == null) {
11096 // We'll generate this again if needed.
11097 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11098 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11099 r.pendingStarts.add(0, si);
11100 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11101 dur *= 2;
11102 if (minDuration < dur) minDuration = dur;
11103 if (resetTime < dur) resetTime = dur;
11104 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011105 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011106 + r.name);
11107 canceled = true;
11108 }
11109 }
11110 r.deliveredStarts.clear();
11111 }
11112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011113 r.totalRestartCount++;
11114 if (r.restartDelay == 0) {
11115 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011116 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011117 } else {
11118 // If it has been a "reasonably long time" since the service
11119 // was started, then reset our restart duration back to
11120 // the beginning, so we don't infinitely increase the duration
11121 // on a service that just occasionally gets killed (which is
11122 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011123 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011124 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011125 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011126 } else {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011127 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011128 if (r.restartDelay < minDuration) {
11129 r.restartDelay = minDuration;
11130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011131 }
11132 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011133
11134 r.nextRestartTime = now + r.restartDelay;
11135
11136 // Make sure that we don't end up restarting a bunch of services
11137 // all at the same time.
11138 boolean repeat;
11139 do {
11140 repeat = false;
11141 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11142 ServiceRecord r2 = mRestartingServices.get(i);
11143 if (r2 != r && r.nextRestartTime
11144 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11145 && r.nextRestartTime
11146 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11147 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11148 r.restartDelay = r.nextRestartTime - now;
11149 repeat = true;
11150 break;
11151 }
11152 }
11153 } while (repeat);
11154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011155 if (!mRestartingServices.contains(r)) {
11156 mRestartingServices.add(r);
11157 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011158
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011159 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011161 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011162 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011163 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011164 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011165 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011166 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011167 r.shortName, r.restartDelay);
11168
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011169 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011170 }
11171
11172 final void performServiceRestartLocked(ServiceRecord r) {
11173 if (!mRestartingServices.contains(r)) {
11174 return;
11175 }
11176 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11177 }
11178
11179 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11180 if (r.restartDelay == 0) {
11181 return false;
11182 }
11183 r.resetRestartCounter();
11184 mRestartingServices.remove(r);
11185 mHandler.removeCallbacks(r.restarter);
11186 return true;
11187 }
11188
11189 private final boolean bringUpServiceLocked(ServiceRecord r,
11190 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011191 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011192 //r.dump(" ");
11193
Dianne Hackborn36124872009-10-08 16:22:03 -070011194 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011195 sendServiceArgsLocked(r, false);
11196 return true;
11197 }
11198
11199 if (!whileRestarting && r.restartDelay > 0) {
11200 // If waiting for a restart, then do nothing.
11201 return true;
11202 }
11203
Joe Onorato8a9b2202010-02-26 18:56:32 -080011204 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011205 + " " + r.intent);
11206
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011207 // We are now bringing the service up, so no longer in the
11208 // restarting state.
11209 mRestartingServices.remove(r);
11210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011211 final String appName = r.processName;
11212 ProcessRecord app = getProcessRecordLocked(appName, r.appInfo.uid);
11213 if (app != null && app.thread != null) {
11214 try {
11215 realStartServiceLocked(r, app);
11216 return true;
11217 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011218 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011219 }
11220
11221 // If a dead object exception was thrown -- fall through to
11222 // restart the application.
11223 }
11224
Dianne Hackborn36124872009-10-08 16:22:03 -070011225 // Not running -- get it started, and enqueue this service record
11226 // to be executed when the app comes up.
11227 if (startProcessLocked(appName, r.appInfo, true, intentFlags,
11228 "service", r.name, false) == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011229 Slog.w(TAG, "Unable to launch app "
Dianne Hackborn36124872009-10-08 16:22:03 -070011230 + r.appInfo.packageName + "/"
11231 + r.appInfo.uid + " for service "
11232 + r.intent.getIntent() + ": process is bad");
11233 bringDownServiceLocked(r, true);
11234 return false;
11235 }
11236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011237 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011238 mPendingServices.add(r);
11239 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011241 return true;
11242 }
11243
11244 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011245 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011246 //r.dump(" ");
11247
11248 // Does it still need to run?
11249 if (!force && r.startRequested) {
11250 return;
11251 }
11252 if (r.connections.size() > 0) {
11253 if (!force) {
11254 // XXX should probably keep a count of the number of auto-create
11255 // connections directly in the service.
11256 Iterator<ConnectionRecord> it = r.connections.values().iterator();
11257 while (it.hasNext()) {
11258 ConnectionRecord cr = it.next();
11259 if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
11260 return;
11261 }
11262 }
11263 }
11264
11265 // Report to all of the connections that the service is no longer
11266 // available.
11267 Iterator<ConnectionRecord> it = r.connections.values().iterator();
11268 while (it.hasNext()) {
11269 ConnectionRecord c = it.next();
11270 try {
11271 // todo: shouldn't be a synchronous call!
11272 c.conn.connected(r.name, null);
11273 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011274 Slog.w(TAG, "Failure disconnecting service " + r.name +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011275 " to connection " + c.conn.asBinder() +
11276 " (in " + c.binding.client.processName + ")", e);
11277 }
11278 }
11279 }
11280
11281 // Tell the service that it has been unbound.
11282 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11283 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11284 while (it.hasNext()) {
11285 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011286 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011287 + ": hasBound=" + ibr.hasBound);
11288 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11289 try {
11290 bumpServiceExecutingLocked(r);
11291 updateOomAdjLocked(r.app);
11292 ibr.hasBound = false;
11293 r.app.thread.scheduleUnbindService(r,
11294 ibr.intent.getIntent());
11295 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011296 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011297 + r.shortName, e);
11298 serviceDoneExecutingLocked(r, true);
11299 }
11300 }
11301 }
11302 }
11303
Joe Onorato8a9b2202010-02-26 18:56:32 -080011304 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011305 + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011306 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011307 System.identityHashCode(r), r.shortName,
11308 (r.app != null) ? r.app.pid : -1);
11309
11310 mServices.remove(r.name);
11311 mServicesByIntent.remove(r.intent);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011312 if (localLOGV) Slog.v(TAG, "BRING DOWN SERVICE: " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011313 r.totalRestartCount = 0;
11314 unscheduleServiceRestartLocked(r);
11315
11316 // Also make sure it is not on the pending list.
11317 int N = mPendingServices.size();
11318 for (int i=0; i<N; i++) {
11319 if (mPendingServices.get(i) == r) {
11320 mPendingServices.remove(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011321 if (DEBUG_SERVICE) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011322 TAG, "Removed pending service: " + r.shortName);
11323 i--;
11324 N--;
11325 }
11326 }
11327
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011328 r.cancelNotification();
11329 r.isForeground = false;
11330 r.foregroundId = 0;
11331 r.foregroundNoti = null;
11332
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011333 // Clear start entries.
11334 r.deliveredStarts.clear();
11335 r.pendingStarts.clear();
11336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011337 if (r.app != null) {
11338 synchronized (r.stats.getBatteryStats()) {
11339 r.stats.stopLaunchedLocked();
11340 }
11341 r.app.services.remove(r);
11342 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011343 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011344 if (DEBUG_SERVICE) Slog.v(TAG,
Dianne Hackborna1e989b2009-09-01 19:54:29 -070011345 "Stopping service: " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011346 bumpServiceExecutingLocked(r);
11347 mStoppingServices.add(r);
11348 updateOomAdjLocked(r.app);
11349 r.app.thread.scheduleStopService(r);
11350 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011351 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011352 + r.shortName, e);
11353 serviceDoneExecutingLocked(r, true);
11354 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011355 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011356 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011357 if (DEBUG_SERVICE) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011358 TAG, "Removed service that has no process: " + r.shortName);
11359 }
11360 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011361 if (DEBUG_SERVICE) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011362 TAG, "Removed service that is not running: " + r.shortName);
11363 }
11364 }
11365
11366 ComponentName startServiceLocked(IApplicationThread caller,
11367 Intent service, String resolvedType,
11368 int callingPid, int callingUid) {
11369 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011370 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011371 + " type=" + resolvedType + " args=" + service.getExtras());
11372
11373 if (caller != null) {
11374 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11375 if (callerApp == null) {
11376 throw new SecurityException(
11377 "Unable to find app for caller " + caller
11378 + " (pid=" + Binder.getCallingPid()
11379 + ") when starting service " + service);
11380 }
11381 }
11382
11383 ServiceLookupResult res =
11384 retrieveServiceLocked(service, resolvedType,
11385 callingPid, callingUid);
11386 if (res == null) {
11387 return null;
11388 }
11389 if (res.record == null) {
11390 return new ComponentName("!", res.permission != null
11391 ? res.permission : "private to package");
11392 }
11393 ServiceRecord r = res.record;
11394 if (unscheduleServiceRestartLocked(r)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011395 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011396 + r.shortName);
11397 }
11398 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011399 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011400 r.lastStartId++;
11401 if (r.lastStartId < 1) {
11402 r.lastStartId = 1;
11403 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011404 r.pendingStarts.add(new ServiceRecord.StartItem(r.lastStartId, service));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011405 r.lastActivity = SystemClock.uptimeMillis();
11406 synchronized (r.stats.getBatteryStats()) {
11407 r.stats.startRunningLocked();
11408 }
11409 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11410 return new ComponentName("!", "Service process is bad");
11411 }
11412 return r.name;
11413 }
11414 }
11415
11416 public ComponentName startService(IApplicationThread caller, Intent service,
11417 String resolvedType) {
11418 // Refuse possible leaked file descriptors
11419 if (service != null && service.hasFileDescriptors() == true) {
11420 throw new IllegalArgumentException("File descriptors passed in Intent");
11421 }
11422
11423 synchronized(this) {
11424 final int callingPid = Binder.getCallingPid();
11425 final int callingUid = Binder.getCallingUid();
11426 final long origId = Binder.clearCallingIdentity();
11427 ComponentName res = startServiceLocked(caller, service,
11428 resolvedType, callingPid, callingUid);
11429 Binder.restoreCallingIdentity(origId);
11430 return res;
11431 }
11432 }
11433
11434 ComponentName startServiceInPackage(int uid,
11435 Intent service, String resolvedType) {
11436 synchronized(this) {
11437 final long origId = Binder.clearCallingIdentity();
11438 ComponentName res = startServiceLocked(null, service,
11439 resolvedType, -1, uid);
11440 Binder.restoreCallingIdentity(origId);
11441 return res;
11442 }
11443 }
11444
11445 public int stopService(IApplicationThread caller, Intent service,
11446 String resolvedType) {
11447 // Refuse possible leaked file descriptors
11448 if (service != null && service.hasFileDescriptors() == true) {
11449 throw new IllegalArgumentException("File descriptors passed in Intent");
11450 }
11451
11452 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011453 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011454 + " type=" + resolvedType);
11455
11456 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11457 if (caller != null && callerApp == null) {
11458 throw new SecurityException(
11459 "Unable to find app for caller " + caller
11460 + " (pid=" + Binder.getCallingPid()
11461 + ") when stopping service " + service);
11462 }
11463
11464 // If this service is active, make sure it is stopped.
11465 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11466 if (r != null) {
11467 if (r.record != null) {
11468 synchronized (r.record.stats.getBatteryStats()) {
11469 r.record.stats.stopRunningLocked();
11470 }
11471 r.record.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011472 r.record.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011473 final long origId = Binder.clearCallingIdentity();
11474 bringDownServiceLocked(r.record, false);
11475 Binder.restoreCallingIdentity(origId);
11476 return 1;
11477 }
11478 return -1;
11479 }
11480 }
11481
11482 return 0;
11483 }
11484
11485 public IBinder peekService(Intent service, String resolvedType) {
11486 // Refuse possible leaked file descriptors
11487 if (service != null && service.hasFileDescriptors() == true) {
11488 throw new IllegalArgumentException("File descriptors passed in Intent");
11489 }
11490
11491 IBinder ret = null;
11492
11493 synchronized(this) {
11494 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11495
11496 if (r != null) {
11497 // r.record is null if findServiceLocked() failed the caller permission check
11498 if (r.record == null) {
11499 throw new SecurityException(
11500 "Permission Denial: Accessing service " + r.record.name
11501 + " from pid=" + Binder.getCallingPid()
11502 + ", uid=" + Binder.getCallingUid()
11503 + " requires " + r.permission);
11504 }
11505 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11506 if (ib != null) {
11507 ret = ib.binder;
11508 }
11509 }
11510 }
11511
11512 return ret;
11513 }
11514
11515 public boolean stopServiceToken(ComponentName className, IBinder token,
11516 int startId) {
11517 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011518 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011519 + " " + token + " startId=" + startId);
11520 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011521 if (r != null) {
11522 if (startId >= 0) {
11523 // Asked to only stop if done with all work. Note that
11524 // to avoid leaks, we will take this as dropping all
11525 // start items up to and including this one.
11526 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11527 if (si != null) {
11528 while (r.deliveredStarts.size() > 0) {
11529 if (r.deliveredStarts.remove(0) == si) {
11530 break;
11531 }
11532 }
11533 }
11534
11535 if (r.lastStartId != startId) {
11536 return false;
11537 }
11538
11539 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011540 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011541 + " is last, but have " + r.deliveredStarts.size()
11542 + " remaining args");
11543 }
11544 }
11545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011546 synchronized (r.stats.getBatteryStats()) {
11547 r.stats.stopRunningLocked();
11548 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011549 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011550 }
11551 final long origId = Binder.clearCallingIdentity();
11552 bringDownServiceLocked(r, false);
11553 Binder.restoreCallingIdentity(origId);
11554 return true;
11555 }
11556 }
11557 return false;
11558 }
11559
11560 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011561 int id, Notification notification, boolean removeNotification) {
11562 final long origId = Binder.clearCallingIdentity();
11563 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011564 synchronized(this) {
11565 ServiceRecord r = findServiceLocked(className, token);
11566 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011567 if (id != 0) {
11568 if (notification == null) {
11569 throw new IllegalArgumentException("null notification");
11570 }
11571 if (r.foregroundId != id) {
11572 r.cancelNotification();
11573 r.foregroundId = id;
11574 }
11575 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11576 r.foregroundNoti = notification;
11577 r.isForeground = true;
11578 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011579 if (r.app != null) {
11580 updateServiceForegroundLocked(r.app, true);
11581 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011582 } else {
11583 if (r.isForeground) {
11584 r.isForeground = false;
11585 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011586 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011587 updateServiceForegroundLocked(r.app, true);
11588 }
11589 }
11590 if (removeNotification) {
11591 r.cancelNotification();
11592 r.foregroundId = 0;
11593 r.foregroundNoti = null;
11594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011595 }
11596 }
11597 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011598 } finally {
11599 Binder.restoreCallingIdentity(origId);
11600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011601 }
11602
11603 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11604 boolean anyForeground = false;
11605 for (ServiceRecord sr : (HashSet<ServiceRecord>)proc.services) {
11606 if (sr.isForeground) {
11607 anyForeground = true;
11608 break;
11609 }
11610 }
11611 if (anyForeground != proc.foregroundServices) {
11612 proc.foregroundServices = anyForeground;
11613 if (oomAdj) {
11614 updateOomAdjLocked();
11615 }
11616 }
11617 }
11618
11619 public int bindService(IApplicationThread caller, IBinder token,
11620 Intent service, String resolvedType,
11621 IServiceConnection connection, int flags) {
11622 // Refuse possible leaked file descriptors
11623 if (service != null && service.hasFileDescriptors() == true) {
11624 throw new IllegalArgumentException("File descriptors passed in Intent");
11625 }
11626
11627 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011628 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011629 + " type=" + resolvedType + " conn=" + connection.asBinder()
11630 + " flags=0x" + Integer.toHexString(flags));
11631 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11632 if (callerApp == null) {
11633 throw new SecurityException(
11634 "Unable to find app for caller " + caller
11635 + " (pid=" + Binder.getCallingPid()
11636 + ") when binding service " + service);
11637 }
11638
11639 HistoryRecord activity = null;
11640 if (token != null) {
Dianne Hackborn75b03852009-06-12 15:43:26 -070011641 int aindex = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011642 if (aindex < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011643 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011644 return 0;
11645 }
11646 activity = (HistoryRecord)mHistory.get(aindex);
11647 }
11648
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011649 int clientLabel = 0;
11650 PendingIntent clientIntent = null;
11651
11652 if (callerApp.info.uid == Process.SYSTEM_UID) {
11653 // Hacky kind of thing -- allow system stuff to tell us
11654 // what they are, so we can report this elsewhere for
11655 // others to know why certain services are running.
11656 try {
11657 clientIntent = (PendingIntent)service.getParcelableExtra(
11658 Intent.EXTRA_CLIENT_INTENT);
11659 } catch (RuntimeException e) {
11660 }
11661 if (clientIntent != null) {
11662 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11663 if (clientLabel != 0) {
11664 // There are no useful extras in the intent, trash them.
11665 // System code calling with this stuff just needs to know
11666 // this will happen.
11667 service = service.cloneFilter();
11668 }
11669 }
11670 }
11671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011672 ServiceLookupResult res =
11673 retrieveServiceLocked(service, resolvedType,
11674 Binder.getCallingPid(), Binder.getCallingUid());
11675 if (res == null) {
11676 return 0;
11677 }
11678 if (res.record == null) {
11679 return -1;
11680 }
11681 ServiceRecord s = res.record;
11682
11683 final long origId = Binder.clearCallingIdentity();
11684
11685 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011686 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011687 + s.shortName);
11688 }
11689
11690 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11691 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011692 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011693
11694 IBinder binder = connection.asBinder();
11695 s.connections.put(binder, c);
11696 b.connections.add(c);
11697 if (activity != null) {
11698 if (activity.connections == null) {
11699 activity.connections = new HashSet<ConnectionRecord>();
11700 }
11701 activity.connections.add(c);
11702 }
11703 b.client.connections.add(c);
11704 mServiceConnections.put(binder, c);
11705
11706 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11707 s.lastActivity = SystemClock.uptimeMillis();
11708 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11709 return 0;
11710 }
11711 }
11712
11713 if (s.app != null) {
11714 // This could have made the service more important.
11715 updateOomAdjLocked(s.app);
11716 }
11717
Joe Onorato8a9b2202010-02-26 18:56:32 -080011718 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011719 + ": received=" + b.intent.received
11720 + " apps=" + b.intent.apps.size()
11721 + " doRebind=" + b.intent.doRebind);
11722
11723 if (s.app != null && b.intent.received) {
11724 // Service is already running, so we can immediately
11725 // publish the connection.
11726 try {
11727 c.conn.connected(s.name, b.intent.binder);
11728 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011729 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011730 + " to connection " + c.conn.asBinder()
11731 + " (in " + c.binding.client.processName + ")", e);
11732 }
11733
11734 // If this is the first app connected back to this binding,
11735 // and the service had previously asked to be told when
11736 // rebound, then do so.
11737 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11738 requestServiceBindingLocked(s, b.intent, true);
11739 }
11740 } else if (!b.intent.requested) {
11741 requestServiceBindingLocked(s, b.intent, false);
11742 }
11743
11744 Binder.restoreCallingIdentity(origId);
11745 }
11746
11747 return 1;
11748 }
11749
11750 private void removeConnectionLocked(
11751 ConnectionRecord c, ProcessRecord skipApp, HistoryRecord skipAct) {
11752 IBinder binder = c.conn.asBinder();
11753 AppBindRecord b = c.binding;
11754 ServiceRecord s = b.service;
11755 s.connections.remove(binder);
11756 b.connections.remove(c);
11757 if (c.activity != null && c.activity != skipAct) {
11758 if (c.activity.connections != null) {
11759 c.activity.connections.remove(c);
11760 }
11761 }
11762 if (b.client != skipApp) {
11763 b.client.connections.remove(c);
11764 }
11765 mServiceConnections.remove(binder);
11766
11767 if (b.connections.size() == 0) {
11768 b.intent.apps.remove(b.client);
11769 }
11770
Joe Onorato8a9b2202010-02-26 18:56:32 -080011771 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011772 + ": shouldUnbind=" + b.intent.hasBound);
11773 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11774 && b.intent.hasBound) {
11775 try {
11776 bumpServiceExecutingLocked(s);
11777 updateOomAdjLocked(s.app);
11778 b.intent.hasBound = false;
11779 // Assume the client doesn't want to know about a rebind;
11780 // we will deal with that later if it asks for one.
11781 b.intent.doRebind = false;
11782 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11783 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011784 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011785 serviceDoneExecutingLocked(s, true);
11786 }
11787 }
11788
11789 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11790 bringDownServiceLocked(s, false);
11791 }
11792 }
11793
11794 public boolean unbindService(IServiceConnection connection) {
11795 synchronized (this) {
11796 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011797 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011798 ConnectionRecord r = mServiceConnections.get(binder);
11799 if (r == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011800 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011801 + connection.asBinder());
11802 return false;
11803 }
11804
11805 final long origId = Binder.clearCallingIdentity();
11806
11807 removeConnectionLocked(r, null, null);
11808
11809 if (r.binding.service.app != null) {
11810 // This could have made the service less important.
11811 updateOomAdjLocked(r.binding.service.app);
11812 }
11813
11814 Binder.restoreCallingIdentity(origId);
11815 }
11816
11817 return true;
11818 }
11819
11820 public void publishService(IBinder token, Intent intent, IBinder service) {
11821 // Refuse possible leaked file descriptors
11822 if (intent != null && intent.hasFileDescriptors() == true) {
11823 throw new IllegalArgumentException("File descriptors passed in Intent");
11824 }
11825
11826 synchronized(this) {
11827 if (!(token instanceof ServiceRecord)) {
11828 throw new IllegalArgumentException("Invalid service token");
11829 }
11830 ServiceRecord r = (ServiceRecord)token;
11831
11832 final long origId = Binder.clearCallingIdentity();
11833
Joe Onorato8a9b2202010-02-26 18:56:32 -080011834 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING SERVICE " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011835 + " " + intent + ": " + service);
11836 if (r != null) {
11837 Intent.FilterComparison filter
11838 = new Intent.FilterComparison(intent);
11839 IntentBindRecord b = r.bindings.get(filter);
11840 if (b != null && !b.received) {
11841 b.binder = service;
11842 b.requested = true;
11843 b.received = true;
11844 if (r.connections.size() > 0) {
11845 Iterator<ConnectionRecord> it
11846 = r.connections.values().iterator();
11847 while (it.hasNext()) {
11848 ConnectionRecord c = it.next();
11849 if (!filter.equals(c.binding.intent.intent)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011850 if (DEBUG_SERVICE) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011851 TAG, "Not publishing to: " + c);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011852 if (DEBUG_SERVICE) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011853 TAG, "Bound intent: " + c.binding.intent.intent);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011854 if (DEBUG_SERVICE) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011855 TAG, "Published intent: " + intent);
11856 continue;
11857 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080011858 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011859 try {
11860 c.conn.connected(r.name, service);
11861 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011862 Slog.w(TAG, "Failure sending service " + r.name +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011863 " to connection " + c.conn.asBinder() +
11864 " (in " + c.binding.client.processName + ")", e);
11865 }
11866 }
11867 }
11868 }
11869
11870 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
11871
11872 Binder.restoreCallingIdentity(origId);
11873 }
11874 }
11875 }
11876
11877 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11878 // Refuse possible leaked file descriptors
11879 if (intent != null && intent.hasFileDescriptors() == true) {
11880 throw new IllegalArgumentException("File descriptors passed in Intent");
11881 }
11882
11883 synchronized(this) {
11884 if (!(token instanceof ServiceRecord)) {
11885 throw new IllegalArgumentException("Invalid service token");
11886 }
11887 ServiceRecord r = (ServiceRecord)token;
11888
11889 final long origId = Binder.clearCallingIdentity();
11890
11891 if (r != null) {
11892 Intent.FilterComparison filter
11893 = new Intent.FilterComparison(intent);
11894 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011895 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011896 + " at " + b + ": apps="
11897 + (b != null ? b.apps.size() : 0));
11898 if (b != null) {
11899 if (b.apps.size() > 0) {
11900 // Applications have already bound since the last
11901 // unbind, so just rebind right here.
11902 requestServiceBindingLocked(r, b, true);
11903 } else {
11904 // Note to tell the service the next time there is
11905 // a new client.
11906 b.doRebind = true;
11907 }
11908 }
11909
11910 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
11911
11912 Binder.restoreCallingIdentity(origId);
11913 }
11914 }
11915 }
11916
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011917 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011918 synchronized(this) {
11919 if (!(token instanceof ServiceRecord)) {
11920 throw new IllegalArgumentException("Invalid service token");
11921 }
11922 ServiceRecord r = (ServiceRecord)token;
11923 boolean inStopping = mStoppingServices.contains(token);
11924 if (r != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011925 if (DEBUG_SERVICE) Slog.v(TAG, "DONE EXECUTING SERVICE " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011926 + ": nesting=" + r.executeNesting
11927 + ", inStopping=" + inStopping);
11928 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011929 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011930 + " with incorrect token: given " + token
11931 + ", expected " + r);
11932 return;
11933 }
11934
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011935 if (type == 1) {
11936 // This is a call from a service start... take care of
11937 // book-keeping.
11938 r.callStart = true;
11939 switch (res) {
11940 case Service.START_STICKY_COMPATIBILITY:
11941 case Service.START_STICKY: {
11942 // We are done with the associated start arguments.
11943 r.findDeliveredStart(startId, true);
11944 // Don't stop if killed.
11945 r.stopIfKilled = false;
11946 break;
11947 }
11948 case Service.START_NOT_STICKY: {
11949 // We are done with the associated start arguments.
11950 r.findDeliveredStart(startId, true);
11951 if (r.lastStartId == startId) {
11952 // There is no more work, and this service
11953 // doesn't want to hang around if killed.
11954 r.stopIfKilled = true;
11955 }
11956 break;
11957 }
11958 case Service.START_REDELIVER_INTENT: {
11959 // We'll keep this item until they explicitly
11960 // call stop for it, but keep track of the fact
11961 // that it was delivered.
11962 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11963 if (si != null) {
11964 si.deliveryCount = 0;
11965 si.doneExecutingCount++;
11966 // Don't stop if killed.
11967 r.stopIfKilled = true;
11968 }
11969 break;
11970 }
11971 default:
11972 throw new IllegalArgumentException(
11973 "Unknown service start result: " + res);
11974 }
11975 if (res == Service.START_STICKY_COMPATIBILITY) {
11976 r.callStart = false;
11977 }
11978 }
11979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011980 final long origId = Binder.clearCallingIdentity();
11981 serviceDoneExecutingLocked(r, inStopping);
11982 Binder.restoreCallingIdentity(origId);
11983 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011984 Slog.w(TAG, "Done executing unknown service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011985 + " with token " + token);
11986 }
11987 }
11988 }
11989
11990 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
11991 r.executeNesting--;
11992 if (r.executeNesting <= 0 && r.app != null) {
11993 r.app.executingServices.remove(r);
11994 if (r.app.executingServices.size() == 0) {
11995 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
11996 }
11997 if (inStopping) {
11998 mStoppingServices.remove(r);
11999 }
12000 updateOomAdjLocked(r.app);
12001 }
12002 }
12003
12004 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012005 String anrMessage = null;
12006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012007 synchronized(this) {
12008 if (proc.executingServices.size() == 0 || proc.thread == null) {
12009 return;
12010 }
12011 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12012 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12013 ServiceRecord timeout = null;
12014 long nextTime = 0;
12015 while (it.hasNext()) {
12016 ServiceRecord sr = it.next();
12017 if (sr.executingStart < maxTime) {
12018 timeout = sr;
12019 break;
12020 }
12021 if (sr.executingStart > nextTime) {
12022 nextTime = sr.executingStart;
12023 }
12024 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012025 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012026 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012027 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012028 } else {
12029 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12030 msg.obj = proc;
12031 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12032 }
12033 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012034
12035 if (anrMessage != null) {
12036 appNotResponding(proc, null, null, anrMessage);
12037 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012038 }
12039
12040 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012041 // BACKUP AND RESTORE
12042 // =========================================================
12043
12044 // Cause the target app to be launched if necessary and its backup agent
12045 // instantiated. The backup agent will invoke backupAgentCreated() on the
12046 // activity manager to announce its creation.
12047 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012048 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012049 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12050
12051 synchronized(this) {
12052 // !!! TODO: currently no check here that we're already bound
12053 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12054 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12055 synchronized (stats) {
12056 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12057 }
12058
12059 BackupRecord r = new BackupRecord(ss, app, backupMode);
12060 ComponentName hostingName = new ComponentName(app.packageName, app.backupAgentName);
12061 // startProcessLocked() returns existing proc's record if it's already running
12062 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012063 false, 0, "backup", hostingName, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012064 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012065 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012066 return false;
12067 }
12068
12069 r.app = proc;
12070 mBackupTarget = r;
12071 mBackupAppName = app.packageName;
12072
Christopher Tate6fa95972009-06-05 18:43:55 -070012073 // Try not to kill the process during backup
12074 updateOomAdjLocked(proc);
12075
Christopher Tate181fafa2009-05-14 11:12:14 -070012076 // If the process is already attached, schedule the creation of the backup agent now.
12077 // If it is not yet live, this will be done when it attaches to the framework.
12078 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012079 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012080 try {
12081 proc.thread.scheduleCreateBackupAgent(app, backupMode);
12082 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012083 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012084 }
12085 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012086 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012087 }
12088 // Invariants: at this point, the target app process exists and the application
12089 // is either already running or in the process of coming up. mBackupTarget and
12090 // mBackupAppName describe the app, so that when it binds back to the AM we
12091 // know that it's scheduled for a backup-agent operation.
12092 }
12093
12094 return true;
12095 }
12096
12097 // A backup agent has just come up
12098 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012099 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012100 + " = " + agent);
12101
12102 synchronized(this) {
12103 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012104 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012105 return;
12106 }
12107
Christopher Tate043dadc2009-06-02 16:11:00 -070012108 long oldIdent = Binder.clearCallingIdentity();
Christopher Tate181fafa2009-05-14 11:12:14 -070012109 try {
12110 IBackupManager bm = IBackupManager.Stub.asInterface(
12111 ServiceManager.getService(Context.BACKUP_SERVICE));
12112 bm.agentConnected(agentPackageName, agent);
12113 } catch (RemoteException e) {
12114 // can't happen; the backup manager service is local
12115 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012116 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
Christopher Tate181fafa2009-05-14 11:12:14 -070012117 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -070012118 } finally {
12119 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012120 }
12121 }
12122 }
12123
12124 // done with this agent
12125 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012126 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012127 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012128 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012129 return;
12130 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012131
12132 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012133 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012134 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012135 return;
12136 }
12137
Christopher Tate181fafa2009-05-14 11:12:14 -070012138 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012139 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012140 return;
12141 }
12142
Christopher Tate6fa95972009-06-05 18:43:55 -070012143 ProcessRecord proc = mBackupTarget.app;
12144 mBackupTarget = null;
12145 mBackupAppName = null;
12146
12147 // Not backing this app up any more; reset its OOM adjustment
12148 updateOomAdjLocked(proc);
12149
Christopher Tatec7b31e32009-06-10 15:49:30 -070012150 // If the app crashed during backup, 'thread' will be null here
12151 if (proc.thread != null) {
12152 try {
12153 proc.thread.scheduleDestroyBackupAgent(appInfo);
12154 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012155 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012156 e.printStackTrace();
12157 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012158 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012159 }
12160 }
12161 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012162 // BROADCASTS
12163 // =========================================================
12164
Josh Bartel7f208742010-02-25 11:01:44 -060012165 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012166 List cur) {
12167 final ContentResolver resolver = mContext.getContentResolver();
12168 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12169 if (list == null) {
12170 return cur;
12171 }
12172 int N = list.size();
12173 for (int i=0; i<N; i++) {
12174 Intent intent = list.get(i);
12175 if (filter.match(resolver, intent, true, TAG) >= 0) {
12176 if (cur == null) {
12177 cur = new ArrayList<Intent>();
12178 }
12179 cur.add(intent);
12180 }
12181 }
12182 return cur;
12183 }
12184
12185 private final void scheduleBroadcastsLocked() {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012186 if (DEBUG_BROADCAST) Slog.v(TAG, "Schedule broadcasts: current="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012187 + mBroadcastsScheduled);
12188
12189 if (mBroadcastsScheduled) {
12190 return;
12191 }
12192 mHandler.sendEmptyMessage(BROADCAST_INTENT_MSG);
12193 mBroadcastsScheduled = true;
12194 }
12195
12196 public Intent registerReceiver(IApplicationThread caller,
12197 IIntentReceiver receiver, IntentFilter filter, String permission) {
12198 synchronized(this) {
12199 ProcessRecord callerApp = null;
12200 if (caller != null) {
12201 callerApp = getRecordForAppLocked(caller);
12202 if (callerApp == null) {
12203 throw new SecurityException(
12204 "Unable to find app for caller " + caller
12205 + " (pid=" + Binder.getCallingPid()
12206 + ") when registering receiver " + receiver);
12207 }
12208 }
12209
12210 List allSticky = null;
12211
12212 // Look for any matching sticky broadcasts...
12213 Iterator actions = filter.actionsIterator();
12214 if (actions != null) {
12215 while (actions.hasNext()) {
12216 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012217 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012218 }
12219 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012220 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012221 }
12222
12223 // The first sticky in the list is returned directly back to
12224 // the client.
12225 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12226
Joe Onorato8a9b2202010-02-26 18:56:32 -080012227 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012228 + ": " + sticky);
12229
12230 if (receiver == null) {
12231 return sticky;
12232 }
12233
12234 ReceiverList rl
12235 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12236 if (rl == null) {
12237 rl = new ReceiverList(this, callerApp,
12238 Binder.getCallingPid(),
12239 Binder.getCallingUid(), receiver);
12240 if (rl.app != null) {
12241 rl.app.receivers.add(rl);
12242 } else {
12243 try {
12244 receiver.asBinder().linkToDeath(rl, 0);
12245 } catch (RemoteException e) {
12246 return sticky;
12247 }
12248 rl.linkedToDeath = true;
12249 }
12250 mRegisteredReceivers.put(receiver.asBinder(), rl);
12251 }
12252 BroadcastFilter bf = new BroadcastFilter(filter, rl, permission);
12253 rl.add(bf);
12254 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012255 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012256 }
12257 mReceiverResolver.addFilter(bf);
12258
12259 // Enqueue broadcasts for all existing stickies that match
12260 // this filter.
12261 if (allSticky != null) {
12262 ArrayList receivers = new ArrayList();
12263 receivers.add(bf);
12264
12265 int N = allSticky.size();
12266 for (int i=0; i<N; i++) {
12267 Intent intent = (Intent)allSticky.get(i);
12268 BroadcastRecord r = new BroadcastRecord(intent, null,
12269 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012270 false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012271 if (mParallelBroadcasts.size() == 0) {
12272 scheduleBroadcastsLocked();
12273 }
12274 mParallelBroadcasts.add(r);
12275 }
12276 }
12277
12278 return sticky;
12279 }
12280 }
12281
12282 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012283 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012284
12285 boolean doNext = false;
12286
12287 synchronized(this) {
12288 ReceiverList rl
12289 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12290 if (rl != null) {
12291 if (rl.curBroadcast != null) {
12292 BroadcastRecord r = rl.curBroadcast;
12293 doNext = finishReceiverLocked(
12294 receiver.asBinder(), r.resultCode, r.resultData,
12295 r.resultExtras, r.resultAbort, true);
12296 }
12297
12298 if (rl.app != null) {
12299 rl.app.receivers.remove(rl);
12300 }
12301 removeReceiverLocked(rl);
12302 if (rl.linkedToDeath) {
12303 rl.linkedToDeath = false;
12304 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12305 }
12306 }
12307 }
12308
12309 if (!doNext) {
12310 return;
12311 }
12312
12313 final long origId = Binder.clearCallingIdentity();
12314 processNextBroadcast(false);
12315 trimApplications();
12316 Binder.restoreCallingIdentity(origId);
12317 }
12318
12319 void removeReceiverLocked(ReceiverList rl) {
12320 mRegisteredReceivers.remove(rl.receiver.asBinder());
12321 int N = rl.size();
12322 for (int i=0; i<N; i++) {
12323 mReceiverResolver.removeFilter(rl.get(i));
12324 }
12325 }
12326
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012327 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12328 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12329 ProcessRecord r = mLruProcesses.get(i);
12330 if (r.thread != null) {
12331 try {
12332 r.thread.dispatchPackageBroadcast(cmd, packages);
12333 } catch (RemoteException ex) {
12334 }
12335 }
12336 }
12337 }
12338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012339 private final int broadcastIntentLocked(ProcessRecord callerApp,
12340 String callerPackage, Intent intent, String resolvedType,
12341 IIntentReceiver resultTo, int resultCode, String resultData,
12342 Bundle map, String requiredPermission,
12343 boolean ordered, boolean sticky, int callingPid, int callingUid) {
12344 intent = new Intent(intent);
12345
Joe Onorato8a9b2202010-02-26 18:56:32 -080012346 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012347 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
12348 + " ordered=" + ordered);
12349 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012350 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012351 }
12352
12353 // Handle special intents: if this broadcast is from the package
12354 // manager about a package being removed, we need to remove all of
12355 // its activities from the history stack.
12356 final boolean uidRemoved = intent.ACTION_UID_REMOVED.equals(
12357 intent.getAction());
12358 if (intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12359 || intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012360 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012361 || uidRemoved) {
12362 if (checkComponentPermission(
12363 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
12364 callingPid, callingUid, -1)
12365 == PackageManager.PERMISSION_GRANTED) {
12366 if (uidRemoved) {
12367 final Bundle intentExtras = intent.getExtras();
12368 final int uid = intentExtras != null
12369 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12370 if (uid >= 0) {
12371 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12372 synchronized (bs) {
12373 bs.removeUidStatsLocked(uid);
12374 }
12375 }
12376 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012377 // If resources are unvailble just force stop all
12378 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012379 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012380 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12381 if (list != null && (list.length > 0)) {
12382 for (String pkg : list) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080012383 forceStopPackageLocked(pkg, -1, false, true, true);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012384 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012385 sendPackageBroadcastLocked(
12386 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012387 }
12388 } else {
12389 Uri data = intent.getData();
12390 String ssp;
12391 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12392 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12393 forceStopPackageLocked(ssp,
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080012394 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012395 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012396 if (intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
12397 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12398 new String[] {ssp});
12399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012400 }
12401 }
12402 }
12403 } else {
12404 String msg = "Permission Denial: " + intent.getAction()
12405 + " broadcast from " + callerPackage + " (pid=" + callingPid
12406 + ", uid=" + callingUid + ")"
12407 + " requires "
12408 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012409 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012410 throw new SecurityException(msg);
12411 }
12412 }
12413
12414 /*
12415 * If this is the time zone changed action, queue up a message that will reset the timezone
12416 * of all currently running processes. This message will get queued up before the broadcast
12417 * happens.
12418 */
12419 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12420 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12421 }
12422
Dianne Hackborn854060af2009-07-09 18:14:31 -070012423 /*
12424 * Prevent non-system code (defined here to be non-persistent
12425 * processes) from sending protected broadcasts.
12426 */
12427 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12428 || callingUid == Process.SHELL_UID || callingUid == 0) {
12429 // Always okay.
12430 } else if (callerApp == null || !callerApp.persistent) {
12431 try {
12432 if (ActivityThread.getPackageManager().isProtectedBroadcast(
12433 intent.getAction())) {
12434 String msg = "Permission Denial: not allowed to send broadcast "
12435 + intent.getAction() + " from pid="
12436 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012437 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012438 throw new SecurityException(msg);
12439 }
12440 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012441 Slog.w(TAG, "Remote exception", e);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012442 return BROADCAST_SUCCESS;
12443 }
12444 }
12445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012446 // Add to the sticky list if requested.
12447 if (sticky) {
12448 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12449 callingPid, callingUid)
12450 != PackageManager.PERMISSION_GRANTED) {
12451 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12452 + callingPid + ", uid=" + callingUid
12453 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012454 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012455 throw new SecurityException(msg);
12456 }
12457 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012458 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012459 + " and enforce permission " + requiredPermission);
12460 return BROADCAST_STICKY_CANT_HAVE_PERMISSION;
12461 }
12462 if (intent.getComponent() != null) {
12463 throw new SecurityException(
12464 "Sticky broadcasts can't target a specific component");
12465 }
12466 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12467 if (list == null) {
12468 list = new ArrayList<Intent>();
12469 mStickyBroadcasts.put(intent.getAction(), list);
12470 }
12471 int N = list.size();
12472 int i;
12473 for (i=0; i<N; i++) {
12474 if (intent.filterEquals(list.get(i))) {
12475 // This sticky already exists, replace it.
12476 list.set(i, new Intent(intent));
12477 break;
12478 }
12479 }
12480 if (i >= N) {
12481 list.add(new Intent(intent));
12482 }
12483 }
12484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012485 // Figure out who all will receive this broadcast.
12486 List receivers = null;
12487 List<BroadcastFilter> registeredReceivers = null;
12488 try {
12489 if (intent.getComponent() != null) {
12490 // Broadcast is going to one specific receiver class...
12491 ActivityInfo ai = ActivityThread.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -070012492 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012493 if (ai != null) {
12494 receivers = new ArrayList();
12495 ResolveInfo ri = new ResolveInfo();
12496 ri.activityInfo = ai;
12497 receivers.add(ri);
12498 }
12499 } else {
12500 // Need to resolve the intent to interested receivers...
12501 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12502 == 0) {
12503 receivers =
12504 ActivityThread.getPackageManager().queryIntentReceivers(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012505 intent, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012506 }
Mihai Preda074edef2009-05-18 17:13:31 +020012507 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012508 }
12509 } catch (RemoteException ex) {
12510 // pm is in same process, this will never happen.
12511 }
12512
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012513 final boolean replacePending =
12514 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12515
Joe Onorato8a9b2202010-02-26 18:56:32 -080012516 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012517 + " replacePending=" + replacePending);
12518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012519 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12520 if (!ordered && NR > 0) {
12521 // If we are not serializing this broadcast, then send the
12522 // registered receivers separately so they don't wait for the
12523 // components to be launched.
12524 BroadcastRecord r = new BroadcastRecord(intent, callerApp,
12525 callerPackage, callingPid, callingUid, requiredPermission,
12526 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012527 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012528 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012529 TAG, "Enqueueing parallel broadcast " + r
12530 + ": prev had " + mParallelBroadcasts.size());
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012531 boolean replaced = false;
12532 if (replacePending) {
12533 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
12534 if (intent.filterEquals(mParallelBroadcasts.get(i).intent)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012535 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012536 "***** DROPPING PARALLEL: " + intent);
12537 mParallelBroadcasts.set(i, r);
12538 replaced = true;
12539 break;
12540 }
12541 }
12542 }
12543 if (!replaced) {
12544 mParallelBroadcasts.add(r);
12545 scheduleBroadcastsLocked();
12546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012547 registeredReceivers = null;
12548 NR = 0;
12549 }
12550
12551 // Merge into one list.
12552 int ir = 0;
12553 if (receivers != null) {
12554 // A special case for PACKAGE_ADDED: do not allow the package
12555 // being added to see this broadcast. This prevents them from
12556 // using this as a back door to get run as soon as they are
12557 // installed. Maybe in the future we want to have a special install
12558 // broadcast or such for apps, but we'd like to deliberately make
12559 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012560 String skipPackages[] = null;
12561 if (intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12562 || intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12563 || intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
12564 Uri data = intent.getData();
12565 if (data != null) {
12566 String pkgName = data.getSchemeSpecificPart();
12567 if (pkgName != null) {
12568 skipPackages = new String[] { pkgName };
12569 }
12570 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012571 } else if (intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012572 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012573 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012574 if (skipPackages != null && (skipPackages.length > 0)) {
12575 for (String skipPackage : skipPackages) {
12576 if (skipPackage != null) {
12577 int NT = receivers.size();
12578 for (int it=0; it<NT; it++) {
12579 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12580 if (curt.activityInfo.packageName.equals(skipPackage)) {
12581 receivers.remove(it);
12582 it--;
12583 NT--;
12584 }
12585 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012586 }
12587 }
12588 }
12589
12590 int NT = receivers != null ? receivers.size() : 0;
12591 int it = 0;
12592 ResolveInfo curt = null;
12593 BroadcastFilter curr = null;
12594 while (it < NT && ir < NR) {
12595 if (curt == null) {
12596 curt = (ResolveInfo)receivers.get(it);
12597 }
12598 if (curr == null) {
12599 curr = registeredReceivers.get(ir);
12600 }
12601 if (curr.getPriority() >= curt.priority) {
12602 // Insert this broadcast record into the final list.
12603 receivers.add(it, curr);
12604 ir++;
12605 curr = null;
12606 it++;
12607 NT++;
12608 } else {
12609 // Skip to the next ResolveInfo in the final list.
12610 it++;
12611 curt = null;
12612 }
12613 }
12614 }
12615 while (ir < NR) {
12616 if (receivers == null) {
12617 receivers = new ArrayList();
12618 }
12619 receivers.add(registeredReceivers.get(ir));
12620 ir++;
12621 }
12622
12623 if ((receivers != null && receivers.size() > 0)
12624 || resultTo != null) {
12625 BroadcastRecord r = new BroadcastRecord(intent, callerApp,
12626 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012627 receivers, resultTo, resultCode, resultData, map, ordered,
12628 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012629 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012630 TAG, "Enqueueing ordered broadcast " + r
12631 + ": prev had " + mOrderedBroadcasts.size());
12632 if (DEBUG_BROADCAST) {
12633 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012634 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012635 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012636 boolean replaced = false;
12637 if (replacePending) {
12638 for (int i=mOrderedBroadcasts.size()-1; i>=0; i--) {
12639 if (intent.filterEquals(mOrderedBroadcasts.get(i).intent)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012640 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012641 "***** DROPPING ORDERED: " + intent);
12642 mOrderedBroadcasts.set(i, r);
12643 replaced = true;
12644 break;
12645 }
12646 }
12647 }
12648 if (!replaced) {
12649 mOrderedBroadcasts.add(r);
12650 scheduleBroadcastsLocked();
12651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012652 }
12653
12654 return BROADCAST_SUCCESS;
12655 }
12656
12657 public final int broadcastIntent(IApplicationThread caller,
12658 Intent intent, String resolvedType, IIntentReceiver resultTo,
12659 int resultCode, String resultData, Bundle map,
12660 String requiredPermission, boolean serialized, boolean sticky) {
12661 // Refuse possible leaked file descriptors
12662 if (intent != null && intent.hasFileDescriptors() == true) {
12663 throw new IllegalArgumentException("File descriptors passed in Intent");
12664 }
12665
12666 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012667 int flags = intent.getFlags();
12668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012669 if (!mSystemReady) {
12670 // if the caller really truly claims to know what they're doing, go
12671 // ahead and allow the broadcast without launching any receivers
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012672 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12673 intent = new Intent(intent);
12674 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12675 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0){
Joe Onorato8a9b2202010-02-26 18:56:32 -080012676 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012677 + " before boot completion");
12678 throw new IllegalStateException("Cannot broadcast before boot completed");
12679 }
12680 }
12681
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012682 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12683 throw new IllegalArgumentException(
12684 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12685 }
12686
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012687 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12688 final int callingPid = Binder.getCallingPid();
12689 final int callingUid = Binder.getCallingUid();
12690 final long origId = Binder.clearCallingIdentity();
12691 int res = broadcastIntentLocked(callerApp,
12692 callerApp != null ? callerApp.info.packageName : null,
12693 intent, resolvedType, resultTo,
12694 resultCode, resultData, map, requiredPermission, serialized,
12695 sticky, callingPid, callingUid);
12696 Binder.restoreCallingIdentity(origId);
12697 return res;
12698 }
12699 }
12700
12701 int broadcastIntentInPackage(String packageName, int uid,
12702 Intent intent, String resolvedType, IIntentReceiver resultTo,
12703 int resultCode, String resultData, Bundle map,
12704 String requiredPermission, boolean serialized, boolean sticky) {
12705 synchronized(this) {
12706 final long origId = Binder.clearCallingIdentity();
12707 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12708 resultTo, resultCode, resultData, map, requiredPermission,
12709 serialized, sticky, -1, uid);
12710 Binder.restoreCallingIdentity(origId);
12711 return res;
12712 }
12713 }
12714
12715 public final void unbroadcastIntent(IApplicationThread caller,
12716 Intent intent) {
12717 // Refuse possible leaked file descriptors
12718 if (intent != null && intent.hasFileDescriptors() == true) {
12719 throw new IllegalArgumentException("File descriptors passed in Intent");
12720 }
12721
12722 synchronized(this) {
12723 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12724 != PackageManager.PERMISSION_GRANTED) {
12725 String msg = "Permission Denial: unbroadcastIntent() from pid="
12726 + Binder.getCallingPid()
12727 + ", uid=" + Binder.getCallingUid()
12728 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012729 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012730 throw new SecurityException(msg);
12731 }
12732 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12733 if (list != null) {
12734 int N = list.size();
12735 int i;
12736 for (i=0; i<N; i++) {
12737 if (intent.filterEquals(list.get(i))) {
12738 list.remove(i);
12739 break;
12740 }
12741 }
12742 }
12743 }
12744 }
12745
12746 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12747 String resultData, Bundle resultExtras, boolean resultAbort,
12748 boolean explicit) {
12749 if (mOrderedBroadcasts.size() == 0) {
12750 if (explicit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012751 Slog.w(TAG, "finishReceiver called but no pending broadcasts");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012752 }
12753 return false;
12754 }
12755 BroadcastRecord r = mOrderedBroadcasts.get(0);
12756 if (r.receiver == null) {
12757 if (explicit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012758 Slog.w(TAG, "finishReceiver called but none active");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012759 }
12760 return false;
12761 }
12762 if (r.receiver != receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012763 Slog.w(TAG, "finishReceiver called but active receiver is different");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012764 return false;
12765 }
12766 int state = r.state;
12767 r.state = r.IDLE;
12768 if (state == r.IDLE) {
12769 if (explicit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012770 Slog.w(TAG, "finishReceiver called but state is IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012771 }
12772 }
12773 r.receiver = null;
12774 r.intent.setComponent(null);
12775 if (r.curApp != null) {
12776 r.curApp.curReceiver = null;
12777 }
12778 if (r.curFilter != null) {
12779 r.curFilter.receiverList.curBroadcast = null;
12780 }
12781 r.curFilter = null;
12782 r.curApp = null;
12783 r.curComponent = null;
12784 r.curReceiver = null;
12785 mPendingBroadcast = null;
12786
12787 r.resultCode = resultCode;
12788 r.resultData = resultData;
12789 r.resultExtras = resultExtras;
12790 r.resultAbort = resultAbort;
12791
12792 // We will process the next receiver right now if this is finishing
12793 // an app receiver (which is always asynchronous) or after we have
12794 // come back from calling a receiver.
12795 return state == BroadcastRecord.APP_RECEIVE
12796 || state == BroadcastRecord.CALL_DONE_RECEIVE;
12797 }
12798
12799 public void finishReceiver(IBinder who, int resultCode, String resultData,
12800 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012801 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012802
12803 // Refuse possible leaked file descriptors
12804 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12805 throw new IllegalArgumentException("File descriptors passed in Bundle");
12806 }
12807
12808 boolean doNext;
12809
12810 final long origId = Binder.clearCallingIdentity();
12811
12812 synchronized(this) {
12813 doNext = finishReceiverLocked(
12814 who, resultCode, resultData, resultExtras, resultAbort, true);
12815 }
12816
12817 if (doNext) {
12818 processNextBroadcast(false);
12819 }
12820 trimApplications();
12821
12822 Binder.restoreCallingIdentity(origId);
12823 }
12824
12825 private final void logBroadcastReceiverDiscard(BroadcastRecord r) {
12826 if (r.nextReceiver > 0) {
12827 Object curReceiver = r.receivers.get(r.nextReceiver-1);
12828 if (curReceiver instanceof BroadcastFilter) {
12829 BroadcastFilter bf = (BroadcastFilter) curReceiver;
Doug Zongker2bec3d42009-12-04 12:52:44 -080012830 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012831 System.identityHashCode(r),
12832 r.intent.getAction(),
12833 r.nextReceiver - 1,
12834 System.identityHashCode(bf));
12835 } else {
Doug Zongker2bec3d42009-12-04 12:52:44 -080012836 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012837 System.identityHashCode(r),
12838 r.intent.getAction(),
12839 r.nextReceiver - 1,
12840 ((ResolveInfo)curReceiver).toString());
12841 }
12842 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012843 Slog.w(TAG, "Discarding broadcast before first receiver is invoked: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012844 + r);
Doug Zongker2bec3d42009-12-04 12:52:44 -080012845 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012846 System.identityHashCode(r),
12847 r.intent.getAction(),
12848 r.nextReceiver,
12849 "NONE");
12850 }
12851 }
12852
12853 private final void broadcastTimeout() {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012854 ProcessRecord app = null;
12855 String anrMessage = null;
12856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012857 synchronized (this) {
12858 if (mOrderedBroadcasts.size() == 0) {
12859 return;
12860 }
12861 long now = SystemClock.uptimeMillis();
12862 BroadcastRecord r = mOrderedBroadcasts.get(0);
Dianne Hackborn12527f92009-11-11 17:39:50 -080012863 if ((r.receiverTime+BROADCAST_TIMEOUT) > now) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012864 if (DEBUG_BROADCAST) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012865 "Premature timeout @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
Dianne Hackborn12527f92009-11-11 17:39:50 -080012866 + (r.receiverTime + BROADCAST_TIMEOUT));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012867 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG);
Dianne Hackborn12527f92009-11-11 17:39:50 -080012868 mHandler.sendMessageAtTime(msg, r.receiverTime+BROADCAST_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012869 return;
12870 }
12871
Joe Onorato8a9b2202010-02-26 18:56:32 -080012872 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r.receiver);
Dianne Hackborn12527f92009-11-11 17:39:50 -080012873 r.receiverTime = now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012874 r.anrCount++;
12875
12876 // Current receiver has passed its expiration date.
12877 if (r.nextReceiver <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012878 Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012879 return;
12880 }
12881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012882 Object curReceiver = r.receivers.get(r.nextReceiver-1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012883 Slog.w(TAG, "Receiver during timeout: " + curReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012884 logBroadcastReceiverDiscard(r);
12885 if (curReceiver instanceof BroadcastFilter) {
12886 BroadcastFilter bf = (BroadcastFilter)curReceiver;
12887 if (bf.receiverList.pid != 0
12888 && bf.receiverList.pid != MY_PID) {
12889 synchronized (this.mPidsSelfLocked) {
12890 app = this.mPidsSelfLocked.get(
12891 bf.receiverList.pid);
12892 }
12893 }
12894 } else {
12895 app = r.curApp;
12896 }
12897
12898 if (app != null) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012899 anrMessage = "Broadcast of " + r.intent.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012900 }
12901
12902 if (mPendingBroadcast == r) {
12903 mPendingBroadcast = null;
12904 }
12905
12906 // Move on to the next receiver.
12907 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
12908 r.resultExtras, r.resultAbort, true);
12909 scheduleBroadcastsLocked();
12910 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012911
12912 if (anrMessage != null) {
12913 appNotResponding(app, null, null, anrMessage);
12914 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012915 }
12916
12917 private final void processCurBroadcastLocked(BroadcastRecord r,
12918 ProcessRecord app) throws RemoteException {
12919 if (app.thread == null) {
12920 throw new RemoteException();
12921 }
12922 r.receiver = app.thread.asBinder();
12923 r.curApp = app;
12924 app.curReceiver = r;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012925 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012926
12927 // Tell the application to launch this receiver.
12928 r.intent.setComponent(r.curComponent);
12929
12930 boolean started = false;
12931 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012932 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012933 "Delivering to component " + r.curComponent
12934 + ": " + r);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070012935 ensurePackageDexOpt(r.intent.getComponent().getPackageName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012936 app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
12937 r.resultCode, r.resultData, r.resultExtras, r.ordered);
12938 started = true;
12939 } finally {
12940 if (!started) {
12941 r.receiver = null;
12942 r.curApp = null;
12943 app.curReceiver = null;
12944 }
12945 }
12946
12947 }
12948
12949 static void performReceive(ProcessRecord app, IIntentReceiver receiver,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070012950 Intent intent, int resultCode, String data, Bundle extras,
12951 boolean ordered, boolean sticky) throws RemoteException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012952 if (app != null && app.thread != null) {
12953 // If we have an app thread, do the call through that so it is
12954 // correctly ordered with other one-way calls.
12955 app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070012956 data, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012957 } else {
Dianne Hackborn68d881c2009-10-05 13:58:17 -070012958 receiver.performReceive(intent, resultCode, data, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012959 }
12960 }
12961
12962 private final void deliverToRegisteredReceiver(BroadcastRecord r,
12963 BroadcastFilter filter, boolean ordered) {
12964 boolean skip = false;
12965 if (filter.requiredPermission != null) {
12966 int perm = checkComponentPermission(filter.requiredPermission,
12967 r.callingPid, r.callingUid, -1);
12968 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012969 Slog.w(TAG, "Permission Denial: broadcasting "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012970 + r.intent.toString()
12971 + " from " + r.callerPackage + " (pid="
12972 + r.callingPid + ", uid=" + r.callingUid + ")"
12973 + " requires " + filter.requiredPermission
12974 + " due to registered receiver " + filter);
12975 skip = true;
12976 }
12977 }
12978 if (r.requiredPermission != null) {
12979 int perm = checkComponentPermission(r.requiredPermission,
12980 filter.receiverList.pid, filter.receiverList.uid, -1);
12981 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012982 Slog.w(TAG, "Permission Denial: receiving "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012983 + r.intent.toString()
12984 + " to " + filter.receiverList.app
12985 + " (pid=" + filter.receiverList.pid
12986 + ", uid=" + filter.receiverList.uid + ")"
12987 + " requires " + r.requiredPermission
12988 + " due to sender " + r.callerPackage
12989 + " (uid " + r.callingUid + ")");
12990 skip = true;
12991 }
12992 }
12993
12994 if (!skip) {
12995 // If this is not being sent as an ordered broadcast, then we
12996 // don't want to touch the fields that keep track of the current
12997 // state of ordered broadcasts.
12998 if (ordered) {
12999 r.receiver = filter.receiverList.receiver.asBinder();
13000 r.curFilter = filter;
13001 filter.receiverList.curBroadcast = r;
13002 r.state = BroadcastRecord.CALL_IN_RECEIVE;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013003 if (filter.receiverList.app != null) {
13004 // Bump hosting application to no longer be in background
13005 // scheduling class. Note that we can't do that if there
13006 // isn't an app... but we can only be in that case for
13007 // things that directly call the IActivityManager API, which
13008 // are already core system stuff so don't matter for this.
13009 r.curApp = filter.receiverList.app;
13010 filter.receiverList.app.curReceiver = r;
13011 updateOomAdjLocked();
13012 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013013 }
13014 try {
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013015 if (DEBUG_BROADCAST_LIGHT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013016 int seq = r.intent.getIntExtra("seq", -1);
Dianne Hackborn399cccb2010-04-13 22:57:49 -070013017 Slog.i(TAG, "Delivering to " + filter
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013018 + " (seq=" + seq + "): " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013019 }
13020 performReceive(filter.receiverList.app, filter.receiverList.receiver,
13021 new Intent(r.intent), r.resultCode,
Dianne Hackborn12527f92009-11-11 17:39:50 -080013022 r.resultData, r.resultExtras, r.ordered, r.initialSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013023 if (ordered) {
13024 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
13025 }
13026 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013027 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013028 if (ordered) {
13029 r.receiver = null;
13030 r.curFilter = null;
13031 filter.receiverList.curBroadcast = null;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013032 if (filter.receiverList.app != null) {
13033 filter.receiverList.app.curReceiver = null;
13034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013035 }
13036 }
13037 }
13038 }
13039
Dianne Hackborn12527f92009-11-11 17:39:50 -080013040 private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
13041 if (r.callingUid < 0) {
13042 // This was from a registerReceiver() call; ignore it.
13043 return;
13044 }
13045 System.arraycopy(mBroadcastHistory, 0, mBroadcastHistory, 1,
13046 MAX_BROADCAST_HISTORY-1);
13047 r.finishTime = SystemClock.uptimeMillis();
13048 mBroadcastHistory[0] = r;
13049 }
13050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013051 private final void processNextBroadcast(boolean fromMsg) {
13052 synchronized(this) {
13053 BroadcastRecord r;
13054
Joe Onorato8a9b2202010-02-26 18:56:32 -080013055 if (DEBUG_BROADCAST) Slog.v(TAG, "processNextBroadcast: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013056 + mParallelBroadcasts.size() + " broadcasts, "
Dianne Hackborn399cccb2010-04-13 22:57:49 -070013057 + mOrderedBroadcasts.size() + " ordered broadcasts");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013058
13059 updateCpuStats();
13060
13061 if (fromMsg) {
13062 mBroadcastsScheduled = false;
13063 }
13064
13065 // First, deliver any non-serialized broadcasts right away.
13066 while (mParallelBroadcasts.size() > 0) {
13067 r = mParallelBroadcasts.remove(0);
Dianne Hackborn12527f92009-11-11 17:39:50 -080013068 r.dispatchTime = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013069 final int N = r.receivers.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013070 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing parallel broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013071 + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013072 for (int i=0; i<N; i++) {
13073 Object target = r.receivers.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013074 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn399cccb2010-04-13 22:57:49 -070013075 "Delivering non-ordered to registered "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013076 + target + ": " + r);
13077 deliverToRegisteredReceiver(r, (BroadcastFilter)target, false);
13078 }
Dianne Hackborn12527f92009-11-11 17:39:50 -080013079 addBroadcastToHistoryLocked(r);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013080 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Done with parallel broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013081 + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013082 }
13083
13084 // Now take care of the next serialized one...
13085
13086 // If we are waiting for a process to come up to handle the next
13087 // broadcast, then do nothing at this point. Just in case, we
13088 // check that the process we're waiting for still exists.
13089 if (mPendingBroadcast != null) {
Dianne Hackbornbd0a81f2009-10-04 13:30:50 -070013090 if (DEBUG_BROADCAST_LIGHT) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013091 Slog.v(TAG, "processNextBroadcast: waiting for "
Dianne Hackbornbd0a81f2009-10-04 13:30:50 -070013092 + mPendingBroadcast.curApp);
13093 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013094
13095 boolean isDead;
13096 synchronized (mPidsSelfLocked) {
13097 isDead = (mPidsSelfLocked.get(mPendingBroadcast.curApp.pid) == null);
13098 }
13099 if (!isDead) {
13100 // It's still alive, so keep waiting
13101 return;
13102 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013103 Slog.w(TAG, "pending app " + mPendingBroadcast.curApp
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013104 + " died before responding to broadcast");
13105 mPendingBroadcast = null;
13106 }
13107 }
13108
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013109 boolean looped = false;
13110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013111 do {
13112 if (mOrderedBroadcasts.size() == 0) {
13113 // No more broadcasts pending, so all done!
13114 scheduleAppGcsLocked();
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013115 if (looped) {
13116 // If we had finished the last ordered broadcast, then
13117 // make sure all processes have correct oom and sched
13118 // adjustments.
13119 updateOomAdjLocked();
13120 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013121 return;
13122 }
13123 r = mOrderedBroadcasts.get(0);
13124 boolean forceReceive = false;
13125
13126 // Ensure that even if something goes awry with the timeout
13127 // detection, we catch "hung" broadcasts here, discard them,
Jeff Hamiltonacf84742010-05-25 22:10:18 -050013128 // and continue to make progress.
13129 //
13130 // This is only done if the system is ready so that PRE_BOOT_COMPLETED
13131 // receivers don't get executed with with timeouts. They're intended for
13132 // one time heavy lifting after system upgrades and can take
13133 // significant amounts of time.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013134 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
Jeff Hamiltonacf84742010-05-25 22:10:18 -050013135 if (mSystemReady && r.dispatchTime > 0) {
13136 long now = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013137 if ((numReceivers > 0) &&
13138 (now > r.dispatchTime + (2*BROADCAST_TIMEOUT*numReceivers))) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013139 Slog.w(TAG, "Hung broadcast discarded after timeout failure:"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013140 + " now=" + now
13141 + " dispatchTime=" + r.dispatchTime
Dianne Hackborn12527f92009-11-11 17:39:50 -080013142 + " startTime=" + r.receiverTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013143 + " intent=" + r.intent
13144 + " numReceivers=" + numReceivers
13145 + " nextReceiver=" + r.nextReceiver
13146 + " state=" + r.state);
13147 broadcastTimeout(); // forcibly finish this broadcast
13148 forceReceive = true;
13149 r.state = BroadcastRecord.IDLE;
13150 }
13151 }
13152
13153 if (r.state != BroadcastRecord.IDLE) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013154 if (DEBUG_BROADCAST) Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013155 "processNextBroadcast() called when not idle (state="
13156 + r.state + ")");
13157 return;
13158 }
13159
13160 if (r.receivers == null || r.nextReceiver >= numReceivers
13161 || r.resultAbort || forceReceive) {
13162 // No more receivers for this broadcast! Send the final
13163 // result if requested...
13164 if (r.resultTo != null) {
13165 try {
13166 if (DEBUG_BROADCAST) {
13167 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013168 Slog.i(TAG, "Finishing broadcast " + r.intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013169 + " seq=" + seq + " app=" + r.callerApp);
13170 }
13171 performReceive(r.callerApp, r.resultTo,
13172 new Intent(r.intent), r.resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070013173 r.resultData, r.resultExtras, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013174 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013175 Slog.w(TAG, "Failure sending broadcast result of " + r.intent, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013176 }
13177 }
13178
Joe Onorato8a9b2202010-02-26 18:56:32 -080013179 if (DEBUG_BROADCAST) Slog.v(TAG, "Cancelling BROADCAST_TIMEOUT_MSG");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013180 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG);
13181
Joe Onorato8a9b2202010-02-26 18:56:32 -080013182 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Finished with ordered broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013183 + r);
13184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013185 // ... and on to the next...
Dianne Hackborn12527f92009-11-11 17:39:50 -080013186 addBroadcastToHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013187 mOrderedBroadcasts.remove(0);
13188 r = null;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013189 looped = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013190 continue;
13191 }
13192 } while (r == null);
13193
13194 // Get the next receiver...
13195 int recIdx = r.nextReceiver++;
13196
13197 // Keep track of when this receiver started, and make sure there
13198 // is a timeout message pending to kill it if need be.
Dianne Hackborn12527f92009-11-11 17:39:50 -080013199 r.receiverTime = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013200 if (recIdx == 0) {
Dianne Hackborn12527f92009-11-11 17:39:50 -080013201 r.dispatchTime = r.receiverTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013202
Joe Onorato8a9b2202010-02-26 18:56:32 -080013203 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing ordered broadcast "
Dianne Hackborn82f3f002009-06-16 18:49:05 -070013204 + r);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013205 if (DEBUG_BROADCAST) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013206 "Submitting BROADCAST_TIMEOUT_MSG for "
Dianne Hackborn12527f92009-11-11 17:39:50 -080013207 + (r.receiverTime + BROADCAST_TIMEOUT));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013208 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG);
Dianne Hackborn12527f92009-11-11 17:39:50 -080013209 mHandler.sendMessageAtTime(msg, r.receiverTime+BROADCAST_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013210 }
13211
13212 Object nextReceiver = r.receivers.get(recIdx);
13213 if (nextReceiver instanceof BroadcastFilter) {
13214 // Simple case: this is a registered receiver who gets
13215 // a direct call.
13216 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013217 if (DEBUG_BROADCAST) Slog.v(TAG,
Dianne Hackborn399cccb2010-04-13 22:57:49 -070013218 "Delivering ordered to registered "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013219 + filter + ": " + r);
13220 deliverToRegisteredReceiver(r, filter, r.ordered);
13221 if (r.receiver == null || !r.ordered) {
13222 // The receiver has already finished, so schedule to
13223 // process the next one.
Dianne Hackborn399cccb2010-04-13 22:57:49 -070013224 if (DEBUG_BROADCAST) Slog.v(TAG, "Quick finishing: ordered="
13225 + r.ordered + " receiver=" + r.receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013226 r.state = BroadcastRecord.IDLE;
13227 scheduleBroadcastsLocked();
13228 }
13229 return;
13230 }
13231
13232 // Hard case: need to instantiate the receiver, possibly
13233 // starting its application process to host it.
13234
13235 ResolveInfo info =
13236 (ResolveInfo)nextReceiver;
13237
13238 boolean skip = false;
13239 int perm = checkComponentPermission(info.activityInfo.permission,
13240 r.callingPid, r.callingUid,
13241 info.activityInfo.exported
13242 ? -1 : info.activityInfo.applicationInfo.uid);
13243 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013244 Slog.w(TAG, "Permission Denial: broadcasting "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013245 + r.intent.toString()
13246 + " from " + r.callerPackage + " (pid=" + r.callingPid
13247 + ", uid=" + r.callingUid + ")"
13248 + " requires " + info.activityInfo.permission
13249 + " due to receiver " + info.activityInfo.packageName
13250 + "/" + info.activityInfo.name);
13251 skip = true;
13252 }
13253 if (r.callingUid != Process.SYSTEM_UID &&
13254 r.requiredPermission != null) {
13255 try {
13256 perm = ActivityThread.getPackageManager().
13257 checkPermission(r.requiredPermission,
13258 info.activityInfo.applicationInfo.packageName);
13259 } catch (RemoteException e) {
13260 perm = PackageManager.PERMISSION_DENIED;
13261 }
13262 if (perm != PackageManager.PERMISSION_GRANTED) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013263 Slog.w(TAG, "Permission Denial: receiving "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013264 + r.intent + " to "
13265 + info.activityInfo.applicationInfo.packageName
13266 + " requires " + r.requiredPermission
13267 + " due to sender " + r.callerPackage
13268 + " (uid " + r.callingUid + ")");
13269 skip = true;
13270 }
13271 }
13272 if (r.curApp != null && r.curApp.crashing) {
13273 // If the target process is crashing, just skip it.
13274 skip = true;
13275 }
13276
13277 if (skip) {
13278 r.receiver = null;
13279 r.curFilter = null;
13280 r.state = BroadcastRecord.IDLE;
13281 scheduleBroadcastsLocked();
13282 return;
13283 }
13284
13285 r.state = BroadcastRecord.APP_RECEIVE;
13286 String targetProcess = info.activityInfo.processName;
13287 r.curComponent = new ComponentName(
13288 info.activityInfo.applicationInfo.packageName,
13289 info.activityInfo.name);
13290 r.curReceiver = info.activityInfo;
13291
13292 // Is this receiver's application already running?
13293 ProcessRecord app = getProcessRecordLocked(targetProcess,
13294 info.activityInfo.applicationInfo.uid);
13295 if (app != null && app.thread != null) {
13296 try {
13297 processCurBroadcastLocked(r, app);
13298 return;
13299 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013300 Slog.w(TAG, "Exception when sending broadcast to "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013301 + r.curComponent, e);
13302 }
13303
13304 // If a dead object exception was thrown -- fall through to
13305 // restart the application.
13306 }
13307
Dianne Hackborn9acc0302009-08-25 00:27:12 -070013308 // Not running -- get it started, to be executed when the app comes up.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013309 if ((r.curApp=startProcessLocked(targetProcess,
13310 info.activityInfo.applicationInfo, true,
13311 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
Dianne Hackborn9acc0302009-08-25 00:27:12 -070013312 "broadcast", r.curComponent,
13313 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0))
13314 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013315 // Ah, this recipient is unavailable. Finish it if necessary,
13316 // and mark the broadcast record as ready for the next.
Joe Onorato8a9b2202010-02-26 18:56:32 -080013317 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013318 + info.activityInfo.applicationInfo.packageName + "/"
13319 + info.activityInfo.applicationInfo.uid + " for broadcast "
13320 + r.intent + ": process is bad");
13321 logBroadcastReceiverDiscard(r);
13322 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
13323 r.resultExtras, r.resultAbort, true);
13324 scheduleBroadcastsLocked();
13325 r.state = BroadcastRecord.IDLE;
13326 return;
13327 }
13328
13329 mPendingBroadcast = r;
13330 }
13331 }
13332
13333 // =========================================================
13334 // INSTRUMENTATION
13335 // =========================================================
13336
13337 public boolean startInstrumentation(ComponentName className,
13338 String profileFile, int flags, Bundle arguments,
13339 IInstrumentationWatcher watcher) {
13340 // Refuse possible leaked file descriptors
13341 if (arguments != null && arguments.hasFileDescriptors()) {
13342 throw new IllegalArgumentException("File descriptors passed in Bundle");
13343 }
13344
13345 synchronized(this) {
13346 InstrumentationInfo ii = null;
13347 ApplicationInfo ai = null;
13348 try {
13349 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013350 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013351 ai = mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013352 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013353 } catch (PackageManager.NameNotFoundException e) {
13354 }
13355 if (ii == null) {
13356 reportStartInstrumentationFailure(watcher, className,
13357 "Unable to find instrumentation info for: " + className);
13358 return false;
13359 }
13360 if (ai == null) {
13361 reportStartInstrumentationFailure(watcher, className,
13362 "Unable to find instrumentation target package: " + ii.targetPackage);
13363 return false;
13364 }
13365
13366 int match = mContext.getPackageManager().checkSignatures(
13367 ii.targetPackage, ii.packageName);
13368 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
13369 String msg = "Permission Denial: starting instrumentation "
13370 + className + " from pid="
13371 + Binder.getCallingPid()
13372 + ", uid=" + Binder.getCallingPid()
13373 + " not allowed because package " + ii.packageName
13374 + " does not have a signature matching the target "
13375 + ii.targetPackage;
13376 reportStartInstrumentationFailure(watcher, className, msg);
13377 throw new SecurityException(msg);
13378 }
13379
13380 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080013381 forceStopPackageLocked(ii.targetPackage, -1, true, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013382 ProcessRecord app = addAppLocked(ai);
13383 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013384 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013385 app.instrumentationProfileFile = profileFile;
13386 app.instrumentationArguments = arguments;
13387 app.instrumentationWatcher = watcher;
13388 app.instrumentationResultClass = className;
13389 Binder.restoreCallingIdentity(origId);
13390 }
13391
13392 return true;
13393 }
13394
13395 /**
13396 * Report errors that occur while attempting to start Instrumentation. Always writes the
13397 * error to the logs, but if somebody is watching, send the report there too. This enables
13398 * the "am" command to report errors with more information.
13399 *
13400 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
13401 * @param cn The component name of the instrumentation.
13402 * @param report The error report.
13403 */
13404 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
13405 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013406 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013407 try {
13408 if (watcher != null) {
13409 Bundle results = new Bundle();
13410 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
13411 results.putString("Error", report);
13412 watcher.instrumentationStatus(cn, -1, results);
13413 }
13414 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013415 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013416 }
13417 }
13418
13419 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
13420 if (app.instrumentationWatcher != null) {
13421 try {
13422 // NOTE: IInstrumentationWatcher *must* be oneway here
13423 app.instrumentationWatcher.instrumentationFinished(
13424 app.instrumentationClass,
13425 resultCode,
13426 results);
13427 } catch (RemoteException e) {
13428 }
13429 }
13430 app.instrumentationWatcher = null;
13431 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013432 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013433 app.instrumentationProfileFile = null;
13434 app.instrumentationArguments = null;
13435
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080013436 forceStopPackageLocked(app.processName, -1, false, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013437 }
13438
13439 public void finishInstrumentation(IApplicationThread target,
13440 int resultCode, Bundle results) {
13441 // Refuse possible leaked file descriptors
13442 if (results != null && results.hasFileDescriptors()) {
13443 throw new IllegalArgumentException("File descriptors passed in Intent");
13444 }
13445
13446 synchronized(this) {
13447 ProcessRecord app = getRecordForAppLocked(target);
13448 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013449 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013450 return;
13451 }
13452 final long origId = Binder.clearCallingIdentity();
13453 finishInstrumentationLocked(app, resultCode, results);
13454 Binder.restoreCallingIdentity(origId);
13455 }
13456 }
13457
13458 // =========================================================
13459 // CONFIGURATION
13460 // =========================================================
13461
13462 public ConfigurationInfo getDeviceConfigurationInfo() {
13463 ConfigurationInfo config = new ConfigurationInfo();
13464 synchronized (this) {
13465 config.reqTouchScreen = mConfiguration.touchscreen;
13466 config.reqKeyboardType = mConfiguration.keyboard;
13467 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013468 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13469 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013470 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13471 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013472 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13473 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013474 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13475 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013476 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013477 }
13478 return config;
13479 }
13480
13481 public Configuration getConfiguration() {
13482 Configuration ci;
13483 synchronized(this) {
13484 ci = new Configuration(mConfiguration);
13485 }
13486 return ci;
13487 }
13488
13489 public void updateConfiguration(Configuration values) {
13490 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13491 "updateConfiguration()");
13492
13493 synchronized(this) {
13494 if (values == null && mWindowManager != null) {
13495 // sentinel: fetch the current configuration from the window manager
13496 values = mWindowManager.computeNewConfiguration();
13497 }
13498
13499 final long origId = Binder.clearCallingIdentity();
13500 updateConfigurationLocked(values, null);
13501 Binder.restoreCallingIdentity(origId);
13502 }
13503 }
13504
13505 /**
13506 * Do either or both things: (1) change the current configuration, and (2)
13507 * make sure the given activity is running with the (now) current
13508 * configuration. Returns true if the activity has been left running, or
13509 * false if <var>starting</var> is being destroyed to match the new
13510 * configuration.
13511 */
13512 public boolean updateConfigurationLocked(Configuration values,
13513 HistoryRecord starting) {
13514 int changes = 0;
13515
13516 boolean kept = true;
13517
13518 if (values != null) {
13519 Configuration newConfig = new Configuration(mConfiguration);
13520 changes = newConfig.updateFrom(values);
13521 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013522 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013523 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013524 }
13525
Doug Zongker2bec3d42009-12-04 12:52:44 -080013526 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013527
13528 if (values.locale != null) {
13529 saveLocaleLocked(values.locale,
13530 !values.locale.equals(mConfiguration.locale),
13531 values.userSetLocale);
13532 }
13533
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013534 mConfigurationSeq++;
13535 if (mConfigurationSeq <= 0) {
13536 mConfigurationSeq = 1;
13537 }
13538 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013539 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013540 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013541
13542 AttributeCache ac = AttributeCache.instance();
13543 if (ac != null) {
13544 ac.updateConfiguration(mConfiguration);
13545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013546
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013547 if (Settings.System.hasInterestingConfigurationChanges(changes)) {
13548 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
13549 msg.obj = new Configuration(mConfiguration);
13550 mHandler.sendMessage(msg);
13551 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013552
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013553 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13554 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013555 try {
13556 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013557 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013558 + app.processName + " new config " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013559 app.thread.scheduleConfigurationChanged(mConfiguration);
13560 }
13561 } catch (Exception e) {
13562 }
13563 }
13564 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013565 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13566 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013567 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
13568 null, false, false, MY_PID, Process.SYSTEM_UID);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013569 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13570 broadcastIntentLocked(null, null,
13571 new Intent(Intent.ACTION_LOCALE_CHANGED),
13572 null, null, 0, null, null,
13573 null, false, false, MY_PID, Process.SYSTEM_UID);
13574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013575 }
13576 }
13577
13578 if (changes != 0 && starting == null) {
13579 // If the configuration changed, and the caller is not already
13580 // in the process of starting an activity, then find the top
13581 // activity to check if its configuration needs to change.
13582 starting = topRunningActivityLocked(null);
13583 }
13584
13585 if (starting != null) {
13586 kept = ensureActivityConfigurationLocked(starting, changes);
13587 if (kept) {
13588 // If this didn't result in the starting activity being
13589 // destroyed, then we need to make sure at this point that all
13590 // other activities are made visible.
Joe Onorato8a9b2202010-02-26 18:56:32 -080013591 if (DEBUG_SWITCH) Slog.i(TAG, "Config didn't destroy " + starting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013592 + ", ensuring others are correct.");
13593 ensureActivitiesVisibleLocked(starting, changes);
13594 }
13595 }
13596
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013597 if (values != null && mWindowManager != null) {
13598 mWindowManager.setNewConfiguration(mConfiguration);
13599 }
13600
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013601 return kept;
13602 }
13603
13604 private final boolean relaunchActivityLocked(HistoryRecord r,
13605 int changes, boolean andResume) {
13606 List<ResultInfo> results = null;
13607 List<Intent> newIntents = null;
13608 if (andResume) {
13609 results = r.results;
13610 newIntents = r.newIntents;
13611 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080013612 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013613 + " with results=" + results + " newIntents=" + newIntents
13614 + " andResume=" + andResume);
Doug Zongker2bec3d42009-12-04 12:52:44 -080013615 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
13616 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013617 r.task.taskId, r.shortComponentName);
13618
13619 r.startFreezingScreenLocked(r.app, 0);
13620
13621 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013622 if (DEBUG_SWITCH) Slog.i(TAG, "Switch is restarting resumed " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013623 r.app.thread.scheduleRelaunchActivity(r, results, newIntents,
Dianne Hackborn871ecdc2009-12-11 15:24:33 -080013624 changes, !andResume, mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013625 // Note: don't need to call pauseIfSleepingLocked() here, because
13626 // the caller will only pass in 'andResume' if this activity is
13627 // currently resumed, which implies we aren't sleeping.
13628 } catch (RemoteException e) {
13629 return false;
13630 }
13631
13632 if (andResume) {
13633 r.results = null;
13634 r.newIntents = null;
Dianne Hackborn1bcf5a82009-09-30 15:22:29 -070013635 reportResumedActivityLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013636 }
13637
13638 return true;
13639 }
13640
13641 /**
13642 * Make sure the given activity matches the current configuration. Returns
13643 * false if the activity had to be destroyed. Returns true if the
13644 * configuration is the same, or the activity will remain running as-is
13645 * for whatever reason. Ensures the HistoryRecord is updated with the
13646 * correct configuration and all other bookkeeping is handled.
13647 */
13648 private final boolean ensureActivityConfigurationLocked(HistoryRecord r,
13649 int globalChanges) {
Dianne Hackborne2522462010-03-29 18:41:30 -070013650 if (mConfigWillChange) {
Dianne Hackbornd49258f2010-03-26 00:44:29 -070013651 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
13652 "Skipping config check (will change): " + r);
13653 return true;
13654 }
13655
Joe Onorato8a9b2202010-02-26 18:56:32 -080013656 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013657 "Ensuring correct configuration: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013658
13659 // Short circuit: if the two configurations are the exact same
13660 // object (the common case), then there is nothing to do.
13661 Configuration newConfig = mConfiguration;
13662 if (r.configuration == newConfig) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013663 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013664 "Configuration unchanged in " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013665 return true;
13666 }
13667
13668 // We don't worry about activities that are finishing.
13669 if (r.finishing) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013670 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013671 "Configuration doesn't matter in finishing " + r);
13672 r.stopFreezingScreenLocked(false);
13673 return true;
13674 }
13675
13676 // Okay we now are going to make this activity have the new config.
13677 // But then we need to figure out how it needs to deal with that.
13678 Configuration oldConfig = r.configuration;
13679 r.configuration = newConfig;
13680
13681 // If the activity isn't currently running, just leave the new
13682 // configuration and it will pick that up next time it starts.
13683 if (r.app == null || r.app.thread == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013684 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013685 "Configuration doesn't matter not running " + r);
13686 r.stopFreezingScreenLocked(false);
13687 return true;
13688 }
13689
13690 // If the activity isn't persistent, there is a chance we will
13691 // need to restart it.
13692 if (!r.persistent) {
13693
13694 // Figure out what has changed between the two configurations.
13695 int changes = oldConfig.diff(newConfig);
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013696 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013697 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013698 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013699 + Integer.toHexString(r.info.configChanges)
13700 + ", newConfig=" + newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013701 }
13702 if ((changes&(~r.info.configChanges)) != 0) {
13703 // Aha, the activity isn't handling the change, so DIE DIE DIE.
13704 r.configChangeFlags |= changes;
13705 r.startFreezingScreenLocked(r.app, globalChanges);
13706 if (r.app == null || r.app.thread == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013707 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013708 "Switch is destroying non-running " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013709 destroyActivityLocked(r, true);
13710 } else if (r.state == ActivityState.PAUSING) {
13711 // A little annoying: we are waiting for this activity to
13712 // finish pausing. Let's not do anything now, but just
13713 // flag that it needs to be restarted when done pausing.
Joe Onorato8a9b2202010-02-26 18:56:32 -080013714 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013715 "Switch is skipping already pausing " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013716 r.configDestroy = true;
13717 return true;
13718 } else if (r.state == ActivityState.RESUMED) {
13719 // Try to optimize this case: the configuration is changing
13720 // and we need to restart the top, resumed activity.
13721 // Instead of doing the normal handshaking, just say
13722 // "restart!".
Joe Onorato8a9b2202010-02-26 18:56:32 -080013723 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013724 "Switch is restarting resumed " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013725 relaunchActivityLocked(r, r.configChangeFlags, true);
13726 r.configChangeFlags = 0;
13727 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013728 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013729 "Switch is restarting non-resumed " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013730 relaunchActivityLocked(r, r.configChangeFlags, false);
13731 r.configChangeFlags = 0;
13732 }
13733
13734 // All done... tell the caller we weren't able to keep this
13735 // activity around.
13736 return false;
13737 }
13738 }
13739
13740 // Default case: the activity can handle this new configuration, so
13741 // hand it over. Note that we don't need to give it the new
13742 // configuration, since we always send configuration changes to all
13743 // process when they happen so it can just use whatever configuration
13744 // it last got.
13745 if (r.app != null && r.app.thread != null) {
13746 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013747 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013748 r.app.thread.scheduleActivityConfigurationChanged(r);
13749 } catch (RemoteException e) {
13750 // If process died, whatever.
13751 }
13752 }
13753 r.stopFreezingScreenLocked(false);
13754
13755 return true;
13756 }
13757
13758 /**
13759 * Save the locale. You must be inside a synchronized (this) block.
13760 */
13761 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13762 if(isDiff) {
13763 SystemProperties.set("user.language", l.getLanguage());
13764 SystemProperties.set("user.region", l.getCountry());
13765 }
13766
13767 if(isPersist) {
13768 SystemProperties.set("persist.sys.language", l.getLanguage());
13769 SystemProperties.set("persist.sys.country", l.getCountry());
13770 SystemProperties.set("persist.sys.localevar", l.getVariant());
13771 }
13772 }
13773
13774 // =========================================================
13775 // LIFETIME MANAGEMENT
13776 // =========================================================
13777
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013778 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
13779 ProcessRecord TOP_APP, boolean recursed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013780 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013781 // This adjustment has already been computed. If we are calling
13782 // from the top, we may have already computed our adjustment with
13783 // an earlier hidden adjustment that isn't really for us... if
13784 // so, use the new hidden adjustment.
13785 if (!recursed && app.hidden) {
13786 app.curAdj = hiddenAdj;
13787 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013788 return app.curAdj;
13789 }
13790
13791 if (app.thread == null) {
13792 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013793 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013794 return (app.curAdj=EMPTY_APP_ADJ);
13795 }
13796
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013797 if (app.maxAdj <= FOREGROUND_APP_ADJ) {
13798 // The max adjustment doesn't allow this app to be anything
13799 // below foreground, so it is not worth doing work for it.
13800 app.adjType = "fixed";
13801 app.adjSeq = mAdjSeq;
13802 app.curRawAdj = app.maxAdj;
13803 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
13804 return (app.curAdj=app.maxAdj);
13805 }
13806
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013807 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013808 app.adjSource = null;
13809 app.adjTarget = null;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013810 app.empty = false;
13811 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013812
The Android Open Source Project4df24232009-03-05 14:34:35 -080013813 // Determine the importance of the process, starting with most
13814 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013815 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013816 int schedGroup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013817 int N;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013818 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013819 // The last app on the list is the foreground app.
13820 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013821 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013822 app.adjType = "top-activity";
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013823 } else if (app.instrumentationClass != null) {
13824 // Don't want to kill running instrumentation.
13825 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013826 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013827 app.adjType = "instrumentation";
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013828 } else if (app.persistentActivities > 0) {
13829 // Special persistent activities... shouldn't be used these days.
13830 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013831 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013832 app.adjType = "persistent";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013833 } else if (app.curReceiver != null ||
13834 (mPendingBroadcast != null && mPendingBroadcast.curApp == app)) {
13835 // An app that is currently receiving a broadcast also
13836 // counts as being in the foreground.
13837 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013838 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013839 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013840 } else if (app.executingServices.size() > 0) {
13841 // An app that is currently executing a service callback also
13842 // counts as being in the foreground.
13843 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013844 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013845 app.adjType = "exec-service";
13846 } else if (app.foregroundServices) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013847 // The user is aware of this app, so make it visible.
13848 adj = VISIBLE_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013849 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013850 app.adjType = "foreground-service";
13851 } else if (app.forcingToForeground != null) {
13852 // The user is aware of this app, so make it visible.
13853 adj = VISIBLE_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013854 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013855 app.adjType = "force-foreground";
13856 app.adjSource = app.forcingToForeground;
The Android Open Source Project4df24232009-03-05 14:34:35 -080013857 } else if (app == mHomeProcess) {
13858 // This process is hosting what we currently consider to be the
13859 // home app, so we don't want to let it go into the background.
13860 adj = HOME_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013861 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013862 app.adjType = "home";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013863 } else if ((N=app.activities.size()) != 0) {
13864 // This app is in the background with paused activities.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013865 app.hidden = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013866 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013867 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013868 app.adjType = "bg-activities";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013869 N = app.activities.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013870 for (int j=0; j<N; j++) {
13871 if (((HistoryRecord)app.activities.get(j)).visible) {
13872 // This app has a visible activity!
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013873 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013874 adj = VISIBLE_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013875 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013876 app.adjType = "visible";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013877 break;
13878 }
13879 }
13880 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013881 // A very not-needed process. If this is lower in the lru list,
13882 // we will push it in to the empty bucket.
13883 app.hidden = true;
13884 app.empty = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013885 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013886 adj = hiddenAdj;
13887 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013888 }
13889
Joe Onorato8a9b2202010-02-26 18:56:32 -080013890 //Slog.i(TAG, "OOM " + app + ": initial adj=" + adj);
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013891
The Android Open Source Project4df24232009-03-05 14:34:35 -080013892 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013893 // there are applications dependent on our services or providers, but
13894 // this gives us a baseline and makes sure we don't get into an
13895 // infinite recursion.
13896 app.adjSeq = mAdjSeq;
13897 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013898
Christopher Tate6fa95972009-06-05 18:43:55 -070013899 if (mBackupTarget != null && app == mBackupTarget.app) {
13900 // If possible we want to avoid killing apps while they're being backed up
13901 if (adj > BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013902 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Christopher Tate6fa95972009-06-05 18:43:55 -070013903 adj = BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013904 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013905 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013906 }
13907 }
13908
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013909 if (app.services.size() != 0 && (adj > FOREGROUND_APP_ADJ
13910 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013911 final long now = SystemClock.uptimeMillis();
13912 // This process is more important if the top activity is
13913 // bound to the service.
13914 Iterator jt = app.services.iterator();
13915 while (jt.hasNext() && adj > FOREGROUND_APP_ADJ) {
13916 ServiceRecord s = (ServiceRecord)jt.next();
13917 if (s.startRequested) {
13918 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13919 // This service has seen some activity within
13920 // recent memory, so we will keep its process ahead
13921 // of the background processes.
13922 if (adj > SECONDARY_SERVER_ADJ) {
13923 adj = SECONDARY_SERVER_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013924 app.adjType = "started-services";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013925 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013926 }
13927 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013928 // If we have let the service slide into the background
13929 // state, still have some text describing what it is doing
13930 // even though the service no longer has an impact.
13931 if (adj > SECONDARY_SERVER_ADJ) {
13932 app.adjType = "started-bg-services";
13933 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013934 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013935 if (s.connections.size() > 0 && (adj > FOREGROUND_APP_ADJ
13936 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013937 Iterator<ConnectionRecord> kt
13938 = s.connections.values().iterator();
13939 while (kt.hasNext() && adj > FOREGROUND_APP_ADJ) {
13940 // XXX should compute this based on the max of
13941 // all connected clients.
13942 ConnectionRecord cr = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013943 if (cr.binding.client == app) {
13944 // Binding to ourself is not interesting.
13945 continue;
13946 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013947 if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
13948 ProcessRecord client = cr.binding.client;
13949 int myHiddenAdj = hiddenAdj;
13950 if (myHiddenAdj > client.hiddenAdj) {
13951 if (client.hiddenAdj > VISIBLE_APP_ADJ) {
13952 myHiddenAdj = client.hiddenAdj;
13953 } else {
13954 myHiddenAdj = VISIBLE_APP_ADJ;
13955 }
13956 }
13957 int clientAdj = computeOomAdjLocked(
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013958 client, myHiddenAdj, TOP_APP, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013959 if (adj > clientAdj) {
13960 adj = clientAdj > VISIBLE_APP_ADJ
13961 ? clientAdj : VISIBLE_APP_ADJ;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013962 if (!client.hidden) {
13963 app.hidden = false;
13964 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013965 app.adjType = "service";
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013966 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13967 .REASON_SERVICE_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013968 app.adjSource = cr.binding.client;
13969 app.adjTarget = s.serviceInfo.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013970 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013971 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13972 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13973 schedGroup = Process.THREAD_GROUP_DEFAULT;
13974 }
13975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013976 }
13977 HistoryRecord a = cr.activity;
13978 //if (a != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013979 // Slog.i(TAG, "Connection to " + a ": state=" + a.state);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013980 //}
13981 if (a != null && adj > FOREGROUND_APP_ADJ &&
13982 (a.state == ActivityState.RESUMED
13983 || a.state == ActivityState.PAUSING)) {
13984 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013985 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013986 app.hidden = false;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013987 app.adjType = "service";
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013988 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13989 .REASON_SERVICE_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013990 app.adjSource = a;
13991 app.adjTarget = s.serviceInfo.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013992 }
13993 }
13994 }
13995 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013996
13997 // Finally, f this process has active services running in it, we
13998 // would like to avoid killing it unless it would prevent the current
13999 // application from running. By default we put the process in
14000 // with the rest of the background processes; as we scan through
14001 // its services we may bump it up from there.
14002 if (adj > hiddenAdj) {
14003 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014004 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070014005 app.adjType = "bg-services";
14006 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014007 }
14008
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014009 if (app.pubProviders.size() != 0 && (adj > FOREGROUND_APP_ADJ
14010 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014011 Iterator jt = app.pubProviders.values().iterator();
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014012 while (jt.hasNext() && (adj > FOREGROUND_APP_ADJ
14013 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014014 ContentProviderRecord cpr = (ContentProviderRecord)jt.next();
14015 if (cpr.clients.size() != 0) {
14016 Iterator<ProcessRecord> kt = cpr.clients.iterator();
14017 while (kt.hasNext() && adj > FOREGROUND_APP_ADJ) {
14018 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070014019 if (client == app) {
14020 // Being our own client is not interesting.
14021 continue;
14022 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014023 int myHiddenAdj = hiddenAdj;
14024 if (myHiddenAdj > client.hiddenAdj) {
14025 if (client.hiddenAdj > FOREGROUND_APP_ADJ) {
14026 myHiddenAdj = client.hiddenAdj;
14027 } else {
14028 myHiddenAdj = FOREGROUND_APP_ADJ;
14029 }
14030 }
14031 int clientAdj = computeOomAdjLocked(
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014032 client, myHiddenAdj, TOP_APP, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014033 if (adj > clientAdj) {
14034 adj = clientAdj > FOREGROUND_APP_ADJ
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014035 ? clientAdj : FOREGROUND_APP_ADJ;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014036 if (!client.hidden) {
14037 app.hidden = false;
14038 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014039 app.adjType = "provider";
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070014040 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
14041 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014042 app.adjSource = client;
14043 app.adjTarget = cpr.info.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014044 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014045 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
14046 schedGroup = Process.THREAD_GROUP_DEFAULT;
14047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014048 }
14049 }
14050 // If the provider has external (non-framework) process
14051 // dependencies, ensure that its adjustment is at least
14052 // FOREGROUND_APP_ADJ.
14053 if (cpr.externals != 0) {
14054 if (adj > FOREGROUND_APP_ADJ) {
14055 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014056 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014057 app.hidden = false;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014058 app.adjType = "provider";
14059 app.adjTarget = cpr.info.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014060 }
14061 }
14062 }
14063 }
14064
14065 app.curRawAdj = adj;
14066
Joe Onorato8a9b2202010-02-26 18:56:32 -080014067 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014068 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
14069 if (adj > app.maxAdj) {
14070 adj = app.maxAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014071 if (app.maxAdj <= VISIBLE_APP_ADJ) {
14072 schedGroup = Process.THREAD_GROUP_DEFAULT;
14073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014074 }
14075
14076 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014077 app.curSchedGroup = schedGroup;
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014079 return adj;
14080 }
14081
14082 /**
14083 * Ask a given process to GC right now.
14084 */
14085 final void performAppGcLocked(ProcessRecord app) {
14086 try {
14087 app.lastRequestedGc = SystemClock.uptimeMillis();
14088 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014089 if (app.reportLowMemory) {
14090 app.reportLowMemory = false;
14091 app.thread.scheduleLowMemory();
14092 } else {
14093 app.thread.processInBackground();
14094 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014095 }
14096 } catch (Exception e) {
14097 // whatever.
14098 }
14099 }
14100
14101 /**
14102 * Returns true if things are idle enough to perform GCs.
14103 */
Josh Bartel7f208742010-02-25 11:01:44 -060014104 private final boolean canGcNowLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014105 return mParallelBroadcasts.size() == 0
14106 && mOrderedBroadcasts.size() == 0
14107 && (mSleeping || (mResumedActivity != null &&
14108 mResumedActivity.idle));
14109 }
14110
14111 /**
14112 * Perform GCs on all processes that are waiting for it, but only
14113 * if things are idle.
14114 */
14115 final void performAppGcsLocked() {
14116 final int N = mProcessesToGc.size();
14117 if (N <= 0) {
14118 return;
14119 }
Josh Bartel7f208742010-02-25 11:01:44 -060014120 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014121 while (mProcessesToGc.size() > 0) {
14122 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014123 if (proc.curRawAdj > VISIBLE_APP_ADJ || proc.reportLowMemory) {
14124 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
14125 <= SystemClock.uptimeMillis()) {
14126 // To avoid spamming the system, we will GC processes one
14127 // at a time, waiting a few seconds between each.
14128 performAppGcLocked(proc);
14129 scheduleAppGcsLocked();
14130 return;
14131 } else {
14132 // It hasn't been long enough since we last GCed this
14133 // process... put it in the list to wait for its time.
14134 addProcessToGcListLocked(proc);
14135 break;
14136 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014137 }
14138 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014139
14140 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014141 }
14142 }
14143
14144 /**
14145 * If all looks good, perform GCs on all processes waiting for them.
14146 */
14147 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060014148 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014149 performAppGcsLocked();
14150 return;
14151 }
14152 // Still not idle, wait some more.
14153 scheduleAppGcsLocked();
14154 }
14155
14156 /**
14157 * Schedule the execution of all pending app GCs.
14158 */
14159 final void scheduleAppGcsLocked() {
14160 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014161
14162 if (mProcessesToGc.size() > 0) {
14163 // Schedule a GC for the time to the next process.
14164 ProcessRecord proc = mProcessesToGc.get(0);
14165 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
14166
14167 long when = mProcessesToGc.get(0).lastRequestedGc + GC_MIN_INTERVAL;
14168 long now = SystemClock.uptimeMillis();
14169 if (when < (now+GC_TIMEOUT)) {
14170 when = now + GC_TIMEOUT;
14171 }
14172 mHandler.sendMessageAtTime(msg, when);
14173 }
14174 }
14175
14176 /**
14177 * Add a process to the array of processes waiting to be GCed. Keeps the
14178 * list in sorted order by the last GC time. The process can't already be
14179 * on the list.
14180 */
14181 final void addProcessToGcListLocked(ProcessRecord proc) {
14182 boolean added = false;
14183 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
14184 if (mProcessesToGc.get(i).lastRequestedGc <
14185 proc.lastRequestedGc) {
14186 added = true;
14187 mProcessesToGc.add(i+1, proc);
14188 break;
14189 }
14190 }
14191 if (!added) {
14192 mProcessesToGc.add(0, proc);
14193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014194 }
14195
14196 /**
14197 * Set up to ask a process to GC itself. This will either do it
14198 * immediately, or put it on the list of processes to gc the next
14199 * time things are idle.
14200 */
14201 final void scheduleAppGcLocked(ProcessRecord app) {
14202 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014203 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014204 return;
14205 }
14206 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014207 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014208 scheduleAppGcsLocked();
14209 }
14210 }
14211
14212 private final boolean updateOomAdjLocked(
14213 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP) {
14214 app.hiddenAdj = hiddenAdj;
14215
14216 if (app.thread == null) {
14217 return true;
14218 }
14219
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014220 int adj = computeOomAdjLocked(app, hiddenAdj, TOP_APP, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014221
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014222 if ((app.pid != 0 && app.pid != MY_PID) || Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014223 if (app.curRawAdj != app.setRawAdj) {
14224 if (app.curRawAdj > FOREGROUND_APP_ADJ
14225 && app.setRawAdj <= FOREGROUND_APP_ADJ) {
14226 // If this app is transitioning from foreground to
14227 // non-foreground, have it do a gc.
14228 scheduleAppGcLocked(app);
14229 } else if (app.curRawAdj >= HIDDEN_APP_MIN_ADJ
14230 && app.setRawAdj < HIDDEN_APP_MIN_ADJ) {
14231 // Likewise do a gc when an app is moving in to the
14232 // background (such as a service stopping).
14233 scheduleAppGcLocked(app);
14234 }
14235 app.setRawAdj = app.curRawAdj;
14236 }
14237 if (adj != app.setAdj) {
14238 if (Process.setOomAdj(app.pid, adj)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014239 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014240 TAG, "Set app " + app.processName +
14241 " oom adj to " + adj);
14242 app.setAdj = adj;
14243 } else {
14244 return false;
14245 }
14246 }
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014247 if (app.setSchedGroup != app.curSchedGroup) {
14248 app.setSchedGroup = app.curSchedGroup;
Joe Onorato8a9b2202010-02-26 18:56:32 -080014249 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014250 "Setting process group of " + app.processName
14251 + " to " + app.curSchedGroup);
14252 if (true) {
San Mehat9438de22009-06-10 09:11:28 -070014253 long oldId = Binder.clearCallingIdentity();
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014254 try {
14255 Process.setProcessGroup(app.pid, app.curSchedGroup);
14256 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014257 Slog.w(TAG, "Failed setting process group of " + app.pid
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014258 + " to " + app.curSchedGroup);
San Mehat9438de22009-06-10 09:11:28 -070014259 e.printStackTrace();
14260 } finally {
14261 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014262 }
14263 }
14264 if (false) {
14265 if (app.thread != null) {
14266 try {
14267 app.thread.setSchedulingGroup(app.curSchedGroup);
14268 } catch (RemoteException e) {
14269 }
14270 }
14271 }
14272 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014273 }
14274
14275 return true;
14276 }
14277
14278 private final HistoryRecord resumedAppLocked() {
14279 HistoryRecord resumedActivity = mResumedActivity;
14280 if (resumedActivity == null || resumedActivity.app == null) {
14281 resumedActivity = mPausingActivity;
14282 if (resumedActivity == null || resumedActivity.app == null) {
14283 resumedActivity = topRunningActivityLocked(null);
14284 }
14285 }
14286 return resumedActivity;
14287 }
14288
14289 private final boolean updateOomAdjLocked(ProcessRecord app) {
14290 final HistoryRecord TOP_ACT = resumedAppLocked();
14291 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14292 int curAdj = app.curAdj;
14293 final boolean wasHidden = app.curAdj >= HIDDEN_APP_MIN_ADJ
14294 && app.curAdj <= HIDDEN_APP_MAX_ADJ;
14295
14296 mAdjSeq++;
14297
14298 final boolean res = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP);
14299 if (res) {
14300 final boolean nowHidden = app.curAdj >= HIDDEN_APP_MIN_ADJ
14301 && app.curAdj <= HIDDEN_APP_MAX_ADJ;
14302 if (nowHidden != wasHidden) {
14303 // Changed to/from hidden state, so apps after it in the LRU
14304 // list may also be changed.
14305 updateOomAdjLocked();
14306 }
14307 }
14308 return res;
14309 }
14310
14311 private final boolean updateOomAdjLocked() {
14312 boolean didOomAdj = true;
14313 final HistoryRecord TOP_ACT = resumedAppLocked();
14314 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14315
14316 if (false) {
14317 RuntimeException e = new RuntimeException();
14318 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014319 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014320 }
14321
14322 mAdjSeq++;
14323
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014324 // Let's determine how many processes we have running vs.
14325 // how many slots we have for background processes; we may want
14326 // to put multiple processes in a slot of there are enough of
14327 // them.
14328 int numSlots = HIDDEN_APP_MAX_ADJ - HIDDEN_APP_MIN_ADJ + 1;
14329 int factor = (mLruProcesses.size()-4)/numSlots;
14330 if (factor < 1) factor = 1;
14331 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014332 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014334 // First try updating the OOM adjustment for each of the
14335 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014336 int i = mLruProcesses.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014337 int curHiddenAdj = HIDDEN_APP_MIN_ADJ;
14338 while (i > 0) {
14339 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014340 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014341 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014342 if (updateOomAdjLocked(app, curHiddenAdj, TOP_APP)) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014343 if (curHiddenAdj < EMPTY_APP_ADJ
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014344 && app.curAdj == curHiddenAdj) {
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014345 step++;
14346 if (step >= factor) {
14347 step = 0;
14348 curHiddenAdj++;
14349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014350 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070014351 if (app.curAdj >= HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn149427c2010-04-23 14:20:03 -070014352 if (!app.killedBackground) {
14353 numHidden++;
14354 if (numHidden > MAX_HIDDEN_APPS) {
Dianne Hackborn906497c2010-05-10 15:57:38 -070014355 Slog.i(TAG, "No longer want " + app.processName
14356 + " (pid " + app.pid + "): hidden #" + numHidden);
Dianne Hackborn149427c2010-04-23 14:20:03 -070014357 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14358 app.processName, app.setAdj, "too many background");
14359 app.killedBackground = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -070014360 Process.killProcessQuiet(app.pid);
Dianne Hackborn149427c2010-04-23 14:20:03 -070014361 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070014362 }
14363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014364 } else {
14365 didOomAdj = false;
14366 }
14367 }
14368
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014369 // If we return false, we will fall back on killing processes to
14370 // have a fixed limit. Do this if a limit has been requested; else
14371 // only return false if one of the adjustments failed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014372 return ENFORCE_PROCESS_LIMIT || mProcessLimit > 0 ? false : didOomAdj;
14373 }
14374
14375 private final void trimApplications() {
14376 synchronized (this) {
14377 int i;
14378
14379 // First remove any unused application processes whose package
14380 // has been removed.
14381 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14382 final ProcessRecord app = mRemovedProcesses.get(i);
14383 if (app.activities.size() == 0
14384 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014385 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014386 TAG, "Exiting empty application process "
14387 + app.processName + " ("
14388 + (app.thread != null ? app.thread.asBinder() : null)
14389 + ")\n");
14390 if (app.pid > 0 && app.pid != MY_PID) {
14391 Process.killProcess(app.pid);
14392 } else {
14393 try {
14394 app.thread.scheduleExit();
14395 } catch (Exception e) {
14396 // Ignore exceptions.
14397 }
14398 }
14399 cleanUpApplicationRecordLocked(app, false, -1);
14400 mRemovedProcesses.remove(i);
14401
14402 if (app.persistent) {
14403 if (app.persistent) {
14404 addAppLocked(app.info);
14405 }
14406 }
14407 }
14408 }
14409
14410 // Now try updating the OOM adjustment for each of the
14411 // application processes based on their current state.
14412 // If the setOomAdj() API is not supported, then go with our
14413 // back-up plan...
14414 if (!updateOomAdjLocked()) {
14415
14416 // Count how many processes are running services.
14417 int numServiceProcs = 0;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014418 for (i=mLruProcesses.size()-1; i>=0; i--) {
14419 final ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014420
14421 if (app.persistent || app.services.size() != 0
14422 || app.curReceiver != null
14423 || app.persistentActivities > 0) {
14424 // Don't count processes holding services against our
14425 // maximum process count.
Joe Onorato8a9b2202010-02-26 18:56:32 -080014426 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014427 TAG, "Not trimming app " + app + " with services: "
14428 + app.services);
14429 numServiceProcs++;
14430 }
14431 }
14432
14433 int curMaxProcs = mProcessLimit;
14434 if (curMaxProcs <= 0) curMaxProcs = MAX_PROCESSES;
14435 if (mAlwaysFinishActivities) {
14436 curMaxProcs = 1;
14437 }
14438 curMaxProcs += numServiceProcs;
14439
14440 // Quit as many processes as we can to get down to the desired
14441 // process count. First remove any processes that no longer
14442 // have activites running in them.
14443 for ( i=0;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014444 i<mLruProcesses.size()
14445 && mLruProcesses.size() > curMaxProcs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014446 i++) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014447 final ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014448 // Quit an application only if it is not currently
14449 // running any activities.
14450 if (!app.persistent && app.activities.size() == 0
14451 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014452 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014453 TAG, "Exiting empty application process "
14454 + app.processName + " ("
14455 + (app.thread != null ? app.thread.asBinder() : null)
14456 + ")\n");
14457 if (app.pid > 0 && app.pid != MY_PID) {
14458 Process.killProcess(app.pid);
14459 } else {
14460 try {
14461 app.thread.scheduleExit();
14462 } catch (Exception e) {
14463 // Ignore exceptions.
14464 }
14465 }
14466 // todo: For now we assume the application is not buggy
14467 // or evil, and will quit as a result of our request.
14468 // Eventually we need to drive this off of the death
14469 // notification, and kill the process if it takes too long.
14470 cleanUpApplicationRecordLocked(app, false, i);
14471 i--;
14472 }
14473 }
14474
14475 // If we still have too many processes, now from the least
14476 // recently used process we start finishing activities.
Joe Onorato8a9b2202010-02-26 18:56:32 -080014477 if (Config.LOGV) Slog.v(
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014478 TAG, "*** NOW HAVE " + mLruProcesses.size() +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014479 " of " + curMaxProcs + " processes");
14480 for ( i=0;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014481 i<mLruProcesses.size()
14482 && mLruProcesses.size() > curMaxProcs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014483 i++) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014484 final ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014485 // Quit the application only if we have a state saved for
14486 // all of its activities.
14487 boolean canQuit = !app.persistent && app.curReceiver == null
14488 && app.services.size() == 0
14489 && app.persistentActivities == 0;
14490 int NUMA = app.activities.size();
14491 int j;
Joe Onorato8a9b2202010-02-26 18:56:32 -080014492 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014493 TAG, "Looking to quit " + app.processName);
14494 for (j=0; j<NUMA && canQuit; j++) {
14495 HistoryRecord r = (HistoryRecord)app.activities.get(j);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014496 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014497 TAG, " " + r.intent.getComponent().flattenToShortString()
14498 + ": frozen=" + r.haveState + ", visible=" + r.visible);
14499 canQuit = (r.haveState || !r.stateNotNeeded)
14500 && !r.visible && r.stopped;
14501 }
14502 if (canQuit) {
14503 // Finish all of the activities, and then the app itself.
14504 for (j=0; j<NUMA; j++) {
14505 HistoryRecord r = (HistoryRecord)app.activities.get(j);
14506 if (!r.finishing) {
14507 destroyActivityLocked(r, false);
14508 }
14509 r.resultTo = null;
14510 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080014511 Slog.i(TAG, "Exiting application process "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014512 + app.processName + " ("
14513 + (app.thread != null ? app.thread.asBinder() : null)
14514 + ")\n");
14515 if (app.pid > 0 && app.pid != MY_PID) {
14516 Process.killProcess(app.pid);
14517 } else {
14518 try {
14519 app.thread.scheduleExit();
14520 } catch (Exception e) {
14521 // Ignore exceptions.
14522 }
14523 }
14524 // todo: For now we assume the application is not buggy
14525 // or evil, and will quit as a result of our request.
14526 // Eventually we need to drive this off of the death
14527 // notification, and kill the process if it takes too long.
14528 cleanUpApplicationRecordLocked(app, false, i);
14529 i--;
14530 //dump();
14531 }
14532 }
14533
14534 }
14535
14536 int curMaxActivities = MAX_ACTIVITIES;
14537 if (mAlwaysFinishActivities) {
14538 curMaxActivities = 1;
14539 }
14540
14541 // Finally, if there are too many activities now running, try to
14542 // finish as many as we can to get back down to the limit.
14543 for ( i=0;
14544 i<mLRUActivities.size()
14545 && mLRUActivities.size() > curMaxActivities;
14546 i++) {
14547 final HistoryRecord r
14548 = (HistoryRecord)mLRUActivities.get(i);
14549
14550 // We can finish this one if we have its icicle saved and
14551 // it is not persistent.
14552 if ((r.haveState || !r.stateNotNeeded) && !r.visible
14553 && r.stopped && !r.persistent && !r.finishing) {
14554 final int origSize = mLRUActivities.size();
14555 destroyActivityLocked(r, true);
14556
14557 // This will remove it from the LRU list, so keep
14558 // our index at the same value. Note that this check to
14559 // see if the size changes is just paranoia -- if
14560 // something unexpected happens, we don't want to end up
14561 // in an infinite loop.
14562 if (origSize > mLRUActivities.size()) {
14563 i--;
14564 }
14565 }
14566 }
14567 }
14568 }
14569
14570 /** This method sends the specified signal to each of the persistent apps */
14571 public void signalPersistentProcesses(int sig) throws RemoteException {
14572 if (sig != Process.SIGNAL_USR1) {
14573 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14574 }
14575
14576 synchronized (this) {
14577 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14578 != PackageManager.PERMISSION_GRANTED) {
14579 throw new SecurityException("Requires permission "
14580 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14581 }
14582
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014583 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14584 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014585 if (r.thread != null && r.persistent) {
14586 Process.sendSignal(r.pid, sig);
14587 }
14588 }
14589 }
14590 }
14591
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014592 public boolean profileControl(String process, boolean start,
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014593 String path, ParcelFileDescriptor fd) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014594
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014595 try {
14596 synchronized (this) {
14597 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14598 // its own permission.
14599 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14600 != PackageManager.PERMISSION_GRANTED) {
14601 throw new SecurityException("Requires permission "
14602 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014603 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014604
14605 if (start && fd == null) {
14606 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014607 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014608
14609 ProcessRecord proc = null;
14610 try {
14611 int pid = Integer.parseInt(process);
14612 synchronized (mPidsSelfLocked) {
14613 proc = mPidsSelfLocked.get(pid);
14614 }
14615 } catch (NumberFormatException e) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014616 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014617
14618 if (proc == null) {
14619 HashMap<String, SparseArray<ProcessRecord>> all
14620 = mProcessNames.getMap();
14621 SparseArray<ProcessRecord> procs = all.get(process);
14622 if (procs != null && procs.size() > 0) {
14623 proc = procs.valueAt(0);
14624 }
14625 }
14626
14627 if (proc == null || proc.thread == null) {
14628 throw new IllegalArgumentException("Unknown process: " + process);
14629 }
14630
14631 boolean isSecure = "1".equals(SystemProperties.get(SYSTEM_SECURE, "0"));
14632 if (isSecure) {
14633 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14634 throw new SecurityException("Process not debuggable: " + proc);
14635 }
14636 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014637
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014638 proc.thread.profilerControl(start, path, fd);
14639 fd = null;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014640 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014641 }
14642 } catch (RemoteException e) {
14643 throw new IllegalStateException("Process disappeared");
14644 } finally {
14645 if (fd != null) {
14646 try {
14647 fd.close();
14648 } catch (IOException e) {
14649 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014650 }
14651 }
14652 }
14653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014654 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14655 public void monitor() {
14656 synchronized (this) { }
14657 }
14658}