blob: 40d194c524b9235a3aabedb14def18d107560110 [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.app.IActivityWatcher;
39import android.app.IApplicationThread;
40import android.app.IInstrumentationWatcher;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.app.IServiceConnection;
42import android.app.IThumbnailReceiver;
43import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070044import android.app.Notification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.app.PendingIntent;
46import android.app.ResultInfo;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070047import android.app.Service;
Christopher Tate181fafa2009-05-14 11:12:14 -070048import android.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020049import android.content.ActivityNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.content.ComponentName;
51import android.content.ContentResolver;
52import android.content.Context;
53import android.content.Intent;
54import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070055import android.content.IIntentReceiver;
56import android.content.IIntentSender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070057import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.content.pm.ActivityInfo;
59import android.content.pm.ApplicationInfo;
60import android.content.pm.ConfigurationInfo;
61import android.content.pm.IPackageDataObserver;
62import android.content.pm.IPackageManager;
63import android.content.pm.InstrumentationInfo;
64import android.content.pm.PackageManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070065import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.content.pm.ProviderInfo;
67import android.content.pm.ResolveInfo;
68import android.content.pm.ServiceInfo;
69import android.content.res.Configuration;
70import android.graphics.Bitmap;
71import android.net.Uri;
72import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080073import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080074import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070075import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080076import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080078import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.os.FileUtils;
80import android.os.Handler;
81import android.os.IBinder;
82import android.os.IPermissionController;
83import android.os.Looper;
84import android.os.Message;
85import android.os.Parcel;
86import android.os.ParcelFileDescriptor;
87import android.os.PowerManager;
88import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070089import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.os.RemoteException;
91import android.os.ServiceManager;
92import android.os.SystemClock;
93import android.os.SystemProperties;
94import android.provider.Checkin;
95import android.provider.Settings;
96import android.text.TextUtils;
97import android.util.Config;
98import android.util.EventLog;
99import android.util.Log;
100import android.util.PrintWriterPrinter;
101import android.util.SparseArray;
102import android.view.Gravity;
103import android.view.LayoutInflater;
104import android.view.View;
105import android.view.WindowManager;
106import android.view.WindowManagerPolicy;
107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import java.io.File;
109import java.io.FileDescriptor;
110import java.io.FileInputStream;
111import java.io.FileNotFoundException;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200112import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import java.io.PrintWriter;
114import java.lang.IllegalStateException;
115import java.lang.ref.WeakReference;
116import java.util.ArrayList;
117import java.util.HashMap;
118import java.util.HashSet;
119import java.util.Iterator;
120import java.util.List;
121import java.util.Locale;
122import java.util.Map;
123
124public final class ActivityManagerService extends ActivityManagerNative implements Watchdog.Monitor {
125 static final String TAG = "ActivityManager";
126 static final boolean DEBUG = false;
127 static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
128 static final boolean DEBUG_SWITCH = localLOGV || false;
129 static final boolean DEBUG_TASKS = localLOGV || false;
130 static final boolean DEBUG_PAUSE = localLOGV || false;
131 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
132 static final boolean DEBUG_TRANSITION = localLOGV || false;
133 static final boolean DEBUG_BROADCAST = localLOGV || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700134 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 static final boolean DEBUG_SERVICE = localLOGV || false;
136 static final boolean DEBUG_VISBILITY = localLOGV || false;
137 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700138 static final boolean DEBUG_PROVIDER = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700140 static final boolean DEBUG_RESULTS = localLOGV || false;
Christopher Tate436344a2009-09-30 16:17:37 -0700141 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700142 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143 static final boolean VALIDATE_TOKENS = false;
144 static final boolean SHOW_ACTIVITY_START_TIME = true;
145
146 // Control over CPU and battery monitoring.
147 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
148 static final boolean MONITOR_CPU_USAGE = true;
149 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
150 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
151 static final boolean MONITOR_THREAD_CPU_USAGE = false;
152
Dianne Hackborn1655be42009-05-08 14:29:01 -0700153 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700154 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156 private static final String SYSTEM_SECURE = "ro.secure";
157
158 // This is the maximum number of application processes we would like
159 // to have running. Due to the asynchronous nature of things, we can
160 // temporarily go beyond this limit.
161 static final int MAX_PROCESSES = 2;
162
163 // Set to false to leave processes running indefinitely, relying on
164 // the kernel killing them as resources are required.
165 static final boolean ENFORCE_PROCESS_LIMIT = false;
166
167 // This is the maximum number of activities that we would like to have
168 // running at a given time.
169 static final int MAX_ACTIVITIES = 20;
170
171 // Maximum number of recent tasks that we can remember.
172 static final int MAX_RECENT_TASKS = 20;
173
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700174 // Amount of time after a call to stopAppSwitches() during which we will
175 // prevent further untrusted switches from happening.
176 static final long APP_SWITCH_DELAY_TIME = 5*1000;
177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 // How long until we reset a task when the user returns to it. Currently
179 // 30 minutes.
180 static final long ACTIVITY_INACTIVE_RESET_TIME = 1000*60*30;
181
182 // Set to true to disable the icon that is shown while a new activity
183 // is being started.
184 static final boolean SHOW_APP_STARTING_ICON = true;
185
186 // How long we wait until giving up on the last activity to pause. This
187 // is short because it directly impacts the responsiveness of starting the
188 // next activity.
189 static final int PAUSE_TIMEOUT = 500;
190
191 /**
192 * How long we can hold the launch wake lock before giving up.
193 */
194 static final int LAUNCH_TIMEOUT = 10*1000;
195
196 // How long we wait for a launched process to attach to the activity manager
197 // before we decide it's never going to come up for real.
198 static final int PROC_START_TIMEOUT = 10*1000;
199
200 // How long we wait until giving up on the last activity telling us it
201 // is idle.
202 static final int IDLE_TIMEOUT = 10*1000;
203
204 // How long to wait after going idle before forcing apps to GC.
205 static final int GC_TIMEOUT = 5*1000;
206
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700207 // The minimum amount of time between successive GC requests for a process.
208 static final int GC_MIN_INTERVAL = 60*1000;
209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 // How long we wait until giving up on an activity telling us it has
211 // finished destroying itself.
212 static final int DESTROY_TIMEOUT = 10*1000;
213
214 // How long we allow a receiver to run before giving up on it.
215 static final int BROADCAST_TIMEOUT = 10*1000;
216
217 // How long we wait for a service to finish executing.
218 static final int SERVICE_TIMEOUT = 20*1000;
219
220 // How long a service needs to be running until restarting its process
221 // is no longer considered to be a relaunch of the service.
222 static final int SERVICE_RESTART_DURATION = 5*1000;
223
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700224 // How long a service needs to be running until it will start back at
225 // SERVICE_RESTART_DURATION after being killed.
226 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
227
228 // Multiplying factor to increase restart duration time by, for each time
229 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
230 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
231
232 // The minimum amount of time between restarting services that we allow.
233 // That is, when multiple services are restarting, we won't allow each
234 // to restart less than this amount of time from the last one.
235 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 // Maximum amount of time for there to be no activity on a service before
238 // we consider it non-essential and allow its process to go on the
239 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700240 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241
242 // How long we wait until we timeout on key dispatching.
243 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
244
245 // The minimum time we allow between crashes, for us to consider this
246 // application to be bad and stop and its services and reject broadcasts.
247 static final int MIN_CRASH_INTERVAL = 60*1000;
248
249 // How long we wait until we timeout on key dispatching during instrumentation.
250 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
251
252 // OOM adjustments for processes in various states:
253
254 // This is a process without anything currently running in it. Definitely
255 // the first to go! Value set in system/rootdir/init.rc on startup.
256 // This value is initalized in the constructor, careful when refering to
257 // this static variable externally.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800258 static final int EMPTY_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259
260 // This is a process only hosting activities that are not visible,
261 // so it can be killed without any disruption. Value set in
262 // system/rootdir/init.rc on startup.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800263 static final int HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 static int HIDDEN_APP_MIN_ADJ;
265
The Android Open Source Project4df24232009-03-05 14:34:35 -0800266 // This is a process holding the home application -- we want to try
267 // avoiding killing it, even if it would normally be in the background,
268 // because the user interacts with it so much.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800269 static final int HOME_APP_ADJ;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800270
Christopher Tate6fa95972009-06-05 18:43:55 -0700271 // This is a process currently hosting a backup operation. Killing it
272 // is not entirely fatal but is generally a bad idea.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800273 static final int BACKUP_APP_ADJ;
Christopher Tate6fa95972009-06-05 18:43:55 -0700274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 // This is a process holding a secondary server -- killing it will not
276 // have much of an impact as far as the user is concerned. Value set in
277 // system/rootdir/init.rc on startup.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800278 static final int SECONDARY_SERVER_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279
280 // This is a process only hosting activities that are visible to the
281 // user, so we'd prefer they don't disappear. Value set in
282 // system/rootdir/init.rc on startup.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800283 static final int VISIBLE_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284
285 // This is the process running the current foreground app. We'd really
286 // rather not kill it! Value set in system/rootdir/init.rc on startup.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800287 static final int FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800288
289 // This is a process running a core server, such as telephony. Definitely
290 // don't want to kill it, but doing so is not completely fatal.
291 static final int CORE_SERVER_ADJ = -12;
292
293 // The system process runs at the default adjustment.
294 static final int SYSTEM_ADJ = -16;
295
296 // Memory pages are 4K.
297 static final int PAGE_SIZE = 4*1024;
298
Jacek Surazski82a73df2009-06-17 14:33:18 +0200299 // System property defining error report receiver for system apps
300 static final String SYSTEM_APPS_ERROR_RECEIVER_PROPERTY = "ro.error.receiver.system.apps";
301
302 // System property defining default error report receiver
303 static final String DEFAULT_ERROR_RECEIVER_PROPERTY = "ro.error.receiver.default";
304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800305 // Corresponding memory levels for above adjustments.
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800306 static final int EMPTY_APP_MEM;
307 static final int HIDDEN_APP_MEM;
308 static final int HOME_APP_MEM;
309 static final int BACKUP_APP_MEM;
310 static final int SECONDARY_SERVER_MEM;
311 static final int VISIBLE_APP_MEM;
312 static final int FOREGROUND_APP_MEM;
313
314 // The minimum number of hidden apps we want to be able to keep around,
315 // without empty apps being able to push them out of memory.
316 static final int MIN_HIDDEN_APPS = 2;
317
318 // We put empty content processes after any hidden processes that have
319 // been idle for less than 30 seconds.
320 static final long CONTENT_APP_IDLE_OFFSET = 30*1000;
321
322 // We put empty content processes after any hidden processes that have
323 // been idle for less than 60 seconds.
324 static final long EMPTY_APP_IDLE_OFFSET = 60*1000;
325
326 static {
327 // These values are set in system/rootdir/init.rc on startup.
328 FOREGROUND_APP_ADJ =
329 Integer.valueOf(SystemProperties.get("ro.FOREGROUND_APP_ADJ"));
330 VISIBLE_APP_ADJ =
331 Integer.valueOf(SystemProperties.get("ro.VISIBLE_APP_ADJ"));
332 SECONDARY_SERVER_ADJ =
333 Integer.valueOf(SystemProperties.get("ro.SECONDARY_SERVER_ADJ"));
334 BACKUP_APP_ADJ =
335 Integer.valueOf(SystemProperties.get("ro.BACKUP_APP_ADJ"));
336 HOME_APP_ADJ =
337 Integer.valueOf(SystemProperties.get("ro.HOME_APP_ADJ"));
338 HIDDEN_APP_MIN_ADJ =
339 Integer.valueOf(SystemProperties.get("ro.HIDDEN_APP_MIN_ADJ"));
340 EMPTY_APP_ADJ =
341 Integer.valueOf(SystemProperties.get("ro.EMPTY_APP_ADJ"));
342 HIDDEN_APP_MAX_ADJ = EMPTY_APP_ADJ-1;
343 FOREGROUND_APP_MEM =
344 Integer.valueOf(SystemProperties.get("ro.FOREGROUND_APP_MEM"))*PAGE_SIZE;
345 VISIBLE_APP_MEM =
346 Integer.valueOf(SystemProperties.get("ro.VISIBLE_APP_MEM"))*PAGE_SIZE;
347 SECONDARY_SERVER_MEM =
348 Integer.valueOf(SystemProperties.get("ro.SECONDARY_SERVER_MEM"))*PAGE_SIZE;
349 BACKUP_APP_MEM =
350 Integer.valueOf(SystemProperties.get("ro.BACKUP_APP_MEM"))*PAGE_SIZE;
351 HOME_APP_MEM =
352 Integer.valueOf(SystemProperties.get("ro.HOME_APP_MEM"))*PAGE_SIZE;
353 HIDDEN_APP_MEM =
354 Integer.valueOf(SystemProperties.get("ro.HIDDEN_APP_MEM"))*PAGE_SIZE;
355 EMPTY_APP_MEM =
356 Integer.valueOf(SystemProperties.get("ro.EMPTY_APP_MEM"))*PAGE_SIZE;
357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358
Dan Egnor42471dd2010-01-07 17:25:22 -0800359 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360
361 static final String[] EMPTY_STRING_ARRAY = new String[0];
362
363 enum ActivityState {
364 INITIALIZING,
365 RESUMED,
366 PAUSING,
367 PAUSED,
368 STOPPING,
369 STOPPED,
370 FINISHING,
371 DESTROYING,
372 DESTROYED
373 }
374
375 /**
376 * The back history of all previous (and possibly still
377 * running) activities. It contains HistoryRecord objects.
378 */
379 final ArrayList mHistory = new ArrayList();
380
381 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700382 * Description of a request to start a new activity, which has been held
383 * due to app switches being disabled.
384 */
385 class PendingActivityLaunch {
386 HistoryRecord r;
387 HistoryRecord sourceRecord;
388 Uri[] grantedUriPermissions;
389 int grantedMode;
390 boolean onlyIfNeeded;
391 }
392
393 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
394 = new ArrayList<PendingActivityLaunch>();
395
396 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800397 * List of all active broadcasts that are to be executed immediately
398 * (without waiting for another broadcast to finish). Currently this only
399 * contains broadcasts to registered receivers, to avoid spinning up
400 * a bunch of processes to execute IntentReceiver components.
401 */
402 final ArrayList<BroadcastRecord> mParallelBroadcasts
403 = new ArrayList<BroadcastRecord>();
404
405 /**
406 * List of all active broadcasts that are to be executed one at a time.
407 * The object at the top of the list is the currently activity broadcasts;
408 * those after it are waiting for the top to finish..
409 */
410 final ArrayList<BroadcastRecord> mOrderedBroadcasts
411 = new ArrayList<BroadcastRecord>();
412
413 /**
Dianne Hackborn12527f92009-11-11 17:39:50 -0800414 * Historical data of past broadcasts, for debugging.
415 */
416 static final int MAX_BROADCAST_HISTORY = 100;
417 final BroadcastRecord[] mBroadcastHistory
418 = new BroadcastRecord[MAX_BROADCAST_HISTORY];
419
420 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800421 * Set when we current have a BROADCAST_INTENT_MSG in flight.
422 */
423 boolean mBroadcastsScheduled = false;
424
425 /**
426 * Set to indicate whether to issue an onUserLeaving callback when a
427 * newly launched activity is being brought in front of us.
428 */
429 boolean mUserLeaving = false;
430
431 /**
432 * When we are in the process of pausing an activity, before starting the
433 * next one, this variable holds the activity that is currently being paused.
434 */
435 HistoryRecord mPausingActivity = null;
436
437 /**
438 * Current activity that is resumed, or null if there is none.
439 */
440 HistoryRecord mResumedActivity = null;
441
442 /**
443 * Activity we have told the window manager to have key focus.
444 */
445 HistoryRecord mFocusedActivity = null;
446
447 /**
448 * This is the last activity that we put into the paused state. This is
449 * used to determine if we need to do an activity transition while sleeping,
450 * when we normally hold the top activity paused.
451 */
452 HistoryRecord mLastPausedActivity = null;
453
454 /**
455 * List of activities that are waiting for a new activity
456 * to become visible before completing whatever operation they are
457 * supposed to do.
458 */
459 final ArrayList mWaitingVisibleActivities = new ArrayList();
460
461 /**
462 * List of activities that are ready to be stopped, but waiting
463 * for the next activity to settle down before doing so. It contains
464 * HistoryRecord objects.
465 */
466 final ArrayList<HistoryRecord> mStoppingActivities
467 = new ArrayList<HistoryRecord>();
468
469 /**
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700470 * Animations that for the current transition have requested not to
471 * be considered for the transition animation.
472 */
473 final ArrayList<HistoryRecord> mNoAnimActivities
474 = new ArrayList<HistoryRecord>();
475
476 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 * List of intents that were used to start the most recent tasks.
478 */
479 final ArrayList<TaskRecord> mRecentTasks
480 = new ArrayList<TaskRecord>();
481
482 /**
483 * List of activities that are ready to be finished, but waiting
484 * for the previous activity to settle down before doing so. It contains
485 * HistoryRecord objects.
486 */
487 final ArrayList mFinishingActivities = new ArrayList();
488
489 /**
490 * All of the applications we currently have running organized by name.
491 * The keys are strings of the application package name (as
492 * returned by the package manager), and the keys are ApplicationRecord
493 * objects.
494 */
495 final ProcessMap<ProcessRecord> mProcessNames
496 = new ProcessMap<ProcessRecord>();
497
498 /**
499 * The last time that various processes have crashed.
500 */
501 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
502
503 /**
504 * Set of applications that we consider to be bad, and will reject
505 * incoming broadcasts from (which the user has no control over).
506 * Processes are added to this set when they have crashed twice within
507 * a minimum amount of time; they are removed from it when they are
508 * later restarted (hopefully due to some user action). The value is the
509 * time it was added to the list.
510 */
511 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
512
513 /**
514 * All of the processes we currently have running organized by pid.
515 * The keys are the pid running the application.
516 *
517 * <p>NOTE: This object is protected by its own lock, NOT the global
518 * activity manager lock!
519 */
520 final SparseArray<ProcessRecord> mPidsSelfLocked
521 = new SparseArray<ProcessRecord>();
522
523 /**
524 * All of the processes that have been forced to be foreground. The key
525 * is the pid of the caller who requested it (we hold a death
526 * link on it).
527 */
528 abstract class ForegroundToken implements IBinder.DeathRecipient {
529 int pid;
530 IBinder token;
531 }
532 final SparseArray<ForegroundToken> mForegroundProcesses
533 = new SparseArray<ForegroundToken>();
534
535 /**
536 * List of records for processes that someone had tried to start before the
537 * system was ready. We don't start them at that point, but ensure they
538 * are started by the time booting is complete.
539 */
540 final ArrayList<ProcessRecord> mProcessesOnHold
541 = new ArrayList<ProcessRecord>();
542
543 /**
544 * List of records for processes that we have started and are waiting
545 * for them to call back. This is really only needed when running in
546 * single processes mode, in which case we do not have a unique pid for
547 * each process.
548 */
549 final ArrayList<ProcessRecord> mStartingProcesses
550 = new ArrayList<ProcessRecord>();
551
552 /**
553 * List of persistent applications that are in the process
554 * of being started.
555 */
556 final ArrayList<ProcessRecord> mPersistentStartingProcesses
557 = new ArrayList<ProcessRecord>();
558
559 /**
560 * Processes that are being forcibly torn down.
561 */
562 final ArrayList<ProcessRecord> mRemovedProcesses
563 = new ArrayList<ProcessRecord>();
564
565 /**
566 * List of running applications, sorted by recent usage.
567 * The first entry in the list is the least recently used.
568 * It contains ApplicationRecord objects. This list does NOT include
569 * any persistent application records (since we never want to exit them).
570 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800571 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 = new ArrayList<ProcessRecord>();
573
574 /**
575 * List of processes that should gc as soon as things are idle.
576 */
577 final ArrayList<ProcessRecord> mProcessesToGc
578 = new ArrayList<ProcessRecord>();
579
580 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800581 * This is the process holding what we currently consider to be
582 * the "home" activity.
583 */
584 private ProcessRecord mHomeProcess;
585
586 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587 * List of running activities, sorted by recent usage.
588 * The first entry in the list is the least recently used.
589 * It contains HistoryRecord objects.
590 */
591 private final ArrayList mLRUActivities = new ArrayList();
592
593 /**
594 * Set of PendingResultRecord objects that are currently active.
595 */
596 final HashSet mPendingResultRecords = new HashSet();
597
598 /**
599 * Set of IntentSenderRecord objects that are currently active.
600 */
601 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
602 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
603
604 /**
605 * Intent broadcast that we have tried to start, but are
606 * waiting for its application's process to be created. We only
607 * need one (instead of a list) because we always process broadcasts
608 * one at a time, so no others can be started while waiting for this
609 * one.
610 */
611 BroadcastRecord mPendingBroadcast = null;
612
613 /**
614 * Keeps track of all IIntentReceivers that have been registered for
615 * broadcasts. Hash keys are the receiver IBinder, hash value is
616 * a ReceiverList.
617 */
618 final HashMap mRegisteredReceivers = new HashMap();
619
620 /**
621 * Resolver for broadcast intents to registered receivers.
622 * Holds BroadcastFilter (subclass of IntentFilter).
623 */
624 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
625 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
626 @Override
627 protected boolean allowFilterResult(
628 BroadcastFilter filter, List<BroadcastFilter> dest) {
629 IBinder target = filter.receiverList.receiver.asBinder();
630 for (int i=dest.size()-1; i>=0; i--) {
631 if (dest.get(i).receiverList.receiver.asBinder() == target) {
632 return false;
633 }
634 }
635 return true;
636 }
637 };
638
639 /**
640 * State of all active sticky broadcasts. Keys are the action of the
641 * sticky Intent, values are an ArrayList of all broadcasted intents with
642 * that action (which should usually be one).
643 */
644 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
645 new HashMap<String, ArrayList<Intent>>();
646
647 /**
648 * All currently running services.
649 */
650 final HashMap<ComponentName, ServiceRecord> mServices =
651 new HashMap<ComponentName, ServiceRecord>();
652
653 /**
654 * All currently running services indexed by the Intent used to start them.
655 */
656 final HashMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent =
657 new HashMap<Intent.FilterComparison, ServiceRecord>();
658
659 /**
660 * All currently bound service connections. Keys are the IBinder of
661 * the client's IServiceConnection.
662 */
663 final HashMap<IBinder, ConnectionRecord> mServiceConnections
664 = new HashMap<IBinder, ConnectionRecord>();
665
666 /**
667 * List of services that we have been asked to start,
668 * but haven't yet been able to. It is used to hold start requests
669 * while waiting for their corresponding application thread to get
670 * going.
671 */
672 final ArrayList<ServiceRecord> mPendingServices
673 = new ArrayList<ServiceRecord>();
674
675 /**
676 * List of services that are scheduled to restart following a crash.
677 */
678 final ArrayList<ServiceRecord> mRestartingServices
679 = new ArrayList<ServiceRecord>();
680
681 /**
682 * List of services that are in the process of being stopped.
683 */
684 final ArrayList<ServiceRecord> mStoppingServices
685 = new ArrayList<ServiceRecord>();
686
687 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700688 * Backup/restore process management
689 */
690 String mBackupAppName = null;
691 BackupRecord mBackupTarget = null;
692
693 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 * List of PendingThumbnailsRecord objects of clients who are still
695 * waiting to receive all of the thumbnails for a task.
696 */
697 final ArrayList mPendingThumbnails = new ArrayList();
698
699 /**
700 * List of HistoryRecord objects that have been finished and must
701 * still report back to a pending thumbnail receiver.
702 */
703 final ArrayList mCancelledThumbnails = new ArrayList();
704
705 /**
706 * All of the currently running global content providers. Keys are a
707 * string containing the provider name and values are a
708 * ContentProviderRecord object containing the data about it. Note
709 * that a single provider may be published under multiple names, so
710 * there may be multiple entries here for a single one in mProvidersByClass.
711 */
712 final HashMap mProvidersByName = new HashMap();
713
714 /**
715 * All of the currently running global content providers. Keys are a
716 * string containing the provider's implementation class and values are a
717 * ContentProviderRecord object containing the data about it.
718 */
719 final HashMap mProvidersByClass = new HashMap();
720
721 /**
722 * List of content providers who have clients waiting for them. The
723 * application is currently being launched and the provider will be
724 * removed from this list once it is published.
725 */
726 final ArrayList mLaunchingProviders = new ArrayList();
727
728 /**
729 * Global set of specific Uri permissions that have been granted.
730 */
731 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
732 = new SparseArray<HashMap<Uri, UriPermission>>();
733
734 /**
735 * Thread-local storage used to carry caller permissions over through
736 * indirect content-provider access.
737 * @see #ActivityManagerService.openContentUri()
738 */
739 private class Identity {
740 public int pid;
741 public int uid;
742
743 Identity(int _pid, int _uid) {
744 pid = _pid;
745 uid = _uid;
746 }
747 }
748 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
749
750 /**
751 * All information we have collected about the runtime performance of
752 * any user id that can impact battery performance.
753 */
754 final BatteryStatsService mBatteryStatsService;
755
756 /**
757 * information about component usage
758 */
759 final UsageStatsService mUsageStatsService;
760
761 /**
762 * Current configuration information. HistoryRecord objects are given
763 * a reference to this object to indicate which configuration they are
764 * currently running in, so this object must be kept immutable.
765 */
766 Configuration mConfiguration = new Configuration();
767
768 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700769 * Hardware-reported OpenGLES version.
770 */
771 final int GL_ES_VERSION;
772
773 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 * List of initialization arguments to pass to all processes when binding applications to them.
775 * For example, references to the commonly used services.
776 */
777 HashMap<String, IBinder> mAppBindArgs;
778
779 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700780 * Temporary to avoid allocations. Protected by main lock.
781 */
782 final StringBuilder mStringBuilder = new StringBuilder(256);
783
784 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 * Used to control how we initialize the service.
786 */
787 boolean mStartRunning = false;
788 ComponentName mTopComponent;
789 String mTopAction;
790 String mTopData;
791 boolean mSystemReady = false;
792 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700793 boolean mWaitingUpdate = false;
794 boolean mDidUpdate = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795
796 Context mContext;
797
798 int mFactoryTest;
799
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700800 boolean mCheckedForSetup;
801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700803 * The time at which we will allow normal application switches again,
804 * after a call to {@link #stopAppSwitches()}.
805 */
806 long mAppSwitchesAllowedTime;
807
808 /**
809 * This is set to true after the first switch after mAppSwitchesAllowedTime
810 * is set; any switches after that will clear the time.
811 */
812 boolean mDidAppSwitch;
813
814 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 * Set while we are wanting to sleep, to prevent any
816 * activities from being started/resumed.
817 */
818 boolean mSleeping = false;
819
820 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700821 * Set if we are shutting down the system, similar to sleeping.
822 */
823 boolean mShuttingDown = false;
824
825 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 * Set when the system is going to sleep, until we have
827 * successfully paused the current activity and released our wake lock.
828 * At that point the system is allowed to actually sleep.
829 */
830 PowerManager.WakeLock mGoingToSleep;
831
832 /**
833 * We don't want to allow the device to go to sleep while in the process
834 * of launching an activity. This is primarily to allow alarm intent
835 * receivers to launch an activity and get that to run before the device
836 * goes back to sleep.
837 */
838 PowerManager.WakeLock mLaunchingActivity;
839
840 /**
841 * Task identifier that activities are currently being started
842 * in. Incremented each time a new task is created.
843 * todo: Replace this with a TokenSpace class that generates non-repeating
844 * integers that won't wrap.
845 */
846 int mCurTask = 1;
847
848 /**
849 * Current sequence id for oom_adj computation traversal.
850 */
851 int mAdjSeq = 0;
852
853 /**
854 * Set to true if the ANDROID_SIMPLE_PROCESS_MANAGEMENT envvar
855 * is set, indicating the user wants processes started in such a way
856 * that they can use ANDROID_PROCESS_WRAPPER and know what will be
857 * running in each process (thus no pre-initialized process, etc).
858 */
859 boolean mSimpleProcessManagement = false;
860
861 /**
862 * System monitoring: number of processes that died since the last
863 * N procs were started.
864 */
865 int[] mProcDeaths = new int[20];
866
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700867 /**
868 * This is set if we had to do a delayed dexopt of an app before launching
869 * it, to increasing the ANR timeouts in that case.
870 */
871 boolean mDidDexOpt;
872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 String mDebugApp = null;
874 boolean mWaitForDebugger = false;
875 boolean mDebugTransient = false;
876 String mOrigDebugApp = null;
877 boolean mOrigWaitForDebugger = false;
878 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700879 IActivityController mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700881 final RemoteCallbackList<IActivityWatcher> mWatchers
882 = new RemoteCallbackList<IActivityWatcher>();
883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 /**
885 * Callback of last caller to {@link #requestPss}.
886 */
887 Runnable mRequestPssCallback;
888
889 /**
890 * Remaining processes for which we are waiting results from the last
891 * call to {@link #requestPss}.
892 */
893 final ArrayList<ProcessRecord> mRequestPssList
894 = new ArrayList<ProcessRecord>();
895
896 /**
897 * Runtime statistics collection thread. This object's lock is used to
898 * protect all related state.
899 */
900 final Thread mProcessStatsThread;
901
902 /**
903 * Used to collect process stats when showing not responding dialog.
904 * Protected by mProcessStatsThread.
905 */
906 final ProcessStats mProcessStats = new ProcessStats(
907 MONITOR_THREAD_CPU_USAGE);
908 long mLastCpuTime = 0;
909 long mLastWriteTime = 0;
910
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700911 long mInitialStartTime = 0;
912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 /**
914 * Set to true after the system has finished booting.
915 */
916 boolean mBooted = false;
917
918 int mProcessLimit = 0;
919
920 WindowManagerService mWindowManager;
921
922 static ActivityManagerService mSelf;
923 static ActivityThread mSystemThread;
924
925 private final class AppDeathRecipient implements IBinder.DeathRecipient {
926 final ProcessRecord mApp;
927 final int mPid;
928 final IApplicationThread mAppThread;
929
930 AppDeathRecipient(ProcessRecord app, int pid,
931 IApplicationThread thread) {
932 if (localLOGV) Log.v(
933 TAG, "New death recipient " + this
934 + " for thread " + thread.asBinder());
935 mApp = app;
936 mPid = pid;
937 mAppThread = thread;
938 }
939
940 public void binderDied() {
941 if (localLOGV) Log.v(
942 TAG, "Death received in " + this
943 + " for thread " + mAppThread.asBinder());
944 removeRequestedPss(mApp);
945 synchronized(ActivityManagerService.this) {
946 appDiedLocked(mApp, mPid, mAppThread);
947 }
948 }
949 }
950
951 static final int SHOW_ERROR_MSG = 1;
952 static final int SHOW_NOT_RESPONDING_MSG = 2;
953 static final int SHOW_FACTORY_ERROR_MSG = 3;
954 static final int UPDATE_CONFIGURATION_MSG = 4;
955 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
956 static final int WAIT_FOR_DEBUGGER_MSG = 6;
957 static final int BROADCAST_INTENT_MSG = 7;
958 static final int BROADCAST_TIMEOUT_MSG = 8;
959 static final int PAUSE_TIMEOUT_MSG = 9;
960 static final int IDLE_TIMEOUT_MSG = 10;
961 static final int IDLE_NOW_MSG = 11;
962 static final int SERVICE_TIMEOUT_MSG = 12;
963 static final int UPDATE_TIME_ZONE = 13;
964 static final int SHOW_UID_ERROR_MSG = 14;
965 static final int IM_FEELING_LUCKY_MSG = 15;
966 static final int LAUNCH_TIMEOUT_MSG = 16;
967 static final int DESTROY_TIMEOUT_MSG = 17;
968 static final int SERVICE_ERROR_MSG = 18;
969 static final int RESUME_TOP_ACTIVITY_MSG = 19;
970 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700971 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700972 static final int KILL_APPLICATION_MSG = 22;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973
974 AlertDialog mUidAlert;
975
976 final Handler mHandler = new Handler() {
977 //public Handler() {
978 // if (localLOGV) Log.v(TAG, "Handler started!");
979 //}
980
981 public void handleMessage(Message msg) {
982 switch (msg.what) {
983 case SHOW_ERROR_MSG: {
984 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 synchronized (ActivityManagerService.this) {
986 ProcessRecord proc = (ProcessRecord)data.get("app");
987 if (proc != null && proc.crashDialog != null) {
988 Log.e(TAG, "App already has crash dialog: " + proc);
989 return;
990 }
991 AppErrorResult res = (AppErrorResult) data.get("result");
Dianne Hackborn55280a92009-05-07 15:53:46 -0700992 if (!mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800993 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 d.show();
995 proc.crashDialog = d;
996 } else {
997 // The device is asleep, so just pretend that the user
998 // saw a crash dialog and hit "force quit".
999 res.set(0);
1000 }
1001 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001002
1003 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 } break;
1005 case SHOW_NOT_RESPONDING_MSG: {
1006 synchronized (ActivityManagerService.this) {
1007 HashMap data = (HashMap) msg.obj;
1008 ProcessRecord proc = (ProcessRecord)data.get("app");
1009 if (proc != null && proc.anrDialog != null) {
1010 Log.e(TAG, "App already has anr dialog: " + proc);
1011 return;
1012 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08001013
1014 broadcastIntentLocked(null, null, new Intent("android.intent.action.ANR"),
1015 null, null, 0, null, null, null,
1016 false, false, MY_PID, Process.SYSTEM_UID);
1017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
1019 mContext, proc, (HistoryRecord)data.get("activity"));
1020 d.show();
1021 proc.anrDialog = d;
1022 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001023
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001024 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 } break;
1026 case SHOW_FACTORY_ERROR_MSG: {
1027 Dialog d = new FactoryErrorDialog(
1028 mContext, msg.getData().getCharSequence("msg"));
1029 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001030 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 } break;
1032 case UPDATE_CONFIGURATION_MSG: {
1033 final ContentResolver resolver = mContext.getContentResolver();
1034 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
1035 } break;
1036 case GC_BACKGROUND_PROCESSES_MSG: {
1037 synchronized (ActivityManagerService.this) {
1038 performAppGcsIfAppropriateLocked();
1039 }
1040 } break;
1041 case WAIT_FOR_DEBUGGER_MSG: {
1042 synchronized (ActivityManagerService.this) {
1043 ProcessRecord app = (ProcessRecord)msg.obj;
1044 if (msg.arg1 != 0) {
1045 if (!app.waitedForDebugger) {
1046 Dialog d = new AppWaitingForDebuggerDialog(
1047 ActivityManagerService.this,
1048 mContext, app);
1049 app.waitDialog = d;
1050 app.waitedForDebugger = true;
1051 d.show();
1052 }
1053 } else {
1054 if (app.waitDialog != null) {
1055 app.waitDialog.dismiss();
1056 app.waitDialog = null;
1057 }
1058 }
1059 }
1060 } break;
1061 case BROADCAST_INTENT_MSG: {
1062 if (DEBUG_BROADCAST) Log.v(
1063 TAG, "Received BROADCAST_INTENT_MSG");
1064 processNextBroadcast(true);
1065 } break;
1066 case BROADCAST_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001067 if (mDidDexOpt) {
1068 mDidDexOpt = false;
1069 Message nmsg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG);
1070 mHandler.sendMessageDelayed(nmsg, BROADCAST_TIMEOUT);
1071 return;
1072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 broadcastTimeout();
1074 } break;
1075 case PAUSE_TIMEOUT_MSG: {
1076 IBinder token = (IBinder)msg.obj;
1077 // We don't at this point know if the activity is fullscreen,
1078 // so we need to be conservative and assume it isn't.
1079 Log.w(TAG, "Activity pause timeout for " + token);
1080 activityPaused(token, null, true);
1081 } break;
1082 case IDLE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001083 if (mDidDexOpt) {
1084 mDidDexOpt = false;
1085 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1086 nmsg.obj = msg.obj;
1087 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
1088 return;
1089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 // We don't at this point know if the activity is fullscreen,
1091 // so we need to be conservative and assume it isn't.
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001092 IBinder token = (IBinder)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 Log.w(TAG, "Activity idle timeout for " + token);
Dianne Hackborne88846e2009-09-30 21:34:25 -07001094 activityIdleInternal(token, true, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 } break;
1096 case DESTROY_TIMEOUT_MSG: {
1097 IBinder token = (IBinder)msg.obj;
1098 // We don't at this point know if the activity is fullscreen,
1099 // so we need to be conservative and assume it isn't.
1100 Log.w(TAG, "Activity destroy timeout for " + token);
1101 activityDestroyed(token);
1102 } break;
1103 case IDLE_NOW_MSG: {
1104 IBinder token = (IBinder)msg.obj;
Dianne Hackborne88846e2009-09-30 21:34:25 -07001105 activityIdle(token, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 } break;
1107 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001108 if (mDidDexOpt) {
1109 mDidDexOpt = false;
1110 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1111 nmsg.obj = msg.obj;
1112 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
1113 return;
1114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 serviceTimeout((ProcessRecord)msg.obj);
1116 } break;
1117 case UPDATE_TIME_ZONE: {
1118 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001119 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1120 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 if (r.thread != null) {
1122 try {
1123 r.thread.updateTimeZone();
1124 } catch (RemoteException ex) {
1125 Log.w(TAG, "Failed to update time zone for: " + r.info.processName);
1126 }
1127 }
1128 }
1129 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001130 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 case SHOW_UID_ERROR_MSG: {
1132 // XXX This is a temporary dialog, no need to localize.
1133 AlertDialog d = new BaseErrorDialog(mContext);
1134 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1135 d.setCancelable(false);
1136 d.setTitle("System UIDs Inconsistent");
1137 d.setMessage("UIDs on the system are inconsistent, you need to wipe your data partition or your device will be unstable.");
1138 d.setButton("I'm Feeling Lucky",
1139 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1140 mUidAlert = d;
1141 d.show();
1142 } break;
1143 case IM_FEELING_LUCKY_MSG: {
1144 if (mUidAlert != null) {
1145 mUidAlert.dismiss();
1146 mUidAlert = null;
1147 }
1148 } break;
1149 case LAUNCH_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001150 if (mDidDexOpt) {
1151 mDidDexOpt = false;
1152 Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
1153 mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
1154 return;
1155 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 synchronized (ActivityManagerService.this) {
1157 if (mLaunchingActivity.isHeld()) {
1158 Log.w(TAG, "Launch timeout has expired, giving up wake lock!");
1159 mLaunchingActivity.release();
1160 }
1161 }
1162 } break;
1163 case SERVICE_ERROR_MSG: {
1164 ServiceRecord srv = (ServiceRecord)msg.obj;
1165 // This needs to be *un*synchronized to avoid deadlock.
1166 Checkin.logEvent(mContext.getContentResolver(),
1167 Checkin.Events.Tag.SYSTEM_SERVICE_LOOPING,
1168 srv.name.toShortString());
1169 } break;
1170 case RESUME_TOP_ACTIVITY_MSG: {
1171 synchronized (ActivityManagerService.this) {
1172 resumeTopActivityLocked(null);
1173 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001174 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001176 if (mDidDexOpt) {
1177 mDidDexOpt = false;
1178 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1179 nmsg.obj = msg.obj;
1180 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1181 return;
1182 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 ProcessRecord app = (ProcessRecord)msg.obj;
1184 synchronized (ActivityManagerService.this) {
1185 processStartTimedOutLocked(app);
1186 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001187 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001188 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1189 synchronized (ActivityManagerService.this) {
1190 doPendingActivityLaunchesLocked(true);
1191 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001192 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001193 case KILL_APPLICATION_MSG: {
1194 synchronized (ActivityManagerService.this) {
1195 int uid = msg.arg1;
1196 boolean restart = (msg.arg2 == 1);
1197 String pkg = (String) msg.obj;
Dianne Hackborn03abb812010-01-04 18:43:19 -08001198 forceStopPackageLocked(pkg, uid, restart);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001199 }
1200 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201 }
1202 }
1203 };
1204
1205 public static void setSystemProcess() {
1206 try {
1207 ActivityManagerService m = mSelf;
1208
1209 ServiceManager.addService("activity", m);
1210 ServiceManager.addService("meminfo", new MemBinder(m));
1211 if (MONITOR_CPU_USAGE) {
1212 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1213 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 ServiceManager.addService("permission", new PermissionController(m));
1215
1216 ApplicationInfo info =
1217 mSelf.mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -07001218 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001219 mSystemThread.installSystemApplicationInfo(info);
1220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221 synchronized (mSelf) {
1222 ProcessRecord app = mSelf.newProcessRecordLocked(
1223 mSystemThread.getApplicationThread(), info,
1224 info.processName);
1225 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001226 app.pid = MY_PID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 app.maxAdj = SYSTEM_ADJ;
1228 mSelf.mProcessNames.put(app.processName, app.info.uid, app);
1229 synchronized (mSelf.mPidsSelfLocked) {
1230 mSelf.mPidsSelfLocked.put(app.pid, app);
1231 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001232 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 }
1234 } catch (PackageManager.NameNotFoundException e) {
1235 throw new RuntimeException(
1236 "Unable to find android system package", e);
1237 }
1238 }
1239
1240 public void setWindowManager(WindowManagerService wm) {
1241 mWindowManager = wm;
1242 }
1243
1244 public static final Context main(int factoryTest) {
1245 AThread thr = new AThread();
1246 thr.start();
1247
1248 synchronized (thr) {
1249 while (thr.mService == null) {
1250 try {
1251 thr.wait();
1252 } catch (InterruptedException e) {
1253 }
1254 }
1255 }
1256
1257 ActivityManagerService m = thr.mService;
1258 mSelf = m;
1259 ActivityThread at = ActivityThread.systemMain();
1260 mSystemThread = at;
1261 Context context = at.getSystemContext();
1262 m.mContext = context;
1263 m.mFactoryTest = factoryTest;
1264 PowerManager pm =
1265 (PowerManager)context.getSystemService(Context.POWER_SERVICE);
1266 m.mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
1267 m.mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
1268 m.mLaunchingActivity.setReferenceCounted(false);
1269
1270 m.mBatteryStatsService.publish(context);
1271 m.mUsageStatsService.publish(context);
1272
1273 synchronized (thr) {
1274 thr.mReady = true;
1275 thr.notifyAll();
1276 }
1277
1278 m.startRunning(null, null, null, null);
1279
1280 return context;
1281 }
1282
1283 public static ActivityManagerService self() {
1284 return mSelf;
1285 }
1286
1287 static class AThread extends Thread {
1288 ActivityManagerService mService;
1289 boolean mReady = false;
1290
1291 public AThread() {
1292 super("ActivityManager");
1293 }
1294
1295 public void run() {
1296 Looper.prepare();
1297
1298 android.os.Process.setThreadPriority(
1299 android.os.Process.THREAD_PRIORITY_FOREGROUND);
1300
1301 ActivityManagerService m = new ActivityManagerService();
1302
1303 synchronized (this) {
1304 mService = m;
1305 notifyAll();
1306 }
1307
1308 synchronized (this) {
1309 while (!mReady) {
1310 try {
1311 wait();
1312 } catch (InterruptedException e) {
1313 }
1314 }
1315 }
1316
1317 Looper.loop();
1318 }
1319 }
1320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 static class MemBinder extends Binder {
1322 ActivityManagerService mActivityManagerService;
1323 MemBinder(ActivityManagerService activityManagerService) {
1324 mActivityManagerService = activityManagerService;
1325 }
1326
1327 @Override
1328 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1329 ActivityManagerService service = mActivityManagerService;
1330 ArrayList<ProcessRecord> procs;
1331 synchronized (mActivityManagerService) {
1332 if (args != null && args.length > 0
1333 && args[0].charAt(0) != '-') {
1334 procs = new ArrayList<ProcessRecord>();
1335 int pid = -1;
1336 try {
1337 pid = Integer.parseInt(args[0]);
1338 } catch (NumberFormatException e) {
1339
1340 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001341 for (int i=service.mLruProcesses.size()-1; i>=0; i--) {
1342 ProcessRecord proc = service.mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 if (proc.pid == pid) {
1344 procs.add(proc);
1345 } else if (proc.processName.equals(args[0])) {
1346 procs.add(proc);
1347 }
1348 }
1349 if (procs.size() <= 0) {
1350 pw.println("No process found for: " + args[0]);
1351 return;
1352 }
1353 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001354 procs = service.mLruProcesses;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 }
1356 }
1357 dumpApplicationMemoryUsage(fd, pw, procs, " ", args);
1358 }
1359 }
1360
1361 static class CpuBinder extends Binder {
1362 ActivityManagerService mActivityManagerService;
1363 CpuBinder(ActivityManagerService activityManagerService) {
1364 mActivityManagerService = activityManagerService;
1365 }
1366
1367 @Override
1368 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1369 synchronized (mActivityManagerService.mProcessStatsThread) {
1370 pw.print(mActivityManagerService.mProcessStats.printCurrentState());
1371 }
1372 }
1373 }
1374
1375 private ActivityManagerService() {
1376 String v = System.getenv("ANDROID_SIMPLE_PROCESS_MANAGEMENT");
1377 if (v != null && Integer.getInteger(v) != 0) {
1378 mSimpleProcessManagement = true;
1379 }
1380 v = System.getenv("ANDROID_DEBUG_APP");
1381 if (v != null) {
1382 mSimpleProcessManagement = true;
1383 }
1384
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001385 Log.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
1386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 File dataDir = Environment.getDataDirectory();
1388 File systemDir = new File(dataDir, "system");
1389 systemDir.mkdirs();
1390 mBatteryStatsService = new BatteryStatsService(new File(
1391 systemDir, "batterystats.bin").toString());
1392 mBatteryStatsService.getActiveStatistics().readLocked();
1393 mBatteryStatsService.getActiveStatistics().writeLocked();
1394
1395 mUsageStatsService = new UsageStatsService( new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001396 systemDir, "usagestats").toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397
Jack Palevichb90d28c2009-07-22 15:35:24 -07001398 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1399 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 mConfiguration.makeDefault();
1402 mProcessStats.init();
1403
1404 // Add ourself to the Watchdog monitors.
1405 Watchdog.getInstance().addMonitor(this);
1406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 mProcessStatsThread = new Thread("ProcessStats") {
1408 public void run() {
1409 while (true) {
1410 try {
1411 try {
1412 synchronized(this) {
1413 final long now = SystemClock.uptimeMillis();
1414 long nextCpuDelay = (mLastCpuTime+MONITOR_CPU_MAX_TIME)-now;
1415 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
1416 //Log.i(TAG, "Cpu delay=" + nextCpuDelay
1417 // + ", write delay=" + nextWriteDelay);
1418 if (nextWriteDelay < nextCpuDelay) {
1419 nextCpuDelay = nextWriteDelay;
1420 }
1421 if (nextCpuDelay > 0) {
1422 this.wait(nextCpuDelay);
1423 }
1424 }
1425 } catch (InterruptedException e) {
1426 }
1427
1428 updateCpuStatsNow();
1429 } catch (Exception e) {
1430 Log.e(TAG, "Unexpected exception collecting process stats", e);
1431 }
1432 }
1433 }
1434 };
1435 mProcessStatsThread.start();
1436 }
1437
1438 @Override
1439 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1440 throws RemoteException {
1441 try {
1442 return super.onTransact(code, data, reply, flags);
1443 } catch (RuntimeException e) {
1444 // The activity manager only throws security exceptions, so let's
1445 // log all others.
1446 if (!(e instanceof SecurityException)) {
1447 Log.e(TAG, "Activity Manager Crash", e);
1448 }
1449 throw e;
1450 }
1451 }
1452
1453 void updateCpuStats() {
1454 synchronized (mProcessStatsThread) {
1455 final long now = SystemClock.uptimeMillis();
1456 if (mLastCpuTime < (now-MONITOR_CPU_MIN_TIME)) {
1457 mProcessStatsThread.notify();
1458 }
1459 }
1460 }
1461
1462 void updateCpuStatsNow() {
1463 synchronized (mProcessStatsThread) {
1464 final long now = SystemClock.uptimeMillis();
1465 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 if (MONITOR_CPU_USAGE &&
1468 mLastCpuTime < (now-MONITOR_CPU_MIN_TIME)) {
1469 mLastCpuTime = now;
1470 haveNewCpuStats = true;
1471 mProcessStats.update();
1472 //Log.i(TAG, mProcessStats.printCurrentState());
1473 //Log.i(TAG, "Total CPU usage: "
1474 // + mProcessStats.getTotalCpuPercent() + "%");
1475
1476 // Log the cpu usage if the property is set.
1477 if ("true".equals(SystemProperties.get("events.cpu"))) {
1478 int user = mProcessStats.getLastUserTime();
1479 int system = mProcessStats.getLastSystemTime();
1480 int iowait = mProcessStats.getLastIoWaitTime();
1481 int irq = mProcessStats.getLastIrqTime();
1482 int softIrq = mProcessStats.getLastSoftIrqTime();
1483 int idle = mProcessStats.getLastIdleTime();
1484
1485 int total = user + system + iowait + irq + softIrq + idle;
1486 if (total == 0) total = 1;
1487
Doug Zongker2bec3d42009-12-04 12:52:44 -08001488 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 ((user+system+iowait+irq+softIrq) * 100) / total,
1490 (user * 100) / total,
1491 (system * 100) / total,
1492 (iowait * 100) / total,
1493 (irq * 100) / total,
1494 (softIrq * 100) / total);
1495 }
1496 }
1497
Amith Yamasanie43530a2009-08-21 13:11:37 -07001498 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001499 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001500 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 synchronized(mPidsSelfLocked) {
1502 if (haveNewCpuStats) {
1503 if (mBatteryStatsService.isOnBattery()) {
1504 final int N = mProcessStats.countWorkingStats();
1505 for (int i=0; i<N; i++) {
1506 ProcessStats.Stats st
1507 = mProcessStats.getWorkingStats(i);
1508 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
1509 if (pr != null) {
1510 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
1511 ps.addCpuTimeLocked(st.rel_utime, st.rel_stime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001512 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001513 } else {
1514 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001515 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001516 if (ps != null) {
1517 ps.addCpuTimeLocked(st.rel_utime, st.rel_stime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001518 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001519 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 }
1521 }
1522 }
1523 }
1524 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1527 mLastWriteTime = now;
1528 mBatteryStatsService.getActiveStatistics().writeLocked();
1529 }
1530 }
1531 }
1532 }
1533
1534 /**
1535 * Initialize the application bind args. These are passed to each
1536 * process when the bindApplication() IPC is sent to the process. They're
1537 * lazily setup to make sure the services are running when they're asked for.
1538 */
1539 private HashMap<String, IBinder> getCommonServicesLocked() {
1540 if (mAppBindArgs == null) {
1541 mAppBindArgs = new HashMap<String, IBinder>();
1542
1543 // Setup the application init args
1544 mAppBindArgs.put("package", ServiceManager.getService("package"));
1545 mAppBindArgs.put("window", ServiceManager.getService("window"));
1546 mAppBindArgs.put(Context.ALARM_SERVICE,
1547 ServiceManager.getService(Context.ALARM_SERVICE));
1548 }
1549 return mAppBindArgs;
1550 }
1551
1552 private final void setFocusedActivityLocked(HistoryRecord r) {
1553 if (mFocusedActivity != r) {
1554 mFocusedActivity = r;
1555 mWindowManager.setFocusedApp(r, true);
1556 }
1557 }
1558
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001559 private final void updateLruProcessLocked(ProcessRecord app,
1560 boolean oomAdj, boolean updateActivityTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001562 int lrui = mLruProcesses.indexOf(app);
1563 if (lrui >= 0) mLruProcesses.remove(lrui);
1564
1565 int i = mLruProcesses.size()-1;
1566 int skipTop = 0;
1567
1568 // compute the new weight for this process.
1569 if (updateActivityTime) {
1570 app.lastActivityTime = SystemClock.uptimeMillis();
1571 }
1572 if (app.activities.size() > 0) {
1573 // If this process has activities, we more strongly want to keep
1574 // it around.
1575 app.lruWeight = app.lastActivityTime;
1576 } else if (app.pubProviders.size() > 0) {
1577 // If this process contains content providers, we want to keep
1578 // it a little more strongly.
1579 app.lruWeight = app.lastActivityTime - CONTENT_APP_IDLE_OFFSET;
1580 // Also don't let it kick out the first few "real" hidden processes.
1581 skipTop = MIN_HIDDEN_APPS;
1582 } else {
1583 // If this process doesn't have activities, we less strongly
1584 // want to keep it around, and generally want to avoid getting
1585 // in front of any very recently used activities.
1586 app.lruWeight = app.lastActivityTime - EMPTY_APP_IDLE_OFFSET;
1587 // Also don't let it kick out the first few "real" hidden processes.
1588 skipTop = MIN_HIDDEN_APPS;
1589 }
1590 while (i >= 0) {
1591 ProcessRecord p = mLruProcesses.get(i);
1592 // If this app shouldn't be in front of the first N background
1593 // apps, then skip over that many that are currently hidden.
1594 if (skipTop > 0 && p.setAdj >= HIDDEN_APP_MIN_ADJ) {
1595 skipTop--;
1596 }
1597 if (p.lruWeight <= app.lruWeight){
1598 mLruProcesses.add(i+1, app);
1599 break;
1600 }
1601 i--;
1602 }
1603 if (i < 0) {
1604 mLruProcesses.add(0, app);
1605 }
1606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 //Log.i(TAG, "Putting proc to front: " + app.processName);
1608 if (oomAdj) {
1609 updateOomAdjLocked();
1610 }
1611 }
1612
1613 private final boolean updateLRUListLocked(HistoryRecord r) {
1614 final boolean hadit = mLRUActivities.remove(r);
1615 mLRUActivities.add(r);
1616 return hadit;
1617 }
1618
1619 private final HistoryRecord topRunningActivityLocked(HistoryRecord notTop) {
1620 int i = mHistory.size()-1;
1621 while (i >= 0) {
1622 HistoryRecord r = (HistoryRecord)mHistory.get(i);
1623 if (!r.finishing && r != notTop) {
1624 return r;
1625 }
1626 i--;
1627 }
1628 return null;
1629 }
1630
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001631 private final HistoryRecord topRunningNonDelayedActivityLocked(HistoryRecord notTop) {
1632 int i = mHistory.size()-1;
1633 while (i >= 0) {
1634 HistoryRecord r = (HistoryRecord)mHistory.get(i);
1635 if (!r.finishing && !r.delayedResume && r != notTop) {
1636 return r;
1637 }
1638 i--;
1639 }
1640 return null;
1641 }
1642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 /**
1644 * This is a simplified version of topRunningActivityLocked that provides a number of
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001645 * optional skip-over modes. It is intended for use with the ActivityController hook only.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 *
1647 * @param token If non-null, any history records matching this token will be skipped.
1648 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
1649 *
1650 * @return Returns the HistoryRecord of the next activity on the stack.
1651 */
1652 private final HistoryRecord topRunningActivityLocked(IBinder token, int taskId) {
1653 int i = mHistory.size()-1;
1654 while (i >= 0) {
1655 HistoryRecord r = (HistoryRecord)mHistory.get(i);
1656 // Note: the taskId check depends on real taskId fields being non-zero
1657 if (!r.finishing && (token != r) && (taskId != r.task.taskId)) {
1658 return r;
1659 }
1660 i--;
1661 }
1662 return null;
1663 }
1664
1665 private final ProcessRecord getProcessRecordLocked(
1666 String processName, int uid) {
1667 if (uid == Process.SYSTEM_UID) {
1668 // The system gets to run in any process. If there are multiple
1669 // processes with the same uid, just pick the first (this
1670 // should never happen).
1671 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1672 processName);
1673 return procs != null ? procs.valueAt(0) : null;
1674 }
1675 ProcessRecord proc = mProcessNames.get(processName, uid);
1676 return proc;
1677 }
1678
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001679 private void ensurePackageDexOpt(String packageName) {
1680 IPackageManager pm = ActivityThread.getPackageManager();
1681 try {
1682 if (pm.performDexOpt(packageName)) {
1683 mDidDexOpt = true;
1684 }
1685 } catch (RemoteException e) {
1686 }
1687 }
1688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 private boolean isNextTransitionForward() {
1690 int transit = mWindowManager.getPendingAppTransition();
1691 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1692 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1693 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1694 }
1695
1696 private final boolean realStartActivityLocked(HistoryRecord r,
1697 ProcessRecord app, boolean andResume, boolean checkConfig)
1698 throws RemoteException {
1699
1700 r.startFreezingScreenLocked(app, 0);
1701 mWindowManager.setAppVisibility(r, true);
1702
1703 // Have the window manager re-evaluate the orientation of
1704 // the screen based on the new activity order. Note that
1705 // as a result of this, it can call back into the activity
1706 // manager with a new orientation. We don't care about that,
1707 // because the activity is not currently running so we are
1708 // just restarting it anyway.
1709 if (checkConfig) {
1710 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07001711 mConfiguration,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 r.mayFreezeScreenLocked(app) ? r : null);
1713 updateConfigurationLocked(config, r);
1714 }
1715
1716 r.app = app;
1717
1718 if (localLOGV) Log.v(TAG, "Launching: " + r);
1719
1720 int idx = app.activities.indexOf(r);
1721 if (idx < 0) {
1722 app.activities.add(r);
1723 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001724 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725
1726 try {
1727 if (app.thread == null) {
1728 throw new RemoteException();
1729 }
1730 List<ResultInfo> results = null;
1731 List<Intent> newIntents = null;
1732 if (andResume) {
1733 results = r.results;
1734 newIntents = r.newIntents;
1735 }
1736 if (DEBUG_SWITCH) Log.v(TAG, "Launching: " + r
1737 + " icicle=" + r.icicle
1738 + " with results=" + results + " newIntents=" + newIntents
1739 + " andResume=" + andResume);
1740 if (andResume) {
Doug Zongker2bec3d42009-12-04 12:52:44 -08001741 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 System.identityHashCode(r),
1743 r.task.taskId, r.shortComponentName);
1744 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08001745 if (r.isHomeActivity) {
1746 mHomeProcess = app;
1747 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001748 ensurePackageDexOpt(r.intent.getComponent().getPackageName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 app.thread.scheduleLaunchActivity(new Intent(r.intent), r,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001750 System.identityHashCode(r),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 r.info, r.icicle, results, newIntents, !andResume,
1752 isNextTransitionForward());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 } catch (RemoteException e) {
1754 if (r.launchFailed) {
1755 // This is the second time we failed -- finish activity
1756 // and give up.
1757 Log.e(TAG, "Second failure launching "
1758 + r.intent.getComponent().flattenToShortString()
1759 + ", giving up", e);
1760 appDiedLocked(app, app.pid, app.thread);
1761 requestFinishActivityLocked(r, Activity.RESULT_CANCELED, null,
1762 "2nd-crash");
1763 return false;
1764 }
1765
1766 // This is the first time we failed -- restart process and
1767 // retry.
1768 app.activities.remove(r);
1769 throw e;
1770 }
1771
1772 r.launchFailed = false;
1773 if (updateLRUListLocked(r)) {
1774 Log.w(TAG, "Activity " + r
1775 + " being launched, but already in LRU list");
1776 }
1777
1778 if (andResume) {
1779 // As part of the process of launching, ActivityThread also performs
1780 // a resume.
1781 r.state = ActivityState.RESUMED;
1782 r.icicle = null;
1783 r.haveState = false;
1784 r.stopped = false;
1785 mResumedActivity = r;
1786 r.task.touchActiveTime();
1787 completeResumeLocked(r);
1788 pauseIfSleepingLocked();
1789 } else {
1790 // This activity is not starting in the resumed state... which
1791 // should look like we asked it to pause+stop (but remain visible),
1792 // and it has done so and reported back the current icicle and
1793 // other state.
1794 r.state = ActivityState.STOPPED;
1795 r.stopped = true;
1796 }
1797
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07001798 // Launch the new version setup screen if needed. We do this -after-
1799 // launching the initial activity (that is, home), so that it can have
1800 // a chance to initialize itself while in the background, making the
1801 // switch back to it faster and look better.
1802 startSetupActivityLocked();
1803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 return true;
1805 }
1806
1807 private final void startSpecificActivityLocked(HistoryRecord r,
1808 boolean andResume, boolean checkConfig) {
1809 // Is this activity's application already running?
1810 ProcessRecord app = getProcessRecordLocked(r.processName,
1811 r.info.applicationInfo.uid);
1812
1813 if (r.startTime == 0) {
1814 r.startTime = SystemClock.uptimeMillis();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07001815 if (mInitialStartTime == 0) {
1816 mInitialStartTime = r.startTime;
1817 }
1818 } else if (mInitialStartTime == 0) {
1819 mInitialStartTime = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 }
1821
1822 if (app != null && app.thread != null) {
1823 try {
1824 realStartActivityLocked(r, app, andResume, checkConfig);
1825 return;
1826 } catch (RemoteException e) {
1827 Log.w(TAG, "Exception when starting activity "
1828 + r.intent.getComponent().flattenToShortString(), e);
1829 }
1830
1831 // If a dead object exception was thrown -- fall through to
1832 // restart the application.
1833 }
1834
1835 startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001836 "activity", r.intent.getComponent(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 }
1838
1839 private final ProcessRecord startProcessLocked(String processName,
1840 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001841 String hostingType, ComponentName hostingName, boolean allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 ProcessRecord app = getProcessRecordLocked(processName, info.uid);
1843 // We don't have to do anything more if:
1844 // (1) There is an existing application record; and
1845 // (2) The caller doesn't think it is dead, OR there is no thread
1846 // object attached to it so we know it couldn't have crashed; and
1847 // (3) There is a pid assigned to it, so it is either starting or
1848 // already running.
1849 if (DEBUG_PROCESSES) Log.v(TAG, "startProcess: name=" + processName
1850 + " app=" + app + " knownToBeDead=" + knownToBeDead
1851 + " thread=" + (app != null ? app.thread : null)
1852 + " pid=" + (app != null ? app.pid : -1));
1853 if (app != null &&
1854 (!knownToBeDead || app.thread == null) && app.pid > 0) {
1855 return app;
1856 }
1857
1858 String hostingNameStr = hostingName != null
1859 ? hostingName.flattenToShortString() : null;
1860
1861 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1862 // If we are in the background, then check to see if this process
1863 // is bad. If so, we will just silently fail.
1864 if (mBadProcesses.get(info.processName, info.uid) != null) {
1865 return null;
1866 }
1867 } else {
1868 // When the user is explicitly starting a process, then clear its
1869 // crash count so that we won't make it bad until they see at
1870 // least one crash dialog again, and make the process good again
1871 // if it had been bad.
1872 mProcessCrashTimes.remove(info.processName, info.uid);
1873 if (mBadProcesses.get(info.processName, info.uid) != null) {
Doug Zongker2bec3d42009-12-04 12:52:44 -08001874 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 info.processName);
1876 mBadProcesses.remove(info.processName, info.uid);
1877 if (app != null) {
1878 app.bad = false;
1879 }
1880 }
1881 }
1882
1883 if (app == null) {
1884 app = newProcessRecordLocked(null, info, processName);
1885 mProcessNames.put(processName, info.uid, app);
1886 } else {
1887 // If this is a new package in the process, add the package to the list
1888 app.addPackage(info.packageName);
1889 }
1890
1891 // If the system is not ready yet, then hold off on starting this
1892 // process until it is.
1893 if (!mSystemReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001894 && !isAllowedWhileBooting(info)
1895 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 if (!mProcessesOnHold.contains(app)) {
1897 mProcessesOnHold.add(app);
1898 }
1899 return app;
1900 }
1901
1902 startProcessLocked(app, hostingType, hostingNameStr);
1903 return (app.pid != 0) ? app : null;
1904 }
1905
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001906 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1907 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1908 }
1909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 private final void startProcessLocked(ProcessRecord app,
1911 String hostingType, String hostingNameStr) {
1912 if (app.pid > 0 && app.pid != MY_PID) {
1913 synchronized (mPidsSelfLocked) {
1914 mPidsSelfLocked.remove(app.pid);
1915 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1916 }
1917 app.pid = 0;
1918 }
1919
1920 mProcessesOnHold.remove(app);
1921
1922 updateCpuStats();
1923
1924 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1925 mProcDeaths[0] = 0;
1926
1927 try {
1928 int uid = app.info.uid;
1929 int[] gids = null;
1930 try {
1931 gids = mContext.getPackageManager().getPackageGids(
1932 app.info.packageName);
1933 } catch (PackageManager.NameNotFoundException e) {
1934 Log.w(TAG, "Unable to retrieve gids", e);
1935 }
1936 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1937 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1938 && mTopComponent != null
1939 && app.processName.equals(mTopComponent.getPackageName())) {
1940 uid = 0;
1941 }
1942 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1943 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1944 uid = 0;
1945 }
1946 }
1947 int debugFlags = 0;
1948 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1949 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
1950 }
1951 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
1952 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
1953 }
1954 if ("1".equals(SystemProperties.get("debug.assert"))) {
1955 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
1956 }
1957 int pid = Process.start("android.app.ActivityThread",
1958 mSimpleProcessManagement ? app.processName : null, uid, uid,
1959 gids, debugFlags, null);
1960 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
1961 synchronized (bs) {
1962 if (bs.isOnBattery()) {
1963 app.batteryStats.incStartsLocked();
1964 }
1965 }
1966
Doug Zongker2bec3d42009-12-04 12:52:44 -08001967 EventLog.writeEvent(EventLogTags.AM_PROC_START, pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 app.processName, hostingType,
1969 hostingNameStr != null ? hostingNameStr : "");
1970
1971 if (app.persistent) {
1972 Watchdog.getInstance().processStarted(app, app.processName, pid);
1973 }
1974
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07001975 StringBuilder buf = mStringBuilder;
1976 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977 buf.append("Start proc ");
1978 buf.append(app.processName);
1979 buf.append(" for ");
1980 buf.append(hostingType);
1981 if (hostingNameStr != null) {
1982 buf.append(" ");
1983 buf.append(hostingNameStr);
1984 }
1985 buf.append(": pid=");
1986 buf.append(pid);
1987 buf.append(" uid=");
1988 buf.append(uid);
1989 buf.append(" gids={");
1990 if (gids != null) {
1991 for (int gi=0; gi<gids.length; gi++) {
1992 if (gi != 0) buf.append(", ");
1993 buf.append(gids[gi]);
1994
1995 }
1996 }
1997 buf.append("}");
1998 Log.i(TAG, buf.toString());
1999 if (pid == 0 || pid == MY_PID) {
2000 // Processes are being emulated with threads.
2001 app.pid = MY_PID;
2002 app.removed = false;
2003 mStartingProcesses.add(app);
2004 } else if (pid > 0) {
2005 app.pid = pid;
2006 app.removed = false;
2007 synchronized (mPidsSelfLocked) {
2008 this.mPidsSelfLocked.put(pid, app);
2009 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2010 msg.obj = app;
2011 mHandler.sendMessageDelayed(msg, PROC_START_TIMEOUT);
2012 }
2013 } else {
2014 app.pid = 0;
2015 RuntimeException e = new RuntimeException(
2016 "Failure starting process " + app.processName
2017 + ": returned pid=" + pid);
2018 Log.e(TAG, e.getMessage(), e);
2019 }
2020 } catch (RuntimeException e) {
2021 // XXX do better error recovery.
2022 app.pid = 0;
2023 Log.e(TAG, "Failure starting process " + app.processName, e);
2024 }
2025 }
2026
2027 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
2028 if (mPausingActivity != null) {
2029 RuntimeException e = new RuntimeException();
2030 Log.e(TAG, "Trying to pause when pause is already pending for "
2031 + mPausingActivity, e);
2032 }
2033 HistoryRecord prev = mResumedActivity;
2034 if (prev == null) {
2035 RuntimeException e = new RuntimeException();
2036 Log.e(TAG, "Trying to pause when nothing is resumed", e);
2037 resumeTopActivityLocked(null);
2038 return;
2039 }
2040 if (DEBUG_PAUSE) Log.v(TAG, "Start pausing: " + prev);
2041 mResumedActivity = null;
2042 mPausingActivity = prev;
2043 mLastPausedActivity = prev;
2044 prev.state = ActivityState.PAUSING;
2045 prev.task.touchActiveTime();
2046
2047 updateCpuStats();
2048
2049 if (prev.app != null && prev.app.thread != null) {
2050 if (DEBUG_PAUSE) Log.v(TAG, "Enqueueing pending pause: " + prev);
2051 try {
Doug Zongker2bec3d42009-12-04 12:52:44 -08002052 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 System.identityHashCode(prev),
2054 prev.shortComponentName);
2055 prev.app.thread.schedulePauseActivity(prev, prev.finishing, userLeaving,
2056 prev.configChangeFlags);
2057 updateUsageStats(prev, false);
2058 } catch (Exception e) {
2059 // Ignore exception, if process died other code will cleanup.
2060 Log.w(TAG, "Exception thrown during pause", e);
2061 mPausingActivity = null;
2062 mLastPausedActivity = null;
2063 }
2064 } else {
2065 mPausingActivity = null;
2066 mLastPausedActivity = null;
2067 }
2068
2069 // If we are not going to sleep, we want to ensure the device is
2070 // awake until the next activity is started.
Dianne Hackborn55280a92009-05-07 15:53:46 -07002071 if (!mSleeping && !mShuttingDown) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 mLaunchingActivity.acquire();
2073 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
2074 // To be safe, don't allow the wake lock to be held for too long.
2075 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
2076 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
2077 }
2078 }
2079
2080
2081 if (mPausingActivity != null) {
2082 // Have the window manager pause its key dispatching until the new
2083 // activity has started. If we're pausing the activity just because
2084 // the screen is being turned off and the UI is sleeping, don't interrupt
2085 // key dispatch; the same activity will pick it up again on wakeup.
2086 if (!uiSleeping) {
2087 prev.pauseKeyDispatchingLocked();
2088 } else {
2089 if (DEBUG_PAUSE) Log.v(TAG, "Key dispatch not paused for screen off");
2090 }
2091
2092 // Schedule a pause timeout in case the app doesn't respond.
2093 // We don't give it much time because this directly impacts the
2094 // responsiveness seen by the user.
2095 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
2096 msg.obj = prev;
2097 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
2098 if (DEBUG_PAUSE) Log.v(TAG, "Waiting for pause to complete...");
2099 } else {
2100 // This activity failed to schedule the
2101 // pause, so just treat it as being paused now.
2102 if (DEBUG_PAUSE) Log.v(TAG, "Activity not running, resuming next.");
2103 resumeTopActivityLocked(null);
2104 }
2105 }
2106
2107 private final void completePauseLocked() {
2108 HistoryRecord prev = mPausingActivity;
2109 if (DEBUG_PAUSE) Log.v(TAG, "Complete pause: " + prev);
2110
2111 if (prev != null) {
2112 if (prev.finishing) {
2113 if (DEBUG_PAUSE) Log.v(TAG, "Executing finish of activity: " + prev);
2114 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE);
2115 } else if (prev.app != null) {
2116 if (DEBUG_PAUSE) Log.v(TAG, "Enqueueing pending stop: " + prev);
2117 if (prev.waitingVisible) {
2118 prev.waitingVisible = false;
2119 mWaitingVisibleActivities.remove(prev);
2120 if (DEBUG_SWITCH || DEBUG_PAUSE) Log.v(
2121 TAG, "Complete pause, no longer waiting: " + prev);
2122 }
2123 if (prev.configDestroy) {
2124 // The previous is being paused because the configuration
2125 // is changing, which means it is actually stopping...
2126 // To juggle the fact that we are also starting a new
2127 // instance right now, we need to first completely stop
2128 // the current instance before starting the new one.
2129 if (DEBUG_PAUSE) Log.v(TAG, "Destroying after pause: " + prev);
2130 destroyActivityLocked(prev, true);
2131 } else {
2132 mStoppingActivities.add(prev);
2133 if (mStoppingActivities.size() > 3) {
2134 // If we already have a few activities waiting to stop,
2135 // then give up on things going idle and start clearing
2136 // them out.
2137 if (DEBUG_PAUSE) Log.v(TAG, "To many pending stops, forcing idle");
2138 Message msg = Message.obtain();
2139 msg.what = ActivityManagerService.IDLE_NOW_MSG;
2140 mHandler.sendMessage(msg);
2141 }
2142 }
2143 } else {
2144 if (DEBUG_PAUSE) Log.v(TAG, "App died during pause, not stopping: " + prev);
2145 prev = null;
2146 }
2147 mPausingActivity = null;
2148 }
2149
Dianne Hackborn55280a92009-05-07 15:53:46 -07002150 if (!mSleeping && !mShuttingDown) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002151 resumeTopActivityLocked(prev);
2152 } else {
2153 if (mGoingToSleep.isHeld()) {
2154 mGoingToSleep.release();
2155 }
Dianne Hackborn55280a92009-05-07 15:53:46 -07002156 if (mShuttingDown) {
2157 notifyAll();
2158 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002159 }
2160
2161 if (prev != null) {
2162 prev.resumeKeyDispatchingLocked();
2163 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07002164
2165 if (prev.app != null && prev.cpuTimeAtResume > 0 && mBatteryStatsService.isOnBattery()) {
2166 long diff = 0;
2167 synchronized (mProcessStatsThread) {
2168 diff = mProcessStats.getCpuTimeForPid(prev.app.pid) - prev.cpuTimeAtResume;
2169 }
2170 if (diff > 0) {
2171 BatteryStatsImpl bsi = mBatteryStatsService.getActiveStatistics();
2172 synchronized (bsi) {
2173 BatteryStatsImpl.Uid.Proc ps =
2174 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
2175 prev.info.packageName);
2176 if (ps != null) {
2177 ps.addForegroundTimeLocked(diff);
2178 }
2179 }
2180 }
2181 }
2182 prev.cpuTimeAtResume = 0; // reset it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002183 }
2184
2185 /**
2186 * Once we know that we have asked an application to put an activity in
2187 * the resumed state (either by launching it or explicitly telling it),
2188 * this function updates the rest of our state to match that fact.
2189 */
2190 private final void completeResumeLocked(HistoryRecord next) {
2191 next.idle = false;
2192 next.results = null;
2193 next.newIntents = null;
2194
2195 // schedule an idle timeout in case the app doesn't do it for us.
2196 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
2197 msg.obj = next;
2198 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
2199
2200 if (false) {
2201 // The activity was never told to pause, so just keep
2202 // things going as-is. To maintain our own state,
2203 // we need to emulate it coming back and saying it is
2204 // idle.
2205 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
2206 msg.obj = next;
2207 mHandler.sendMessage(msg);
2208 }
2209
Dianne Hackborn1bcf5a82009-09-30 15:22:29 -07002210 reportResumedActivityLocked(next);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002212 next.thumbnail = null;
2213 setFocusedActivityLocked(next);
2214 next.resumeKeyDispatchingLocked();
2215 ensureActivitiesVisibleLocked(null, 0);
2216 mWindowManager.executeAppTransition();
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07002217 mNoAnimActivities.clear();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07002218
2219 // Mark the point when the activity is resuming
2220 // TODO: To be more accurate, the mark should be before the onCreate,
2221 // not after the onResume. But for subsequent starts, onResume is fine.
2222 if (next.app != null) {
2223 synchronized (mProcessStatsThread) {
2224 next.cpuTimeAtResume = mProcessStats.getCpuTimeForPid(next.app.pid);
2225 }
2226 } else {
2227 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
2228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002229 }
2230
2231 /**
2232 * Make sure that all activities that need to be visible (that is, they
2233 * currently can be seen by the user) actually are.
2234 */
2235 private final void ensureActivitiesVisibleLocked(HistoryRecord top,
2236 HistoryRecord starting, String onlyThisProcess, int configChanges) {
2237 if (DEBUG_VISBILITY) Log.v(
2238 TAG, "ensureActivitiesVisible behind " + top
2239 + " configChanges=0x" + Integer.toHexString(configChanges));
2240
2241 // If the top activity is not fullscreen, then we need to
2242 // make sure any activities under it are now visible.
2243 final int count = mHistory.size();
2244 int i = count-1;
2245 while (mHistory.get(i) != top) {
2246 i--;
2247 }
2248 HistoryRecord r;
2249 boolean behindFullscreen = false;
2250 for (; i>=0; i--) {
2251 r = (HistoryRecord)mHistory.get(i);
2252 if (DEBUG_VISBILITY) Log.v(
2253 TAG, "Make visible? " + r + " finishing=" + r.finishing
2254 + " state=" + r.state);
2255 if (r.finishing) {
2256 continue;
2257 }
2258
2259 final boolean doThisProcess = onlyThisProcess == null
2260 || onlyThisProcess.equals(r.processName);
2261
2262 // First: if this is not the current activity being started, make
2263 // sure it matches the current configuration.
2264 if (r != starting && doThisProcess) {
2265 ensureActivityConfigurationLocked(r, 0);
2266 }
2267
2268 if (r.app == null || r.app.thread == null) {
2269 if (onlyThisProcess == null
2270 || onlyThisProcess.equals(r.processName)) {
2271 // This activity needs to be visible, but isn't even
2272 // running... get it started, but don't resume it
2273 // at this point.
2274 if (DEBUG_VISBILITY) Log.v(
2275 TAG, "Start and freeze screen for " + r);
2276 if (r != starting) {
2277 r.startFreezingScreenLocked(r.app, configChanges);
2278 }
2279 if (!r.visible) {
2280 if (DEBUG_VISBILITY) Log.v(
2281 TAG, "Starting and making visible: " + r);
2282 mWindowManager.setAppVisibility(r, true);
2283 }
2284 if (r != starting) {
2285 startSpecificActivityLocked(r, false, false);
2286 }
2287 }
2288
2289 } else if (r.visible) {
2290 // If this activity is already visible, then there is nothing
2291 // else to do here.
2292 if (DEBUG_VISBILITY) Log.v(
2293 TAG, "Skipping: already visible at " + r);
2294 r.stopFreezingScreenLocked(false);
2295
2296 } else if (onlyThisProcess == null) {
2297 // This activity is not currently visible, but is running.
2298 // Tell it to become visible.
2299 r.visible = true;
2300 if (r.state != ActivityState.RESUMED && r != starting) {
2301 // If this activity is paused, tell it
2302 // to now show its window.
2303 if (DEBUG_VISBILITY) Log.v(
2304 TAG, "Making visible and scheduling visibility: " + r);
2305 try {
2306 mWindowManager.setAppVisibility(r, true);
2307 r.app.thread.scheduleWindowVisibility(r, true);
2308 r.stopFreezingScreenLocked(false);
2309 } catch (Exception e) {
2310 // Just skip on any failure; we'll make it
2311 // visible when it next restarts.
2312 Log.w(TAG, "Exception thrown making visibile: "
2313 + r.intent.getComponent(), e);
2314 }
2315 }
2316 }
2317
2318 // Aggregate current change flags.
2319 configChanges |= r.configChangeFlags;
2320
2321 if (r.fullscreen) {
2322 // At this point, nothing else needs to be shown
2323 if (DEBUG_VISBILITY) Log.v(
2324 TAG, "Stopping: fullscreen at " + r);
2325 behindFullscreen = true;
2326 i--;
2327 break;
2328 }
2329 }
2330
2331 // Now for any activities that aren't visible to the user, make
2332 // sure they no longer are keeping the screen frozen.
2333 while (i >= 0) {
2334 r = (HistoryRecord)mHistory.get(i);
2335 if (DEBUG_VISBILITY) Log.v(
2336 TAG, "Make invisible? " + r + " finishing=" + r.finishing
2337 + " state=" + r.state
2338 + " behindFullscreen=" + behindFullscreen);
2339 if (!r.finishing) {
2340 if (behindFullscreen) {
2341 if (r.visible) {
2342 if (DEBUG_VISBILITY) Log.v(
2343 TAG, "Making invisible: " + r);
2344 r.visible = false;
2345 try {
2346 mWindowManager.setAppVisibility(r, false);
2347 if ((r.state == ActivityState.STOPPING
2348 || r.state == ActivityState.STOPPED)
2349 && r.app != null && r.app.thread != null) {
2350 if (DEBUG_VISBILITY) Log.v(
2351 TAG, "Scheduling invisibility: " + r);
2352 r.app.thread.scheduleWindowVisibility(r, false);
2353 }
2354 } catch (Exception e) {
2355 // Just skip on any failure; we'll make it
2356 // visible when it next restarts.
2357 Log.w(TAG, "Exception thrown making hidden: "
2358 + r.intent.getComponent(), e);
2359 }
2360 } else {
2361 if (DEBUG_VISBILITY) Log.v(
2362 TAG, "Already invisible: " + r);
2363 }
2364 } else if (r.fullscreen) {
2365 if (DEBUG_VISBILITY) Log.v(
2366 TAG, "Now behindFullscreen: " + r);
2367 behindFullscreen = true;
2368 }
2369 }
2370 i--;
2371 }
2372 }
2373
2374 /**
2375 * Version of ensureActivitiesVisible that can easily be called anywhere.
2376 */
2377 private final void ensureActivitiesVisibleLocked(HistoryRecord starting,
2378 int configChanges) {
2379 HistoryRecord r = topRunningActivityLocked(null);
2380 if (r != null) {
2381 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
2382 }
2383 }
2384
2385 private void updateUsageStats(HistoryRecord resumedComponent, boolean resumed) {
2386 if (resumed) {
2387 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2388 } else {
2389 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2390 }
2391 }
2392
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002393 private boolean startHomeActivityLocked() {
2394 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2395 && mTopAction == null) {
2396 // We are running in factory test mode, but unable to find
2397 // the factory test app, so just sit around displaying the
2398 // error message and don't try to start anything.
2399 return false;
2400 }
2401 Intent intent = new Intent(
2402 mTopAction,
2403 mTopData != null ? Uri.parse(mTopData) : null);
2404 intent.setComponent(mTopComponent);
2405 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2406 intent.addCategory(Intent.CATEGORY_HOME);
2407 }
2408 ActivityInfo aInfo =
2409 intent.resolveActivityInfo(mContext.getPackageManager(),
2410 STOCK_PM_FLAGS);
2411 if (aInfo != null) {
2412 intent.setComponent(new ComponentName(
2413 aInfo.applicationInfo.packageName, aInfo.name));
2414 // Don't do this if the home app is currently being
2415 // instrumented.
2416 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2417 aInfo.applicationInfo.uid);
2418 if (app == null || app.instrumentationClass == null) {
2419 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
2420 startActivityLocked(null, intent, null, null, 0, aInfo,
2421 null, null, 0, 0, 0, false, false);
2422 }
2423 }
2424
2425
2426 return true;
2427 }
2428
2429 /**
2430 * Starts the "new version setup screen" if appropriate.
2431 */
2432 private void startSetupActivityLocked() {
2433 // Only do this once per boot.
2434 if (mCheckedForSetup) {
2435 return;
2436 }
2437
2438 // We will show this screen if the current one is a different
2439 // version than the last one shown, and we are not running in
2440 // low-level factory test mode.
2441 final ContentResolver resolver = mContext.getContentResolver();
2442 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2443 Settings.Secure.getInt(resolver,
2444 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2445 mCheckedForSetup = true;
2446
2447 // See if we should be showing the platform update setup UI.
2448 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2449 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2450 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2451
2452 // We don't allow third party apps to replace this.
2453 ResolveInfo ri = null;
2454 for (int i=0; ris != null && i<ris.size(); i++) {
2455 if ((ris.get(i).activityInfo.applicationInfo.flags
2456 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2457 ri = ris.get(i);
2458 break;
2459 }
2460 }
2461
2462 if (ri != null) {
2463 String vers = ri.activityInfo.metaData != null
2464 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2465 : null;
2466 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2467 vers = ri.activityInfo.applicationInfo.metaData.getString(
2468 Intent.METADATA_SETUP_VERSION);
2469 }
2470 String lastVers = Settings.Secure.getString(
2471 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2472 if (vers != null && !vers.equals(lastVers)) {
2473 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2474 intent.setComponent(new ComponentName(
2475 ri.activityInfo.packageName, ri.activityInfo.name));
2476 startActivityLocked(null, intent, null, null, 0, ri.activityInfo,
2477 null, null, 0, 0, 0, false, false);
2478 }
2479 }
2480 }
2481 }
2482
Dianne Hackborn1bcf5a82009-09-30 15:22:29 -07002483 private void reportResumedActivityLocked(HistoryRecord r) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002484 //Log.i(TAG, "**** REPORT RESUME: " + r);
2485
2486 final int identHash = System.identityHashCode(r);
2487 updateUsageStats(r, true);
2488
2489 int i = mWatchers.beginBroadcast();
2490 while (i > 0) {
2491 i--;
2492 IActivityWatcher w = mWatchers.getBroadcastItem(i);
2493 if (w != null) {
2494 try {
2495 w.activityResuming(identHash);
2496 } catch (RemoteException e) {
2497 }
2498 }
2499 }
2500 mWatchers.finishBroadcast();
2501 }
2502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 /**
2504 * Ensure that the top activity in the stack is resumed.
2505 *
2506 * @param prev The previously resumed activity, for when in the process
2507 * of pausing; can be null to call from elsewhere.
2508 *
2509 * @return Returns true if something is being resumed, or false if
2510 * nothing happened.
2511 */
2512 private final boolean resumeTopActivityLocked(HistoryRecord prev) {
2513 // Find the first activity that is not finishing.
2514 HistoryRecord next = topRunningActivityLocked(null);
2515
2516 // Remember how we'll process this pause/resume situation, and ensure
2517 // that the state is reset however we wind up proceeding.
2518 final boolean userLeaving = mUserLeaving;
2519 mUserLeaving = false;
2520
2521 if (next == null) {
2522 // There are no more activities! Let's just start up the
2523 // Launcher...
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002524 return startHomeActivityLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 }
2526
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002527 next.delayedResume = false;
2528
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 // If the top activity is the resumed one, nothing to do.
2530 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
2531 // Make sure we have executed any pending transitions, since there
2532 // should be nothing left to do at this point.
2533 mWindowManager.executeAppTransition();
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07002534 mNoAnimActivities.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535 return false;
2536 }
2537
2538 // If we are sleeping, and there is no resumed activity, and the top
2539 // activity is paused, well that is the state we want.
Dianne Hackborn55280a92009-05-07 15:53:46 -07002540 if ((mSleeping || mShuttingDown)
2541 && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 // Make sure we have executed any pending transitions, since there
2543 // should be nothing left to do at this point.
2544 mWindowManager.executeAppTransition();
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07002545 mNoAnimActivities.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 return false;
2547 }
2548
2549 // The activity may be waiting for stop, but that is no longer
2550 // appropriate for it.
2551 mStoppingActivities.remove(next);
2552 mWaitingVisibleActivities.remove(next);
2553
2554 if (DEBUG_SWITCH) Log.v(TAG, "Resuming " + next);
2555
2556 // If we are currently pausing an activity, then don't do anything
2557 // until that is done.
2558 if (mPausingActivity != null) {
2559 if (DEBUG_SWITCH) Log.v(TAG, "Skip resume: pausing=" + mPausingActivity);
2560 return false;
2561 }
2562
2563 // We need to start pausing the current activity so the top one
2564 // can be resumed...
2565 if (mResumedActivity != null) {
2566 if (DEBUG_SWITCH) Log.v(TAG, "Skip resume: need to start pausing");
2567 startPausingLocked(userLeaving, false);
2568 return true;
2569 }
2570
2571 if (prev != null && prev != next) {
2572 if (!prev.waitingVisible && next != null && !next.nowVisible) {
2573 prev.waitingVisible = true;
2574 mWaitingVisibleActivities.add(prev);
2575 if (DEBUG_SWITCH) Log.v(
2576 TAG, "Resuming top, waiting visible to hide: " + prev);
2577 } else {
2578 // The next activity is already visible, so hide the previous
2579 // activity's windows right now so we can show the new one ASAP.
2580 // We only do this if the previous is finishing, which should mean
2581 // it is on top of the one being resumed so hiding it quickly
2582 // is good. Otherwise, we want to do the normal route of allowing
2583 // the resumed activity to be shown so we can decide if the
2584 // previous should actually be hidden depending on whether the
2585 // new one is found to be full-screen or not.
2586 if (prev.finishing) {
2587 mWindowManager.setAppVisibility(prev, false);
2588 if (DEBUG_SWITCH) Log.v(TAG, "Not waiting for visible to hide: "
2589 + prev + ", waitingVisible="
2590 + (prev != null ? prev.waitingVisible : null)
2591 + ", nowVisible=" + next.nowVisible);
2592 } else {
2593 if (DEBUG_SWITCH) Log.v(TAG, "Previous already visible but still waiting to hide: "
2594 + prev + ", waitingVisible="
2595 + (prev != null ? prev.waitingVisible : null)
2596 + ", nowVisible=" + next.nowVisible);
2597 }
2598 }
2599 }
2600
2601 // We are starting up the next activity, so tell the window manager
2602 // that the previous one will be hidden soon. This way it can know
2603 // to ignore it when computing the desired screen orientation.
2604 if (prev != null) {
2605 if (prev.finishing) {
2606 if (DEBUG_TRANSITION) Log.v(TAG,
2607 "Prepare close transition: prev=" + prev);
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07002608 if (mNoAnimActivities.contains(prev)) {
2609 mWindowManager.prepareAppTransition(WindowManagerPolicy.TRANSIT_NONE);
2610 } else {
2611 mWindowManager.prepareAppTransition(prev.task == next.task
2612 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
2613 : WindowManagerPolicy.TRANSIT_TASK_CLOSE);
2614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 mWindowManager.setAppWillBeHidden(prev);
2616 mWindowManager.setAppVisibility(prev, false);
2617 } else {
2618 if (DEBUG_TRANSITION) Log.v(TAG,
2619 "Prepare open transition: prev=" + prev);
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07002620 if (mNoAnimActivities.contains(next)) {
2621 mWindowManager.prepareAppTransition(WindowManagerPolicy.TRANSIT_NONE);
2622 } else {
2623 mWindowManager.prepareAppTransition(prev.task == next.task
2624 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
2625 : WindowManagerPolicy.TRANSIT_TASK_OPEN);
2626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002627 }
2628 if (false) {
2629 mWindowManager.setAppWillBeHidden(prev);
2630 mWindowManager.setAppVisibility(prev, false);
2631 }
2632 } else if (mHistory.size() > 1) {
2633 if (DEBUG_TRANSITION) Log.v(TAG,
2634 "Prepare open transition: no previous");
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07002635 if (mNoAnimActivities.contains(next)) {
2636 mWindowManager.prepareAppTransition(WindowManagerPolicy.TRANSIT_NONE);
2637 } else {
2638 mWindowManager.prepareAppTransition(WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN);
2639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640 }
2641
2642 if (next.app != null && next.app.thread != null) {
2643 if (DEBUG_SWITCH) Log.v(TAG, "Resume running: " + next);
2644
2645 // This activity is now becoming visible.
2646 mWindowManager.setAppVisibility(next, true);
2647
2648 HistoryRecord lastResumedActivity = mResumedActivity;
2649 ActivityState lastState = next.state;
2650
2651 updateCpuStats();
2652
2653 next.state = ActivityState.RESUMED;
2654 mResumedActivity = next;
2655 next.task.touchActiveTime();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002656 updateLruProcessLocked(next.app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002657 updateLRUListLocked(next);
2658
2659 // Have the window manager re-evaluate the orientation of
2660 // the screen based on the new activity order.
Eric Fischerd4d04de2009-10-27 18:55:57 -07002661 boolean updated;
2662 synchronized (this) {
2663 Configuration config = mWindowManager.updateOrientationFromAppTokens(
2664 mConfiguration,
2665 next.mayFreezeScreenLocked(next.app) ? next : null);
2666 if (config != null) {
2667 /*
2668 * Explicitly restore the locale to the one from the
2669 * old configuration, since the one that comes back from
2670 * the window manager has the default (boot) locale.
2671 *
2672 * It looks like previously the locale picker only worked
2673 * by coincidence: usually it would do its setting of
2674 * the locale after the activity transition, so it didn't
2675 * matter that this lost it. With the synchronized
2676 * block now keeping them from happening at the same time,
2677 * this one always would happen second and undo what the
2678 * locale picker had just done.
2679 */
2680 config.locale = mConfiguration.locale;
2681 next.frozenBeforeDestroy = true;
2682 }
2683 updated = updateConfigurationLocked(config, next);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 }
Eric Fischerd4d04de2009-10-27 18:55:57 -07002685 if (!updated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 // The configuration update wasn't able to keep the existing
2687 // instance of the activity, and instead started a new one.
2688 // We should be all done, but let's just make sure our activity
2689 // is still at the top and schedule another run if something
2690 // weird happened.
2691 HistoryRecord nextNext = topRunningActivityLocked(null);
2692 if (DEBUG_SWITCH) Log.i(TAG,
2693 "Activity config changed during resume: " + next
2694 + ", new next: " + nextNext);
2695 if (nextNext != next) {
2696 // Do over!
2697 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
2698 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002699 setFocusedActivityLocked(next);
2700 ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002701 mWindowManager.executeAppTransition();
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07002702 mNoAnimActivities.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 return true;
2704 }
2705
2706 try {
2707 // Deliver all pending results.
2708 ArrayList a = next.results;
2709 if (a != null) {
2710 final int N = a.size();
2711 if (!next.finishing && N > 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002712 if (DEBUG_RESULTS) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002713 TAG, "Delivering results to " + next
2714 + ": " + a);
2715 next.app.thread.scheduleSendResult(next, a);
2716 }
2717 }
2718
2719 if (next.newIntents != null) {
2720 next.app.thread.scheduleNewIntent(next.newIntents, next);
2721 }
2722
Doug Zongker2bec3d42009-12-04 12:52:44 -08002723 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 System.identityHashCode(next),
2725 next.task.taskId, next.shortComponentName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002726
2727 next.app.thread.scheduleResumeActivity(next,
2728 isNextTransitionForward());
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002730 pauseIfSleepingLocked();
2731
2732 } catch (Exception e) {
2733 // Whoops, need to restart this activity!
2734 next.state = lastState;
2735 mResumedActivity = lastResumedActivity;
Dianne Hackborn03abb812010-01-04 18:43:19 -08002736 Log.i(TAG, "Restarting because process died: " + next);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002737 if (!next.hasBeenLaunched) {
2738 next.hasBeenLaunched = true;
2739 } else {
2740 if (SHOW_APP_STARTING_ICON) {
2741 mWindowManager.setAppStartingWindow(
2742 next, next.packageName, next.theme,
2743 next.nonLocalizedLabel,
2744 next.labelRes, next.icon, null, true);
2745 }
2746 }
2747 startSpecificActivityLocked(next, true, false);
2748 return true;
2749 }
2750
2751 // From this point on, if something goes wrong there is no way
2752 // to recover the activity.
2753 try {
2754 next.visible = true;
2755 completeResumeLocked(next);
2756 } catch (Exception e) {
2757 // If any exception gets thrown, toss away this
2758 // activity and try the next one.
2759 Log.w(TAG, "Exception thrown during resume of " + next, e);
2760 requestFinishActivityLocked(next, Activity.RESULT_CANCELED, null,
2761 "resume-exception");
2762 return true;
2763 }
2764
2765 // Didn't need to use the icicle, and it is now out of date.
2766 next.icicle = null;
2767 next.haveState = false;
2768 next.stopped = false;
2769
2770 } else {
2771 // Whoops, need to restart this activity!
2772 if (!next.hasBeenLaunched) {
2773 next.hasBeenLaunched = true;
2774 } else {
2775 if (SHOW_APP_STARTING_ICON) {
2776 mWindowManager.setAppStartingWindow(
2777 next, next.packageName, next.theme,
2778 next.nonLocalizedLabel,
2779 next.labelRes, next.icon, null, true);
2780 }
2781 if (DEBUG_SWITCH) Log.v(TAG, "Restarting: " + next);
2782 }
2783 startSpecificActivityLocked(next, true, true);
2784 }
2785
2786 return true;
2787 }
2788
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002789 private final void startActivityLocked(HistoryRecord r, boolean newTask,
2790 boolean doResume) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002791 final int NH = mHistory.size();
2792
2793 int addPos = -1;
2794
2795 if (!newTask) {
2796 // If starting in an existing task, find where that is...
2797 HistoryRecord next = null;
2798 boolean startIt = true;
2799 for (int i = NH-1; i >= 0; i--) {
2800 HistoryRecord p = (HistoryRecord)mHistory.get(i);
2801 if (p.finishing) {
2802 continue;
2803 }
2804 if (p.task == r.task) {
2805 // Here it is! Now, if this is not yet visible to the
2806 // user, then just add it without starting; it will
2807 // get started when the user navigates back to it.
2808 addPos = i+1;
2809 if (!startIt) {
2810 mHistory.add(addPos, r);
2811 r.inHistory = true;
2812 r.task.numActivities++;
2813 mWindowManager.addAppToken(addPos, r, r.task.taskId,
2814 r.info.screenOrientation, r.fullscreen);
2815 if (VALIDATE_TOKENS) {
2816 mWindowManager.validateAppTokens(mHistory);
2817 }
2818 return;
2819 }
2820 break;
2821 }
2822 if (p.fullscreen) {
2823 startIt = false;
2824 }
2825 next = p;
2826 }
2827 }
2828
2829 // Place a new activity at top of stack, so it is next to interact
2830 // with the user.
2831 if (addPos < 0) {
2832 addPos = mHistory.size();
2833 }
2834
2835 // If we are not placing the new activity frontmost, we do not want
2836 // to deliver the onUserLeaving callback to the actual frontmost
2837 // activity
2838 if (addPos < NH) {
2839 mUserLeaving = false;
2840 if (DEBUG_USER_LEAVING) Log.v(TAG, "startActivity() behind front, mUserLeaving=false");
2841 }
2842
2843 // Slot the activity into the history stack and proceed
2844 mHistory.add(addPos, r);
2845 r.inHistory = true;
2846 r.frontOfTask = newTask;
2847 r.task.numActivities++;
2848 if (NH > 0) {
2849 // We want to show the starting preview window if we are
2850 // switching to a new task, or the next activity's process is
2851 // not currently running.
2852 boolean showStartingIcon = newTask;
2853 ProcessRecord proc = r.app;
2854 if (proc == null) {
2855 proc = mProcessNames.get(r.processName, r.info.applicationInfo.uid);
2856 }
2857 if (proc == null || proc.thread == null) {
2858 showStartingIcon = true;
2859 }
2860 if (DEBUG_TRANSITION) Log.v(TAG,
2861 "Prepare open transition: starting " + r);
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07002862 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
2863 mWindowManager.prepareAppTransition(WindowManagerPolicy.TRANSIT_NONE);
2864 mNoAnimActivities.add(r);
2865 } else if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
2866 mWindowManager.prepareAppTransition(WindowManagerPolicy.TRANSIT_TASK_OPEN);
2867 mNoAnimActivities.remove(r);
2868 } else {
2869 mWindowManager.prepareAppTransition(newTask
2870 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
2871 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN);
2872 mNoAnimActivities.remove(r);
2873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874 mWindowManager.addAppToken(
2875 addPos, r, r.task.taskId, r.info.screenOrientation, r.fullscreen);
2876 boolean doShow = true;
2877 if (newTask) {
2878 // Even though this activity is starting fresh, we still need
2879 // to reset it to make sure we apply affinities to move any
2880 // existing activities from other tasks in to it.
2881 // If the caller has requested that the target task be
2882 // reset, then do so.
2883 if ((r.intent.getFlags()
2884 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2885 resetTaskIfNeededLocked(r, r);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002886 doShow = topRunningNonDelayedActivityLocked(null) == r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002887 }
2888 }
2889 if (SHOW_APP_STARTING_ICON && doShow) {
2890 // Figure out if we are transitioning from another activity that is
2891 // "has the same starting icon" as the next one. This allows the
2892 // window manager to keep the previous window it had previously
2893 // created, if it still had one.
2894 HistoryRecord prev = mResumedActivity;
2895 if (prev != null) {
2896 // We don't want to reuse the previous starting preview if:
2897 // (1) The current activity is in a different task.
2898 if (prev.task != r.task) prev = null;
2899 // (2) The current activity is already displayed.
2900 else if (prev.nowVisible) prev = null;
2901 }
2902 mWindowManager.setAppStartingWindow(
2903 r, r.packageName, r.theme, r.nonLocalizedLabel,
2904 r.labelRes, r.icon, prev, showStartingIcon);
2905 }
2906 } else {
2907 // If this is the first activity, don't do any fancy animations,
2908 // because there is nothing for it to animate on top of.
2909 mWindowManager.addAppToken(addPos, r, r.task.taskId,
2910 r.info.screenOrientation, r.fullscreen);
2911 }
2912 if (VALIDATE_TOKENS) {
2913 mWindowManager.validateAppTokens(mHistory);
2914 }
2915
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002916 if (doResume) {
2917 resumeTopActivityLocked(null);
2918 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002919 }
2920
2921 /**
2922 * Perform clear operation as requested by
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002923 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2924 * stack to the given task, then look for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002925 * an instance of that activity in the stack and, if found, finish all
2926 * activities on top of it and return the instance.
2927 *
2928 * @param newR Description of the new activity being started.
2929 * @return Returns the old activity that should be continue to be used,
2930 * or null if none was found.
2931 */
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002932 private final HistoryRecord performClearTaskLocked(int taskId,
Dianne Hackbornaa52f9a2009-08-25 16:01:15 -07002933 HistoryRecord newR, int launchFlags, boolean doClear) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002934 int i = mHistory.size();
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002935
2936 // First find the requested task.
2937 while (i > 0) {
2938 i--;
2939 HistoryRecord r = (HistoryRecord)mHistory.get(i);
2940 if (r.task.taskId == taskId) {
2941 i++;
2942 break;
2943 }
2944 }
2945
2946 // Now clear it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002947 while (i > 0) {
2948 i--;
2949 HistoryRecord r = (HistoryRecord)mHistory.get(i);
2950 if (r.finishing) {
2951 continue;
2952 }
2953 if (r.task.taskId != taskId) {
2954 return null;
2955 }
2956 if (r.realActivity.equals(newR.realActivity)) {
2957 // Here it is! Now finish everything in front...
2958 HistoryRecord ret = r;
2959 if (doClear) {
2960 while (i < (mHistory.size()-1)) {
2961 i++;
2962 r = (HistoryRecord)mHistory.get(i);
2963 if (r.finishing) {
2964 continue;
2965 }
2966 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2967 null, "clear")) {
2968 i--;
2969 }
2970 }
2971 }
2972
2973 // Finally, if this is a normal launch mode (that is, not
2974 // expecting onNewIntent()), then we will finish the current
2975 // instance of the activity so a new fresh one can be started.
Dianne Hackbornaa52f9a2009-08-25 16:01:15 -07002976 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2977 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002978 if (!ret.finishing) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07002979 int index = indexOfTokenLocked(ret);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980 if (index >= 0) {
2981 finishActivityLocked(ret, 0, Activity.RESULT_CANCELED,
2982 null, "clear");
2983 }
2984 return null;
2985 }
2986 }
2987
2988 return ret;
2989 }
2990 }
2991
2992 return null;
2993 }
2994
2995 /**
2996 * Find the activity in the history stack within the given task. Returns
2997 * the index within the history at which it's found, or < 0 if not found.
2998 */
2999 private final int findActivityInHistoryLocked(HistoryRecord r, int task) {
3000 int i = mHistory.size();
3001 while (i > 0) {
3002 i--;
3003 HistoryRecord candidate = (HistoryRecord)mHistory.get(i);
3004 if (candidate.task.taskId != task) {
3005 break;
3006 }
3007 if (candidate.realActivity.equals(r.realActivity)) {
3008 return i;
3009 }
3010 }
3011
3012 return -1;
3013 }
3014
3015 /**
3016 * Reorder the history stack so that the activity at the given index is
3017 * brought to the front.
3018 */
3019 private final HistoryRecord moveActivityToFrontLocked(int where) {
3020 HistoryRecord newTop = (HistoryRecord)mHistory.remove(where);
3021 int top = mHistory.size();
3022 HistoryRecord oldTop = (HistoryRecord)mHistory.get(top-1);
3023 mHistory.add(top, newTop);
3024 oldTop.frontOfTask = false;
3025 newTop.frontOfTask = true;
3026 return newTop;
3027 }
3028
3029 /**
3030 * Deliver a new Intent to an existing activity, so that its onNewIntent()
3031 * method will be called at the proper time.
3032 */
3033 private final void deliverNewIntentLocked(HistoryRecord r, Intent intent) {
3034 boolean sent = false;
3035 if (r.state == ActivityState.RESUMED
3036 && r.app != null && r.app.thread != null) {
3037 try {
3038 ArrayList<Intent> ar = new ArrayList<Intent>();
3039 ar.add(new Intent(intent));
3040 r.app.thread.scheduleNewIntent(ar, r);
3041 sent = true;
3042 } catch (Exception e) {
3043 Log.w(TAG, "Exception thrown sending new intent to " + r, e);
3044 }
3045 }
3046 if (!sent) {
3047 r.addNewIntentLocked(new Intent(intent));
3048 }
3049 }
3050
3051 private final void logStartActivity(int tag, HistoryRecord r,
3052 TaskRecord task) {
3053 EventLog.writeEvent(tag,
3054 System.identityHashCode(r), task.taskId,
3055 r.shortComponentName, r.intent.getAction(),
3056 r.intent.getType(), r.intent.getDataString(),
3057 r.intent.getFlags());
3058 }
3059
3060 private final int startActivityLocked(IApplicationThread caller,
3061 Intent intent, String resolvedType,
3062 Uri[] grantedUriPermissions,
3063 int grantedMode, ActivityInfo aInfo, IBinder resultTo,
3064 String resultWho, int requestCode,
The Android Open Source Project4df24232009-03-05 14:34:35 -08003065 int callingPid, int callingUid, boolean onlyIfNeeded,
3066 boolean componentSpecified) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003067 Log.i(TAG, "Starting activity: " + intent);
3068
3069 HistoryRecord sourceRecord = null;
3070 HistoryRecord resultRecord = null;
3071 if (resultTo != null) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07003072 int index = indexOfTokenLocked(resultTo);
The Android Open Source Project10592532009-03-18 17:39:46 -07003073 if (DEBUG_RESULTS) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003074 TAG, "Sending result to " + resultTo + " (index " + index + ")");
3075 if (index >= 0) {
3076 sourceRecord = (HistoryRecord)mHistory.get(index);
3077 if (requestCode >= 0 && !sourceRecord.finishing) {
3078 resultRecord = sourceRecord;
3079 }
3080 }
3081 }
3082
3083 int launchFlags = intent.getFlags();
3084
3085 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
3086 && sourceRecord != null) {
3087 // Transfer the result target from the source activity to the new
3088 // one being started, including any failures.
3089 if (requestCode >= 0) {
3090 return START_FORWARD_AND_REQUEST_CONFLICT;
3091 }
3092 resultRecord = sourceRecord.resultTo;
3093 resultWho = sourceRecord.resultWho;
3094 requestCode = sourceRecord.requestCode;
3095 sourceRecord.resultTo = null;
3096 if (resultRecord != null) {
3097 resultRecord.removeResultsLocked(
3098 sourceRecord, resultWho, requestCode);
3099 }
3100 }
3101
3102 int err = START_SUCCESS;
3103
3104 if (intent.getComponent() == null) {
3105 // We couldn't find a class that can handle the given Intent.
3106 // That's the end of that!
3107 err = START_INTENT_NOT_RESOLVED;
3108 }
3109
3110 if (err == START_SUCCESS && aInfo == null) {
3111 // We couldn't find the specific class specified in the Intent.
3112 // Also the end of the line.
3113 err = START_CLASS_NOT_FOUND;
3114 }
3115
3116 ProcessRecord callerApp = null;
3117 if (err == START_SUCCESS && caller != null) {
3118 callerApp = getRecordForAppLocked(caller);
3119 if (callerApp != null) {
3120 callingPid = callerApp.pid;
3121 callingUid = callerApp.info.uid;
3122 } else {
3123 Log.w(TAG, "Unable to find app for caller " + caller
3124 + " (pid=" + callingPid + ") when starting: "
3125 + intent.toString());
3126 err = START_PERMISSION_DENIED;
3127 }
3128 }
3129
3130 if (err != START_SUCCESS) {
3131 if (resultRecord != null) {
3132 sendActivityResultLocked(-1,
3133 resultRecord, resultWho, requestCode,
3134 Activity.RESULT_CANCELED, null);
3135 }
3136 return err;
3137 }
3138
3139 final int perm = checkComponentPermission(aInfo.permission, callingPid,
3140 callingUid, aInfo.exported ? -1 : aInfo.applicationInfo.uid);
3141 if (perm != PackageManager.PERMISSION_GRANTED) {
3142 if (resultRecord != null) {
3143 sendActivityResultLocked(-1,
3144 resultRecord, resultWho, requestCode,
3145 Activity.RESULT_CANCELED, null);
3146 }
3147 String msg = "Permission Denial: starting " + intent.toString()
3148 + " from " + callerApp + " (pid=" + callingPid
3149 + ", uid=" + callingUid + ")"
3150 + " requires " + aInfo.permission;
3151 Log.w(TAG, msg);
3152 throw new SecurityException(msg);
3153 }
3154
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003155 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003156 boolean abort = false;
3157 try {
3158 // The Intent we give to the watcher has the extra data
3159 // stripped off, since it can contain private information.
3160 Intent watchIntent = intent.cloneFilter();
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003161 abort = !mController.activityStarting(watchIntent,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003162 aInfo.applicationInfo.packageName);
3163 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003164 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003165 }
3166
3167 if (abort) {
3168 if (resultRecord != null) {
3169 sendActivityResultLocked(-1,
3170 resultRecord, resultWho, requestCode,
3171 Activity.RESULT_CANCELED, null);
3172 }
3173 // We pretend to the caller that it was really started, but
3174 // they will just get a cancel result.
3175 return START_SUCCESS;
3176 }
3177 }
3178
3179 HistoryRecord r = new HistoryRecord(this, callerApp, callingUid,
3180 intent, resolvedType, aInfo, mConfiguration,
The Android Open Source Project4df24232009-03-05 14:34:35 -08003181 resultRecord, resultWho, requestCode, componentSpecified);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003183 if (mResumedActivity == null
3184 || mResumedActivity.info.applicationInfo.uid != callingUid) {
3185 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
3186 PendingActivityLaunch pal = new PendingActivityLaunch();
3187 pal.r = r;
3188 pal.sourceRecord = sourceRecord;
3189 pal.grantedUriPermissions = grantedUriPermissions;
3190 pal.grantedMode = grantedMode;
3191 pal.onlyIfNeeded = onlyIfNeeded;
3192 mPendingActivityLaunches.add(pal);
3193 return START_SWITCHES_CANCELED;
3194 }
3195 }
3196
3197 if (mDidAppSwitch) {
3198 // This is the second allowed switch since we stopped switches,
3199 // so now just generally allow switches. Use case: user presses
3200 // home (switches disabled, switch to home, mDidAppSwitch now true);
3201 // user taps a home icon (coming from home so allowed, we hit here
3202 // and now allow anyone to switch again).
3203 mAppSwitchesAllowedTime = 0;
3204 } else {
3205 mDidAppSwitch = true;
3206 }
3207
3208 doPendingActivityLaunchesLocked(false);
3209
3210 return startActivityUncheckedLocked(r, sourceRecord,
3211 grantedUriPermissions, grantedMode, onlyIfNeeded, true);
3212 }
3213
3214 private final void doPendingActivityLaunchesLocked(boolean doResume) {
3215 final int N = mPendingActivityLaunches.size();
3216 if (N <= 0) {
3217 return;
3218 }
3219 for (int i=0; i<N; i++) {
3220 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
3221 startActivityUncheckedLocked(pal.r, pal.sourceRecord,
3222 pal.grantedUriPermissions, pal.grantedMode, pal.onlyIfNeeded,
3223 doResume && i == (N-1));
3224 }
3225 mPendingActivityLaunches.clear();
3226 }
3227
3228 private final int startActivityUncheckedLocked(HistoryRecord r,
3229 HistoryRecord sourceRecord, Uri[] grantedUriPermissions,
3230 int grantedMode, boolean onlyIfNeeded, boolean doResume) {
3231 final Intent intent = r.intent;
3232 final int callingUid = r.launchedFromUid;
3233
3234 int launchFlags = intent.getFlags();
3235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003236 // We'll invoke onUserLeaving before onPause only if the launching
3237 // activity did not explicitly state that this is an automated launch.
3238 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
3239 if (DEBUG_USER_LEAVING) Log.v(TAG,
3240 "startActivity() => mUserLeaving=" + mUserLeaving);
3241
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003242 // If the caller has asked not to resume at this point, we make note
3243 // of this in the record so that we can skip it when trying to find
3244 // the top running activity.
3245 if (!doResume) {
3246 r.delayedResume = true;
3247 }
3248
3249 HistoryRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
3250 != 0 ? r : null;
3251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003252 // If the onlyIfNeeded flag is set, then we can do this if the activity
3253 // being launched is the same as the one making the call... or, as
3254 // a special case, if we do not know the caller then we count the
3255 // current top activity as the caller.
3256 if (onlyIfNeeded) {
3257 HistoryRecord checkedCaller = sourceRecord;
3258 if (checkedCaller == null) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003259 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003260 }
3261 if (!checkedCaller.realActivity.equals(r.realActivity)) {
3262 // Caller is not the same as launcher, so always needed.
3263 onlyIfNeeded = false;
3264 }
3265 }
3266
3267 if (grantedUriPermissions != null && callingUid > 0) {
3268 for (int i=0; i<grantedUriPermissions.length; i++) {
3269 grantUriPermissionLocked(callingUid, r.packageName,
3270 grantedUriPermissions[i], grantedMode, r);
3271 }
3272 }
3273
3274 grantUriPermissionFromIntentLocked(callingUid, r.packageName,
3275 intent, r);
3276
3277 if (sourceRecord == null) {
3278 // This activity is not being started from another... in this
3279 // case we -always- start a new task.
3280 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
3281 Log.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
3282 + intent);
3283 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
3284 }
3285 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
3286 // The original activity who is starting us is running as a single
3287 // instance... this new activity it is starting must go on its
3288 // own task.
3289 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
3290 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
3291 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
3292 // The activity being started is a single instance... it always
3293 // gets launched into its own task.
3294 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
3295 }
3296
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003297 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003298 // For whatever reason this activity is being launched into a new
3299 // task... yet the caller has requested a result back. Well, that
3300 // is pretty messed up, so instead immediately send back a cancel
3301 // and let the new task continue launched as normal without a
3302 // dependency on its originator.
3303 Log.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
3304 sendActivityResultLocked(-1,
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003305 r.resultTo, r.resultWho, r.requestCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306 Activity.RESULT_CANCELED, null);
3307 r.resultTo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003308 }
3309
3310 boolean addingToTask = false;
3311 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
3312 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
3313 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
3314 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
3315 // If bring to front is requested, and no result is requested, and
3316 // we can find a task that was started with this same
3317 // component, then instead of launching bring that one to the front.
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003318 if (r.resultTo == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 // See if there is a task to bring to the front. If this is
3320 // a SINGLE_INSTANCE activity, there can be one and only one
3321 // instance of it in the history, and it is always in its own
3322 // unique task, so we do a special search.
3323 HistoryRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
3324 ? findTaskLocked(intent, r.info)
3325 : findActivityLocked(intent, r.info);
3326 if (taskTop != null) {
3327 if (taskTop.task.intent == null) {
3328 // This task was started because of movement of
3329 // the activity based on affinity... now that we
3330 // are actually launching it, we can assign the
3331 // base intent.
3332 taskTop.task.setIntent(intent, r.info);
3333 }
3334 // If the target task is not in the front, then we need
3335 // to bring it to the front... except... well, with
3336 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
3337 // to have the same behavior as if a new instance was
3338 // being started, which means not bringing it to the front
3339 // if the caller is not itself in the front.
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003340 HistoryRecord curTop = topRunningNonDelayedActivityLocked(notTop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341 if (curTop.task != taskTop.task) {
3342 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
3343 boolean callerAtFront = sourceRecord == null
3344 || curTop.task == sourceRecord.task;
3345 if (callerAtFront) {
3346 // We really do want to push this one into the
3347 // user's face, right now.
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07003348 moveTaskToFrontLocked(taskTop.task, r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003349 }
3350 }
3351 // If the caller has requested that the target task be
3352 // reset, then do so.
3353 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
3354 taskTop = resetTaskIfNeededLocked(taskTop, r);
3355 }
3356 if (onlyIfNeeded) {
3357 // We don't need to start a new activity, and
3358 // the client said not to do anything if that
3359 // is the case, so this is it! And for paranoia, make
3360 // sure we have correctly resumed the top activity.
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003361 if (doResume) {
3362 resumeTopActivityLocked(null);
3363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003364 return START_RETURN_INTENT_TO_CALLER;
3365 }
3366 if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
3367 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
3368 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
3369 // In this situation we want to remove all activities
3370 // from the task up to the one being started. In most
3371 // cases this means we are resetting the task to its
3372 // initial state.
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003373 HistoryRecord top = performClearTaskLocked(
Dianne Hackbornaa52f9a2009-08-25 16:01:15 -07003374 taskTop.task.taskId, r, launchFlags, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003375 if (top != null) {
3376 if (top.frontOfTask) {
3377 // Activity aliases may mean we use different
3378 // intents for the top activity, so make sure
3379 // the task now has the identity of the new
3380 // intent.
3381 top.task.setIntent(r.intent, r.info);
3382 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08003383 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003384 deliverNewIntentLocked(top, r.intent);
3385 } else {
3386 // A special case: we need to
3387 // start the activity because it is not currently
3388 // running, and the caller has asked to clear the
3389 // current task to have this activity at the top.
3390 addingToTask = true;
3391 // Now pretend like this activity is being started
3392 // by the top of its task, so it is put in the
3393 // right place.
3394 sourceRecord = taskTop;
3395 }
3396 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
3397 // In this case the top activity on the task is the
3398 // same as the one being launched, so we take that
3399 // as a request to bring the task to the foreground.
3400 // If the top activity in the task is the root
3401 // activity, deliver this new intent to it if it
3402 // desires.
3403 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
3404 && taskTop.realActivity.equals(r.realActivity)) {
Doug Zongker2bec3d42009-12-04 12:52:44 -08003405 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003406 if (taskTop.frontOfTask) {
3407 taskTop.task.setIntent(r.intent, r.info);
3408 }
3409 deliverNewIntentLocked(taskTop, r.intent);
3410 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
3411 // In this case we are launching the root activity
3412 // of the task, but with a different intent. We
3413 // should start a new instance on top.
3414 addingToTask = true;
3415 sourceRecord = taskTop;
3416 }
3417 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
3418 // In this case an activity is being launched in to an
3419 // existing task, without resetting that task. This
3420 // is typically the situation of launching an activity
3421 // from a notification or shortcut. We want to place
3422 // the new activity on top of the current task.
3423 addingToTask = true;
3424 sourceRecord = taskTop;
3425 } else if (!taskTop.task.rootWasReset) {
3426 // In this case we are launching in to an existing task
3427 // that has not yet been started from its front door.
3428 // The current task has been brought to the front.
3429 // Ideally, we'd probably like to place this new task
3430 // at the bottom of its stack, but that's a little hard
3431 // to do with the current organization of the code so
3432 // for now we'll just drop it.
3433 taskTop.task.setIntent(r.intent, r.info);
3434 }
3435 if (!addingToTask) {
3436 // We didn't do anything... but it was needed (a.k.a., client
3437 // don't use that intent!) And for paranoia, make
3438 // sure we have correctly resumed the top activity.
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003439 if (doResume) {
3440 resumeTopActivityLocked(null);
3441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003442 return START_TASK_TO_FRONT;
3443 }
3444 }
3445 }
3446 }
3447
3448 //String uri = r.intent.toURI();
3449 //Intent intent2 = new Intent(uri);
3450 //Log.i(TAG, "Given intent: " + r.intent);
3451 //Log.i(TAG, "URI is: " + uri);
3452 //Log.i(TAG, "To intent: " + intent2);
3453
3454 if (r.packageName != null) {
3455 // If the activity being launched is the same as the one currently
3456 // at the top, then we need to check if it should only be launched
3457 // once.
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003458 HistoryRecord top = topRunningNonDelayedActivityLocked(notTop);
3459 if (top != null && r.resultTo == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003460 if (top.realActivity.equals(r.realActivity)) {
3461 if (top.app != null && top.app.thread != null) {
3462 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
3463 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
3464 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
Doug Zongker2bec3d42009-12-04 12:52:44 -08003465 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003466 // For paranoia, make sure we have correctly
3467 // resumed the top activity.
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003468 if (doResume) {
3469 resumeTopActivityLocked(null);
3470 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003471 if (onlyIfNeeded) {
3472 // We don't need to start a new activity, and
3473 // the client said not to do anything if that
3474 // is the case, so this is it!
3475 return START_RETURN_INTENT_TO_CALLER;
3476 }
3477 deliverNewIntentLocked(top, r.intent);
3478 return START_DELIVERED_TO_TOP;
3479 }
3480 }
3481 }
3482 }
3483
3484 } else {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003485 if (r.resultTo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003486 sendActivityResultLocked(-1,
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003487 r.resultTo, r.resultWho, r.requestCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003488 Activity.RESULT_CANCELED, null);
3489 }
3490 return START_CLASS_NOT_FOUND;
3491 }
3492
3493 boolean newTask = false;
3494
3495 // Should this be considered a new task?
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003496 if (r.resultTo == null && !addingToTask
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003497 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
3498 // todo: should do better management of integers.
3499 mCurTask++;
3500 if (mCurTask <= 0) {
3501 mCurTask = 1;
3502 }
3503 r.task = new TaskRecord(mCurTask, r.info, intent,
3504 (r.info.flags&ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0);
3505 if (DEBUG_TASKS) Log.v(TAG, "Starting new activity " + r
3506 + " in new task " + r.task);
3507 newTask = true;
3508 addRecentTask(r.task);
3509
3510 } else if (sourceRecord != null) {
3511 if (!addingToTask &&
3512 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
3513 // In this case, we are adding the activity to an existing
3514 // task, but the caller has asked to clear that task if the
3515 // activity is already running.
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003516 HistoryRecord top = performClearTaskLocked(
Dianne Hackbornaa52f9a2009-08-25 16:01:15 -07003517 sourceRecord.task.taskId, r, launchFlags, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518 if (top != null) {
Doug Zongker2bec3d42009-12-04 12:52:44 -08003519 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003520 deliverNewIntentLocked(top, r.intent);
3521 // For paranoia, make sure we have correctly
3522 // resumed the top activity.
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003523 if (doResume) {
3524 resumeTopActivityLocked(null);
3525 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003526 return START_DELIVERED_TO_TOP;
3527 }
3528 } else if (!addingToTask &&
3529 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
3530 // In this case, we are launching an activity in our own task
3531 // that may already be running somewhere in the history, and
3532 // we want to shuffle it to the front of the stack if so.
3533 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
3534 if (where >= 0) {
3535 HistoryRecord top = moveActivityToFrontLocked(where);
Doug Zongker2bec3d42009-12-04 12:52:44 -08003536 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003537 deliverNewIntentLocked(top, r.intent);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003538 if (doResume) {
3539 resumeTopActivityLocked(null);
3540 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003541 return START_DELIVERED_TO_TOP;
3542 }
3543 }
3544 // An existing activity is starting this new activity, so we want
3545 // to keep the new one in the same task as the one that is starting
3546 // it.
3547 r.task = sourceRecord.task;
3548 if (DEBUG_TASKS) Log.v(TAG, "Starting new activity " + r
3549 + " in existing task " + r.task);
3550
3551 } else {
3552 // This not being started from an existing activity, and not part
3553 // of a new task... just put it in the top task, though these days
3554 // this case should never happen.
3555 final int N = mHistory.size();
3556 HistoryRecord prev =
3557 N > 0 ? (HistoryRecord)mHistory.get(N-1) : null;
3558 r.task = prev != null
3559 ? prev.task
3560 : new TaskRecord(mCurTask, r.info, intent,
3561 (r.info.flags&ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0);
3562 if (DEBUG_TASKS) Log.v(TAG, "Starting new activity " + r
3563 + " in new guessed " + r.task);
3564 }
3565 if (newTask) {
Doug Zongker2bec3d42009-12-04 12:52:44 -08003566 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003567 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08003568 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07003569 startActivityLocked(r, newTask, doResume);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003570 return START_SUCCESS;
3571 }
3572
3573 public final int startActivity(IApplicationThread caller,
3574 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
3575 int grantedMode, IBinder resultTo,
3576 String resultWho, int requestCode, boolean onlyIfNeeded,
3577 boolean debug) {
3578 // Refuse possible leaked file descriptors
3579 if (intent != null && intent.hasFileDescriptors()) {
3580 throw new IllegalArgumentException("File descriptors passed in Intent");
3581 }
3582
The Android Open Source Project4df24232009-03-05 14:34:35 -08003583 final boolean componentSpecified = intent.getComponent() != null;
3584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003585 // Don't modify the client's object!
3586 intent = new Intent(intent);
3587
3588 // Collect information about the target of the Intent.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003589 ActivityInfo aInfo;
3590 try {
3591 ResolveInfo rInfo =
3592 ActivityThread.getPackageManager().resolveIntent(
3593 intent, resolvedType,
3594 PackageManager.MATCH_DEFAULT_ONLY
Dianne Hackborn1655be42009-05-08 14:29:01 -07003595 | STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003596 aInfo = rInfo != null ? rInfo.activityInfo : null;
3597 } catch (RemoteException e) {
3598 aInfo = null;
3599 }
3600
3601 if (aInfo != null) {
3602 // Store the found target back into the intent, because now that
3603 // we have it we never want to do this again. For example, if the
3604 // user navigates back to this point in the history, we should
3605 // always restart the exact same activity.
3606 intent.setComponent(new ComponentName(
3607 aInfo.applicationInfo.packageName, aInfo.name));
3608
3609 // Don't debug things in the system process
3610 if (debug) {
3611 if (!aInfo.processName.equals("system")) {
3612 setDebugApp(aInfo.processName, true, false);
3613 }
3614 }
3615 }
3616
3617 synchronized(this) {
3618 final long origId = Binder.clearCallingIdentity();
3619 int res = startActivityLocked(caller, intent, resolvedType,
3620 grantedUriPermissions, grantedMode, aInfo,
3621 resultTo, resultWho, requestCode, -1, -1,
The Android Open Source Project4df24232009-03-05 14:34:35 -08003622 onlyIfNeeded, componentSpecified);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003623 Binder.restoreCallingIdentity(origId);
3624 return res;
3625 }
3626 }
3627
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003628 public int startActivityIntentSender(IApplicationThread caller,
3629 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003630 IBinder resultTo, String resultWho, int requestCode,
3631 int flagsMask, int flagsValues) {
3632 // Refuse possible leaked file descriptors
3633 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
3634 throw new IllegalArgumentException("File descriptors passed in Intent");
3635 }
3636
3637 IIntentSender sender = intent.getTarget();
3638 if (!(sender instanceof PendingIntentRecord)) {
3639 throw new IllegalArgumentException("Bad PendingIntent object");
3640 }
3641
3642 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003643
3644 synchronized (this) {
3645 // If this is coming from the currently resumed activity, it is
3646 // effectively saying that app switches are allowed at this point.
3647 if (mResumedActivity != null
3648 && mResumedActivity.info.applicationInfo.uid ==
3649 Binder.getCallingUid()) {
3650 mAppSwitchesAllowedTime = 0;
3651 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003652 }
3653
3654 return pir.sendInner(0, fillInIntent, resolvedType,
3655 null, resultTo, resultWho, requestCode, flagsMask, flagsValues);
3656 }
3657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658 public boolean startNextMatchingActivity(IBinder callingActivity,
3659 Intent intent) {
3660 // Refuse possible leaked file descriptors
3661 if (intent != null && intent.hasFileDescriptors() == true) {
3662 throw new IllegalArgumentException("File descriptors passed in Intent");
3663 }
3664
3665 synchronized (this) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07003666 int index = indexOfTokenLocked(callingActivity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003667 if (index < 0) {
3668 return false;
3669 }
3670 HistoryRecord r = (HistoryRecord)mHistory.get(index);
3671 if (r.app == null || r.app.thread == null) {
3672 // The caller is not running... d'oh!
3673 return false;
3674 }
3675 intent = new Intent(intent);
3676 // The caller is not allowed to change the data.
3677 intent.setDataAndType(r.intent.getData(), r.intent.getType());
3678 // And we are resetting to find the next component...
3679 intent.setComponent(null);
3680
3681 ActivityInfo aInfo = null;
3682 try {
3683 List<ResolveInfo> resolves =
3684 ActivityThread.getPackageManager().queryIntentActivities(
3685 intent, r.resolvedType,
Dianne Hackborn1655be42009-05-08 14:29:01 -07003686 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003687
3688 // Look for the original activity in the list...
3689 final int N = resolves != null ? resolves.size() : 0;
3690 for (int i=0; i<N; i++) {
3691 ResolveInfo rInfo = resolves.get(i);
3692 if (rInfo.activityInfo.packageName.equals(r.packageName)
3693 && rInfo.activityInfo.name.equals(r.info.name)) {
3694 // We found the current one... the next matching is
3695 // after it.
3696 i++;
3697 if (i<N) {
3698 aInfo = resolves.get(i).activityInfo;
3699 }
3700 break;
3701 }
3702 }
3703 } catch (RemoteException e) {
3704 }
3705
3706 if (aInfo == null) {
3707 // Nobody who is next!
3708 return false;
3709 }
3710
3711 intent.setComponent(new ComponentName(
3712 aInfo.applicationInfo.packageName, aInfo.name));
3713 intent.setFlags(intent.getFlags()&~(
3714 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
3715 Intent.FLAG_ACTIVITY_CLEAR_TOP|
3716 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
3717 Intent.FLAG_ACTIVITY_NEW_TASK));
3718
3719 // Okay now we need to start the new activity, replacing the
3720 // currently running activity. This is a little tricky because
3721 // we want to start the new one as if the current one is finished,
3722 // but not finish the current one first so that there is no flicker.
3723 // And thus...
3724 final boolean wasFinishing = r.finishing;
3725 r.finishing = true;
3726
3727 // Propagate reply information over to the new activity.
3728 final HistoryRecord resultTo = r.resultTo;
3729 final String resultWho = r.resultWho;
3730 final int requestCode = r.requestCode;
3731 r.resultTo = null;
3732 if (resultTo != null) {
3733 resultTo.removeResultsLocked(r, resultWho, requestCode);
3734 }
3735
3736 final long origId = Binder.clearCallingIdentity();
3737 // XXX we are not dealing with propagating grantedUriPermissions...
3738 // those are not yet exposed to user code, so there is no need.
3739 int res = startActivityLocked(r.app.thread, intent,
3740 r.resolvedType, null, 0, aInfo, resultTo, resultWho,
The Android Open Source Project4df24232009-03-05 14:34:35 -08003741 requestCode, -1, r.launchedFromUid, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003742 Binder.restoreCallingIdentity(origId);
3743
3744 r.finishing = wasFinishing;
3745 if (res != START_SUCCESS) {
3746 return false;
3747 }
3748 return true;
3749 }
3750 }
3751
Dianne Hackborn2d91af02009-07-16 13:34:33 -07003752 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003753 Intent intent, String resolvedType, IBinder resultTo,
3754 String resultWho, int requestCode, boolean onlyIfNeeded) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07003755
3756 // This is so super not safe, that only the system (or okay root)
3757 // can do it.
3758 final int callingUid = Binder.getCallingUid();
3759 if (callingUid != 0 && callingUid != Process.myUid()) {
3760 throw new SecurityException(
3761 "startActivityInPackage only available to the system");
3762 }
3763
The Android Open Source Project4df24232009-03-05 14:34:35 -08003764 final boolean componentSpecified = intent.getComponent() != null;
3765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003766 // Don't modify the client's object!
3767 intent = new Intent(intent);
3768
3769 // Collect information about the target of the Intent.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003770 ActivityInfo aInfo;
3771 try {
3772 ResolveInfo rInfo =
3773 ActivityThread.getPackageManager().resolveIntent(
3774 intent, resolvedType,
Dianne Hackborn1655be42009-05-08 14:29:01 -07003775 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003776 aInfo = rInfo != null ? rInfo.activityInfo : null;
3777 } catch (RemoteException e) {
3778 aInfo = null;
3779 }
3780
3781 if (aInfo != null) {
3782 // Store the found target back into the intent, because now that
3783 // we have it we never want to do this again. For example, if the
3784 // user navigates back to this point in the history, we should
3785 // always restart the exact same activity.
3786 intent.setComponent(new ComponentName(
3787 aInfo.applicationInfo.packageName, aInfo.name));
3788 }
3789
3790 synchronized(this) {
3791 return startActivityLocked(null, intent, resolvedType,
3792 null, 0, aInfo, resultTo, resultWho, requestCode, -1, uid,
The Android Open Source Project4df24232009-03-05 14:34:35 -08003793 onlyIfNeeded, componentSpecified);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003794 }
3795 }
3796
3797 private final void addRecentTask(TaskRecord task) {
3798 // Remove any existing entries that are the same kind of task.
3799 int N = mRecentTasks.size();
3800 for (int i=0; i<N; i++) {
3801 TaskRecord tr = mRecentTasks.get(i);
3802 if ((task.affinity != null && task.affinity.equals(tr.affinity))
3803 || (task.intent != null && task.intent.filterEquals(tr.intent))) {
3804 mRecentTasks.remove(i);
3805 i--;
3806 N--;
3807 if (task.intent == null) {
3808 // If the new recent task we are adding is not fully
3809 // specified, then replace it with the existing recent task.
3810 task = tr;
3811 }
3812 }
3813 }
3814 if (N >= MAX_RECENT_TASKS) {
3815 mRecentTasks.remove(N-1);
3816 }
3817 mRecentTasks.add(0, task);
3818 }
3819
3820 public void setRequestedOrientation(IBinder token,
3821 int requestedOrientation) {
3822 synchronized (this) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07003823 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003824 if (index < 0) {
3825 return;
3826 }
3827 HistoryRecord r = (HistoryRecord)mHistory.get(index);
3828 final long origId = Binder.clearCallingIdentity();
3829 mWindowManager.setAppOrientation(r, requestedOrientation);
3830 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07003831 mConfiguration,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 r.mayFreezeScreenLocked(r.app) ? r : null);
3833 if (config != null) {
3834 r.frozenBeforeDestroy = true;
3835 if (!updateConfigurationLocked(config, r)) {
3836 resumeTopActivityLocked(null);
3837 }
3838 }
3839 Binder.restoreCallingIdentity(origId);
3840 }
3841 }
3842
3843 public int getRequestedOrientation(IBinder token) {
3844 synchronized (this) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07003845 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003846 if (index < 0) {
3847 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
3848 }
3849 HistoryRecord r = (HistoryRecord)mHistory.get(index);
3850 return mWindowManager.getAppOrientation(r);
3851 }
3852 }
3853
3854 private final void stopActivityLocked(HistoryRecord r) {
3855 if (DEBUG_SWITCH) Log.d(TAG, "Stopping: " + r);
3856 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3857 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3858 if (!r.finishing) {
3859 requestFinishActivityLocked(r, Activity.RESULT_CANCELED, null,
3860 "no-history");
3861 }
3862 } else if (r.app != null && r.app.thread != null) {
3863 if (mFocusedActivity == r) {
3864 setFocusedActivityLocked(topRunningActivityLocked(null));
3865 }
3866 r.resumeKeyDispatchingLocked();
3867 try {
3868 r.stopped = false;
3869 r.state = ActivityState.STOPPING;
3870 if (DEBUG_VISBILITY) Log.v(
3871 TAG, "Stopping visible=" + r.visible + " for " + r);
3872 if (!r.visible) {
3873 mWindowManager.setAppVisibility(r, false);
3874 }
3875 r.app.thread.scheduleStopActivity(r, r.visible, r.configChangeFlags);
3876 } catch (Exception e) {
3877 // Maybe just ignore exceptions here... if the process
3878 // has crashed, our death notification will clean things
3879 // up.
3880 Log.w(TAG, "Exception thrown during pause", e);
3881 // Just in case, assume it to be stopped.
3882 r.stopped = true;
3883 r.state = ActivityState.STOPPED;
3884 if (r.configDestroy) {
3885 destroyActivityLocked(r, true);
3886 }
3887 }
3888 }
3889 }
3890
3891 /**
3892 * @return Returns true if the activity is being finished, false if for
3893 * some reason it is being left as-is.
3894 */
3895 private final boolean requestFinishActivityLocked(IBinder token, int resultCode,
3896 Intent resultData, String reason) {
Chris Tate8a7dc172009-03-24 20:11:42 -07003897 if (DEBUG_RESULTS) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003898 TAG, "Finishing activity: token=" + token
3899 + ", result=" + resultCode + ", data=" + resultData);
3900
Dianne Hackborn75b03852009-06-12 15:43:26 -07003901 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003902 if (index < 0) {
3903 return false;
3904 }
3905 HistoryRecord r = (HistoryRecord)mHistory.get(index);
3906
3907 // Is this the last activity left?
3908 boolean lastActivity = true;
3909 for (int i=mHistory.size()-1; i>=0; i--) {
3910 HistoryRecord p = (HistoryRecord)mHistory.get(i);
3911 if (!p.finishing && p != r) {
3912 lastActivity = false;
3913 break;
3914 }
3915 }
3916
3917 // If this is the last activity, but it is the home activity, then
3918 // just don't finish it.
3919 if (lastActivity) {
3920 if (r.intent.hasCategory(Intent.CATEGORY_HOME)) {
3921 return false;
3922 }
3923 }
3924
3925 finishActivityLocked(r, index, resultCode, resultData, reason);
3926 return true;
3927 }
3928
3929 /**
3930 * @return Returns true if this activity has been removed from the history
3931 * list, or false if it is still in the list and will be removed later.
3932 */
3933 private final boolean finishActivityLocked(HistoryRecord r, int index,
3934 int resultCode, Intent resultData, String reason) {
3935 if (r.finishing) {
3936 Log.w(TAG, "Duplicate finish request for " + r);
3937 return false;
3938 }
3939
3940 r.finishing = true;
Doug Zongker2bec3d42009-12-04 12:52:44 -08003941 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003942 System.identityHashCode(r),
3943 r.task.taskId, r.shortComponentName, reason);
3944 r.task.numActivities--;
3945 if (r.frontOfTask && index < (mHistory.size()-1)) {
3946 HistoryRecord next = (HistoryRecord)mHistory.get(index+1);
3947 if (next.task == r.task) {
3948 next.frontOfTask = true;
3949 }
3950 }
3951
3952 r.pauseKeyDispatchingLocked();
3953 if (mFocusedActivity == r) {
3954 setFocusedActivityLocked(topRunningActivityLocked(null));
3955 }
3956
3957 // send the result
3958 HistoryRecord resultTo = r.resultTo;
3959 if (resultTo != null) {
Chris Tate8a7dc172009-03-24 20:11:42 -07003960 if (DEBUG_RESULTS) Log.v(TAG, "Adding result to " + resultTo
3961 + " who=" + r.resultWho + " req=" + r.requestCode
3962 + " res=" + resultCode + " data=" + resultData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003963 if (r.info.applicationInfo.uid > 0) {
3964 grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3965 r.packageName, resultData, r);
3966 }
3967 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3968 resultData);
3969 r.resultTo = null;
3970 }
Chris Tate8a7dc172009-03-24 20:11:42 -07003971 else if (DEBUG_RESULTS) Log.v(TAG, "No result destination from " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003972
3973 // Make sure this HistoryRecord is not holding on to other resources,
3974 // because clients have remote IPC references to this object so we
3975 // can't assume that will go away and want to avoid circular IPC refs.
3976 r.results = null;
3977 r.pendingResults = null;
3978 r.newIntents = null;
3979 r.icicle = null;
3980
3981 if (mPendingThumbnails.size() > 0) {
3982 // There are clients waiting to receive thumbnails so, in case
3983 // this is an activity that someone is waiting for, add it
3984 // to the pending list so we can correctly update the clients.
3985 mCancelledThumbnails.add(r);
3986 }
3987
3988 if (mResumedActivity == r) {
3989 boolean endTask = index <= 0
3990 || ((HistoryRecord)mHistory.get(index-1)).task != r.task;
3991 if (DEBUG_TRANSITION) Log.v(TAG,
3992 "Prepare close transition: finishing " + r);
3993 mWindowManager.prepareAppTransition(endTask
3994 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
3995 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE);
3996
3997 // Tell window manager to prepare for this one to be removed.
3998 mWindowManager.setAppVisibility(r, false);
3999
4000 if (mPausingActivity == null) {
4001 if (DEBUG_PAUSE) Log.v(TAG, "Finish needs to pause: " + r);
4002 if (DEBUG_USER_LEAVING) Log.v(TAG, "finish() => pause with userLeaving=false");
4003 startPausingLocked(false, false);
4004 }
4005
4006 } else if (r.state != ActivityState.PAUSING) {
4007 // If the activity is PAUSING, we will complete the finish once
4008 // it is done pausing; else we can just directly finish it here.
4009 if (DEBUG_PAUSE) Log.v(TAG, "Finish not pausing: " + r);
4010 return finishCurrentActivityLocked(r, index,
4011 FINISH_AFTER_PAUSE) == null;
4012 } else {
4013 if (DEBUG_PAUSE) Log.v(TAG, "Finish waiting for pause of: " + r);
4014 }
4015
4016 return false;
4017 }
4018
4019 private static final int FINISH_IMMEDIATELY = 0;
4020 private static final int FINISH_AFTER_PAUSE = 1;
4021 private static final int FINISH_AFTER_VISIBLE = 2;
4022
4023 private final HistoryRecord finishCurrentActivityLocked(HistoryRecord r,
4024 int mode) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07004025 final int index = indexOfTokenLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004026 if (index < 0) {
4027 return null;
4028 }
4029
4030 return finishCurrentActivityLocked(r, index, mode);
4031 }
4032
4033 private final HistoryRecord finishCurrentActivityLocked(HistoryRecord r,
4034 int index, int mode) {
4035 // First things first: if this activity is currently visible,
4036 // and the resumed activity is not yet visible, then hold off on
4037 // finishing until the resumed one becomes visible.
4038 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
4039 if (!mStoppingActivities.contains(r)) {
4040 mStoppingActivities.add(r);
4041 if (mStoppingActivities.size() > 3) {
4042 // If we already have a few activities waiting to stop,
4043 // then give up on things going idle and start clearing
4044 // them out.
4045 Message msg = Message.obtain();
4046 msg.what = ActivityManagerService.IDLE_NOW_MSG;
4047 mHandler.sendMessage(msg);
4048 }
4049 }
4050 r.state = ActivityState.STOPPING;
4051 updateOomAdjLocked();
4052 return r;
4053 }
4054
4055 // make sure the record is cleaned out of other places.
4056 mStoppingActivities.remove(r);
4057 mWaitingVisibleActivities.remove(r);
4058 if (mResumedActivity == r) {
4059 mResumedActivity = null;
4060 }
4061 final ActivityState prevState = r.state;
4062 r.state = ActivityState.FINISHING;
4063
4064 if (mode == FINISH_IMMEDIATELY
4065 || prevState == ActivityState.STOPPED
4066 || prevState == ActivityState.INITIALIZING) {
4067 // If this activity is already stopped, we can just finish
4068 // it right now.
4069 return destroyActivityLocked(r, true) ? null : r;
4070 } else {
4071 // Need to go through the full pause cycle to get this
4072 // activity into the stopped state and then finish it.
4073 if (localLOGV) Log.v(TAG, "Enqueueing pending finish: " + r);
4074 mFinishingActivities.add(r);
4075 resumeTopActivityLocked(null);
4076 }
4077 return r;
4078 }
4079
4080 /**
4081 * This is the internal entry point for handling Activity.finish().
4082 *
4083 * @param token The Binder token referencing the Activity we want to finish.
4084 * @param resultCode Result code, if any, from this Activity.
4085 * @param resultData Result data (Intent), if any, from this Activity.
4086 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11004087 * @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 -08004088 */
4089 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
4090 // Refuse possible leaked file descriptors
4091 if (resultData != null && resultData.hasFileDescriptors() == true) {
4092 throw new IllegalArgumentException("File descriptors passed in Intent");
4093 }
4094
4095 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004096 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004097 // Find the first activity that is not finishing.
4098 HistoryRecord next = topRunningActivityLocked(token, 0);
4099 if (next != null) {
4100 // ask watcher if this is allowed
4101 boolean resumeOK = true;
4102 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004103 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004104 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004105 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004106 }
4107
4108 if (!resumeOK) {
4109 return false;
4110 }
4111 }
4112 }
4113 final long origId = Binder.clearCallingIdentity();
4114 boolean res = requestFinishActivityLocked(token, resultCode,
4115 resultData, "app-request");
4116 Binder.restoreCallingIdentity(origId);
4117 return res;
4118 }
4119 }
4120
4121 void sendActivityResultLocked(int callingUid, HistoryRecord r,
4122 String resultWho, int requestCode, int resultCode, Intent data) {
4123
4124 if (callingUid > 0) {
4125 grantUriPermissionFromIntentLocked(callingUid, r.packageName,
4126 data, r);
4127 }
4128
The Android Open Source Project10592532009-03-18 17:39:46 -07004129 if (DEBUG_RESULTS) Log.v(TAG, "Send activity result to " + r
4130 + " : who=" + resultWho + " req=" + requestCode
4131 + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004132 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
4133 try {
4134 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
4135 list.add(new ResultInfo(resultWho, requestCode,
4136 resultCode, data));
4137 r.app.thread.scheduleSendResult(r, list);
4138 return;
4139 } catch (Exception e) {
4140 Log.w(TAG, "Exception thrown sending result to " + r, e);
4141 }
4142 }
4143
4144 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
4145 }
4146
4147 public final void finishSubActivity(IBinder token, String resultWho,
4148 int requestCode) {
4149 synchronized(this) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07004150 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004151 if (index < 0) {
4152 return;
4153 }
4154 HistoryRecord self = (HistoryRecord)mHistory.get(index);
4155
4156 final long origId = Binder.clearCallingIdentity();
4157
4158 int i;
4159 for (i=mHistory.size()-1; i>=0; i--) {
4160 HistoryRecord r = (HistoryRecord)mHistory.get(i);
4161 if (r.resultTo == self && r.requestCode == requestCode) {
4162 if ((r.resultWho == null && resultWho == null) ||
4163 (r.resultWho != null && r.resultWho.equals(resultWho))) {
4164 finishActivityLocked(r, i,
4165 Activity.RESULT_CANCELED, null, "request-sub");
4166 }
4167 }
4168 }
4169
4170 Binder.restoreCallingIdentity(origId);
4171 }
4172 }
4173
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07004174 public void overridePendingTransition(IBinder token, String packageName,
4175 int enterAnim, int exitAnim) {
4176 synchronized(this) {
4177 int index = indexOfTokenLocked(token);
4178 if (index < 0) {
4179 return;
4180 }
4181 HistoryRecord self = (HistoryRecord)mHistory.get(index);
4182
4183 final long origId = Binder.clearCallingIdentity();
4184
4185 if (self.state == ActivityState.RESUMED
4186 || self.state == ActivityState.PAUSING) {
4187 mWindowManager.overridePendingAppTransition(packageName,
4188 enterAnim, exitAnim);
4189 }
4190
4191 Binder.restoreCallingIdentity(origId);
4192 }
4193 }
4194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004195 /**
4196 * Perform clean-up of service connections in an activity record.
4197 */
4198 private final void cleanUpActivityServicesLocked(HistoryRecord r) {
4199 // Throw away any services that have been bound by this activity.
4200 if (r.connections != null) {
4201 Iterator<ConnectionRecord> it = r.connections.iterator();
4202 while (it.hasNext()) {
4203 ConnectionRecord c = it.next();
4204 removeConnectionLocked(c, null, r);
4205 }
4206 r.connections = null;
4207 }
4208 }
4209
4210 /**
4211 * Perform the common clean-up of an activity record. This is called both
4212 * as part of destroyActivityLocked() (when destroying the client-side
4213 * representation) and cleaning things up as a result of its hosting
4214 * processing going away, in which case there is no remaining client-side
4215 * state to destroy so only the cleanup here is needed.
4216 */
4217 private final void cleanUpActivityLocked(HistoryRecord r, boolean cleanServices) {
4218 if (mResumedActivity == r) {
4219 mResumedActivity = null;
4220 }
4221 if (mFocusedActivity == r) {
4222 mFocusedActivity = null;
4223 }
4224
4225 r.configDestroy = false;
4226 r.frozenBeforeDestroy = false;
4227
4228 // Make sure this record is no longer in the pending finishes list.
4229 // This could happen, for example, if we are trimming activities
4230 // down to the max limit while they are still waiting to finish.
4231 mFinishingActivities.remove(r);
4232 mWaitingVisibleActivities.remove(r);
4233
4234 // Remove any pending results.
4235 if (r.finishing && r.pendingResults != null) {
4236 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
4237 PendingIntentRecord rec = apr.get();
4238 if (rec != null) {
4239 cancelIntentSenderLocked(rec, false);
4240 }
4241 }
4242 r.pendingResults = null;
4243 }
4244
4245 if (cleanServices) {
4246 cleanUpActivityServicesLocked(r);
4247 }
4248
4249 if (mPendingThumbnails.size() > 0) {
4250 // There are clients waiting to receive thumbnails so, in case
4251 // this is an activity that someone is waiting for, add it
4252 // to the pending list so we can correctly update the clients.
4253 mCancelledThumbnails.add(r);
4254 }
4255
4256 // Get rid of any pending idle timeouts.
4257 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
4258 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
4259 }
4260
4261 private final void removeActivityFromHistoryLocked(HistoryRecord r) {
4262 if (r.state != ActivityState.DESTROYED) {
4263 mHistory.remove(r);
4264 r.inHistory = false;
4265 r.state = ActivityState.DESTROYED;
4266 mWindowManager.removeAppToken(r);
4267 if (VALIDATE_TOKENS) {
4268 mWindowManager.validateAppTokens(mHistory);
4269 }
4270 cleanUpActivityServicesLocked(r);
4271 removeActivityUriPermissionsLocked(r);
4272 }
4273 }
4274
4275 /**
4276 * Destroy the current CLIENT SIDE instance of an activity. This may be
4277 * called both when actually finishing an activity, or when performing
4278 * a configuration switch where we destroy the current client-side object
4279 * but then create a new client-side object for this same HistoryRecord.
4280 */
4281 private final boolean destroyActivityLocked(HistoryRecord r,
4282 boolean removeFromApp) {
4283 if (DEBUG_SWITCH) Log.v(
4284 TAG, "Removing activity: token=" + r
4285 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
Doug Zongker2bec3d42009-12-04 12:52:44 -08004286 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004287 System.identityHashCode(r),
4288 r.task.taskId, r.shortComponentName);
4289
4290 boolean removedFromHistory = false;
4291
4292 cleanUpActivityLocked(r, false);
4293
Dianne Hackborn03abb812010-01-04 18:43:19 -08004294 final boolean hadApp = r.app != null;
4295
4296 if (hadApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004297 if (removeFromApp) {
4298 int idx = r.app.activities.indexOf(r);
4299 if (idx >= 0) {
4300 r.app.activities.remove(idx);
4301 }
4302 if (r.persistent) {
4303 decPersistentCountLocked(r.app);
4304 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004305 if (r.app.activities.size() == 0) {
4306 // No longer have activities, so update location in
4307 // LRU list.
4308 updateLruProcessLocked(r.app, true, false);
4309 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004310 }
4311
4312 boolean skipDestroy = false;
4313
4314 try {
4315 if (DEBUG_SWITCH) Log.i(TAG, "Destroying: " + r);
4316 r.app.thread.scheduleDestroyActivity(r, r.finishing,
4317 r.configChangeFlags);
4318 } catch (Exception e) {
4319 // We can just ignore exceptions here... if the process
4320 // has crashed, our death notification will clean things
4321 // up.
4322 //Log.w(TAG, "Exception thrown during finish", e);
4323 if (r.finishing) {
4324 removeActivityFromHistoryLocked(r);
4325 removedFromHistory = true;
4326 skipDestroy = true;
4327 }
4328 }
4329
4330 r.app = null;
4331 r.nowVisible = false;
4332
4333 if (r.finishing && !skipDestroy) {
4334 r.state = ActivityState.DESTROYING;
4335 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
4336 msg.obj = r;
4337 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
4338 } else {
4339 r.state = ActivityState.DESTROYED;
4340 }
4341 } else {
4342 // remove this record from the history.
4343 if (r.finishing) {
4344 removeActivityFromHistoryLocked(r);
4345 removedFromHistory = true;
4346 } else {
4347 r.state = ActivityState.DESTROYED;
4348 }
4349 }
4350
4351 r.configChangeFlags = 0;
4352
Dianne Hackborn03abb812010-01-04 18:43:19 -08004353 if (!mLRUActivities.remove(r) && hadApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004354 Log.w(TAG, "Activity " + r + " being finished, but not in LRU list");
4355 }
4356
4357 return removedFromHistory;
4358 }
4359
Dianne Hackborn03abb812010-01-04 18:43:19 -08004360 private static void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004361 int i = list.size();
4362 if (localLOGV) Log.v(
4363 TAG, "Removing app " + app + " from list " + list
4364 + " with " + i + " entries");
4365 while (i > 0) {
4366 i--;
4367 HistoryRecord r = (HistoryRecord)list.get(i);
4368 if (localLOGV) Log.v(
4369 TAG, "Record #" + i + " " + r + ": app=" + r.app);
4370 if (r.app == app) {
4371 if (localLOGV) Log.v(TAG, "Removing this entry!");
4372 list.remove(i);
4373 }
4374 }
4375 }
4376
4377 /**
4378 * Main function for removing an existing process from the activity manager
4379 * as a result of that process going away. Clears out all connections
4380 * to the process.
4381 */
4382 private final void handleAppDiedLocked(ProcessRecord app,
4383 boolean restarting) {
4384 cleanUpApplicationRecordLocked(app, restarting, -1);
4385 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004386 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004387 }
4388
4389 // Just in case...
4390 if (mPausingActivity != null && mPausingActivity.app == app) {
4391 if (DEBUG_PAUSE) Log.v(TAG, "App died while pausing: " + mPausingActivity);
4392 mPausingActivity = null;
4393 }
4394 if (mLastPausedActivity != null && mLastPausedActivity.app == app) {
4395 mLastPausedActivity = null;
4396 }
4397
4398 // Remove this application's activities from active lists.
4399 removeHistoryRecordsForAppLocked(mLRUActivities, app);
4400 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
4401 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
4402 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
4403
4404 boolean atTop = true;
4405 boolean hasVisibleActivities = false;
4406
4407 // Clean out the history list.
4408 int i = mHistory.size();
4409 if (localLOGV) Log.v(
4410 TAG, "Removing app " + app + " from history with " + i + " entries");
4411 while (i > 0) {
4412 i--;
4413 HistoryRecord r = (HistoryRecord)mHistory.get(i);
4414 if (localLOGV) Log.v(
4415 TAG, "Record #" + i + " " + r + ": app=" + r.app);
4416 if (r.app == app) {
4417 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
4418 if (localLOGV) Log.v(
4419 TAG, "Removing this entry! frozen=" + r.haveState
4420 + " finishing=" + r.finishing);
4421 mHistory.remove(i);
4422
4423 r.inHistory = false;
4424 mWindowManager.removeAppToken(r);
4425 if (VALIDATE_TOKENS) {
4426 mWindowManager.validateAppTokens(mHistory);
4427 }
4428 removeActivityUriPermissionsLocked(r);
4429
4430 } else {
4431 // We have the current state for this activity, so
4432 // it can be restarted later when needed.
4433 if (localLOGV) Log.v(
4434 TAG, "Keeping entry, setting app to null");
4435 if (r.visible) {
4436 hasVisibleActivities = true;
4437 }
4438 r.app = null;
4439 r.nowVisible = false;
4440 if (!r.haveState) {
4441 r.icicle = null;
4442 }
4443 }
4444
4445 cleanUpActivityLocked(r, true);
4446 r.state = ActivityState.STOPPED;
4447 }
4448 atTop = false;
4449 }
4450
4451 app.activities.clear();
4452
4453 if (app.instrumentationClass != null) {
4454 Log.w(TAG, "Crash of app " + app.processName
4455 + " running instrumentation " + app.instrumentationClass);
4456 Bundle info = new Bundle();
4457 info.putString("shortMsg", "Process crashed.");
4458 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
4459 }
4460
4461 if (!restarting) {
4462 if (!resumeTopActivityLocked(null)) {
4463 // If there was nothing to resume, and we are not already
4464 // restarting this process, but there is a visible activity that
4465 // is hosted by the process... then make sure all visible
4466 // activities are running, taking care of restarting this
4467 // process.
4468 if (hasVisibleActivities) {
4469 ensureActivitiesVisibleLocked(null, 0);
4470 }
4471 }
4472 }
4473 }
4474
4475 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
4476 IBinder threadBinder = thread.asBinder();
4477
4478 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004479 for (int i=mLruProcesses.size()-1; i>=0; i--) {
4480 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004481 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
4482 return i;
4483 }
4484 }
4485 return -1;
4486 }
4487
4488 private final ProcessRecord getRecordForAppLocked(
4489 IApplicationThread thread) {
4490 if (thread == null) {
4491 return null;
4492 }
4493
4494 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004495 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004496 }
4497
4498 private final void appDiedLocked(ProcessRecord app, int pid,
4499 IApplicationThread thread) {
4500
4501 mProcDeaths[0]++;
4502
4503 if (app.thread != null && app.thread.asBinder() == thread.asBinder()) {
4504 Log.i(TAG, "Process " + app.processName + " (pid " + pid
4505 + ") has died.");
Doug Zongker2bec3d42009-12-04 12:52:44 -08004506 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004507 if (localLOGV) Log.v(
4508 TAG, "Dying app: " + app + ", pid: " + pid
4509 + ", thread: " + thread.asBinder());
4510 boolean doLowMem = app.instrumentationClass == null;
4511 handleAppDiedLocked(app, false);
4512
4513 if (doLowMem) {
4514 // If there are no longer any background processes running,
4515 // and the app that died was not running instrumentation,
4516 // then tell everyone we are now low on memory.
4517 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004518 for (int i=mLruProcesses.size()-1; i>=0; i--) {
4519 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004520 if (rec.thread != null && rec.setAdj >= HIDDEN_APP_MIN_ADJ) {
4521 haveBg = true;
4522 break;
4523 }
4524 }
4525
4526 if (!haveBg) {
4527 Log.i(TAG, "Low Memory: No more background processes.");
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004528 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004529 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004530 for (int i=mLruProcesses.size()-1; i>=0; i--) {
4531 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07004532 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004533 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
4534 // The low memory report is overriding any current
4535 // state for a GC request. Make sure to do
4536 // visible/foreground processes first.
4537 if (rec.setAdj <= VISIBLE_APP_ADJ) {
4538 rec.lastRequestedGc = 0;
4539 } else {
4540 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004541 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004542 rec.reportLowMemory = true;
4543 rec.lastLowMemory = now;
4544 mProcessesToGc.remove(rec);
4545 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004546 }
4547 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004548 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004549 }
4550 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08004551 } else if (DEBUG_PROCESSES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004552 Log.d(TAG, "Received spurious death notification for thread "
4553 + thread.asBinder());
4554 }
4555 }
4556
Dan Egnor42471dd2010-01-07 17:25:22 -08004557 /**
4558 * If a stack trace dump file is configured, dump process stack traces.
4559 * @param pids of dalvik VM processes to dump stack traces for
4560 * @return file containing stack traces, or null if no dump file is configured
4561 */
4562 private static File dumpStackTraces(ArrayList<Integer> pids) {
4563 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
4564 if (tracesPath == null || tracesPath.length() == 0) {
4565 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004566 }
Dan Egnor42471dd2010-01-07 17:25:22 -08004567
4568 File tracesFile = new File(tracesPath);
4569 try {
4570 File tracesDir = tracesFile.getParentFile();
4571 if (!tracesDir.exists()) tracesFile.mkdirs();
4572 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
4573
4574 if (tracesFile.exists()) tracesFile.delete();
4575 tracesFile.createNewFile();
4576 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
4577 } catch (IOException e) {
4578 Log.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
4579 return null;
4580 }
4581
4582 // Use a FileObserver to detect when traces finish writing.
4583 // The order of traces is considered important to maintain for legibility.
4584 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
4585 public synchronized void onEvent(int event, String path) { notify(); }
4586 };
4587
4588 try {
4589 observer.startWatching();
4590 int num = pids.size();
4591 for (int i = 0; i < num; i++) {
4592 synchronized (observer) {
4593 Process.sendSignal(pids.get(i), Process.SIGNAL_QUIT);
4594 observer.wait(200); // Wait for write-close, give up after 200msec
4595 }
4596 }
4597 } catch (InterruptedException e) {
4598 Log.wtf(TAG, e);
4599 } finally {
4600 observer.stopWatching();
4601 }
4602
4603 return tracesFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004604 }
4605
Dan Egnor42471dd2010-01-07 17:25:22 -08004606 final void appNotRespondingLocked(ProcessRecord app, HistoryRecord activity,
4607 HistoryRecord parent, final String annotation) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004608 if (app.notResponding || app.crashing) {
4609 return;
4610 }
Dan Egnor42471dd2010-01-07 17:25:22 -08004611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004612 // Log the ANR to the event log.
Doug Zongker2bec3d42009-12-04 12:52:44 -08004613 EventLog.writeEvent(EventLogTags.ANR, app.pid, app.processName, annotation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004614
Dan Egnor42471dd2010-01-07 17:25:22 -08004615 // Dump thread traces as quickly as we can, starting with "interesting" processes.
4616 ArrayList<Integer> pids = new ArrayList<Integer>(20);
4617 pids.add(app.pid);
4618
4619 int parentPid = app.pid;
4620 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
4621 if (parentPid != app.pid) pids.add(parentPid);
4622
4623 if (MY_PID != app.pid && MY_PID != parentPid) pids.add(MY_PID);
4624
4625 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
4626 ProcessRecord r = mLruProcesses.get(i);
4627 if (r != null && r.thread != null) {
4628 int pid = r.pid;
4629 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) pids.add(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004630 }
4631 }
4632
Dan Egnor42471dd2010-01-07 17:25:22 -08004633 File tracesFile = dumpStackTraces(pids);
4634
4635 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07004636 StringBuilder info = mStringBuilder;
4637 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08004638 info.append("ANR in ").append(app.processName);
4639 if (activity != null && activity.shortComponentName != null) {
4640 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07004641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004642 if (annotation != null) {
Dan Egnor42471dd2010-01-07 17:25:22 -08004643 info.append("\nReason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004644 }
Dan Egnor42471dd2010-01-07 17:25:22 -08004645 if (parent != null && parent != activity) {
4646 info.append("\nParent: ").append(parent.shortComponentName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004647 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004648
Dan Egnor42471dd2010-01-07 17:25:22 -08004649 String cpuInfo = null;
4650 if (MONITOR_CPU_USAGE) {
4651 updateCpuStatsNow();
4652 synchronized (mProcessStatsThread) { cpuInfo = mProcessStats.printCurrentState(); }
4653 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004654 }
4655
Dan Egnor42471dd2010-01-07 17:25:22 -08004656 Log.e(TAG, info.toString());
4657 if (tracesFile == null) {
4658 // There is no trace file, so dump (only) the alleged culprit's threads to the log
4659 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
4660 }
4661
4662 addErrorToDropBox("anr", app, activity, parent, annotation, cpuInfo, tracesFile, null);
4663
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004664 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004665 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08004666 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
4667 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004668 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08004669 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
4670 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004671 }
4672 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004673 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004674 }
4675 }
4676
Dan Egnor42471dd2010-01-07 17:25:22 -08004677 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
4678 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
4679 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
4680 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
4681 Process.killProcess(app.pid);
4682 return;
4683 }
4684
4685 // Set the app's notResponding state, and look up the errorReportReceiver
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004686 makeAppNotRespondingLocked(app,
4687 activity != null ? activity.shortComponentName : null,
4688 annotation != null ? "ANR " + annotation : "ANR",
Dan Egnorb7f03672009-12-09 16:22:32 -08004689 info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08004690
4691 // Bring up the infamous App Not Responding dialog
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004692 Message msg = Message.obtain();
4693 HashMap map = new HashMap();
4694 msg.what = SHOW_NOT_RESPONDING_MSG;
4695 msg.obj = map;
4696 map.put("app", app);
4697 if (activity != null) {
4698 map.put("activity", activity);
4699 }
4700
4701 mHandler.sendMessage(msg);
4702 return;
4703 }
4704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004705 private final void decPersistentCountLocked(ProcessRecord app)
4706 {
4707 app.persistentActivities--;
4708 if (app.persistentActivities > 0) {
4709 // Still more of 'em...
4710 return;
4711 }
4712 if (app.persistent) {
4713 // Ah, but the application itself is persistent. Whatever!
4714 return;
4715 }
4716
4717 // App is no longer persistent... make sure it and the ones
4718 // following it in the LRU list have the correc oom_adj.
4719 updateOomAdjLocked();
4720 }
4721
4722 public void setPersistent(IBinder token, boolean isPersistent) {
4723 if (checkCallingPermission(android.Manifest.permission.PERSISTENT_ACTIVITY)
4724 != PackageManager.PERMISSION_GRANTED) {
4725 String msg = "Permission Denial: setPersistent() from pid="
4726 + Binder.getCallingPid()
4727 + ", uid=" + Binder.getCallingUid()
4728 + " requires " + android.Manifest.permission.PERSISTENT_ACTIVITY;
4729 Log.w(TAG, msg);
4730 throw new SecurityException(msg);
4731 }
4732
4733 synchronized(this) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07004734 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004735 if (index < 0) {
4736 return;
4737 }
4738 HistoryRecord r = (HistoryRecord)mHistory.get(index);
4739 ProcessRecord app = r.app;
4740
4741 if (localLOGV) Log.v(
4742 TAG, "Setting persistence " + isPersistent + ": " + r);
4743
4744 if (isPersistent) {
4745 if (r.persistent) {
4746 // Okay okay, I heard you already!
4747 if (localLOGV) Log.v(TAG, "Already persistent!");
4748 return;
4749 }
4750 r.persistent = true;
4751 app.persistentActivities++;
4752 if (localLOGV) Log.v(TAG, "Num persistent now: " + app.persistentActivities);
4753 if (app.persistentActivities > 1) {
4754 // We aren't the first...
4755 if (localLOGV) Log.v(TAG, "Not the first!");
4756 return;
4757 }
4758 if (app.persistent) {
4759 // This would be redundant.
4760 if (localLOGV) Log.v(TAG, "App is persistent!");
4761 return;
4762 }
4763
4764 // App is now persistent... make sure it and the ones
4765 // following it now have the correct oom_adj.
4766 final long origId = Binder.clearCallingIdentity();
4767 updateOomAdjLocked();
4768 Binder.restoreCallingIdentity(origId);
4769
4770 } else {
4771 if (!r.persistent) {
4772 // Okay okay, I heard you already!
4773 return;
4774 }
4775 r.persistent = false;
4776 final long origId = Binder.clearCallingIdentity();
4777 decPersistentCountLocked(app);
4778 Binder.restoreCallingIdentity(origId);
4779
4780 }
4781 }
4782 }
4783
4784 public boolean clearApplicationUserData(final String packageName,
4785 final IPackageDataObserver observer) {
4786 int uid = Binder.getCallingUid();
4787 int pid = Binder.getCallingPid();
4788 long callingId = Binder.clearCallingIdentity();
4789 try {
4790 IPackageManager pm = ActivityThread.getPackageManager();
4791 int pkgUid = -1;
4792 synchronized(this) {
4793 try {
4794 pkgUid = pm.getPackageUid(packageName);
4795 } catch (RemoteException e) {
4796 }
4797 if (pkgUid == -1) {
4798 Log.w(TAG, "Invalid packageName:" + packageName);
4799 return false;
4800 }
4801 if (uid == pkgUid || checkComponentPermission(
4802 android.Manifest.permission.CLEAR_APP_USER_DATA,
4803 pid, uid, -1)
4804 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08004805 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004806 } else {
4807 throw new SecurityException(pid+" does not have permission:"+
4808 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
4809 "for process:"+packageName);
4810 }
4811 }
4812
4813 try {
4814 //clear application user data
4815 pm.clearApplicationUserData(packageName, observer);
4816 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
4817 Uri.fromParts("package", packageName, null));
4818 intent.putExtra(Intent.EXTRA_UID, pkgUid);
4819 broadcastIntentLocked(null, null, intent,
4820 null, null, 0, null, null, null,
4821 false, false, MY_PID, Process.SYSTEM_UID);
4822 } catch (RemoteException e) {
4823 }
4824 } finally {
4825 Binder.restoreCallingIdentity(callingId);
4826 }
4827 return true;
4828 }
4829
Dianne Hackborn03abb812010-01-04 18:43:19 -08004830 public void killBackgroundProcesses(final String packageName) {
4831 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
4832 != PackageManager.PERMISSION_GRANTED &&
4833 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
4834 != PackageManager.PERMISSION_GRANTED) {
4835 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004836 + Binder.getCallingPid()
4837 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08004838 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004839 Log.w(TAG, msg);
4840 throw new SecurityException(msg);
4841 }
4842
4843 long callingId = Binder.clearCallingIdentity();
4844 try {
4845 IPackageManager pm = ActivityThread.getPackageManager();
4846 int pkgUid = -1;
4847 synchronized(this) {
4848 try {
4849 pkgUid = pm.getPackageUid(packageName);
4850 } catch (RemoteException e) {
4851 }
4852 if (pkgUid == -1) {
4853 Log.w(TAG, "Invalid packageName: " + packageName);
4854 return;
4855 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08004856 killPackageProcessesLocked(packageName, pkgUid,
4857 SECONDARY_SERVER_ADJ, false);
4858 }
4859 } finally {
4860 Binder.restoreCallingIdentity(callingId);
4861 }
4862 }
4863
4864 public void forceStopPackage(final String packageName) {
4865 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
4866 != PackageManager.PERMISSION_GRANTED) {
4867 String msg = "Permission Denial: forceStopPackage() from pid="
4868 + Binder.getCallingPid()
4869 + ", uid=" + Binder.getCallingUid()
4870 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
4871 Log.w(TAG, msg);
4872 throw new SecurityException(msg);
4873 }
4874
4875 long callingId = Binder.clearCallingIdentity();
4876 try {
4877 IPackageManager pm = ActivityThread.getPackageManager();
4878 int pkgUid = -1;
4879 synchronized(this) {
4880 try {
4881 pkgUid = pm.getPackageUid(packageName);
4882 } catch (RemoteException e) {
4883 }
4884 if (pkgUid == -1) {
4885 Log.w(TAG, "Invalid packageName: " + packageName);
4886 return;
4887 }
4888 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004889 }
4890 } finally {
4891 Binder.restoreCallingIdentity(callingId);
4892 }
4893 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004894
4895 /*
4896 * The pkg name and uid have to be specified.
4897 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
4898 */
4899 public void killApplicationWithUid(String pkg, int uid) {
4900 if (pkg == null) {
4901 return;
4902 }
4903 // Make sure the uid is valid.
4904 if (uid < 0) {
4905 Log.w(TAG, "Invalid uid specified for pkg : " + pkg);
4906 return;
4907 }
4908 int callerUid = Binder.getCallingUid();
4909 // Only the system server can kill an application
4910 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07004911 // Post an aysnc message to kill the application
4912 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
4913 msg.arg1 = uid;
4914 msg.arg2 = 0;
4915 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07004916 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004917 } else {
4918 throw new SecurityException(callerUid + " cannot kill pkg: " +
4919 pkg);
4920 }
4921 }
4922
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07004923 public void closeSystemDialogs(String reason) {
4924 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
4925 if (reason != null) {
4926 intent.putExtra("reason", reason);
4927 }
4928
4929 final int uid = Binder.getCallingUid();
4930 final long origId = Binder.clearCallingIdentity();
4931 synchronized (this) {
4932 int i = mWatchers.beginBroadcast();
4933 while (i > 0) {
4934 i--;
4935 IActivityWatcher w = mWatchers.getBroadcastItem(i);
4936 if (w != null) {
4937 try {
4938 w.closingSystemDialogs(reason);
4939 } catch (RemoteException e) {
4940 }
4941 }
4942 }
4943 mWatchers.finishBroadcast();
4944
Dianne Hackbornffa42482009-09-23 22:20:11 -07004945 mWindowManager.closeSystemDialogs(reason);
4946
4947 for (i=mHistory.size()-1; i>=0; i--) {
4948 HistoryRecord r = (HistoryRecord)mHistory.get(i);
4949 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
4950 finishActivityLocked(r, i,
4951 Activity.RESULT_CANCELED, null, "close-sys");
4952 }
4953 }
4954
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07004955 broadcastIntentLocked(null, null, intent, null,
4956 null, 0, null, null, null, false, false, -1, uid);
4957 }
4958 Binder.restoreCallingIdentity(origId);
4959 }
4960
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07004961 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07004962 throws RemoteException {
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07004963 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
4964 for (int i=pids.length-1; i>=0; i--) {
4965 infos[i] = new Debug.MemoryInfo();
4966 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07004967 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07004968 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07004969 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07004970
4971 public void killApplicationProcess(String processName, int uid) {
4972 if (processName == null) {
4973 return;
4974 }
4975
4976 int callerUid = Binder.getCallingUid();
4977 // Only the system server can kill an application
4978 if (callerUid == Process.SYSTEM_UID) {
4979 synchronized (this) {
4980 ProcessRecord app = getProcessRecordLocked(processName, uid);
4981 if (app != null) {
4982 try {
4983 app.thread.scheduleSuicide();
4984 } catch (RemoteException e) {
4985 // If the other end already died, then our work here is done.
4986 }
4987 } else {
4988 Log.w(TAG, "Process/uid not found attempting kill of "
4989 + processName + " / " + uid);
4990 }
4991 }
4992 } else {
4993 throw new SecurityException(callerUid + " cannot kill app process: " +
4994 processName);
4995 }
4996 }
4997
Dianne Hackborn03abb812010-01-04 18:43:19 -08004998 private void forceStopPackageLocked(final String packageName, int uid) {
4999 forceStopPackageLocked(packageName, uid, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005000 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
5001 Uri.fromParts("package", packageName, null));
5002 intent.putExtra(Intent.EXTRA_UID, uid);
5003 broadcastIntentLocked(null, null, intent,
5004 null, null, 0, null, null, null,
5005 false, false, MY_PID, Process.SYSTEM_UID);
5006 }
5007
Dianne Hackborn03abb812010-01-04 18:43:19 -08005008 private final void killPackageProcessesLocked(String packageName, int uid,
5009 int minOomAdj, boolean callerWillRestart) {
5010 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005011
Dianne Hackborn03abb812010-01-04 18:43:19 -08005012 // Remove all processes this package may have touched: all with the
5013 // same UID (except for the system or root user), and all whose name
5014 // matches the package name.
5015 final String procNamePrefix = packageName + ":";
5016 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
5017 final int NA = apps.size();
5018 for (int ia=0; ia<NA; ia++) {
5019 ProcessRecord app = apps.valueAt(ia);
5020 if (app.removed) {
5021 procs.add(app);
5022 } else if ((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
5023 || app.processName.equals(packageName)
5024 || app.processName.startsWith(procNamePrefix)) {
5025 if (app.setAdj >= minOomAdj) {
5026 app.removed = true;
5027 procs.add(app);
5028 }
5029 }
5030 }
5031 }
5032
5033 int N = procs.size();
5034 for (int i=0; i<N; i++) {
5035 removeProcessLocked(procs.get(i), callerWillRestart);
5036 }
5037 }
5038
5039 private final void forceStopPackageLocked(String name, int uid,
5040 boolean callerWillRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005041 int i, N;
5042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005043 if (uid < 0) {
5044 try {
5045 uid = ActivityThread.getPackageManager().getPackageUid(name);
5046 } catch (RemoteException e) {
5047 }
5048 }
5049
Dianne Hackborn03abb812010-01-04 18:43:19 -08005050 Log.i(TAG, "Force stopping package " + name + " uid=" + uid);
5051
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005052 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
5053 while (badApps.hasNext()) {
5054 SparseArray<Long> ba = badApps.next();
5055 if (ba.get(uid) != null) {
5056 badApps.remove();
5057 }
5058 }
5059
Dianne Hackborn03abb812010-01-04 18:43:19 -08005060 killPackageProcessesLocked(name, uid, -100, callerWillRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005061
5062 for (i=mHistory.size()-1; i>=0; i--) {
5063 HistoryRecord r = (HistoryRecord)mHistory.get(i);
5064 if (r.packageName.equals(name)) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08005065 Log.i(TAG, " Force finishing activity " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005066 if (r.app != null) {
5067 r.app.removed = true;
5068 }
5069 r.app = null;
5070 finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "uninstall");
5071 }
5072 }
5073
5074 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
5075 for (ServiceRecord service : mServices.values()) {
5076 if (service.packageName.equals(name)) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08005077 Log.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005078 if (service.app != null) {
5079 service.app.removed = true;
5080 }
5081 service.app = null;
5082 services.add(service);
5083 }
5084 }
5085
5086 N = services.size();
5087 for (i=0; i<N; i++) {
5088 bringDownServiceLocked(services.get(i), true);
5089 }
5090
5091 resumeTopActivityLocked(null);
5092 }
5093
5094 private final boolean removeProcessLocked(ProcessRecord app, boolean callerWillRestart) {
5095 final String name = app.processName;
5096 final int uid = app.info.uid;
Dianne Hackborn03abb812010-01-04 18:43:19 -08005097 if (DEBUG_PROCESSES) Log.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005098 TAG, "Force removing process " + app + " (" + name
5099 + "/" + uid + ")");
5100
5101 mProcessNames.remove(name, uid);
5102 boolean needRestart = false;
5103 if (app.pid > 0 && app.pid != MY_PID) {
5104 int pid = app.pid;
5105 synchronized (mPidsSelfLocked) {
5106 mPidsSelfLocked.remove(pid);
5107 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
5108 }
5109 handleAppDiedLocked(app, true);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08005110 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005111 Process.killProcess(pid);
5112
5113 if (app.persistent) {
5114 if (!callerWillRestart) {
5115 addAppLocked(app.info);
5116 } else {
5117 needRestart = true;
5118 }
5119 }
5120 } else {
5121 mRemovedProcesses.add(app);
5122 }
5123
5124 return needRestart;
5125 }
5126
5127 private final void processStartTimedOutLocked(ProcessRecord app) {
5128 final int pid = app.pid;
5129 boolean gone = false;
5130 synchronized (mPidsSelfLocked) {
5131 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
5132 if (knownApp != null && knownApp.thread == null) {
5133 mPidsSelfLocked.remove(pid);
5134 gone = true;
5135 }
5136 }
5137
5138 if (gone) {
5139 Log.w(TAG, "Process " + app + " failed to attach");
Doug Zongker2bec3d42009-12-04 12:52:44 -08005140 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.info.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08005141 app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005142 mProcessNames.remove(app.processName, app.info.uid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08005143 // Take care of any launching providers waiting for this process.
5144 checkAppInLaunchingProvidersLocked(app, true);
5145 // Take care of any services that are waiting for the process.
5146 for (int i=0; i<mPendingServices.size(); i++) {
5147 ServiceRecord sr = mPendingServices.get(i);
5148 if (app.info.uid == sr.appInfo.uid
5149 && app.processName.equals(sr.processName)) {
5150 Log.w(TAG, "Forcing bringing down service: " + sr);
5151 mPendingServices.remove(i);
5152 i--;
5153 bringDownServiceLocked(sr, true);
5154 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005155 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08005156 Process.killProcess(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07005157 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
5158 Log.w(TAG, "Unattached app died before backup, skipping");
5159 try {
5160 IBackupManager bm = IBackupManager.Stub.asInterface(
5161 ServiceManager.getService(Context.BACKUP_SERVICE));
5162 bm.agentDisconnected(app.info.packageName);
5163 } catch (RemoteException e) {
5164 // Can't happen; the backup manager is local
5165 }
5166 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08005167 if (mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid) {
5168 Log.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
5169 mPendingBroadcast = null;
5170 scheduleBroadcastsLocked();
5171 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005172 } else {
5173 Log.w(TAG, "Spurious process start timeout - pid not known for " + app);
5174 }
5175 }
5176
5177 private final boolean attachApplicationLocked(IApplicationThread thread,
5178 int pid) {
5179
5180 // Find the application record that is being attached... either via
5181 // the pid if we are running in multiple processes, or just pull the
5182 // next app record if we are emulating process with anonymous threads.
5183 ProcessRecord app;
5184 if (pid != MY_PID && pid >= 0) {
5185 synchronized (mPidsSelfLocked) {
5186 app = mPidsSelfLocked.get(pid);
5187 }
5188 } else if (mStartingProcesses.size() > 0) {
5189 app = mStartingProcesses.remove(0);
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07005190 app.setPid(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005191 } else {
5192 app = null;
5193 }
5194
5195 if (app == null) {
5196 Log.w(TAG, "No pending application record for pid " + pid
5197 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08005198 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005199 if (pid > 0 && pid != MY_PID) {
5200 Process.killProcess(pid);
5201 } else {
5202 try {
5203 thread.scheduleExit();
5204 } catch (Exception e) {
5205 // Ignore exceptions.
5206 }
5207 }
5208 return false;
5209 }
5210
5211 // If this application record is still attached to a previous
5212 // process, clean it up now.
5213 if (app.thread != null) {
5214 handleAppDiedLocked(app, true);
5215 }
5216
5217 // Tell the process all about itself.
5218
5219 if (localLOGV) Log.v(
5220 TAG, "Binding process pid " + pid + " to record " + app);
5221
5222 String processName = app.processName;
5223 try {
5224 thread.asBinder().linkToDeath(new AppDeathRecipient(
5225 app, pid, thread), 0);
5226 } catch (RemoteException e) {
5227 app.resetPackageList();
5228 startProcessLocked(app, "link fail", processName);
5229 return false;
5230 }
5231
Doug Zongker2bec3d42009-12-04 12:52:44 -08005232 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005233
5234 app.thread = thread;
5235 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08005236 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
5237 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005238 app.forcingToForeground = null;
5239 app.foregroundServices = false;
5240 app.debugging = false;
5241
5242 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
5243
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005244 boolean normalMode = mSystemReady || isAllowedWhileBooting(app.info);
5245 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005246
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005247 if (!normalMode) {
5248 Log.i(TAG, "Launching preboot mode app: " + app);
5249 }
5250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005251 if (localLOGV) Log.v(
5252 TAG, "New app record " + app
5253 + " thread=" + thread.asBinder() + " pid=" + pid);
5254 try {
5255 int testMode = IApplicationThread.DEBUG_OFF;
5256 if (mDebugApp != null && mDebugApp.equals(processName)) {
5257 testMode = mWaitForDebugger
5258 ? IApplicationThread.DEBUG_WAIT
5259 : IApplicationThread.DEBUG_ON;
5260 app.debugging = true;
5261 if (mDebugTransient) {
5262 mDebugApp = mOrigDebugApp;
5263 mWaitForDebugger = mOrigWaitForDebugger;
5264 }
5265 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005266
Christopher Tate181fafa2009-05-14 11:12:14 -07005267 // If the app is being launched for restore or full backup, set it up specially
5268 boolean isRestrictedBackupMode = false;
5269 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
5270 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
5271 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
5272 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005273
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07005274 ensurePackageDexOpt(app.instrumentationInfo != null
5275 ? app.instrumentationInfo.packageName
5276 : app.info.packageName);
5277 if (app.instrumentationClass != null) {
5278 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005279 }
Dianne Hackborndc6b6352009-09-30 14:20:09 -07005280 if (DEBUG_CONFIGURATION) Log.v(TAG, "Binding proc "
5281 + processName + " with config " + mConfiguration);
Dianne Hackborn1655be42009-05-08 14:29:01 -07005282 thread.bindApplication(processName, app.instrumentationInfo != null
5283 ? app.instrumentationInfo : app.info, providers,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005284 app.instrumentationClass, app.instrumentationProfileFile,
5285 app.instrumentationArguments, app.instrumentationWatcher, testMode,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005286 isRestrictedBackupMode || !normalMode,
5287 mConfiguration, getCommonServicesLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08005288 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07005289 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005290 } catch (Exception e) {
5291 // todo: Yikes! What should we do? For now we will try to
5292 // start another process, but that could easily get us in
5293 // an infinite loop of restarting processes...
5294 Log.w(TAG, "Exception thrown during bind!", e);
5295
5296 app.resetPackageList();
5297 startProcessLocked(app, "bind fail", processName);
5298 return false;
5299 }
5300
5301 // Remove this record from the list of starting applications.
5302 mPersistentStartingProcesses.remove(app);
5303 mProcessesOnHold.remove(app);
5304
5305 boolean badApp = false;
5306 boolean didSomething = false;
5307
5308 // See if the top visible activity is waiting to run in this process...
5309 HistoryRecord hr = topRunningActivityLocked(null);
5310 if (hr != null) {
5311 if (hr.app == null && app.info.uid == hr.info.applicationInfo.uid
5312 && processName.equals(hr.processName)) {
5313 try {
5314 if (realStartActivityLocked(hr, app, true, true)) {
5315 didSomething = true;
5316 }
5317 } catch (Exception e) {
5318 Log.w(TAG, "Exception in new application when starting activity "
5319 + hr.intent.getComponent().flattenToShortString(), e);
5320 badApp = true;
5321 }
5322 } else {
5323 ensureActivitiesVisibleLocked(hr, null, processName, 0);
5324 }
5325 }
5326
5327 // Find any services that should be running in this process...
5328 if (!badApp && mPendingServices.size() > 0) {
5329 ServiceRecord sr = null;
5330 try {
5331 for (int i=0; i<mPendingServices.size(); i++) {
5332 sr = mPendingServices.get(i);
5333 if (app.info.uid != sr.appInfo.uid
5334 || !processName.equals(sr.processName)) {
5335 continue;
5336 }
5337
5338 mPendingServices.remove(i);
5339 i--;
5340 realStartServiceLocked(sr, app);
5341 didSomething = true;
5342 }
5343 } catch (Exception e) {
5344 Log.w(TAG, "Exception in new application when starting service "
5345 + sr.shortName, e);
5346 badApp = true;
5347 }
5348 }
5349
5350 // Check if the next broadcast receiver is in this process...
5351 BroadcastRecord br = mPendingBroadcast;
5352 if (!badApp && br != null && br.curApp == app) {
5353 try {
5354 mPendingBroadcast = null;
5355 processCurBroadcastLocked(br, app);
5356 didSomething = true;
5357 } catch (Exception e) {
5358 Log.w(TAG, "Exception in new application when starting receiver "
5359 + br.curComponent.flattenToShortString(), e);
5360 badApp = true;
5361 logBroadcastReceiverDiscard(br);
5362 finishReceiverLocked(br.receiver, br.resultCode, br.resultData,
5363 br.resultExtras, br.resultAbort, true);
5364 scheduleBroadcastsLocked();
5365 }
5366 }
5367
Christopher Tate181fafa2009-05-14 11:12:14 -07005368 // Check whether the next backup agent is in this process...
5369 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.info.uid) {
5370 if (DEBUG_BACKUP) Log.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005371 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07005372 try {
5373 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo, mBackupTarget.backupMode);
5374 } catch (Exception e) {
5375 Log.w(TAG, "Exception scheduling backup agent creation: ");
5376 e.printStackTrace();
5377 }
5378 }
5379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005380 if (badApp) {
5381 // todo: Also need to kill application to deal with all
5382 // kinds of exceptions.
5383 handleAppDiedLocked(app, false);
5384 return false;
5385 }
5386
5387 if (!didSomething) {
5388 updateOomAdjLocked();
5389 }
5390
5391 return true;
5392 }
5393
5394 public final void attachApplication(IApplicationThread thread) {
5395 synchronized (this) {
5396 int callingPid = Binder.getCallingPid();
5397 final long origId = Binder.clearCallingIdentity();
5398 attachApplicationLocked(thread, callingPid);
5399 Binder.restoreCallingIdentity(origId);
5400 }
5401 }
5402
Dianne Hackborne88846e2009-09-30 21:34:25 -07005403 public final void activityIdle(IBinder token, Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005404 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne88846e2009-09-30 21:34:25 -07005405 activityIdleInternal(token, false, config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005406 Binder.restoreCallingIdentity(origId);
5407 }
5408
5409 final ArrayList<HistoryRecord> processStoppingActivitiesLocked(
5410 boolean remove) {
5411 int N = mStoppingActivities.size();
5412 if (N <= 0) return null;
5413
5414 ArrayList<HistoryRecord> stops = null;
5415
5416 final boolean nowVisible = mResumedActivity != null
5417 && mResumedActivity.nowVisible
5418 && !mResumedActivity.waitingVisible;
5419 for (int i=0; i<N; i++) {
5420 HistoryRecord s = mStoppingActivities.get(i);
5421 if (localLOGV) Log.v(TAG, "Stopping " + s + ": nowVisible="
5422 + nowVisible + " waitingVisible=" + s.waitingVisible
5423 + " finishing=" + s.finishing);
5424 if (s.waitingVisible && nowVisible) {
5425 mWaitingVisibleActivities.remove(s);
5426 s.waitingVisible = false;
5427 if (s.finishing) {
5428 // If this activity is finishing, it is sitting on top of
5429 // everyone else but we now know it is no longer needed...
5430 // so get rid of it. Otherwise, we need to go through the
5431 // normal flow and hide it once we determine that it is
5432 // hidden by the activities in front of it.
5433 if (localLOGV) Log.v(TAG, "Before stopping, can hide: " + s);
5434 mWindowManager.setAppVisibility(s, false);
5435 }
5436 }
5437 if (!s.waitingVisible && remove) {
5438 if (localLOGV) Log.v(TAG, "Ready to stop: " + s);
5439 if (stops == null) {
5440 stops = new ArrayList<HistoryRecord>();
5441 }
5442 stops.add(s);
5443 mStoppingActivities.remove(i);
5444 N--;
5445 i--;
5446 }
5447 }
5448
5449 return stops;
5450 }
5451
5452 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08005453 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005454 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005455 mWindowManager.enableScreenAfterBoot();
5456 }
5457
Dianne Hackborne88846e2009-09-30 21:34:25 -07005458 final void activityIdleInternal(IBinder token, boolean fromTimeout,
5459 Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005460 if (localLOGV) Log.v(TAG, "Activity idle: " + token);
5461
5462 ArrayList<HistoryRecord> stops = null;
5463 ArrayList<HistoryRecord> finishes = null;
5464 ArrayList<HistoryRecord> thumbnails = null;
5465 int NS = 0;
5466 int NF = 0;
5467 int NT = 0;
5468 IApplicationThread sendThumbnail = null;
5469 boolean booting = false;
5470 boolean enableScreen = false;
5471
5472 synchronized (this) {
5473 if (token != null) {
5474 mHandler.removeMessages(IDLE_TIMEOUT_MSG, token);
5475 }
5476
5477 // Get the activity record.
Dianne Hackborn75b03852009-06-12 15:43:26 -07005478 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005479 if (index >= 0) {
5480 HistoryRecord r = (HistoryRecord)mHistory.get(index);
5481
Dianne Hackborne88846e2009-09-30 21:34:25 -07005482 // This is a hack to semi-deal with a race condition
5483 // in the client where it can be constructed with a
5484 // newer configuration from when we asked it to launch.
5485 // We'll update with whatever configuration it now says
5486 // it used to launch.
5487 if (config != null) {
5488 r.configuration = config;
5489 }
5490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005491 // No longer need to keep the device awake.
5492 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
5493 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
5494 mLaunchingActivity.release();
5495 }
5496
5497 // We are now idle. If someone is waiting for a thumbnail from
5498 // us, we can now deliver.
5499 r.idle = true;
5500 scheduleAppGcsLocked();
5501 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
5502 sendThumbnail = r.app.thread;
5503 r.thumbnailNeeded = false;
5504 }
5505
5506 // If this activity is fullscreen, set up to hide those under it.
5507
5508 if (DEBUG_VISBILITY) Log.v(TAG, "Idle activity for " + r);
5509 ensureActivitiesVisibleLocked(null, 0);
5510
5511 //Log.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
5512 if (!mBooted && !fromTimeout) {
5513 mBooted = true;
5514 enableScreen = true;
5515 }
5516 }
5517
5518 // Atomically retrieve all of the other things to do.
5519 stops = processStoppingActivitiesLocked(true);
5520 NS = stops != null ? stops.size() : 0;
5521 if ((NF=mFinishingActivities.size()) > 0) {
5522 finishes = new ArrayList<HistoryRecord>(mFinishingActivities);
5523 mFinishingActivities.clear();
5524 }
5525 if ((NT=mCancelledThumbnails.size()) > 0) {
5526 thumbnails = new ArrayList<HistoryRecord>(mCancelledThumbnails);
5527 mCancelledThumbnails.clear();
5528 }
5529
5530 booting = mBooting;
5531 mBooting = false;
5532 }
5533
5534 int i;
5535
5536 // Send thumbnail if requested.
5537 if (sendThumbnail != null) {
5538 try {
5539 sendThumbnail.requestThumbnail(token);
5540 } catch (Exception e) {
5541 Log.w(TAG, "Exception thrown when requesting thumbnail", e);
5542 sendPendingThumbnail(null, token, null, null, true);
5543 }
5544 }
5545
5546 // Stop any activities that are scheduled to do so but have been
5547 // waiting for the next one to start.
5548 for (i=0; i<NS; i++) {
5549 HistoryRecord r = (HistoryRecord)stops.get(i);
5550 synchronized (this) {
5551 if (r.finishing) {
5552 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY);
5553 } else {
5554 stopActivityLocked(r);
5555 }
5556 }
5557 }
5558
5559 // Finish any activities that are scheduled to do so but have been
5560 // waiting for the next one to start.
5561 for (i=0; i<NF; i++) {
5562 HistoryRecord r = (HistoryRecord)finishes.get(i);
5563 synchronized (this) {
5564 destroyActivityLocked(r, true);
5565 }
5566 }
5567
5568 // Report back to any thumbnail receivers.
5569 for (i=0; i<NT; i++) {
5570 HistoryRecord r = (HistoryRecord)thumbnails.get(i);
5571 sendPendingThumbnail(r, null, null, null, true);
5572 }
5573
5574 if (booting) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005575 finishBooting();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005576 }
5577
5578 trimApplications();
5579 //dump();
5580 //mWindowManager.dump();
5581
5582 if (enableScreen) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005583 enableScreenAfterBoot();
5584 }
5585 }
5586
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005587 final void finishBooting() {
5588 // Ensure that any processes we had put on hold are now started
5589 // up.
5590 final int NP = mProcessesOnHold.size();
5591 if (NP > 0) {
5592 ArrayList<ProcessRecord> procs =
5593 new ArrayList<ProcessRecord>(mProcessesOnHold);
5594 for (int ip=0; ip<NP; ip++) {
5595 this.startProcessLocked(procs.get(ip), "on-hold", null);
5596 }
5597 }
5598 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
5599 // Tell anyone interested that we are done booting!
5600 synchronized (this) {
5601 broadcastIntentLocked(null, null,
5602 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
5603 null, null, 0, null, null,
5604 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
5605 false, false, MY_PID, Process.SYSTEM_UID);
5606 }
5607 }
5608 }
5609
5610 final void ensureBootCompleted() {
5611 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005612 boolean enableScreen;
5613 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005614 booting = mBooting;
5615 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005616 enableScreen = !mBooted;
5617 mBooted = true;
5618 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005619
5620 if (booting) {
5621 finishBooting();
5622 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005623
5624 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005625 enableScreenAfterBoot();
5626 }
5627 }
5628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005629 public final void activityPaused(IBinder token, Bundle icicle) {
5630 // Refuse possible leaked file descriptors
5631 if (icicle != null && icicle.hasFileDescriptors()) {
5632 throw new IllegalArgumentException("File descriptors passed in Bundle");
5633 }
5634
5635 final long origId = Binder.clearCallingIdentity();
5636 activityPaused(token, icicle, false);
5637 Binder.restoreCallingIdentity(origId);
5638 }
5639
5640 final void activityPaused(IBinder token, Bundle icicle, boolean timeout) {
5641 if (DEBUG_PAUSE) Log.v(
5642 TAG, "Activity paused: token=" + token + ", icicle=" + icicle
5643 + ", timeout=" + timeout);
5644
5645 HistoryRecord r = null;
5646
5647 synchronized (this) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07005648 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005649 if (index >= 0) {
5650 r = (HistoryRecord)mHistory.get(index);
5651 if (!timeout) {
5652 r.icicle = icicle;
5653 r.haveState = true;
5654 }
5655 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
5656 if (mPausingActivity == r) {
5657 r.state = ActivityState.PAUSED;
5658 completePauseLocked();
5659 } else {
Doug Zongker2bec3d42009-12-04 12:52:44 -08005660 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005661 System.identityHashCode(r), r.shortComponentName,
5662 mPausingActivity != null
5663 ? mPausingActivity.shortComponentName : "(none)");
5664 }
5665 }
5666 }
5667 }
5668
5669 public final void activityStopped(IBinder token, Bitmap thumbnail,
5670 CharSequence description) {
5671 if (localLOGV) Log.v(
5672 TAG, "Activity stopped: token=" + token);
5673
5674 HistoryRecord r = null;
5675
5676 final long origId = Binder.clearCallingIdentity();
5677
5678 synchronized (this) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07005679 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005680 if (index >= 0) {
5681 r = (HistoryRecord)mHistory.get(index);
5682 r.thumbnail = thumbnail;
5683 r.description = description;
5684 r.stopped = true;
5685 r.state = ActivityState.STOPPED;
5686 if (!r.finishing) {
5687 if (r.configDestroy) {
5688 destroyActivityLocked(r, true);
5689 resumeTopActivityLocked(null);
5690 }
5691 }
5692 }
5693 }
5694
5695 if (r != null) {
5696 sendPendingThumbnail(r, null, null, null, false);
5697 }
5698
5699 trimApplications();
5700
5701 Binder.restoreCallingIdentity(origId);
5702 }
5703
5704 public final void activityDestroyed(IBinder token) {
5705 if (DEBUG_SWITCH) Log.v(TAG, "ACTIVITY DESTROYED: " + token);
5706 synchronized (this) {
5707 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, token);
5708
Dianne Hackborn75b03852009-06-12 15:43:26 -07005709 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005710 if (index >= 0) {
5711 HistoryRecord r = (HistoryRecord)mHistory.get(index);
5712 if (r.state == ActivityState.DESTROYING) {
5713 final long origId = Binder.clearCallingIdentity();
5714 removeActivityFromHistoryLocked(r);
5715 Binder.restoreCallingIdentity(origId);
5716 }
5717 }
5718 }
5719 }
5720
5721 public String getCallingPackage(IBinder token) {
5722 synchronized (this) {
5723 HistoryRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07005724 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005725 }
5726 }
5727
5728 public ComponentName getCallingActivity(IBinder token) {
5729 synchronized (this) {
5730 HistoryRecord r = getCallingRecordLocked(token);
5731 return r != null ? r.intent.getComponent() : null;
5732 }
5733 }
5734
5735 private HistoryRecord getCallingRecordLocked(IBinder token) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07005736 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005737 if (index >= 0) {
5738 HistoryRecord r = (HistoryRecord)mHistory.get(index);
5739 if (r != null) {
5740 return r.resultTo;
5741 }
5742 }
5743 return null;
5744 }
5745
5746 public ComponentName getActivityClassForToken(IBinder token) {
5747 synchronized(this) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07005748 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005749 if (index >= 0) {
5750 HistoryRecord r = (HistoryRecord)mHistory.get(index);
5751 return r.intent.getComponent();
5752 }
5753 return null;
5754 }
5755 }
5756
5757 public String getPackageForToken(IBinder token) {
5758 synchronized(this) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07005759 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005760 if (index >= 0) {
5761 HistoryRecord r = (HistoryRecord)mHistory.get(index);
5762 return r.packageName;
5763 }
5764 return null;
5765 }
5766 }
5767
5768 public IIntentSender getIntentSender(int type,
5769 String packageName, IBinder token, String resultWho,
5770 int requestCode, Intent intent, String resolvedType, int flags) {
5771 // Refuse possible leaked file descriptors
5772 if (intent != null && intent.hasFileDescriptors() == true) {
5773 throw new IllegalArgumentException("File descriptors passed in Intent");
5774 }
5775
Dianne Hackborn9acc0302009-08-25 00:27:12 -07005776 if (type == INTENT_SENDER_BROADCAST) {
5777 if ((intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
5778 throw new IllegalArgumentException(
5779 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
5780 }
5781 }
5782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005783 synchronized(this) {
5784 int callingUid = Binder.getCallingUid();
5785 try {
5786 if (callingUid != 0 && callingUid != Process.SYSTEM_UID &&
5787 Process.supportsProcesses()) {
5788 int uid = ActivityThread.getPackageManager()
5789 .getPackageUid(packageName);
5790 if (uid != Binder.getCallingUid()) {
5791 String msg = "Permission Denial: getIntentSender() from pid="
5792 + Binder.getCallingPid()
5793 + ", uid=" + Binder.getCallingUid()
5794 + ", (need uid=" + uid + ")"
5795 + " is not allowed to send as package " + packageName;
5796 Log.w(TAG, msg);
5797 throw new SecurityException(msg);
5798 }
5799 }
5800 } catch (RemoteException e) {
5801 throw new SecurityException(e);
5802 }
5803 HistoryRecord activity = null;
5804 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07005805 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005806 if (index < 0) {
5807 return null;
5808 }
5809 activity = (HistoryRecord)mHistory.get(index);
5810 if (activity.finishing) {
5811 return null;
5812 }
5813 }
5814
5815 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
5816 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
5817 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
5818 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
5819 |PendingIntent.FLAG_UPDATE_CURRENT);
5820
5821 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
5822 type, packageName, activity, resultWho,
5823 requestCode, intent, resolvedType, flags);
5824 WeakReference<PendingIntentRecord> ref;
5825 ref = mIntentSenderRecords.get(key);
5826 PendingIntentRecord rec = ref != null ? ref.get() : null;
5827 if (rec != null) {
5828 if (!cancelCurrent) {
5829 if (updateCurrent) {
5830 rec.key.requestIntent.replaceExtras(intent);
5831 }
5832 return rec;
5833 }
5834 rec.canceled = true;
5835 mIntentSenderRecords.remove(key);
5836 }
5837 if (noCreate) {
5838 return rec;
5839 }
5840 rec = new PendingIntentRecord(this, key, callingUid);
5841 mIntentSenderRecords.put(key, rec.ref);
5842 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
5843 if (activity.pendingResults == null) {
5844 activity.pendingResults
5845 = new HashSet<WeakReference<PendingIntentRecord>>();
5846 }
5847 activity.pendingResults.add(rec.ref);
5848 }
5849 return rec;
5850 }
5851 }
5852
5853 public void cancelIntentSender(IIntentSender sender) {
5854 if (!(sender instanceof PendingIntentRecord)) {
5855 return;
5856 }
5857 synchronized(this) {
5858 PendingIntentRecord rec = (PendingIntentRecord)sender;
5859 try {
5860 int uid = ActivityThread.getPackageManager()
5861 .getPackageUid(rec.key.packageName);
5862 if (uid != Binder.getCallingUid()) {
5863 String msg = "Permission Denial: cancelIntentSender() from pid="
5864 + Binder.getCallingPid()
5865 + ", uid=" + Binder.getCallingUid()
5866 + " is not allowed to cancel packges "
5867 + rec.key.packageName;
5868 Log.w(TAG, msg);
5869 throw new SecurityException(msg);
5870 }
5871 } catch (RemoteException e) {
5872 throw new SecurityException(e);
5873 }
5874 cancelIntentSenderLocked(rec, true);
5875 }
5876 }
5877
5878 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
5879 rec.canceled = true;
5880 mIntentSenderRecords.remove(rec.key);
5881 if (cleanActivity && rec.key.activity != null) {
5882 rec.key.activity.pendingResults.remove(rec.ref);
5883 }
5884 }
5885
5886 public String getPackageForIntentSender(IIntentSender pendingResult) {
5887 if (!(pendingResult instanceof PendingIntentRecord)) {
5888 return null;
5889 }
5890 synchronized(this) {
5891 try {
5892 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5893 return res.key.packageName;
5894 } catch (ClassCastException e) {
5895 }
5896 }
5897 return null;
5898 }
5899
5900 public void setProcessLimit(int max) {
5901 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
5902 "setProcessLimit()");
5903 mProcessLimit = max;
5904 }
5905
5906 public int getProcessLimit() {
5907 return mProcessLimit;
5908 }
5909
5910 void foregroundTokenDied(ForegroundToken token) {
5911 synchronized (ActivityManagerService.this) {
5912 synchronized (mPidsSelfLocked) {
5913 ForegroundToken cur
5914 = mForegroundProcesses.get(token.pid);
5915 if (cur != token) {
5916 return;
5917 }
5918 mForegroundProcesses.remove(token.pid);
5919 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
5920 if (pr == null) {
5921 return;
5922 }
5923 pr.forcingToForeground = null;
5924 pr.foregroundServices = false;
5925 }
5926 updateOomAdjLocked();
5927 }
5928 }
5929
5930 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
5931 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
5932 "setProcessForeground()");
5933 synchronized(this) {
5934 boolean changed = false;
5935
5936 synchronized (mPidsSelfLocked) {
5937 ProcessRecord pr = mPidsSelfLocked.get(pid);
5938 if (pr == null) {
5939 Log.w(TAG, "setProcessForeground called on unknown pid: " + pid);
5940 return;
5941 }
5942 ForegroundToken oldToken = mForegroundProcesses.get(pid);
5943 if (oldToken != null) {
5944 oldToken.token.unlinkToDeath(oldToken, 0);
5945 mForegroundProcesses.remove(pid);
5946 pr.forcingToForeground = null;
5947 changed = true;
5948 }
5949 if (isForeground && token != null) {
5950 ForegroundToken newToken = new ForegroundToken() {
5951 public void binderDied() {
5952 foregroundTokenDied(this);
5953 }
5954 };
5955 newToken.pid = pid;
5956 newToken.token = token;
5957 try {
5958 token.linkToDeath(newToken, 0);
5959 mForegroundProcesses.put(pid, newToken);
5960 pr.forcingToForeground = token;
5961 changed = true;
5962 } catch (RemoteException e) {
5963 // If the process died while doing this, we will later
5964 // do the cleanup with the process death link.
5965 }
5966 }
5967 }
5968
5969 if (changed) {
5970 updateOomAdjLocked();
5971 }
5972 }
5973 }
5974
5975 // =========================================================
5976 // PERMISSIONS
5977 // =========================================================
5978
5979 static class PermissionController extends IPermissionController.Stub {
5980 ActivityManagerService mActivityManagerService;
5981 PermissionController(ActivityManagerService activityManagerService) {
5982 mActivityManagerService = activityManagerService;
5983 }
5984
5985 public boolean checkPermission(String permission, int pid, int uid) {
5986 return mActivityManagerService.checkPermission(permission, pid,
5987 uid) == PackageManager.PERMISSION_GRANTED;
5988 }
5989 }
5990
5991 /**
5992 * This can be called with or without the global lock held.
5993 */
5994 int checkComponentPermission(String permission, int pid, int uid,
5995 int reqUid) {
5996 // We might be performing an operation on behalf of an indirect binder
5997 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
5998 // client identity accordingly before proceeding.
5999 Identity tlsIdentity = sCallerIdentity.get();
6000 if (tlsIdentity != null) {
6001 Log.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
6002 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
6003 uid = tlsIdentity.uid;
6004 pid = tlsIdentity.pid;
6005 }
6006
6007 // Root, system server and our own process get to do everything.
6008 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID ||
6009 !Process.supportsProcesses()) {
6010 return PackageManager.PERMISSION_GRANTED;
6011 }
6012 // If the target requires a specific UID, always fail for others.
6013 if (reqUid >= 0 && uid != reqUid) {
root0369a7c2009-03-23 15:20:47 +01006014 Log.w(TAG, "Permission denied: checkComponentPermission() reqUid=" + reqUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006015 return PackageManager.PERMISSION_DENIED;
6016 }
6017 if (permission == null) {
6018 return PackageManager.PERMISSION_GRANTED;
6019 }
6020 try {
6021 return ActivityThread.getPackageManager()
6022 .checkUidPermission(permission, uid);
6023 } catch (RemoteException e) {
6024 // Should never happen, but if it does... deny!
6025 Log.e(TAG, "PackageManager is dead?!?", e);
6026 }
6027 return PackageManager.PERMISSION_DENIED;
6028 }
6029
6030 /**
6031 * As the only public entry point for permissions checking, this method
6032 * can enforce the semantic that requesting a check on a null global
6033 * permission is automatically denied. (Internally a null permission
6034 * string is used when calling {@link #checkComponentPermission} in cases
6035 * when only uid-based security is needed.)
6036 *
6037 * This can be called with or without the global lock held.
6038 */
6039 public int checkPermission(String permission, int pid, int uid) {
6040 if (permission == null) {
6041 return PackageManager.PERMISSION_DENIED;
6042 }
6043 return checkComponentPermission(permission, pid, uid, -1);
6044 }
6045
6046 /**
6047 * Binder IPC calls go through the public entry point.
6048 * This can be called with or without the global lock held.
6049 */
6050 int checkCallingPermission(String permission) {
6051 return checkPermission(permission,
6052 Binder.getCallingPid(),
6053 Binder.getCallingUid());
6054 }
6055
6056 /**
6057 * This can be called with or without the global lock held.
6058 */
6059 void enforceCallingPermission(String permission, String func) {
6060 if (checkCallingPermission(permission)
6061 == PackageManager.PERMISSION_GRANTED) {
6062 return;
6063 }
6064
6065 String msg = "Permission Denial: " + func + " from pid="
6066 + Binder.getCallingPid()
6067 + ", uid=" + Binder.getCallingUid()
6068 + " requires " + permission;
6069 Log.w(TAG, msg);
6070 throw new SecurityException(msg);
6071 }
6072
6073 private final boolean checkHoldingPermissionsLocked(IPackageManager pm,
6074 ProviderInfo pi, int uid, int modeFlags) {
6075 try {
6076 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
6077 if ((pi.readPermission != null) &&
6078 (pm.checkUidPermission(pi.readPermission, uid)
6079 != PackageManager.PERMISSION_GRANTED)) {
6080 return false;
6081 }
6082 }
6083 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
6084 if ((pi.writePermission != null) &&
6085 (pm.checkUidPermission(pi.writePermission, uid)
6086 != PackageManager.PERMISSION_GRANTED)) {
6087 return false;
6088 }
6089 }
6090 return true;
6091 } catch (RemoteException e) {
6092 return false;
6093 }
6094 }
6095
6096 private final boolean checkUriPermissionLocked(Uri uri, int uid,
6097 int modeFlags) {
6098 // Root gets to do everything.
6099 if (uid == 0 || !Process.supportsProcesses()) {
6100 return true;
6101 }
6102 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
6103 if (perms == null) return false;
6104 UriPermission perm = perms.get(uri);
6105 if (perm == null) return false;
6106 return (modeFlags&perm.modeFlags) == modeFlags;
6107 }
6108
6109 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
6110 // Another redirected-binder-call permissions check as in
6111 // {@link checkComponentPermission}.
6112 Identity tlsIdentity = sCallerIdentity.get();
6113 if (tlsIdentity != null) {
6114 uid = tlsIdentity.uid;
6115 pid = tlsIdentity.pid;
6116 }
6117
6118 // Our own process gets to do everything.
6119 if (pid == MY_PID) {
6120 return PackageManager.PERMISSION_GRANTED;
6121 }
6122 synchronized(this) {
6123 return checkUriPermissionLocked(uri, uid, modeFlags)
6124 ? PackageManager.PERMISSION_GRANTED
6125 : PackageManager.PERMISSION_DENIED;
6126 }
6127 }
6128
6129 private void grantUriPermissionLocked(int callingUid,
6130 String targetPkg, Uri uri, int modeFlags, HistoryRecord activity) {
6131 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
6132 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
6133 if (modeFlags == 0) {
6134 return;
6135 }
6136
6137 final IPackageManager pm = ActivityThread.getPackageManager();
6138
6139 // If this is not a content: uri, we can't do anything with it.
6140 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
6141 return;
6142 }
6143
6144 String name = uri.getAuthority();
6145 ProviderInfo pi = null;
6146 ContentProviderRecord cpr
6147 = (ContentProviderRecord)mProvidersByName.get(name);
6148 if (cpr != null) {
6149 pi = cpr.info;
6150 } else {
6151 try {
6152 pi = pm.resolveContentProvider(name,
6153 PackageManager.GET_URI_PERMISSION_PATTERNS);
6154 } catch (RemoteException ex) {
6155 }
6156 }
6157 if (pi == null) {
6158 Log.w(TAG, "No content provider found for: " + name);
6159 return;
6160 }
6161
6162 int targetUid;
6163 try {
6164 targetUid = pm.getPackageUid(targetPkg);
6165 if (targetUid < 0) {
6166 return;
6167 }
6168 } catch (RemoteException ex) {
6169 return;
6170 }
6171
6172 // First... does the target actually need this permission?
6173 if (checkHoldingPermissionsLocked(pm, pi, targetUid, modeFlags)) {
6174 // No need to grant the target this permission.
6175 return;
6176 }
6177
6178 // Second... maybe someone else has already granted the
6179 // permission?
6180 if (checkUriPermissionLocked(uri, targetUid, modeFlags)) {
6181 // No need to grant the target this permission.
6182 return;
6183 }
6184
6185 // Third... is the provider allowing granting of URI permissions?
6186 if (!pi.grantUriPermissions) {
6187 throw new SecurityException("Provider " + pi.packageName
6188 + "/" + pi.name
6189 + " does not allow granting of Uri permissions (uri "
6190 + uri + ")");
6191 }
6192 if (pi.uriPermissionPatterns != null) {
6193 final int N = pi.uriPermissionPatterns.length;
6194 boolean allowed = false;
6195 for (int i=0; i<N; i++) {
6196 if (pi.uriPermissionPatterns[i] != null
6197 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
6198 allowed = true;
6199 break;
6200 }
6201 }
6202 if (!allowed) {
6203 throw new SecurityException("Provider " + pi.packageName
6204 + "/" + pi.name
6205 + " does not allow granting of permission to path of Uri "
6206 + uri);
6207 }
6208 }
6209
6210 // Fourth... does the caller itself have permission to access
6211 // this uri?
6212 if (!checkHoldingPermissionsLocked(pm, pi, callingUid, modeFlags)) {
6213 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
6214 throw new SecurityException("Uid " + callingUid
6215 + " does not have permission to uri " + uri);
6216 }
6217 }
6218
6219 // Okay! So here we are: the caller has the assumed permission
6220 // to the uri, and the target doesn't. Let's now give this to
6221 // the target.
6222
6223 HashMap<Uri, UriPermission> targetUris
6224 = mGrantedUriPermissions.get(targetUid);
6225 if (targetUris == null) {
6226 targetUris = new HashMap<Uri, UriPermission>();
6227 mGrantedUriPermissions.put(targetUid, targetUris);
6228 }
6229
6230 UriPermission perm = targetUris.get(uri);
6231 if (perm == null) {
6232 perm = new UriPermission(targetUid, uri);
6233 targetUris.put(uri, perm);
6234
6235 }
6236 perm.modeFlags |= modeFlags;
6237 if (activity == null) {
6238 perm.globalModeFlags |= modeFlags;
6239 } else if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
6240 perm.readActivities.add(activity);
6241 if (activity.readUriPermissions == null) {
6242 activity.readUriPermissions = new HashSet<UriPermission>();
6243 }
6244 activity.readUriPermissions.add(perm);
6245 } else if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
6246 perm.writeActivities.add(activity);
6247 if (activity.writeUriPermissions == null) {
6248 activity.writeUriPermissions = new HashSet<UriPermission>();
6249 }
6250 activity.writeUriPermissions.add(perm);
6251 }
6252 }
6253
6254 private void grantUriPermissionFromIntentLocked(int callingUid,
6255 String targetPkg, Intent intent, HistoryRecord activity) {
6256 if (intent == null) {
6257 return;
6258 }
6259 Uri data = intent.getData();
6260 if (data == null) {
6261 return;
6262 }
6263 grantUriPermissionLocked(callingUid, targetPkg, data,
6264 intent.getFlags(), activity);
6265 }
6266
6267 public void grantUriPermission(IApplicationThread caller, String targetPkg,
6268 Uri uri, int modeFlags) {
6269 synchronized(this) {
6270 final ProcessRecord r = getRecordForAppLocked(caller);
6271 if (r == null) {
6272 throw new SecurityException("Unable to find app for caller "
6273 + caller
6274 + " when granting permission to uri " + uri);
6275 }
6276 if (targetPkg == null) {
6277 Log.w(TAG, "grantUriPermission: null target");
6278 return;
6279 }
6280 if (uri == null) {
6281 Log.w(TAG, "grantUriPermission: null uri");
6282 return;
6283 }
6284
6285 grantUriPermissionLocked(r.info.uid, targetPkg, uri, modeFlags,
6286 null);
6287 }
6288 }
6289
6290 private void removeUriPermissionIfNeededLocked(UriPermission perm) {
6291 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
6292 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
6293 HashMap<Uri, UriPermission> perms
6294 = mGrantedUriPermissions.get(perm.uid);
6295 if (perms != null) {
6296 perms.remove(perm.uri);
6297 if (perms.size() == 0) {
6298 mGrantedUriPermissions.remove(perm.uid);
6299 }
6300 }
6301 }
6302 }
6303
6304 private void removeActivityUriPermissionsLocked(HistoryRecord activity) {
6305 if (activity.readUriPermissions != null) {
6306 for (UriPermission perm : activity.readUriPermissions) {
6307 perm.readActivities.remove(activity);
6308 if (perm.readActivities.size() == 0 && (perm.globalModeFlags
6309 &Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0) {
6310 perm.modeFlags &= ~Intent.FLAG_GRANT_READ_URI_PERMISSION;
6311 removeUriPermissionIfNeededLocked(perm);
6312 }
6313 }
6314 }
6315 if (activity.writeUriPermissions != null) {
6316 for (UriPermission perm : activity.writeUriPermissions) {
6317 perm.writeActivities.remove(activity);
6318 if (perm.writeActivities.size() == 0 && (perm.globalModeFlags
6319 &Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0) {
6320 perm.modeFlags &= ~Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
6321 removeUriPermissionIfNeededLocked(perm);
6322 }
6323 }
6324 }
6325 }
6326
6327 private void revokeUriPermissionLocked(int callingUid, Uri uri,
6328 int modeFlags) {
6329 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
6330 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
6331 if (modeFlags == 0) {
6332 return;
6333 }
6334
6335 final IPackageManager pm = ActivityThread.getPackageManager();
6336
6337 final String authority = uri.getAuthority();
6338 ProviderInfo pi = null;
6339 ContentProviderRecord cpr
6340 = (ContentProviderRecord)mProvidersByName.get(authority);
6341 if (cpr != null) {
6342 pi = cpr.info;
6343 } else {
6344 try {
6345 pi = pm.resolveContentProvider(authority,
6346 PackageManager.GET_URI_PERMISSION_PATTERNS);
6347 } catch (RemoteException ex) {
6348 }
6349 }
6350 if (pi == null) {
6351 Log.w(TAG, "No content provider found for: " + authority);
6352 return;
6353 }
6354
6355 // Does the caller have this permission on the URI?
6356 if (!checkHoldingPermissionsLocked(pm, pi, callingUid, modeFlags)) {
6357 // Right now, if you are not the original owner of the permission,
6358 // you are not allowed to revoke it.
6359 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
6360 throw new SecurityException("Uid " + callingUid
6361 + " does not have permission to uri " + uri);
6362 //}
6363 }
6364
6365 // Go through all of the permissions and remove any that match.
6366 final List<String> SEGMENTS = uri.getPathSegments();
6367 if (SEGMENTS != null) {
6368 final int NS = SEGMENTS.size();
6369 int N = mGrantedUriPermissions.size();
6370 for (int i=0; i<N; i++) {
6371 HashMap<Uri, UriPermission> perms
6372 = mGrantedUriPermissions.valueAt(i);
6373 Iterator<UriPermission> it = perms.values().iterator();
6374 toploop:
6375 while (it.hasNext()) {
6376 UriPermission perm = it.next();
6377 Uri targetUri = perm.uri;
6378 if (!authority.equals(targetUri.getAuthority())) {
6379 continue;
6380 }
6381 List<String> targetSegments = targetUri.getPathSegments();
6382 if (targetSegments == null) {
6383 continue;
6384 }
6385 if (targetSegments.size() < NS) {
6386 continue;
6387 }
6388 for (int j=0; j<NS; j++) {
6389 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
6390 continue toploop;
6391 }
6392 }
6393 perm.clearModes(modeFlags);
6394 if (perm.modeFlags == 0) {
6395 it.remove();
6396 }
6397 }
6398 if (perms.size() == 0) {
6399 mGrantedUriPermissions.remove(
6400 mGrantedUriPermissions.keyAt(i));
6401 N--;
6402 i--;
6403 }
6404 }
6405 }
6406 }
6407
6408 public void revokeUriPermission(IApplicationThread caller, Uri uri,
6409 int modeFlags) {
6410 synchronized(this) {
6411 final ProcessRecord r = getRecordForAppLocked(caller);
6412 if (r == null) {
6413 throw new SecurityException("Unable to find app for caller "
6414 + caller
6415 + " when revoking permission to uri " + uri);
6416 }
6417 if (uri == null) {
6418 Log.w(TAG, "revokeUriPermission: null uri");
6419 return;
6420 }
6421
6422 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
6423 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
6424 if (modeFlags == 0) {
6425 return;
6426 }
6427
6428 final IPackageManager pm = ActivityThread.getPackageManager();
6429
6430 final String authority = uri.getAuthority();
6431 ProviderInfo pi = null;
6432 ContentProviderRecord cpr
6433 = (ContentProviderRecord)mProvidersByName.get(authority);
6434 if (cpr != null) {
6435 pi = cpr.info;
6436 } else {
6437 try {
6438 pi = pm.resolveContentProvider(authority,
6439 PackageManager.GET_URI_PERMISSION_PATTERNS);
6440 } catch (RemoteException ex) {
6441 }
6442 }
6443 if (pi == null) {
6444 Log.w(TAG, "No content provider found for: " + authority);
6445 return;
6446 }
6447
6448 revokeUriPermissionLocked(r.info.uid, uri, modeFlags);
6449 }
6450 }
6451
6452 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
6453 synchronized (this) {
6454 ProcessRecord app =
6455 who != null ? getRecordForAppLocked(who) : null;
6456 if (app == null) return;
6457
6458 Message msg = Message.obtain();
6459 msg.what = WAIT_FOR_DEBUGGER_MSG;
6460 msg.obj = app;
6461 msg.arg1 = waiting ? 1 : 0;
6462 mHandler.sendMessage(msg);
6463 }
6464 }
6465
6466 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
6467 outInfo.availMem = Process.getFreeMemory();
The Android Open Source Project4df24232009-03-05 14:34:35 -08006468 outInfo.threshold = HOME_APP_MEM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006469 outInfo.lowMemory = outInfo.availMem <
The Android Open Source Project4df24232009-03-05 14:34:35 -08006470 (HOME_APP_MEM + ((HIDDEN_APP_MEM-HOME_APP_MEM)/2));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006471 }
6472
6473 // =========================================================
6474 // TASK MANAGEMENT
6475 // =========================================================
6476
6477 public List getTasks(int maxNum, int flags,
6478 IThumbnailReceiver receiver) {
6479 ArrayList list = new ArrayList();
6480
6481 PendingThumbnailsRecord pending = null;
6482 IApplicationThread topThumbnail = null;
6483 HistoryRecord topRecord = null;
6484
6485 synchronized(this) {
6486 if (localLOGV) Log.v(
6487 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
6488 + ", receiver=" + receiver);
6489
6490 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
6491 != PackageManager.PERMISSION_GRANTED) {
6492 if (receiver != null) {
6493 // If the caller wants to wait for pending thumbnails,
6494 // it ain't gonna get them.
6495 try {
6496 receiver.finished();
6497 } catch (RemoteException ex) {
6498 }
6499 }
6500 String msg = "Permission Denial: getTasks() from pid="
6501 + Binder.getCallingPid()
6502 + ", uid=" + Binder.getCallingUid()
6503 + " requires " + android.Manifest.permission.GET_TASKS;
6504 Log.w(TAG, msg);
6505 throw new SecurityException(msg);
6506 }
6507
6508 int pos = mHistory.size()-1;
6509 HistoryRecord next =
6510 pos >= 0 ? (HistoryRecord)mHistory.get(pos) : null;
6511 HistoryRecord top = null;
6512 CharSequence topDescription = null;
6513 TaskRecord curTask = null;
6514 int numActivities = 0;
6515 int numRunning = 0;
6516 while (pos >= 0 && maxNum > 0) {
6517 final HistoryRecord r = next;
6518 pos--;
6519 next = pos >= 0 ? (HistoryRecord)mHistory.get(pos) : null;
6520
6521 // Initialize state for next task if needed.
6522 if (top == null ||
6523 (top.state == ActivityState.INITIALIZING
6524 && top.task == r.task)) {
6525 top = r;
6526 topDescription = r.description;
6527 curTask = r.task;
6528 numActivities = numRunning = 0;
6529 }
6530
6531 // Add 'r' into the current task.
6532 numActivities++;
6533 if (r.app != null && r.app.thread != null) {
6534 numRunning++;
6535 }
6536 if (topDescription == null) {
6537 topDescription = r.description;
6538 }
6539
6540 if (localLOGV) Log.v(
6541 TAG, r.intent.getComponent().flattenToShortString()
6542 + ": task=" + r.task);
6543
6544 // If the next one is a different task, generate a new
6545 // TaskInfo entry for what we have.
6546 if (next == null || next.task != curTask) {
6547 ActivityManager.RunningTaskInfo ci
6548 = new ActivityManager.RunningTaskInfo();
6549 ci.id = curTask.taskId;
6550 ci.baseActivity = r.intent.getComponent();
6551 ci.topActivity = top.intent.getComponent();
6552 ci.thumbnail = top.thumbnail;
6553 ci.description = topDescription;
6554 ci.numActivities = numActivities;
6555 ci.numRunning = numRunning;
6556 //System.out.println(
6557 // "#" + maxNum + ": " + " descr=" + ci.description);
6558 if (ci.thumbnail == null && receiver != null) {
6559 if (localLOGV) Log.v(
6560 TAG, "State=" + top.state + "Idle=" + top.idle
6561 + " app=" + top.app
6562 + " thr=" + (top.app != null ? top.app.thread : null));
6563 if (top.state == ActivityState.RESUMED
6564 || top.state == ActivityState.PAUSING) {
6565 if (top.idle && top.app != null
6566 && top.app.thread != null) {
6567 topRecord = top;
6568 topThumbnail = top.app.thread;
6569 } else {
6570 top.thumbnailNeeded = true;
6571 }
6572 }
6573 if (pending == null) {
6574 pending = new PendingThumbnailsRecord(receiver);
6575 }
6576 pending.pendingRecords.add(top);
6577 }
6578 list.add(ci);
6579 maxNum--;
6580 top = null;
6581 }
6582 }
6583
6584 if (pending != null) {
6585 mPendingThumbnails.add(pending);
6586 }
6587 }
6588
6589 if (localLOGV) Log.v(TAG, "We have pending thumbnails: " + pending);
6590
6591 if (topThumbnail != null) {
6592 if (localLOGV) Log.v(TAG, "Requesting top thumbnail");
6593 try {
6594 topThumbnail.requestThumbnail(topRecord);
6595 } catch (Exception e) {
6596 Log.w(TAG, "Exception thrown when requesting thumbnail", e);
6597 sendPendingThumbnail(null, topRecord, null, null, true);
6598 }
6599 }
6600
6601 if (pending == null && receiver != null) {
6602 // In this case all thumbnails were available and the client
6603 // is being asked to be told when the remaining ones come in...
6604 // which is unusually, since the top-most currently running
6605 // activity should never have a canned thumbnail! Oh well.
6606 try {
6607 receiver.finished();
6608 } catch (RemoteException ex) {
6609 }
6610 }
6611
6612 return list;
6613 }
6614
6615 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
6616 int flags) {
6617 synchronized (this) {
6618 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
6619 "getRecentTasks()");
6620
6621 final int N = mRecentTasks.size();
6622 ArrayList<ActivityManager.RecentTaskInfo> res
6623 = new ArrayList<ActivityManager.RecentTaskInfo>(
6624 maxNum < N ? maxNum : N);
6625 for (int i=0; i<N && maxNum > 0; i++) {
6626 TaskRecord tr = mRecentTasks.get(i);
6627 if (((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
6628 || (tr.intent == null)
6629 || ((tr.intent.getFlags()
6630 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
6631 ActivityManager.RecentTaskInfo rti
6632 = new ActivityManager.RecentTaskInfo();
6633 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
6634 rti.baseIntent = new Intent(
6635 tr.intent != null ? tr.intent : tr.affinityIntent);
6636 rti.origActivity = tr.origActivity;
6637 res.add(rti);
6638 maxNum--;
6639 }
6640 }
6641 return res;
6642 }
6643 }
6644
6645 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
6646 int j;
6647 TaskRecord startTask = ((HistoryRecord)mHistory.get(startIndex)).task;
6648 TaskRecord jt = startTask;
6649
6650 // First look backwards
6651 for (j=startIndex-1; j>=0; j--) {
6652 HistoryRecord r = (HistoryRecord)mHistory.get(j);
6653 if (r.task != jt) {
6654 jt = r.task;
6655 if (affinity.equals(jt.affinity)) {
6656 return j;
6657 }
6658 }
6659 }
6660
6661 // Now look forwards
6662 final int N = mHistory.size();
6663 jt = startTask;
6664 for (j=startIndex+1; j<N; j++) {
6665 HistoryRecord r = (HistoryRecord)mHistory.get(j);
6666 if (r.task != jt) {
6667 if (affinity.equals(jt.affinity)) {
6668 return j;
6669 }
6670 jt = r.task;
6671 }
6672 }
6673
6674 // Might it be at the top?
6675 if (affinity.equals(((HistoryRecord)mHistory.get(N-1)).task.affinity)) {
6676 return N-1;
6677 }
6678
6679 return -1;
6680 }
6681
6682 /**
6683 * Perform a reset of the given task, if needed as part of launching it.
6684 * Returns the new HistoryRecord at the top of the task.
6685 */
6686 private final HistoryRecord resetTaskIfNeededLocked(HistoryRecord taskTop,
6687 HistoryRecord newActivity) {
6688 boolean forceReset = (newActivity.info.flags
6689 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
6690 if (taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
6691 if ((newActivity.info.flags
6692 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
6693 forceReset = true;
6694 }
6695 }
6696
6697 final TaskRecord task = taskTop.task;
6698
6699 // We are going to move through the history list so that we can look
6700 // at each activity 'target' with 'below' either the interesting
6701 // activity immediately below it in the stack or null.
6702 HistoryRecord target = null;
6703 int targetI = 0;
6704 int taskTopI = -1;
6705 int replyChainEnd = -1;
6706 int lastReparentPos = -1;
6707 for (int i=mHistory.size()-1; i>=-1; i--) {
6708 HistoryRecord below = i >= 0 ? (HistoryRecord)mHistory.get(i) : null;
6709
6710 if (below != null && below.finishing) {
6711 continue;
6712 }
6713 if (target == null) {
6714 target = below;
6715 targetI = i;
6716 // If we were in the middle of a reply chain before this
6717 // task, it doesn't appear like the root of the chain wants
6718 // anything interesting, so drop it.
6719 replyChainEnd = -1;
6720 continue;
6721 }
6722
6723 final int flags = target.info.flags;
6724
6725 final boolean finishOnTaskLaunch =
6726 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
6727 final boolean allowTaskReparenting =
6728 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
6729
6730 if (target.task == task) {
6731 // We are inside of the task being reset... we'll either
6732 // finish this activity, push it out for another task,
6733 // or leave it as-is. We only do this
6734 // for activities that are not the root of the task (since
6735 // if we finish the root, we may no longer have the task!).
6736 if (taskTopI < 0) {
6737 taskTopI = targetI;
6738 }
6739 if (below != null && below.task == task) {
6740 final boolean clearWhenTaskReset =
6741 (target.intent.getFlags()
6742 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
Ed Heyl73798232009-03-24 21:32:21 -07006743 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006744 // If this activity is sending a reply to a previous
6745 // activity, we can't do anything with it now until
6746 // we reach the start of the reply chain.
6747 // XXX note that we are assuming the result is always
6748 // to the previous activity, which is almost always
6749 // the case but we really shouldn't count on.
6750 if (replyChainEnd < 0) {
6751 replyChainEnd = targetI;
6752 }
Ed Heyl73798232009-03-24 21:32:21 -07006753 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006754 && target.taskAffinity != null
6755 && !target.taskAffinity.equals(task.affinity)) {
6756 // If this activity has an affinity for another
6757 // task, then we need to move it out of here. We will
6758 // move it as far out of the way as possible, to the
6759 // bottom of the activity stack. This also keeps it
6760 // correctly ordered with any activities we previously
6761 // moved.
6762 HistoryRecord p = (HistoryRecord)mHistory.get(0);
6763 if (target.taskAffinity != null
6764 && target.taskAffinity.equals(p.task.affinity)) {
6765 // If the activity currently at the bottom has the
6766 // same task affinity as the one we are moving,
6767 // then merge it into the same task.
6768 target.task = p.task;
6769 if (DEBUG_TASKS) Log.v(TAG, "Start pushing activity " + target
6770 + " out to bottom task " + p.task);
6771 } else {
6772 mCurTask++;
6773 if (mCurTask <= 0) {
6774 mCurTask = 1;
6775 }
6776 target.task = new TaskRecord(mCurTask, target.info, null,
6777 (target.info.flags&ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0);
6778 target.task.affinityIntent = target.intent;
6779 if (DEBUG_TASKS) Log.v(TAG, "Start pushing activity " + target
6780 + " out to new task " + target.task);
6781 }
6782 mWindowManager.setAppGroupId(target, task.taskId);
6783 if (replyChainEnd < 0) {
6784 replyChainEnd = targetI;
6785 }
6786 int dstPos = 0;
6787 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
6788 p = (HistoryRecord)mHistory.get(srcPos);
6789 if (p.finishing) {
6790 continue;
6791 }
6792 if (DEBUG_TASKS) Log.v(TAG, "Pushing next activity " + p
6793 + " out to target's task " + target.task);
6794 task.numActivities--;
6795 p.task = target.task;
6796 target.task.numActivities++;
6797 mHistory.remove(srcPos);
6798 mHistory.add(dstPos, p);
6799 mWindowManager.moveAppToken(dstPos, p);
6800 mWindowManager.setAppGroupId(p, p.task.taskId);
6801 dstPos++;
6802 if (VALIDATE_TOKENS) {
6803 mWindowManager.validateAppTokens(mHistory);
6804 }
6805 i++;
6806 }
6807 if (taskTop == p) {
6808 taskTop = below;
6809 }
6810 if (taskTopI == replyChainEnd) {
6811 taskTopI = -1;
6812 }
6813 replyChainEnd = -1;
6814 addRecentTask(target.task);
6815 } else if (forceReset || finishOnTaskLaunch
6816 || clearWhenTaskReset) {
6817 // If the activity should just be removed -- either
6818 // because it asks for it, or the task should be
6819 // cleared -- then finish it and anything that is
6820 // part of its reply chain.
6821 if (clearWhenTaskReset) {
6822 // In this case, we want to finish this activity
6823 // and everything above it, so be sneaky and pretend
6824 // like these are all in the reply chain.
6825 replyChainEnd = targetI+1;
6826 while (replyChainEnd < mHistory.size() &&
6827 ((HistoryRecord)mHistory.get(
6828 replyChainEnd)).task == task) {
6829 replyChainEnd++;
6830 }
6831 replyChainEnd--;
6832 } else if (replyChainEnd < 0) {
6833 replyChainEnd = targetI;
6834 }
6835 HistoryRecord p = null;
6836 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
6837 p = (HistoryRecord)mHistory.get(srcPos);
6838 if (p.finishing) {
6839 continue;
6840 }
6841 if (finishActivityLocked(p, srcPos,
6842 Activity.RESULT_CANCELED, null, "reset")) {
6843 replyChainEnd--;
6844 srcPos--;
6845 }
6846 }
6847 if (taskTop == p) {
6848 taskTop = below;
6849 }
6850 if (taskTopI == replyChainEnd) {
6851 taskTopI = -1;
6852 }
6853 replyChainEnd = -1;
6854 } else {
6855 // If we were in the middle of a chain, well the
6856 // activity that started it all doesn't want anything
6857 // special, so leave it all as-is.
6858 replyChainEnd = -1;
6859 }
6860 } else {
6861 // Reached the bottom of the task -- any reply chain
6862 // should be left as-is.
6863 replyChainEnd = -1;
6864 }
6865
6866 } else if (target.resultTo != null) {
6867 // If this activity is sending a reply to a previous
6868 // activity, we can't do anything with it now until
6869 // we reach the start of the reply chain.
6870 // XXX note that we are assuming the result is always
6871 // to the previous activity, which is almost always
6872 // the case but we really shouldn't count on.
6873 if (replyChainEnd < 0) {
6874 replyChainEnd = targetI;
6875 }
6876
6877 } else if (taskTopI >= 0 && allowTaskReparenting
6878 && task.affinity != null
6879 && task.affinity.equals(target.taskAffinity)) {
6880 // We are inside of another task... if this activity has
6881 // an affinity for our task, then either remove it if we are
6882 // clearing or move it over to our task. Note that
6883 // we currently punt on the case where we are resetting a
6884 // task that is not at the top but who has activities above
6885 // with an affinity to it... this is really not a normal
6886 // case, and we will need to later pull that task to the front
6887 // and usually at that point we will do the reset and pick
6888 // up those remaining activities. (This only happens if
6889 // someone starts an activity in a new task from an activity
6890 // in a task that is not currently on top.)
6891 if (forceReset || finishOnTaskLaunch) {
6892 if (replyChainEnd < 0) {
6893 replyChainEnd = targetI;
6894 }
6895 HistoryRecord p = null;
6896 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
6897 p = (HistoryRecord)mHistory.get(srcPos);
6898 if (p.finishing) {
6899 continue;
6900 }
6901 if (finishActivityLocked(p, srcPos,
6902 Activity.RESULT_CANCELED, null, "reset")) {
6903 taskTopI--;
6904 lastReparentPos--;
6905 replyChainEnd--;
6906 srcPos--;
6907 }
6908 }
6909 replyChainEnd = -1;
6910 } else {
6911 if (replyChainEnd < 0) {
6912 replyChainEnd = targetI;
6913 }
6914 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
6915 HistoryRecord p = (HistoryRecord)mHistory.get(srcPos);
6916 if (p.finishing) {
6917 continue;
6918 }
6919 if (lastReparentPos < 0) {
6920 lastReparentPos = taskTopI;
6921 taskTop = p;
6922 } else {
6923 lastReparentPos--;
6924 }
6925 mHistory.remove(srcPos);
6926 p.task.numActivities--;
6927 p.task = task;
6928 mHistory.add(lastReparentPos, p);
6929 if (DEBUG_TASKS) Log.v(TAG, "Pulling activity " + p
6930 + " in to resetting task " + task);
6931 task.numActivities++;
6932 mWindowManager.moveAppToken(lastReparentPos, p);
6933 mWindowManager.setAppGroupId(p, p.task.taskId);
6934 if (VALIDATE_TOKENS) {
6935 mWindowManager.validateAppTokens(mHistory);
6936 }
6937 }
6938 replyChainEnd = -1;
6939
6940 // Now we've moved it in to place... but what if this is
6941 // a singleTop activity and we have put it on top of another
6942 // instance of the same activity? Then we drop the instance
6943 // below so it remains singleTop.
6944 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
6945 for (int j=lastReparentPos-1; j>=0; j--) {
6946 HistoryRecord p = (HistoryRecord)mHistory.get(j);
6947 if (p.finishing) {
6948 continue;
6949 }
6950 if (p.intent.getComponent().equals(target.intent.getComponent())) {
6951 if (finishActivityLocked(p, j,
6952 Activity.RESULT_CANCELED, null, "replace")) {
6953 taskTopI--;
6954 lastReparentPos--;
6955 }
6956 }
6957 }
6958 }
6959 }
6960 }
6961
6962 target = below;
6963 targetI = i;
6964 }
6965
6966 return taskTop;
6967 }
6968
6969 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006970 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006971 */
6972 public void moveTaskToFront(int task) {
6973 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6974 "moveTaskToFront()");
6975
6976 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006977 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6978 Binder.getCallingUid(), "Task to front")) {
6979 return;
6980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006981 final long origId = Binder.clearCallingIdentity();
6982 try {
6983 int N = mRecentTasks.size();
6984 for (int i=0; i<N; i++) {
6985 TaskRecord tr = mRecentTasks.get(i);
6986 if (tr.taskId == task) {
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07006987 moveTaskToFrontLocked(tr, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006988 return;
6989 }
6990 }
6991 for (int i=mHistory.size()-1; i>=0; i--) {
6992 HistoryRecord hr = (HistoryRecord)mHistory.get(i);
6993 if (hr.task.taskId == task) {
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07006994 moveTaskToFrontLocked(hr.task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006995 return;
6996 }
6997 }
6998 } finally {
6999 Binder.restoreCallingIdentity(origId);
7000 }
7001 }
7002 }
7003
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07007004 private final void moveTaskToFrontLocked(TaskRecord tr, HistoryRecord reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007005 if (DEBUG_SWITCH) Log.v(TAG, "moveTaskToFront: " + tr);
7006
7007 final int task = tr.taskId;
7008 int top = mHistory.size()-1;
7009
7010 if (top < 0 || ((HistoryRecord)mHistory.get(top)).task.taskId == task) {
7011 // nothing to do!
7012 return;
7013 }
7014
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007015 ArrayList moved = new ArrayList();
7016
7017 // Applying the affinities may have removed entries from the history,
7018 // so get the size again.
7019 top = mHistory.size()-1;
7020 int pos = top;
7021
7022 // Shift all activities with this task up to the top
7023 // of the stack, keeping them in the same internal order.
7024 while (pos >= 0) {
7025 HistoryRecord r = (HistoryRecord)mHistory.get(pos);
7026 if (localLOGV) Log.v(
7027 TAG, "At " + pos + " ckp " + r.task + ": " + r);
7028 boolean first = true;
7029 if (r.task.taskId == task) {
7030 if (localLOGV) Log.v(TAG, "Removing and adding at " + top);
7031 mHistory.remove(pos);
7032 mHistory.add(top, r);
7033 moved.add(0, r);
7034 top--;
7035 if (first) {
7036 addRecentTask(r.task);
7037 first = false;
7038 }
7039 }
7040 pos--;
7041 }
7042
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07007043 if (DEBUG_TRANSITION) Log.v(TAG,
7044 "Prepare to front transition: task=" + tr);
7045 if (reason != null &&
7046 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
7047 mWindowManager.prepareAppTransition(WindowManagerPolicy.TRANSIT_NONE);
7048 HistoryRecord r = topRunningActivityLocked(null);
7049 if (r != null) {
7050 mNoAnimActivities.add(r);
7051 }
7052 } else {
7053 mWindowManager.prepareAppTransition(WindowManagerPolicy.TRANSIT_TASK_TO_FRONT);
7054 }
7055
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007056 mWindowManager.moveAppTokensToTop(moved);
7057 if (VALIDATE_TOKENS) {
7058 mWindowManager.validateAppTokens(mHistory);
7059 }
7060
7061 finishTaskMove(task);
Doug Zongker2bec3d42009-12-04 12:52:44 -08007062 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007063 }
7064
7065 private final void finishTaskMove(int task) {
7066 resumeTopActivityLocked(null);
7067 }
7068
7069 public void moveTaskToBack(int task) {
7070 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
7071 "moveTaskToBack()");
7072
7073 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007074 if (mResumedActivity != null && mResumedActivity.task.taskId == task) {
7075 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
7076 Binder.getCallingUid(), "Task to back")) {
7077 return;
7078 }
7079 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007080 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07007081 moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007082 Binder.restoreCallingIdentity(origId);
7083 }
7084 }
7085
7086 /**
7087 * Moves an activity, and all of the other activities within the same task, to the bottom
7088 * of the history stack. The activity's order within the task is unchanged.
7089 *
7090 * @param token A reference to the activity we wish to move
7091 * @param nonRoot If false then this only works if the activity is the root
7092 * of a task; if true it will work for any activity in a task.
7093 * @return Returns true if the move completed, false if not.
7094 */
7095 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
7096 synchronized(this) {
7097 final long origId = Binder.clearCallingIdentity();
7098 int taskId = getTaskForActivityLocked(token, !nonRoot);
7099 if (taskId >= 0) {
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07007100 return moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007101 }
7102 Binder.restoreCallingIdentity(origId);
7103 }
7104 return false;
7105 }
7106
7107 /**
7108 * Worker method for rearranging history stack. Implements the function of moving all
7109 * activities for a specific task (gathering them if disjoint) into a single group at the
7110 * bottom of the stack.
7111 *
7112 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
7113 * to premeptively cancel the move.
7114 *
7115 * @param task The taskId to collect and move to the bottom.
7116 * @return Returns true if the move completed, false if not.
7117 */
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07007118 private final boolean moveTaskToBackLocked(int task, HistoryRecord reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007119 Log.i(TAG, "moveTaskToBack: " + task);
7120
7121 // If we have a watcher, preflight the move before committing to it. First check
7122 // for *other* available tasks, but if none are available, then try again allowing the
7123 // current task to be selected.
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007124 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007125 HistoryRecord next = topRunningActivityLocked(null, task);
7126 if (next == null) {
7127 next = topRunningActivityLocked(null, 0);
7128 }
7129 if (next != null) {
7130 // ask watcher if this is allowed
7131 boolean moveOK = true;
7132 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007133 moveOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007134 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007135 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007136 }
7137 if (!moveOK) {
7138 return false;
7139 }
7140 }
7141 }
7142
7143 ArrayList moved = new ArrayList();
7144
7145 if (DEBUG_TRANSITION) Log.v(TAG,
7146 "Prepare to back transition: task=" + task);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007147
7148 final int N = mHistory.size();
7149 int bottom = 0;
7150 int pos = 0;
7151
7152 // Shift all activities with this task down to the bottom
7153 // of the stack, keeping them in the same internal order.
7154 while (pos < N) {
7155 HistoryRecord r = (HistoryRecord)mHistory.get(pos);
7156 if (localLOGV) Log.v(
7157 TAG, "At " + pos + " ckp " + r.task + ": " + r);
7158 if (r.task.taskId == task) {
7159 if (localLOGV) Log.v(TAG, "Removing and adding at " + (N-1));
7160 mHistory.remove(pos);
7161 mHistory.add(bottom, r);
7162 moved.add(r);
7163 bottom++;
7164 }
7165 pos++;
7166 }
7167
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07007168 if (reason != null &&
7169 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
7170 mWindowManager.prepareAppTransition(WindowManagerPolicy.TRANSIT_NONE);
7171 HistoryRecord r = topRunningActivityLocked(null);
7172 if (r != null) {
7173 mNoAnimActivities.add(r);
7174 }
7175 } else {
Suchi Amalapurapuc9568e32009-11-05 18:51:16 -08007176 mWindowManager.prepareAppTransition(WindowManagerPolicy.TRANSIT_TASK_TO_BACK);
Dianne Hackbornbfe319e2009-09-21 00:34:05 -07007177 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007178 mWindowManager.moveAppTokensToBottom(moved);
7179 if (VALIDATE_TOKENS) {
7180 mWindowManager.validateAppTokens(mHistory);
7181 }
7182
7183 finishTaskMove(task);
7184 return true;
7185 }
7186
7187 public void moveTaskBackwards(int task) {
7188 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
7189 "moveTaskBackwards()");
7190
7191 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007192 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
7193 Binder.getCallingUid(), "Task backwards")) {
7194 return;
7195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007196 final long origId = Binder.clearCallingIdentity();
7197 moveTaskBackwardsLocked(task);
7198 Binder.restoreCallingIdentity(origId);
7199 }
7200 }
7201
7202 private final void moveTaskBackwardsLocked(int task) {
7203 Log.e(TAG, "moveTaskBackwards not yet implemented!");
7204 }
7205
7206 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
7207 synchronized(this) {
7208 return getTaskForActivityLocked(token, onlyRoot);
7209 }
7210 }
7211
7212 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
7213 final int N = mHistory.size();
7214 TaskRecord lastTask = null;
7215 for (int i=0; i<N; i++) {
7216 HistoryRecord r = (HistoryRecord)mHistory.get(i);
7217 if (r == token) {
7218 if (!onlyRoot || lastTask != r.task) {
7219 return r.task.taskId;
7220 }
7221 return -1;
7222 }
7223 lastTask = r.task;
7224 }
7225
7226 return -1;
7227 }
7228
7229 /**
7230 * Returns the top activity in any existing task matching the given
7231 * Intent. Returns null if no such task is found.
7232 */
7233 private HistoryRecord findTaskLocked(Intent intent, ActivityInfo info) {
7234 ComponentName cls = intent.getComponent();
7235 if (info.targetActivity != null) {
7236 cls = new ComponentName(info.packageName, info.targetActivity);
7237 }
7238
7239 TaskRecord cp = null;
7240
7241 final int N = mHistory.size();
7242 for (int i=(N-1); i>=0; i--) {
7243 HistoryRecord r = (HistoryRecord)mHistory.get(i);
7244 if (!r.finishing && r.task != cp
7245 && r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
7246 cp = r.task;
7247 //Log.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
7248 // + "/aff=" + r.task.affinity + " to new cls="
7249 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
7250 if (r.task.affinity != null) {
7251 if (r.task.affinity.equals(info.taskAffinity)) {
7252 //Log.i(TAG, "Found matching affinity!");
7253 return r;
7254 }
7255 } else if (r.task.intent != null
7256 && r.task.intent.getComponent().equals(cls)) {
7257 //Log.i(TAG, "Found matching class!");
7258 //dump();
7259 //Log.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
7260 return r;
7261 } else if (r.task.affinityIntent != null
7262 && r.task.affinityIntent.getComponent().equals(cls)) {
7263 //Log.i(TAG, "Found matching class!");
7264 //dump();
7265 //Log.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
7266 return r;
7267 }
7268 }
7269 }
7270
7271 return null;
7272 }
7273
7274 /**
7275 * Returns the first activity (starting from the top of the stack) that
7276 * is the same as the given activity. Returns null if no such activity
7277 * is found.
7278 */
7279 private HistoryRecord findActivityLocked(Intent intent, ActivityInfo info) {
7280 ComponentName cls = intent.getComponent();
7281 if (info.targetActivity != null) {
7282 cls = new ComponentName(info.packageName, info.targetActivity);
7283 }
7284
7285 final int N = mHistory.size();
7286 for (int i=(N-1); i>=0; i--) {
7287 HistoryRecord r = (HistoryRecord)mHistory.get(i);
7288 if (!r.finishing) {
7289 if (r.intent.getComponent().equals(cls)) {
7290 //Log.i(TAG, "Found matching class!");
7291 //dump();
7292 //Log.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
7293 return r;
7294 }
7295 }
7296 }
7297
7298 return null;
7299 }
7300
7301 public void finishOtherInstances(IBinder token, ComponentName className) {
7302 synchronized(this) {
7303 final long origId = Binder.clearCallingIdentity();
7304
7305 int N = mHistory.size();
7306 TaskRecord lastTask = null;
7307 for (int i=0; i<N; i++) {
7308 HistoryRecord r = (HistoryRecord)mHistory.get(i);
7309 if (r.realActivity.equals(className)
7310 && r != token && lastTask != r.task) {
7311 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
7312 null, "others")) {
7313 i--;
7314 N--;
7315 }
7316 }
7317 lastTask = r.task;
7318 }
7319
7320 Binder.restoreCallingIdentity(origId);
7321 }
7322 }
7323
7324 // =========================================================
7325 // THUMBNAILS
7326 // =========================================================
7327
7328 public void reportThumbnail(IBinder token,
7329 Bitmap thumbnail, CharSequence description) {
7330 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
7331 final long origId = Binder.clearCallingIdentity();
7332 sendPendingThumbnail(null, token, thumbnail, description, true);
7333 Binder.restoreCallingIdentity(origId);
7334 }
7335
7336 final void sendPendingThumbnail(HistoryRecord r, IBinder token,
7337 Bitmap thumbnail, CharSequence description, boolean always) {
7338 TaskRecord task = null;
7339 ArrayList receivers = null;
7340
7341 //System.out.println("Send pending thumbnail: " + r);
7342
7343 synchronized(this) {
7344 if (r == null) {
Dianne Hackborn75b03852009-06-12 15:43:26 -07007345 int index = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007346 if (index < 0) {
7347 return;
7348 }
7349 r = (HistoryRecord)mHistory.get(index);
7350 }
7351 if (thumbnail == null) {
7352 thumbnail = r.thumbnail;
7353 description = r.description;
7354 }
7355 if (thumbnail == null && !always) {
7356 // If there is no thumbnail, and this entry is not actually
7357 // going away, then abort for now and pick up the next
7358 // thumbnail we get.
7359 return;
7360 }
7361 task = r.task;
7362
7363 int N = mPendingThumbnails.size();
7364 int i=0;
7365 while (i<N) {
7366 PendingThumbnailsRecord pr =
7367 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
7368 //System.out.println("Looking in " + pr.pendingRecords);
7369 if (pr.pendingRecords.remove(r)) {
7370 if (receivers == null) {
7371 receivers = new ArrayList();
7372 }
7373 receivers.add(pr);
7374 if (pr.pendingRecords.size() == 0) {
7375 pr.finished = true;
7376 mPendingThumbnails.remove(i);
7377 N--;
7378 continue;
7379 }
7380 }
7381 i++;
7382 }
7383 }
7384
7385 if (receivers != null) {
7386 final int N = receivers.size();
7387 for (int i=0; i<N; i++) {
7388 try {
7389 PendingThumbnailsRecord pr =
7390 (PendingThumbnailsRecord)receivers.get(i);
7391 pr.receiver.newThumbnail(
7392 task != null ? task.taskId : -1, thumbnail, description);
7393 if (pr.finished) {
7394 pr.receiver.finished();
7395 }
7396 } catch (Exception e) {
7397 Log.w(TAG, "Exception thrown when sending thumbnail", e);
7398 }
7399 }
7400 }
7401 }
7402
7403 // =========================================================
7404 // CONTENT PROVIDERS
7405 // =========================================================
7406
7407 private final List generateApplicationProvidersLocked(ProcessRecord app) {
7408 List providers = null;
7409 try {
7410 providers = ActivityThread.getPackageManager().
7411 queryContentProviders(app.processName, app.info.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07007412 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007413 } catch (RemoteException ex) {
7414 }
7415 if (providers != null) {
7416 final int N = providers.size();
7417 for (int i=0; i<N; i++) {
7418 ProviderInfo cpi =
7419 (ProviderInfo)providers.get(i);
7420 ContentProviderRecord cpr =
7421 (ContentProviderRecord)mProvidersByClass.get(cpi.name);
7422 if (cpr == null) {
7423 cpr = new ContentProviderRecord(cpi, app.info);
7424 mProvidersByClass.put(cpi.name, cpr);
7425 }
7426 app.pubProviders.put(cpi.name, cpr);
7427 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07007428 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007429 }
7430 }
7431 return providers;
7432 }
7433
7434 private final String checkContentProviderPermissionLocked(
7435 ProviderInfo cpi, ProcessRecord r, int mode) {
7436 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
7437 final int callingUid = (r != null) ? r.info.uid : Binder.getCallingUid();
7438 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
7439 cpi.exported ? -1 : cpi.applicationInfo.uid)
7440 == PackageManager.PERMISSION_GRANTED
7441 && mode == ParcelFileDescriptor.MODE_READ_ONLY || mode == -1) {
7442 return null;
7443 }
7444 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
7445 cpi.exported ? -1 : cpi.applicationInfo.uid)
7446 == PackageManager.PERMISSION_GRANTED) {
7447 return null;
7448 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07007449
7450 PathPermission[] pps = cpi.pathPermissions;
7451 if (pps != null) {
7452 int i = pps.length;
7453 while (i > 0) {
7454 i--;
7455 PathPermission pp = pps[i];
7456 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
7457 cpi.exported ? -1 : cpi.applicationInfo.uid)
7458 == PackageManager.PERMISSION_GRANTED
7459 && mode == ParcelFileDescriptor.MODE_READ_ONLY || mode == -1) {
7460 return null;
7461 }
7462 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
7463 cpi.exported ? -1 : cpi.applicationInfo.uid)
7464 == PackageManager.PERMISSION_GRANTED) {
7465 return null;
7466 }
7467 }
7468 }
7469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007470 String msg = "Permission Denial: opening provider " + cpi.name
7471 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
7472 + ", uid=" + callingUid + ") requires "
7473 + cpi.readPermission + " or " + cpi.writePermission;
7474 Log.w(TAG, msg);
7475 return msg;
7476 }
7477
7478 private final ContentProviderHolder getContentProviderImpl(
7479 IApplicationThread caller, String name) {
7480 ContentProviderRecord cpr;
7481 ProviderInfo cpi = null;
7482
7483 synchronized(this) {
7484 ProcessRecord r = null;
7485 if (caller != null) {
7486 r = getRecordForAppLocked(caller);
7487 if (r == null) {
7488 throw new SecurityException(
7489 "Unable to find app for caller " + caller
7490 + " (pid=" + Binder.getCallingPid()
7491 + ") when getting content provider " + name);
7492 }
7493 }
7494
7495 // First check if this content provider has been published...
7496 cpr = (ContentProviderRecord)mProvidersByName.get(name);
7497 if (cpr != null) {
7498 cpi = cpr.info;
7499 if (checkContentProviderPermissionLocked(cpi, r, -1) != null) {
7500 return new ContentProviderHolder(cpi,
7501 cpi.readPermission != null
7502 ? cpi.readPermission : cpi.writePermission);
7503 }
7504
7505 if (r != null && cpr.canRunHere(r)) {
7506 // This provider has been published or is in the process
7507 // of being published... but it is also allowed to run
7508 // in the caller's process, so don't make a connection
7509 // and just let the caller instantiate its own instance.
7510 if (cpr.provider != null) {
7511 // don't give caller the provider object, it needs
7512 // to make its own.
7513 cpr = new ContentProviderRecord(cpr);
7514 }
7515 return cpr;
7516 }
7517
7518 final long origId = Binder.clearCallingIdentity();
7519
Dianne Hackborna1e989b2009-09-01 19:54:29 -07007520 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007521 // return it right away.
7522 if (r != null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07007523 if (DEBUG_PROVIDER) Log.v(TAG,
7524 "Adding provider requested by "
7525 + r.processName + " from process "
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07007526 + cpr.info.processName);
7527 Integer cnt = r.conProviders.get(cpr);
7528 if (cnt == null) {
7529 r.conProviders.put(cpr, new Integer(1));
7530 } else {
7531 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
7532 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007533 cpr.clients.add(r);
7534 } else {
7535 cpr.externals++;
7536 }
7537
7538 if (cpr.app != null) {
7539 updateOomAdjLocked(cpr.app);
7540 }
7541
7542 Binder.restoreCallingIdentity(origId);
7543
7544 } else {
7545 try {
7546 cpi = ActivityThread.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007547 resolveContentProvider(name,
7548 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007549 } catch (RemoteException ex) {
7550 }
7551 if (cpi == null) {
7552 return null;
7553 }
7554
7555 if (checkContentProviderPermissionLocked(cpi, r, -1) != null) {
7556 return new ContentProviderHolder(cpi,
7557 cpi.readPermission != null
7558 ? cpi.readPermission : cpi.writePermission);
7559 }
7560
7561 cpr = (ContentProviderRecord)mProvidersByClass.get(cpi.name);
7562 final boolean firstClass = cpr == null;
7563 if (firstClass) {
7564 try {
7565 ApplicationInfo ai =
7566 ActivityThread.getPackageManager().
7567 getApplicationInfo(
7568 cpi.applicationInfo.packageName,
Dianne Hackborn1655be42009-05-08 14:29:01 -07007569 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007570 if (ai == null) {
7571 Log.w(TAG, "No package info for content provider "
7572 + cpi.name);
7573 return null;
7574 }
7575 cpr = new ContentProviderRecord(cpi, ai);
7576 } catch (RemoteException ex) {
7577 // pm is in same process, this will never happen.
7578 }
7579 }
7580
7581 if (r != null && cpr.canRunHere(r)) {
7582 // If this is a multiprocess provider, then just return its
7583 // info and allow the caller to instantiate it. Only do
7584 // this if the provider is the same user as the caller's
7585 // process, or can run as root (so can be in any process).
7586 return cpr;
7587 }
7588
Dianne Hackborna1e989b2009-09-01 19:54:29 -07007589 if (DEBUG_PROVIDER) {
7590 RuntimeException e = new RuntimeException("here");
7591 Log.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.info.uid
7592 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007593 }
7594
7595 // This is single process, and our app is now connecting to it.
7596 // See if we are already in the process of launching this
7597 // provider.
7598 final int N = mLaunchingProviders.size();
7599 int i;
7600 for (i=0; i<N; i++) {
7601 if (mLaunchingProviders.get(i) == cpr) {
7602 break;
7603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007604 }
7605
7606 // If the provider is not already being launched, then get it
7607 // started.
7608 if (i >= N) {
7609 final long origId = Binder.clearCallingIdentity();
7610 ProcessRecord proc = startProcessLocked(cpi.processName,
7611 cpr.appInfo, false, 0, "content provider",
7612 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007613 cpi.name), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007614 if (proc == null) {
7615 Log.w(TAG, "Unable to launch app "
7616 + cpi.applicationInfo.packageName + "/"
7617 + cpi.applicationInfo.uid + " for provider "
7618 + name + ": process is bad");
7619 return null;
7620 }
7621 cpr.launchingApp = proc;
7622 mLaunchingProviders.add(cpr);
7623 Binder.restoreCallingIdentity(origId);
7624 }
7625
7626 // Make sure the provider is published (the same provider class
7627 // may be published under multiple names).
7628 if (firstClass) {
7629 mProvidersByClass.put(cpi.name, cpr);
7630 }
7631 mProvidersByName.put(name, cpr);
7632
7633 if (r != null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07007634 if (DEBUG_PROVIDER) Log.v(TAG,
7635 "Adding provider requested by "
7636 + r.processName + " from process "
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07007637 + cpr.info.processName);
7638 Integer cnt = r.conProviders.get(cpr);
7639 if (cnt == null) {
7640 r.conProviders.put(cpr, new Integer(1));
7641 } else {
7642 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
7643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007644 cpr.clients.add(r);
7645 } else {
7646 cpr.externals++;
7647 }
7648 }
7649 }
7650
7651 // Wait for the provider to be published...
7652 synchronized (cpr) {
7653 while (cpr.provider == null) {
7654 if (cpr.launchingApp == null) {
7655 Log.w(TAG, "Unable to launch app "
7656 + cpi.applicationInfo.packageName + "/"
7657 + cpi.applicationInfo.uid + " for provider "
7658 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007659 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007660 cpi.applicationInfo.packageName,
7661 cpi.applicationInfo.uid, name);
7662 return null;
7663 }
7664 try {
7665 cpr.wait();
7666 } catch (InterruptedException ex) {
7667 }
7668 }
7669 }
7670 return cpr;
7671 }
7672
7673 public final ContentProviderHolder getContentProvider(
7674 IApplicationThread caller, String name) {
7675 if (caller == null) {
7676 String msg = "null IApplicationThread when getting content provider "
7677 + name;
7678 Log.w(TAG, msg);
7679 throw new SecurityException(msg);
7680 }
7681
7682 return getContentProviderImpl(caller, name);
7683 }
7684
7685 private ContentProviderHolder getContentProviderExternal(String name) {
7686 return getContentProviderImpl(null, name);
7687 }
7688
7689 /**
7690 * Drop a content provider from a ProcessRecord's bookkeeping
7691 * @param cpr
7692 */
7693 public void removeContentProvider(IApplicationThread caller, String name) {
7694 synchronized (this) {
7695 ContentProviderRecord cpr = (ContentProviderRecord)mProvidersByName.get(name);
7696 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07007697 // remove from mProvidersByClass
7698 if (DEBUG_PROVIDER) Log.v(TAG, name +
7699 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007700 return;
7701 }
7702 final ProcessRecord r = getRecordForAppLocked(caller);
7703 if (r == null) {
7704 throw new SecurityException(
7705 "Unable to find app for caller " + caller +
7706 " when removing content provider " + name);
7707 }
7708 //update content provider record entry info
Dianne Hackborna1e989b2009-09-01 19:54:29 -07007709 ContentProviderRecord localCpr = (ContentProviderRecord)
7710 mProvidersByClass.get(cpr.info.name);
7711 if (DEBUG_PROVIDER) Log.v(TAG, "Removing provider requested by "
7712 + r.info.processName + " from process "
7713 + localCpr.appInfo.processName);
7714 if (localCpr.app == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007715 //should not happen. taken care of as a local provider
Dianne Hackborna1e989b2009-09-01 19:54:29 -07007716 Log.w(TAG, "removeContentProvider called on local provider: "
7717 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007718 return;
7719 } else {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07007720 Integer cnt = r.conProviders.get(localCpr);
7721 if (cnt == null || cnt.intValue() <= 1) {
7722 localCpr.clients.remove(r);
7723 r.conProviders.remove(localCpr);
7724 } else {
7725 r.conProviders.put(localCpr, new Integer(cnt.intValue()-1));
7726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007727 }
7728 updateOomAdjLocked();
7729 }
7730 }
7731
7732 private void removeContentProviderExternal(String name) {
7733 synchronized (this) {
7734 ContentProviderRecord cpr = (ContentProviderRecord)mProvidersByName.get(name);
7735 if(cpr == null) {
7736 //remove from mProvidersByClass
7737 if(localLOGV) Log.v(TAG, name+" content provider not found in providers list");
7738 return;
7739 }
7740
7741 //update content provider record entry info
7742 ContentProviderRecord localCpr = (ContentProviderRecord) mProvidersByClass.get(cpr.info.name);
7743 localCpr.externals--;
7744 if (localCpr.externals < 0) {
7745 Log.e(TAG, "Externals < 0 for content provider " + localCpr);
7746 }
7747 updateOomAdjLocked();
7748 }
7749 }
7750
7751 public final void publishContentProviders(IApplicationThread caller,
7752 List<ContentProviderHolder> providers) {
7753 if (providers == null) {
7754 return;
7755 }
7756
7757 synchronized(this) {
7758 final ProcessRecord r = getRecordForAppLocked(caller);
7759 if (r == null) {
7760 throw new SecurityException(
7761 "Unable to find app for caller " + caller
7762 + " (pid=" + Binder.getCallingPid()
7763 + ") when publishing content providers");
7764 }
7765
7766 final long origId = Binder.clearCallingIdentity();
7767
7768 final int N = providers.size();
7769 for (int i=0; i<N; i++) {
7770 ContentProviderHolder src = providers.get(i);
7771 if (src == null || src.info == null || src.provider == null) {
7772 continue;
7773 }
7774 ContentProviderRecord dst =
7775 (ContentProviderRecord)r.pubProviders.get(src.info.name);
7776 if (dst != null) {
7777 mProvidersByClass.put(dst.info.name, dst);
7778 String names[] = dst.info.authority.split(";");
7779 for (int j = 0; j < names.length; j++) {
7780 mProvidersByName.put(names[j], dst);
7781 }
7782
7783 int NL = mLaunchingProviders.size();
7784 int j;
7785 for (j=0; j<NL; j++) {
7786 if (mLaunchingProviders.get(j) == dst) {
7787 mLaunchingProviders.remove(j);
7788 j--;
7789 NL--;
7790 }
7791 }
7792 synchronized (dst) {
7793 dst.provider = src.provider;
7794 dst.app = r;
7795 dst.notifyAll();
7796 }
7797 updateOomAdjLocked(r);
7798 }
7799 }
7800
7801 Binder.restoreCallingIdentity(origId);
7802 }
7803 }
7804
7805 public static final void installSystemProviders() {
7806 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
7807 List providers = mSelf.generateApplicationProvidersLocked(app);
7808 mSystemThread.installSystemProviders(providers);
7809 }
7810
7811 // =========================================================
7812 // GLOBAL MANAGEMENT
7813 // =========================================================
7814
7815 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
7816 ApplicationInfo info, String customProcess) {
7817 String proc = customProcess != null ? customProcess : info.processName;
7818 BatteryStatsImpl.Uid.Proc ps = null;
7819 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7820 synchronized (stats) {
7821 ps = stats.getProcessStatsLocked(info.uid, proc);
7822 }
7823 return new ProcessRecord(ps, thread, info, proc);
7824 }
7825
7826 final ProcessRecord addAppLocked(ApplicationInfo info) {
7827 ProcessRecord app = getProcessRecordLocked(info.processName, info.uid);
7828
7829 if (app == null) {
7830 app = newProcessRecordLocked(null, info, null);
7831 mProcessNames.put(info.processName, info.uid, app);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007832 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007833 }
7834
7835 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
7836 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
7837 app.persistent = true;
7838 app.maxAdj = CORE_SERVER_ADJ;
7839 }
7840 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
7841 mPersistentStartingProcesses.add(app);
7842 startProcessLocked(app, "added application", app.processName);
7843 }
7844
7845 return app;
7846 }
7847
7848 public void unhandledBack() {
7849 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
7850 "unhandledBack()");
7851
7852 synchronized(this) {
7853 int count = mHistory.size();
Dianne Hackborn03abb812010-01-04 18:43:19 -08007854 if (DEBUG_SWITCH) Log.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007855 TAG, "Performing unhandledBack(): stack size = " + count);
7856 if (count > 1) {
7857 final long origId = Binder.clearCallingIdentity();
7858 finishActivityLocked((HistoryRecord)mHistory.get(count-1),
7859 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
7860 Binder.restoreCallingIdentity(origId);
7861 }
7862 }
7863 }
7864
7865 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
7866 String name = uri.getAuthority();
7867 ContentProviderHolder cph = getContentProviderExternal(name);
7868 ParcelFileDescriptor pfd = null;
7869 if (cph != null) {
7870 // We record the binder invoker's uid in thread-local storage before
7871 // going to the content provider to open the file. Later, in the code
7872 // that handles all permissions checks, we look for this uid and use
7873 // that rather than the Activity Manager's own uid. The effect is that
7874 // we do the check against the caller's permissions even though it looks
7875 // to the content provider like the Activity Manager itself is making
7876 // the request.
7877 sCallerIdentity.set(new Identity(
7878 Binder.getCallingPid(), Binder.getCallingUid()));
7879 try {
7880 pfd = cph.provider.openFile(uri, "r");
7881 } catch (FileNotFoundException e) {
7882 // do nothing; pfd will be returned null
7883 } finally {
7884 // Ensure that whatever happens, we clean up the identity state
7885 sCallerIdentity.remove();
7886 }
7887
7888 // We've got the fd now, so we're done with the provider.
7889 removeContentProviderExternal(name);
7890 } else {
7891 Log.d(TAG, "Failed to get provider for authority '" + name + "'");
7892 }
7893 return pfd;
7894 }
7895
7896 public void goingToSleep() {
7897 synchronized(this) {
7898 mSleeping = true;
7899 mWindowManager.setEventDispatching(false);
7900
7901 if (mResumedActivity != null) {
7902 pauseIfSleepingLocked();
7903 } else {
7904 Log.w(TAG, "goingToSleep with no resumed activity!");
7905 }
7906 }
7907 }
7908
Dianne Hackborn55280a92009-05-07 15:53:46 -07007909 public boolean shutdown(int timeout) {
7910 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7911 != PackageManager.PERMISSION_GRANTED) {
7912 throw new SecurityException("Requires permission "
7913 + android.Manifest.permission.SHUTDOWN);
7914 }
7915
7916 boolean timedout = false;
7917
7918 synchronized(this) {
7919 mShuttingDown = true;
7920 mWindowManager.setEventDispatching(false);
7921
7922 if (mResumedActivity != null) {
7923 pauseIfSleepingLocked();
7924 final long endTime = System.currentTimeMillis() + timeout;
7925 while (mResumedActivity != null || mPausingActivity != null) {
7926 long delay = endTime - System.currentTimeMillis();
7927 if (delay <= 0) {
7928 Log.w(TAG, "Activity manager shutdown timed out");
7929 timedout = true;
7930 break;
7931 }
7932 try {
7933 this.wait();
7934 } catch (InterruptedException e) {
7935 }
7936 }
7937 }
7938 }
7939
7940 mUsageStatsService.shutdown();
7941 mBatteryStatsService.shutdown();
7942
7943 return timedout;
7944 }
7945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007946 void pauseIfSleepingLocked() {
Dianne Hackborn55280a92009-05-07 15:53:46 -07007947 if (mSleeping || mShuttingDown) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007948 if (!mGoingToSleep.isHeld()) {
7949 mGoingToSleep.acquire();
7950 if (mLaunchingActivity.isHeld()) {
7951 mLaunchingActivity.release();
7952 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
7953 }
7954 }
7955
7956 // If we are not currently pausing an activity, get the current
7957 // one to pause. If we are pausing one, we will just let that stuff
7958 // run and release the wake lock when all done.
7959 if (mPausingActivity == null) {
7960 if (DEBUG_PAUSE) Log.v(TAG, "Sleep needs to pause...");
7961 if (DEBUG_USER_LEAVING) Log.v(TAG, "Sleep => pause with userLeaving=false");
7962 startPausingLocked(false, true);
7963 }
7964 }
7965 }
7966
7967 public void wakingUp() {
7968 synchronized(this) {
7969 if (mGoingToSleep.isHeld()) {
7970 mGoingToSleep.release();
7971 }
7972 mWindowManager.setEventDispatching(true);
7973 mSleeping = false;
7974 resumeTopActivityLocked(null);
7975 }
7976 }
7977
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007978 public void stopAppSwitches() {
7979 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7980 != PackageManager.PERMISSION_GRANTED) {
7981 throw new SecurityException("Requires permission "
7982 + android.Manifest.permission.STOP_APP_SWITCHES);
7983 }
7984
7985 synchronized(this) {
7986 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7987 + APP_SWITCH_DELAY_TIME;
7988 mDidAppSwitch = false;
7989 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7990 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7991 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7992 }
7993 }
7994
7995 public void resumeAppSwitches() {
7996 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7997 != PackageManager.PERMISSION_GRANTED) {
7998 throw new SecurityException("Requires permission "
7999 + android.Manifest.permission.STOP_APP_SWITCHES);
8000 }
8001
8002 synchronized(this) {
8003 // Note that we don't execute any pending app switches... we will
8004 // let those wait until either the timeout, or the next start
8005 // activity request.
8006 mAppSwitchesAllowedTime = 0;
8007 }
8008 }
8009
8010 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
8011 String name) {
8012 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
8013 return true;
8014 }
8015
8016 final int perm = checkComponentPermission(
8017 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
8018 callingUid, -1);
8019 if (perm == PackageManager.PERMISSION_GRANTED) {
8020 return true;
8021 }
8022
8023 Log.w(TAG, name + " request from " + callingUid + " stopped");
8024 return false;
8025 }
8026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008027 public void setDebugApp(String packageName, boolean waitForDebugger,
8028 boolean persistent) {
8029 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
8030 "setDebugApp()");
8031
8032 // Note that this is not really thread safe if there are multiple
8033 // callers into it at the same time, but that's not a situation we
8034 // care about.
8035 if (persistent) {
8036 final ContentResolver resolver = mContext.getContentResolver();
8037 Settings.System.putString(
8038 resolver, Settings.System.DEBUG_APP,
8039 packageName);
8040 Settings.System.putInt(
8041 resolver, Settings.System.WAIT_FOR_DEBUGGER,
8042 waitForDebugger ? 1 : 0);
8043 }
8044
8045 synchronized (this) {
8046 if (!persistent) {
8047 mOrigDebugApp = mDebugApp;
8048 mOrigWaitForDebugger = mWaitForDebugger;
8049 }
8050 mDebugApp = packageName;
8051 mWaitForDebugger = waitForDebugger;
8052 mDebugTransient = !persistent;
8053 if (packageName != null) {
8054 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn03abb812010-01-04 18:43:19 -08008055 forceStopPackageLocked(packageName, -1, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008056 Binder.restoreCallingIdentity(origId);
8057 }
8058 }
8059 }
8060
8061 public void setAlwaysFinish(boolean enabled) {
8062 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
8063 "setAlwaysFinish()");
8064
8065 Settings.System.putInt(
8066 mContext.getContentResolver(),
8067 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
8068
8069 synchronized (this) {
8070 mAlwaysFinishActivities = enabled;
8071 }
8072 }
8073
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008074 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008075 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008076 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008077 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008078 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008079 }
8080 }
8081
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008082 public void registerActivityWatcher(IActivityWatcher watcher) {
8083 mWatchers.register(watcher);
8084 }
8085
8086 public void unregisterActivityWatcher(IActivityWatcher watcher) {
8087 mWatchers.unregister(watcher);
8088 }
8089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008090 public final void enterSafeMode() {
8091 synchronized(this) {
8092 // It only makes sense to do this before the system is ready
8093 // and started launching other packages.
8094 if (!mSystemReady) {
8095 try {
8096 ActivityThread.getPackageManager().enterSafeMode();
8097 } catch (RemoteException e) {
8098 }
8099
8100 View v = LayoutInflater.from(mContext).inflate(
8101 com.android.internal.R.layout.safe_mode, null);
8102 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
8103 lp.type = WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;
8104 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
8105 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
8106 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
8107 lp.format = v.getBackground().getOpacity();
8108 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
8109 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
8110 ((WindowManager)mContext.getSystemService(
8111 Context.WINDOW_SERVICE)).addView(v, lp);
8112 }
8113 }
8114 }
8115
8116 public void noteWakeupAlarm(IIntentSender sender) {
8117 if (!(sender instanceof PendingIntentRecord)) {
8118 return;
8119 }
8120 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
8121 synchronized (stats) {
8122 if (mBatteryStatsService.isOnBattery()) {
8123 mBatteryStatsService.enforceCallingPermission();
8124 PendingIntentRecord rec = (PendingIntentRecord)sender;
8125 int MY_UID = Binder.getCallingUid();
8126 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
8127 BatteryStatsImpl.Uid.Pkg pkg =
8128 stats.getPackageStatsLocked(uid, rec.key.packageName);
8129 pkg.incWakeupsLocked();
8130 }
8131 }
8132 }
8133
8134 public boolean killPidsForMemory(int[] pids) {
8135 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
8136 throw new SecurityException("killPidsForMemory only available to the system");
8137 }
8138
8139 // XXX Note: don't acquire main activity lock here, because the window
8140 // manager calls in with its locks held.
8141
8142 boolean killed = false;
8143 synchronized (mPidsSelfLocked) {
8144 int[] types = new int[pids.length];
8145 int worstType = 0;
8146 for (int i=0; i<pids.length; i++) {
8147 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
8148 if (proc != null) {
8149 int type = proc.setAdj;
8150 types[i] = type;
8151 if (type > worstType) {
8152 worstType = type;
8153 }
8154 }
8155 }
8156
8157 // If the worse oom_adj is somewhere in the hidden proc LRU range,
8158 // then constrain it so we will kill all hidden procs.
8159 if (worstType < EMPTY_APP_ADJ && worstType > HIDDEN_APP_MIN_ADJ) {
8160 worstType = HIDDEN_APP_MIN_ADJ;
8161 }
8162 Log.w(TAG, "Killing processes for memory at adjustment " + worstType);
8163 for (int i=0; i<pids.length; i++) {
8164 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
8165 if (proc == null) {
8166 continue;
8167 }
8168 int adj = proc.setAdj;
8169 if (adj >= worstType) {
8170 Log.w(TAG, "Killing for memory: " + proc + " (adj "
8171 + adj + ")");
Doug Zongker2bec3d42009-12-04 12:52:44 -08008172 EventLog.writeEvent(EventLogTags.AM_KILL_FOR_MEMORY, proc.pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008173 proc.processName, adj);
8174 killed = true;
8175 Process.killProcess(pids[i]);
8176 }
8177 }
8178 }
8179 return killed;
8180 }
8181
8182 public void reportPss(IApplicationThread caller, int pss) {
8183 Watchdog.PssRequestor req;
8184 String name;
8185 ProcessRecord callerApp;
8186 synchronized (this) {
8187 if (caller == null) {
8188 return;
8189 }
8190 callerApp = getRecordForAppLocked(caller);
8191 if (callerApp == null) {
8192 return;
8193 }
8194 callerApp.lastPss = pss;
8195 req = callerApp;
8196 name = callerApp.processName;
8197 }
8198 Watchdog.getInstance().reportPss(req, name, pss);
8199 if (!callerApp.persistent) {
8200 removeRequestedPss(callerApp);
8201 }
8202 }
8203
8204 public void requestPss(Runnable completeCallback) {
8205 ArrayList<ProcessRecord> procs;
8206 synchronized (this) {
8207 mRequestPssCallback = completeCallback;
8208 mRequestPssList.clear();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008209 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8210 ProcessRecord proc = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008211 if (!proc.persistent) {
8212 mRequestPssList.add(proc);
8213 }
8214 }
8215 procs = new ArrayList<ProcessRecord>(mRequestPssList);
8216 }
8217
8218 int oldPri = Process.getThreadPriority(Process.myTid());
8219 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
8220 for (int i=procs.size()-1; i>=0; i--) {
8221 ProcessRecord proc = procs.get(i);
8222 proc.lastPss = 0;
8223 proc.requestPss();
8224 }
8225 Process.setThreadPriority(oldPri);
8226 }
8227
8228 void removeRequestedPss(ProcessRecord proc) {
8229 Runnable callback = null;
8230 synchronized (this) {
8231 if (mRequestPssList.remove(proc)) {
8232 if (mRequestPssList.size() == 0) {
8233 callback = mRequestPssCallback;
8234 mRequestPssCallback = null;
8235 }
8236 }
8237 }
8238
8239 if (callback != null) {
8240 callback.run();
8241 }
8242 }
8243
8244 public void collectPss(Watchdog.PssStats stats) {
8245 stats.mEmptyPss = 0;
8246 stats.mEmptyCount = 0;
8247 stats.mBackgroundPss = 0;
8248 stats.mBackgroundCount = 0;
8249 stats.mServicePss = 0;
8250 stats.mServiceCount = 0;
8251 stats.mVisiblePss = 0;
8252 stats.mVisibleCount = 0;
8253 stats.mForegroundPss = 0;
8254 stats.mForegroundCount = 0;
8255 stats.mNoPssCount = 0;
8256 synchronized (this) {
8257 int i;
8258 int NPD = mProcDeaths.length < stats.mProcDeaths.length
8259 ? mProcDeaths.length : stats.mProcDeaths.length;
8260 int aggr = 0;
8261 for (i=0; i<NPD; i++) {
8262 aggr += mProcDeaths[i];
8263 stats.mProcDeaths[i] = aggr;
8264 }
8265 while (i<stats.mProcDeaths.length) {
8266 stats.mProcDeaths[i] = 0;
8267 i++;
8268 }
8269
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008270 for (i=mLruProcesses.size()-1; i>=0; i--) {
8271 ProcessRecord proc = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008272 if (proc.persistent) {
8273 continue;
8274 }
8275 //Log.i(TAG, "Proc " + proc + ": pss=" + proc.lastPss);
8276 if (proc.lastPss == 0) {
8277 stats.mNoPssCount++;
8278 continue;
8279 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008280 if (proc.setAdj >= HIDDEN_APP_MIN_ADJ) {
8281 if (proc.empty) {
8282 stats.mEmptyPss += proc.lastPss;
8283 stats.mEmptyCount++;
8284 } else {
8285 stats.mBackgroundPss += proc.lastPss;
8286 stats.mBackgroundCount++;
8287 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008288 } else if (proc.setAdj >= VISIBLE_APP_ADJ) {
8289 stats.mVisiblePss += proc.lastPss;
8290 stats.mVisibleCount++;
8291 } else {
8292 stats.mForegroundPss += proc.lastPss;
8293 stats.mForegroundCount++;
8294 }
8295 }
8296 }
8297 }
8298
8299 public final void startRunning(String pkg, String cls, String action,
8300 String data) {
8301 synchronized(this) {
8302 if (mStartRunning) {
8303 return;
8304 }
8305 mStartRunning = true;
8306 mTopComponent = pkg != null && cls != null
8307 ? new ComponentName(pkg, cls) : null;
8308 mTopAction = action != null ? action : Intent.ACTION_MAIN;
8309 mTopData = data;
8310 if (!mSystemReady) {
8311 return;
8312 }
8313 }
8314
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07008315 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008316 }
8317
8318 private void retrieveSettings() {
8319 final ContentResolver resolver = mContext.getContentResolver();
8320 String debugApp = Settings.System.getString(
8321 resolver, Settings.System.DEBUG_APP);
8322 boolean waitForDebugger = Settings.System.getInt(
8323 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
8324 boolean alwaysFinishActivities = Settings.System.getInt(
8325 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
8326
8327 Configuration configuration = new Configuration();
8328 Settings.System.getConfiguration(resolver, configuration);
8329
8330 synchronized (this) {
8331 mDebugApp = mOrigDebugApp = debugApp;
8332 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
8333 mAlwaysFinishActivities = alwaysFinishActivities;
8334 // This happens before any activities are started, so we can
8335 // change mConfiguration in-place.
8336 mConfiguration.updateFrom(configuration);
Dianne Hackborndc6b6352009-09-30 14:20:09 -07008337 if (DEBUG_CONFIGURATION) Log.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008338 }
8339 }
8340
8341 public boolean testIsSystemReady() {
8342 // no need to synchronize(this) just to read & return the value
8343 return mSystemReady;
8344 }
8345
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07008346 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008347 // In the simulator, startRunning will never have been called, which
8348 // normally sets a few crucial variables. Do it here instead.
8349 if (!Process.supportsProcesses()) {
8350 mStartRunning = true;
8351 mTopAction = Intent.ACTION_MAIN;
8352 }
8353
8354 synchronized(this) {
8355 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07008356 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008357 return;
8358 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008359
8360 // Check to see if there are any update receivers to run.
8361 if (!mDidUpdate) {
8362 if (mWaitingUpdate) {
8363 return;
8364 }
8365 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
8366 List<ResolveInfo> ris = null;
8367 try {
8368 ris = ActivityThread.getPackageManager().queryIntentReceivers(
8369 intent, null, 0);
8370 } catch (RemoteException e) {
8371 }
8372 if (ris != null) {
8373 for (int i=ris.size()-1; i>=0; i--) {
8374 if ((ris.get(i).activityInfo.applicationInfo.flags
8375 &ApplicationInfo.FLAG_SYSTEM) == 0) {
8376 ris.remove(i);
8377 }
8378 }
8379 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
8380 for (int i=0; i<ris.size(); i++) {
8381 ActivityInfo ai = ris.get(i).activityInfo;
8382 intent.setComponent(new ComponentName(ai.packageName, ai.name));
8383 IIntentReceiver finisher = null;
8384 if (i == 0) {
8385 finisher = new IIntentReceiver.Stub() {
8386 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07008387 String data, Bundle extras, boolean ordered,
8388 boolean sticky)
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008389 throws RemoteException {
8390 synchronized (ActivityManagerService.this) {
8391 mDidUpdate = true;
8392 }
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07008393 systemReady(goingCallback);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008394 }
8395 };
8396 }
8397 Log.i(TAG, "Sending system update to: " + intent.getComponent());
8398 broadcastIntentLocked(null, null, intent, null, finisher,
8399 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID);
8400 if (i == 0) {
8401 mWaitingUpdate = true;
8402 }
8403 }
8404 }
8405 if (mWaitingUpdate) {
8406 return;
8407 }
8408 mDidUpdate = true;
8409 }
8410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008411 mSystemReady = true;
8412 if (!mStartRunning) {
8413 return;
8414 }
8415 }
8416
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008417 ArrayList<ProcessRecord> procsToKill = null;
8418 synchronized(mPidsSelfLocked) {
8419 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
8420 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
8421 if (!isAllowedWhileBooting(proc.info)){
8422 if (procsToKill == null) {
8423 procsToKill = new ArrayList<ProcessRecord>();
8424 }
8425 procsToKill.add(proc);
8426 }
8427 }
8428 }
8429
8430 if (procsToKill != null) {
8431 synchronized(this) {
8432 for (int i=procsToKill.size()-1; i>=0; i--) {
8433 ProcessRecord proc = procsToKill.get(i);
8434 Log.i(TAG, "Removing system update proc: " + proc);
8435 removeProcessLocked(proc, true);
8436 }
8437 }
8438 }
8439
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07008440 Log.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08008441 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008442 SystemClock.uptimeMillis());
8443
8444 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008445 // Make sure we have no pre-ready processes sitting around.
8446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008447 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
8448 ResolveInfo ri = mContext.getPackageManager()
8449 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07008450 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008451 CharSequence errorMsg = null;
8452 if (ri != null) {
8453 ActivityInfo ai = ri.activityInfo;
8454 ApplicationInfo app = ai.applicationInfo;
8455 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8456 mTopAction = Intent.ACTION_FACTORY_TEST;
8457 mTopData = null;
8458 mTopComponent = new ComponentName(app.packageName,
8459 ai.name);
8460 } else {
8461 errorMsg = mContext.getResources().getText(
8462 com.android.internal.R.string.factorytest_not_system);
8463 }
8464 } else {
8465 errorMsg = mContext.getResources().getText(
8466 com.android.internal.R.string.factorytest_no_action);
8467 }
8468 if (errorMsg != null) {
8469 mTopAction = null;
8470 mTopData = null;
8471 mTopComponent = null;
8472 Message msg = Message.obtain();
8473 msg.what = SHOW_FACTORY_ERROR_MSG;
8474 msg.getData().putCharSequence("msg", errorMsg);
8475 mHandler.sendMessage(msg);
8476 }
8477 }
8478 }
8479
8480 retrieveSettings();
8481
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07008482 if (goingCallback != null) goingCallback.run();
8483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008484 synchronized (this) {
8485 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
8486 try {
8487 List apps = ActivityThread.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07008488 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008489 if (apps != null) {
8490 int N = apps.size();
8491 int i;
8492 for (i=0; i<N; i++) {
8493 ApplicationInfo info
8494 = (ApplicationInfo)apps.get(i);
8495 if (info != null &&
8496 !info.packageName.equals("android")) {
8497 addAppLocked(info);
8498 }
8499 }
8500 }
8501 } catch (RemoteException ex) {
8502 // pm is in same process, this will never happen.
8503 }
8504 }
8505
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008506 // Start up initial activity.
8507 mBooting = true;
8508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008509 try {
8510 if (ActivityThread.getPackageManager().hasSystemUidErrors()) {
8511 Message msg = Message.obtain();
8512 msg.what = SHOW_UID_ERROR_MSG;
8513 mHandler.sendMessage(msg);
8514 }
8515 } catch (RemoteException e) {
8516 }
8517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008518 resumeTopActivityLocked(null);
8519 }
8520 }
8521
Dan Egnorb7f03672009-12-09 16:22:32 -08008522 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008523 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008524 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08008525 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08008526 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008527 startAppProblemLocked(app);
8528 app.stopFreezingAllLocked();
8529 return handleAppCrashLocked(app);
8530 }
8531
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008532 private ComponentName getErrorReportReceiver(ProcessRecord app) {
Doug Zongker43866e02010-01-07 12:09:54 -08008533 // check if error reporting is enabled in secure settings
8534 int enabled = Settings.Secure.getInt(mContext.getContentResolver(),
8535 Settings.Secure.SEND_ACTION_APP_ERROR, 0);
Jacek Surazskia2339432009-09-18 15:01:26 +02008536 if (enabled == 0) {
8537 return null;
8538 }
8539
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008540 IPackageManager pm = ActivityThread.getPackageManager();
Jacek Surazski82a73df2009-06-17 14:33:18 +02008541
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008542 try {
Jacek Surazski82a73df2009-06-17 14:33:18 +02008543 // look for receiver in the installer package
8544 String candidate = pm.getInstallerPackageName(app.info.packageName);
8545 ComponentName result = getErrorReportReceiver(pm, app.info.packageName, candidate);
8546 if (result != null) {
8547 return result;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008548 }
8549
Jacek Surazski82a73df2009-06-17 14:33:18 +02008550 // if the error app is on the system image, look for system apps
8551 // error receiver
8552 if ((app.info.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8553 candidate = SystemProperties.get(SYSTEM_APPS_ERROR_RECEIVER_PROPERTY);
8554 result = getErrorReportReceiver(pm, app.info.packageName, candidate);
8555 if (result != null) {
8556 return result;
8557 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008558 }
8559
Jacek Surazski82a73df2009-06-17 14:33:18 +02008560 // if there is a default receiver, try that
8561 candidate = SystemProperties.get(DEFAULT_ERROR_RECEIVER_PROPERTY);
8562 return getErrorReportReceiver(pm, app.info.packageName, candidate);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008563 } catch (RemoteException e) {
Jacek Surazski82a73df2009-06-17 14:33:18 +02008564 // should not happen
8565 Log.e(TAG, "error talking to PackageManager", e);
8566 return null;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008567 }
Jacek Surazski82a73df2009-06-17 14:33:18 +02008568 }
8569
8570 /**
8571 * Return activity in receiverPackage that handles ACTION_APP_ERROR.
8572 *
8573 * @param pm PackageManager isntance
8574 * @param errorPackage package which caused the error
8575 * @param receiverPackage candidate package to receive the error
8576 * @return activity component within receiverPackage which handles
8577 * ACTION_APP_ERROR, or null if not found
8578 */
8579 private ComponentName getErrorReportReceiver(IPackageManager pm, String errorPackage,
8580 String receiverPackage) throws RemoteException {
8581 if (receiverPackage == null || receiverPackage.length() == 0) {
8582 return null;
8583 }
8584
8585 // break the loop if it's the error report receiver package that crashed
8586 if (receiverPackage.equals(errorPackage)) {
8587 return null;
8588 }
8589
8590 Intent intent = new Intent(Intent.ACTION_APP_ERROR);
8591 intent.setPackage(receiverPackage);
8592 ResolveInfo info = pm.resolveIntent(intent, null, 0);
8593 if (info == null || info.activityInfo == null) {
8594 return null;
8595 }
8596 return new ComponentName(receiverPackage, info.activityInfo.name);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008597 }
8598
Dan Egnorb7f03672009-12-09 16:22:32 -08008599 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008600 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008601 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08008602 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08008603 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
8604 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008605 startAppProblemLocked(app);
8606 app.stopFreezingAllLocked();
8607 }
8608
8609 /**
8610 * Generate a process error record, suitable for attachment to a ProcessRecord.
8611 *
8612 * @param app The ProcessRecord in which the error occurred.
8613 * @param condition Crashing, Application Not Responding, etc. Values are defined in
8614 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08008615 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008616 * @param shortMsg Short message describing the crash.
8617 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08008618 * @param stackTrace Full crash stack trace, may be null.
8619 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008620 * @return Returns a fully-formed AppErrorStateInfo record.
8621 */
8622 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008623 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008624 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08008625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008626 report.condition = condition;
8627 report.processName = app.processName;
8628 report.pid = app.pid;
8629 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08008630 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008631 report.shortMsg = shortMsg;
8632 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08008633 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008634
8635 return report;
8636 }
8637
Dan Egnor42471dd2010-01-07 17:25:22 -08008638 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008639 synchronized (this) {
8640 app.crashing = false;
8641 app.crashingReport = null;
8642 app.notResponding = false;
8643 app.notRespondingReport = null;
8644 if (app.anrDialog == fromDialog) {
8645 app.anrDialog = null;
8646 }
8647 if (app.waitDialog == fromDialog) {
8648 app.waitDialog = null;
8649 }
8650 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08008651 handleAppCrashLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008652 Log.i(ActivityManagerService.TAG, "Killing process "
8653 + app.processName
8654 + " (pid=" + app.pid + ") at user's request");
8655 Process.killProcess(app.pid);
8656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008657 }
8658 }
Dan Egnor42471dd2010-01-07 17:25:22 -08008659
Dan Egnorb7f03672009-12-09 16:22:32 -08008660 private boolean handleAppCrashLocked(ProcessRecord app) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008661 long now = SystemClock.uptimeMillis();
8662
8663 Long crashTime = mProcessCrashTimes.get(app.info.processName,
8664 app.info.uid);
8665 if (crashTime != null && now < crashTime+MIN_CRASH_INTERVAL) {
8666 // This process loses!
8667 Log.w(TAG, "Process " + app.info.processName
8668 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08008669 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008670 app.info.processName, app.info.uid);
8671 killServicesLocked(app, false);
8672 for (int i=mHistory.size()-1; i>=0; i--) {
8673 HistoryRecord r = (HistoryRecord)mHistory.get(i);
8674 if (r.app == app) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08008675 Log.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008676 + r.intent.getComponent().flattenToShortString());
8677 finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
8678 }
8679 }
8680 if (!app.persistent) {
8681 // We don't want to start this process again until the user
8682 // explicitly does so... but for persistent process, we really
8683 // need to keep it running. If a persistent process is actually
8684 // repeatedly crashing, then badness for everyone.
Doug Zongker2bec3d42009-12-04 12:52:44 -08008685 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.info.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008686 app.info.processName);
8687 mBadProcesses.put(app.info.processName, app.info.uid, now);
8688 app.bad = true;
8689 mProcessCrashTimes.remove(app.info.processName, app.info.uid);
8690 app.removed = true;
8691 removeProcessLocked(app, false);
8692 return false;
8693 }
8694 }
8695
8696 // Bump up the crash count of any services currently running in the proc.
8697 if (app.services.size() != 0) {
8698 // Any services running in the application need to be placed
8699 // back in the pending list.
8700 Iterator it = app.services.iterator();
8701 while (it.hasNext()) {
8702 ServiceRecord sr = (ServiceRecord)it.next();
8703 sr.crashCount++;
8704 }
8705 }
8706
8707 mProcessCrashTimes.put(app.info.processName, app.info.uid, now);
8708 return true;
8709 }
8710
8711 void startAppProblemLocked(ProcessRecord app) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008712 app.errorReportReceiver = getErrorReportReceiver(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008713 skipCurrentReceiverLocked(app);
8714 }
8715
8716 void skipCurrentReceiverLocked(ProcessRecord app) {
8717 boolean reschedule = false;
8718 BroadcastRecord r = app.curReceiver;
8719 if (r != null) {
8720 // The current broadcast is waiting for this app's receiver
8721 // to be finished. Looks like that's not going to happen, so
8722 // let the broadcast continue.
8723 logBroadcastReceiverDiscard(r);
8724 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
8725 r.resultExtras, r.resultAbort, true);
8726 reschedule = true;
8727 }
8728 r = mPendingBroadcast;
8729 if (r != null && r.curApp == app) {
8730 if (DEBUG_BROADCAST) Log.v(TAG,
8731 "skip & discard pending app " + r);
8732 logBroadcastReceiverDiscard(r);
8733 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
8734 r.resultExtras, r.resultAbort, true);
8735 reschedule = true;
8736 }
8737 if (reschedule) {
8738 scheduleBroadcastsLocked();
8739 }
8740 }
8741
Dan Egnor60d87622009-12-16 16:32:58 -08008742 /**
8743 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8744 * The application process will exit immediately after this call returns.
8745 * @param app object of the crashing app, null for the system server
8746 * @param crashInfo describing the exception
8747 */
8748 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
8749 ProcessRecord r = findAppProcess(app);
8750
8751 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
8752 app == null ? "system" : (r == null ? "unknown" : r.processName),
8753 crashInfo.exceptionClassName,
8754 crashInfo.exceptionMessage,
8755 crashInfo.throwFileName,
8756 crashInfo.throwLineNumber);
8757
Dan Egnor42471dd2010-01-07 17:25:22 -08008758 addErrorToDropBox("crash", r, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008759
8760 crashApplication(r, crashInfo);
8761 }
8762
8763 /**
8764 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8765 * @param app object of the crashing app, null for the system server
8766 * @param tag reported by the caller
8767 * @param crashInfo describing the context of the error
8768 * @return true if the process should exit immediately (WTF is fatal)
8769 */
8770 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008771 ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnor60d87622009-12-16 16:32:58 -08008772 ProcessRecord r = findAppProcess(app);
8773
8774 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
8775 app == null ? "system" : (r == null ? "unknown" : r.processName),
8776 tag, crashInfo.exceptionMessage);
8777
Dan Egnor42471dd2010-01-07 17:25:22 -08008778 addErrorToDropBox("wtf", r, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008779
Doug Zongker43866e02010-01-07 12:09:54 -08008780 if (Settings.Secure.getInt(mContext.getContentResolver(),
8781 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008782 crashApplication(r, crashInfo);
8783 return true;
8784 } else {
8785 return false;
8786 }
8787 }
8788
8789 /**
8790 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8791 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8792 */
8793 private ProcessRecord findAppProcess(IBinder app) {
8794 if (app == null) {
8795 return null;
8796 }
8797
8798 synchronized (this) {
8799 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8800 final int NA = apps.size();
8801 for (int ia=0; ia<NA; ia++) {
8802 ProcessRecord p = apps.valueAt(ia);
8803 if (p.thread != null && p.thread.asBinder() == app) {
8804 return p;
8805 }
8806 }
8807 }
8808
8809 Log.w(TAG, "Can't find mystery application: " + app);
8810 return null;
8811 }
8812 }
8813
8814 /**
Dan Egnor42471dd2010-01-07 17:25:22 -08008815 * Write a description of an error (crash, WTF, ANR) to the drop box.
Dan Egnor60d87622009-12-16 16:32:58 -08008816 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
Dan Egnor42471dd2010-01-07 17:25:22 -08008817 * @param process which caused the error, null means the system server
8818 * @param activity which triggered the error, null if unknown
8819 * @param parent activity related to the error, null if unknown
8820 * @param subject line related to the error, null if absent
8821 * @param report in long form describing the error, null if absent
8822 * @param logFile to include in the report, null if none
8823 * @param crashInfo giving an application stack trace, null if absent
Dan Egnor60d87622009-12-16 16:32:58 -08008824 */
Dan Egnor42471dd2010-01-07 17:25:22 -08008825 private void addErrorToDropBox(String eventType,
8826 ProcessRecord process, HistoryRecord activity, HistoryRecord parent,
8827 String subject, String report, File logFile,
Dan Egnor60d87622009-12-16 16:32:58 -08008828 ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnor42471dd2010-01-07 17:25:22 -08008829 String dropboxTag;
8830 if (process == null || process.pid == MY_PID) {
Dan Egnor60d87622009-12-16 16:32:58 -08008831 dropboxTag = "system_server_" + eventType;
Dan Egnor42471dd2010-01-07 17:25:22 -08008832 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008833 dropboxTag = "system_app_" + eventType;
8834 } else {
8835 dropboxTag = "data_app_" + eventType;
8836 }
8837
8838 DropBoxManager dbox = (DropBoxManager) mContext.getSystemService(Context.DROPBOX_SERVICE);
8839 if (dbox != null && dbox.isTagEnabled(dropboxTag)) {
8840 StringBuilder sb = new StringBuilder(1024);
Dan Egnor42471dd2010-01-07 17:25:22 -08008841 if (process == null || process.pid == MY_PID) {
Dan Egnor60d87622009-12-16 16:32:58 -08008842 sb.append("Process: system_server\n");
8843 } else {
Dan Egnor42471dd2010-01-07 17:25:22 -08008844 sb.append("Process: ").append(process.processName).append("\n");
8845 }
8846 if (activity != null) {
8847 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8848 }
8849 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8850 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8851 }
8852 if (parent != null && parent != activity) {
8853 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8854 }
8855 if (subject != null) {
8856 sb.append("Subject: ").append(subject).append("\n");
8857 }
8858 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8859 sb.append("\n");
8860 if (report != null) {
8861 sb.append(report);
8862 }
8863 if (logFile != null) {
8864 try {
8865 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8866 } catch (IOException e) {
8867 Log.e(TAG, "Error reading " + logFile, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008868 }
8869 }
Dan Egnor60d87622009-12-16 16:32:58 -08008870 if (crashInfo != null && crashInfo.stackTrace != null) {
Dan Egnor42471dd2010-01-07 17:25:22 -08008871 sb.append(crashInfo.stackTrace);
Dan Egnor60d87622009-12-16 16:32:58 -08008872 }
8873 dbox.addText(dropboxTag, sb.toString());
8874 }
8875 }
8876
8877 /**
8878 * Bring up the "unexpected error" dialog box for a crashing app.
8879 * Deal with edge cases (intercepts from instrumented applications,
8880 * ActivityController, error intent receivers, that sort of thing).
8881 * @param r the application crashing
8882 * @param crashInfo describing the failure
8883 */
8884 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008885 long timeMillis = System.currentTimeMillis();
8886 String shortMsg = crashInfo.exceptionClassName;
8887 String longMsg = crashInfo.exceptionMessage;
8888 String stackTrace = crashInfo.stackTrace;
8889 if (shortMsg != null && longMsg != null) {
8890 longMsg = shortMsg + ": " + longMsg;
8891 } else if (shortMsg != null) {
8892 longMsg = shortMsg;
8893 }
8894
Dan Egnor60d87622009-12-16 16:32:58 -08008895 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008896 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008897 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008898 try {
8899 String name = r != null ? r.processName : null;
8900 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008901 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008902 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008903 Log.w(TAG, "Force-killing crashed app " + name
8904 + " at watcher's request");
8905 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008906 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008907 }
8908 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008909 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008910 }
8911 }
8912
8913 final long origId = Binder.clearCallingIdentity();
8914
8915 // If this process is running instrumentation, finish it.
8916 if (r != null && r.instrumentationClass != null) {
8917 Log.w(TAG, "Error in app " + r.processName
8918 + " running instrumentation " + r.instrumentationClass + ":");
8919 if (shortMsg != null) Log.w(TAG, " " + shortMsg);
8920 if (longMsg != null) Log.w(TAG, " " + longMsg);
8921 Bundle info = new Bundle();
8922 info.putString("shortMsg", shortMsg);
8923 info.putString("longMsg", longMsg);
8924 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8925 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008926 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008927 }
8928
Dan Egnor60d87622009-12-16 16:32:58 -08008929 // If we can't identify the process or it's already exceeded its crash quota,
8930 // quit right away without showing a crash dialog.
8931 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008932 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008933 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008934 }
8935
8936 Message msg = Message.obtain();
8937 msg.what = SHOW_ERROR_MSG;
8938 HashMap data = new HashMap();
8939 data.put("result", result);
8940 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008941 msg.obj = data;
8942 mHandler.sendMessage(msg);
8943
8944 Binder.restoreCallingIdentity(origId);
8945 }
8946
8947 int res = result.get();
8948
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008949 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008950 synchronized (this) {
8951 if (r != null) {
8952 mProcessCrashTimes.put(r.info.processName, r.info.uid,
8953 SystemClock.uptimeMillis());
8954 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008955 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008956 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008957 }
8958 }
8959
8960 if (appErrorIntent != null) {
8961 try {
8962 mContext.startActivity(appErrorIntent);
8963 } catch (ActivityNotFoundException e) {
8964 Log.w(TAG, "bug report receiver dissappeared", e);
8965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008967 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008968
8969 Intent createAppErrorIntentLocked(ProcessRecord r,
8970 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8971 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008972 if (report == null) {
8973 return null;
8974 }
8975 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8976 result.setComponent(r.errorReportReceiver);
8977 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8978 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8979 return result;
8980 }
8981
Dan Egnorb7f03672009-12-09 16:22:32 -08008982 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8983 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008984 if (r.errorReportReceiver == null) {
8985 return null;
8986 }
8987
8988 if (!r.crashing && !r.notResponding) {
8989 return null;
8990 }
8991
Dan Egnorb7f03672009-12-09 16:22:32 -08008992 ApplicationErrorReport report = new ApplicationErrorReport();
8993 report.packageName = r.info.packageName;
8994 report.installerPackageName = r.errorReportReceiver.getPackageName();
8995 report.processName = r.processName;
8996 report.time = timeMillis;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008997
Dan Egnorb7f03672009-12-09 16:22:32 -08008998 if (r.crashing) {
8999 report.type = ApplicationErrorReport.TYPE_CRASH;
9000 report.crashInfo = crashInfo;
9001 } else if (r.notResponding) {
9002 report.type = ApplicationErrorReport.TYPE_ANR;
9003 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02009004
Dan Egnorb7f03672009-12-09 16:22:32 -08009005 report.anrInfo.activity = r.notRespondingReport.tag;
9006 report.anrInfo.cause = r.notRespondingReport.shortMsg;
9007 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02009008 }
9009
Dan Egnorb7f03672009-12-09 16:22:32 -08009010 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02009011 }
9012
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009013 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
9014 // assume our apps are happy - lazy create the list
9015 List<ActivityManager.ProcessErrorStateInfo> errList = null;
9016
9017 synchronized (this) {
9018
9019 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08009020 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9021 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009022 if ((app.thread != null) && (app.crashing || app.notResponding)) {
9023 // This one's in trouble, so we'll generate a report for it
9024 // crashes are higher priority (in case there's a crash *and* an anr)
9025 ActivityManager.ProcessErrorStateInfo report = null;
9026 if (app.crashing) {
9027 report = app.crashingReport;
9028 } else if (app.notResponding) {
9029 report = app.notRespondingReport;
9030 }
9031
9032 if (report != null) {
9033 if (errList == null) {
9034 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
9035 }
9036 errList.add(report);
9037 } else {
9038 Log.w(TAG, "Missing app error report, app = " + app.processName +
9039 " crashing = " + app.crashing +
9040 " notResponding = " + app.notResponding);
9041 }
9042 }
9043 }
9044 }
9045
9046 return errList;
9047 }
9048
9049 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
9050 // Lazy instantiation of list
9051 List<ActivityManager.RunningAppProcessInfo> runList = null;
9052 synchronized (this) {
9053 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08009054 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9055 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009056 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
9057 // Generate process state info for running application
9058 ActivityManager.RunningAppProcessInfo currApp =
9059 new ActivityManager.RunningAppProcessInfo(app.processName,
9060 app.pid, app.getPackageList());
Dianne Hackborneb034652009-09-07 00:49:58 -07009061 currApp.uid = app.info.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009062 int adj = app.curAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08009063 if (adj >= EMPTY_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009064 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_EMPTY;
9065 } else if (adj >= HIDDEN_APP_MIN_ADJ) {
9066 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
The Android Open Source Project4df24232009-03-05 14:34:35 -08009067 currApp.lru = adj - HIDDEN_APP_MIN_ADJ + 1;
9068 } else if (adj >= HOME_APP_ADJ) {
9069 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
9070 currApp.lru = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009071 } else if (adj >= SECONDARY_SERVER_ADJ) {
9072 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
9073 } else if (adj >= VISIBLE_APP_ADJ) {
9074 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
9075 } else {
9076 currApp.importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
9077 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07009078 currApp.importanceReasonCode = app.adjTypeCode;
9079 if (app.adjSource instanceof ProcessRecord) {
9080 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
9081 } else if (app.adjSource instanceof HistoryRecord) {
9082 HistoryRecord r = (HistoryRecord)app.adjSource;
9083 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
9084 }
9085 if (app.adjTarget instanceof ComponentName) {
9086 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
9087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009088 //Log.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
9089 // + " lru=" + currApp.lru);
9090 if (runList == null) {
9091 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
9092 }
9093 runList.add(currApp);
9094 }
9095 }
9096 }
9097 return runList;
9098 }
9099
9100 @Override
9101 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009102 if (checkCallingPermission(android.Manifest.permission.DUMP)
9103 != PackageManager.PERMISSION_GRANTED) {
9104 pw.println("Permission Denial: can't dump ActivityManager from from pid="
9105 + Binder.getCallingPid()
9106 + ", uid=" + Binder.getCallingUid()
9107 + " without permission "
9108 + android.Manifest.permission.DUMP);
9109 return;
9110 }
9111
9112 boolean dumpAll = false;
9113
9114 int opti = 0;
9115 while (opti < args.length) {
9116 String opt = args[opti];
9117 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9118 break;
9119 }
9120 opti++;
9121 if ("-a".equals(opt)) {
9122 dumpAll = true;
9123 } else if ("-h".equals(opt)) {
9124 pw.println("Activity manager dump options:");
9125 pw.println(" [-a] [h- [cmd] ...");
9126 pw.println(" cmd may be one of:");
9127 pw.println(" activities: activity stack state");
9128 pw.println(" broadcasts: broadcast state");
9129 pw.println(" intents: pending intent state");
9130 pw.println(" processes: process state");
9131 pw.println(" providers: content provider state");
9132 pw.println(" services: service state");
9133 pw.println(" service [name]: service client-side state");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009134 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009135 } else {
9136 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009137 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009138 }
9139
9140 // Is the caller requesting to dump a particular piece of data?
9141 if (opti < args.length) {
9142 String cmd = args[opti];
9143 opti++;
9144 if ("activities".equals(cmd) || "a".equals(cmd)) {
9145 synchronized (this) {
9146 dumpActivitiesLocked(fd, pw, args, opti, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009147 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009148 return;
9149 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
9150 synchronized (this) {
9151 dumpBroadcastsLocked(fd, pw, args, opti, true);
9152 }
9153 return;
9154 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
9155 synchronized (this) {
9156 dumpPendingIntentsLocked(fd, pw, args, opti, true);
9157 }
9158 return;
9159 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
9160 synchronized (this) {
9161 dumpProcessesLocked(fd, pw, args, opti, true);
9162 }
9163 return;
9164 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
9165 synchronized (this) {
9166 dumpProvidersLocked(fd, pw, args, opti, true);
9167 }
9168 return;
9169 } else if ("service".equals(cmd)) {
9170 dumpService(fd, pw, args, opti, true);
9171 return;
9172 } else if ("services".equals(cmd) || "s".equals(cmd)) {
9173 synchronized (this) {
9174 dumpServicesLocked(fd, pw, args, opti, true);
9175 }
9176 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009177 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009178 }
9179
9180 // No piece of data specified, dump everything.
9181 synchronized (this) {
9182 boolean needSep;
9183 if (dumpAll) {
9184 pw.println("Providers in Current Activity Manager State:");
9185 }
9186 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll);
9187 if (needSep) {
9188 pw.println(" ");
9189 }
9190 if (dumpAll) {
9191 pw.println("-------------------------------------------------------------------------------");
9192 pw.println("Broadcasts in Current Activity Manager State:");
9193 }
9194 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll);
9195 if (needSep) {
9196 pw.println(" ");
9197 }
9198 if (dumpAll) {
9199 pw.println("-------------------------------------------------------------------------------");
9200 pw.println("Services in Current Activity Manager State:");
9201 }
9202 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll);
9203 if (needSep) {
9204 pw.println(" ");
9205 }
9206 if (dumpAll) {
9207 pw.println("-------------------------------------------------------------------------------");
9208 pw.println("PendingIntents in Current Activity Manager State:");
9209 }
9210 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll);
9211 if (needSep) {
9212 pw.println(" ");
9213 }
9214 if (dumpAll) {
9215 pw.println("-------------------------------------------------------------------------------");
9216 pw.println("Activities in Current Activity Manager State:");
9217 }
9218 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, !dumpAll);
9219 if (needSep) {
9220 pw.println(" ");
9221 }
9222 if (dumpAll) {
9223 pw.println("-------------------------------------------------------------------------------");
9224 pw.println("Processes in Current Activity Manager State:");
9225 }
9226 dumpProcessesLocked(fd, pw, args, opti, dumpAll);
9227 }
9228 }
9229
9230 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9231 int opti, boolean dumpAll, boolean needHeader) {
9232 if (needHeader) {
9233 pw.println(" Activity stack:");
9234 }
9235 dumpHistoryList(pw, mHistory, " ", "Hist", true);
9236 pw.println(" ");
9237 pw.println(" Running activities (most recent first):");
9238 dumpHistoryList(pw, mLRUActivities, " ", "Run", false);
9239 if (mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009240 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009241 pw.println(" Activities waiting for another to become visible:");
9242 dumpHistoryList(pw, mWaitingVisibleActivities, " ", "Wait", false);
9243 }
9244 if (mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009245 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009246 pw.println(" Activities waiting to stop:");
9247 dumpHistoryList(pw, mStoppingActivities, " ", "Stop", false);
9248 }
9249 if (mFinishingActivities.size() > 0) {
9250 pw.println(" ");
9251 pw.println(" Activities waiting to finish:");
9252 dumpHistoryList(pw, mFinishingActivities, " ", "Fin", false);
9253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009254
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009255 pw.println(" ");
9256 pw.println(" mPausingActivity: " + mPausingActivity);
9257 pw.println(" mResumedActivity: " + mResumedActivity);
9258 pw.println(" mFocusedActivity: " + mFocusedActivity);
9259 pw.println(" mLastPausedActivity: " + mLastPausedActivity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009260
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009261 if (dumpAll && mRecentTasks.size() > 0) {
9262 pw.println(" ");
9263 pw.println("Recent tasks in Current Activity Manager State:");
9264
9265 final int N = mRecentTasks.size();
9266 for (int i=0; i<N; i++) {
9267 TaskRecord tr = mRecentTasks.get(i);
9268 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9269 pw.println(tr);
9270 mRecentTasks.get(i).dump(pw, " ");
9271 }
9272 }
9273
9274 pw.println(" ");
9275 pw.println(" mCurTask: " + mCurTask);
9276
9277 return true;
9278 }
9279
9280 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9281 int opti, boolean dumpAll) {
9282 boolean needSep = false;
9283 int numPers = 0;
9284
9285 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009286 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9287 final int NA = procs.size();
9288 for (int ia=0; ia<NA; ia++) {
9289 if (!needSep) {
9290 pw.println(" All known processes:");
9291 needSep = true;
9292 }
9293 ProcessRecord r = procs.valueAt(ia);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009294 pw.print(r.persistent ? " *PERS*" : " *APP*");
9295 pw.print(" UID "); pw.print(procs.keyAt(ia));
9296 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009297 r.dump(pw, " ");
9298 if (r.persistent) {
9299 numPers++;
9300 }
9301 }
9302 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009303 }
9304
9305 if (mLruProcesses.size() > 0) {
9306 if (needSep) pw.println(" ");
9307 needSep = true;
9308 pw.println(" Running processes (most recent first):");
9309 dumpProcessList(pw, this, mLruProcesses, " ",
9310 "App ", "PERS", true);
9311 needSep = true;
9312 }
9313
9314 synchronized (mPidsSelfLocked) {
9315 if (mPidsSelfLocked.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009316 if (needSep) pw.println(" ");
9317 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009318 pw.println(" PID mappings:");
9319 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9320 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9321 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009322 }
9323 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009324 }
9325
9326 if (mForegroundProcesses.size() > 0) {
9327 if (needSep) pw.println(" ");
9328 needSep = true;
9329 pw.println(" Foreground Processes:");
9330 for (int i=0; i<mForegroundProcesses.size(); i++) {
9331 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9332 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009333 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009334 }
9335
9336 if (mPersistentStartingProcesses.size() > 0) {
9337 if (needSep) pw.println(" ");
9338 needSep = true;
9339 pw.println(" Persisent processes that are starting:");
9340 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
9341 "Starting Norm", "Restarting PERS", false);
9342 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009343
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009344 if (mStartingProcesses.size() > 0) {
9345 if (needSep) pw.println(" ");
9346 needSep = true;
9347 pw.println(" Processes that are starting:");
9348 dumpProcessList(pw, this, mStartingProcesses, " ",
9349 "Starting Norm", "Starting PERS", false);
9350 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009351
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009352 if (mRemovedProcesses.size() > 0) {
9353 if (needSep) pw.println(" ");
9354 needSep = true;
9355 pw.println(" Processes that are being removed:");
9356 dumpProcessList(pw, this, mRemovedProcesses, " ",
9357 "Removed Norm", "Removed PERS", false);
9358 }
9359
9360 if (mProcessesOnHold.size() > 0) {
9361 if (needSep) pw.println(" ");
9362 needSep = true;
9363 pw.println(" Processes that are on old until the system is ready:");
9364 dumpProcessList(pw, this, mProcessesOnHold, " ",
9365 "OnHold Norm", "OnHold PERS", false);
9366 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009367
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009368 if (mProcessesToGc.size() > 0) {
9369 if (needSep) pw.println(" ");
9370 needSep = true;
9371 pw.println(" Processes that are waiting to GC:");
9372 long now = SystemClock.uptimeMillis();
9373 for (int i=0; i<mProcessesToGc.size(); i++) {
9374 ProcessRecord proc = mProcessesToGc.get(i);
9375 pw.print(" Process "); pw.println(proc);
9376 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9377 pw.print(", last gced=");
9378 pw.print(now-proc.lastRequestedGc);
9379 pw.print(" ms ago, last lowMem=");
9380 pw.print(now-proc.lastLowMemory);
9381 pw.println(" ms ago");
9382
9383 }
9384 }
9385
9386 if (mProcessCrashTimes.getMap().size() > 0) {
9387 if (needSep) pw.println(" ");
9388 needSep = true;
9389 pw.println(" Time since processes crashed:");
9390 long now = SystemClock.uptimeMillis();
9391 for (Map.Entry<String, SparseArray<Long>> procs
9392 : mProcessCrashTimes.getMap().entrySet()) {
9393 SparseArray<Long> uids = procs.getValue();
9394 final int N = uids.size();
9395 for (int i=0; i<N; i++) {
9396 pw.print(" Process "); pw.print(procs.getKey());
9397 pw.print(" uid "); pw.print(uids.keyAt(i));
9398 pw.print(": last crashed ");
9399 pw.print((now-uids.valueAt(i)));
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009400 pw.println(" ms ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009401 }
9402 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009403 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009404
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009405 if (mBadProcesses.getMap().size() > 0) {
9406 if (needSep) pw.println(" ");
9407 needSep = true;
9408 pw.println(" Bad processes:");
9409 for (Map.Entry<String, SparseArray<Long>> procs
9410 : mBadProcesses.getMap().entrySet()) {
9411 SparseArray<Long> uids = procs.getValue();
9412 final int N = uids.size();
9413 for (int i=0; i<N; i++) {
9414 pw.print(" Bad process "); pw.print(procs.getKey());
9415 pw.print(" uid "); pw.print(uids.keyAt(i));
9416 pw.print(": crashed at time ");
9417 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009418 }
9419 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009420 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009421
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009422 pw.println(" ");
9423 pw.println(" mHomeProcess: " + mHomeProcess);
9424 pw.println(" mConfiguration: " + mConfiguration);
9425 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
9426 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9427 || mOrigWaitForDebugger) {
9428 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9429 + " mDebugTransient=" + mDebugTransient
9430 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9431 }
9432 if (mAlwaysFinishActivities || mController != null) {
9433 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9434 + " mController=" + mController);
9435 }
9436 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009437 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009438 pw.println(" mStartRunning=" + mStartRunning
9439 + " mSystemReady=" + mSystemReady
9440 + " mBooting=" + mBooting
9441 + " mBooted=" + mBooted
9442 + " mFactoryTest=" + mFactoryTest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009443 pw.println(" mGoingToSleep=" + mGoingToSleep);
9444 pw.println(" mLaunchingActivity=" + mLaunchingActivity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009445 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009446
9447 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009448 }
9449
9450 /**
9451 * There are three ways to call this:
9452 * - no service specified: dump all the services
9453 * - a flattened component name that matched an existing service was specified as the
9454 * first arg: dump that one service
9455 * - the first arg isn't the flattened component name of an existing service:
9456 * dump all services whose component contains the first arg as a substring
9457 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009458 protected void dumpService(FileDescriptor fd, PrintWriter pw, String[] args,
9459 int opti, boolean dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009460 String[] newArgs;
9461 String componentNameString;
9462 ServiceRecord r;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009463 if (opti <= args.length) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009464 componentNameString = null;
9465 newArgs = EMPTY_STRING_ARRAY;
9466 r = null;
9467 } else {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009468 componentNameString = args[opti];
9469 opti++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009470 ComponentName componentName = ComponentName.unflattenFromString(componentNameString);
9471 r = componentName != null ? mServices.get(componentName) : null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009472 newArgs = new String[args.length - opti];
9473 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009474 }
9475
9476 if (r != null) {
9477 dumpService(fd, pw, r, newArgs);
9478 } else {
9479 for (ServiceRecord r1 : mServices.values()) {
9480 if (componentNameString == null
9481 || r1.name.flattenToString().contains(componentNameString)) {
9482 dumpService(fd, pw, r1, newArgs);
9483 }
9484 }
9485 }
9486 }
9487
9488 /**
9489 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
9490 * there is a thread associated with the service.
9491 */
9492 private void dumpService(FileDescriptor fd, PrintWriter pw, ServiceRecord r, String[] args) {
9493 pw.println(" Service " + r.name.flattenToString());
9494 if (r.app != null && r.app.thread != null) {
9495 try {
9496 // flush anything that is already in the PrintWriter since the thread is going
9497 // to write to the file descriptor directly
9498 pw.flush();
9499 r.app.thread.dumpService(fd, r, args);
9500 pw.print("\n");
9501 } catch (RemoteException e) {
9502 pw.println("got a RemoteException while dumping the service");
9503 }
9504 }
9505 }
9506
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009507 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9508 int opti, boolean dumpAll) {
9509 boolean needSep = false;
9510
9511 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009512 if (mRegisteredReceivers.size() > 0) {
9513 pw.println(" ");
9514 pw.println(" Registered Receivers:");
9515 Iterator it = mRegisteredReceivers.values().iterator();
9516 while (it.hasNext()) {
9517 ReceiverList r = (ReceiverList)it.next();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009518 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009519 r.dump(pw, " ");
9520 }
9521 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009523 pw.println(" ");
9524 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009525 mReceiverResolver.dump(pw, " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009526 needSep = true;
9527 }
9528
9529 if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
9530 || mPendingBroadcast != null) {
9531 if (mParallelBroadcasts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009532 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009533 pw.println(" Active broadcasts:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009534 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009535 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
9536 pw.println(" Broadcast #" + i + ":");
9537 mParallelBroadcasts.get(i).dump(pw, " ");
9538 }
9539 if (mOrderedBroadcasts.size() > 0) {
9540 pw.println(" ");
9541 pw.println(" Active serialized broadcasts:");
9542 }
9543 for (int i=mOrderedBroadcasts.size()-1; i>=0; i--) {
9544 pw.println(" Serialized Broadcast #" + i + ":");
9545 mOrderedBroadcasts.get(i).dump(pw, " ");
9546 }
9547 pw.println(" ");
9548 pw.println(" Pending broadcast:");
9549 if (mPendingBroadcast != null) {
9550 mPendingBroadcast.dump(pw, " ");
9551 } else {
9552 pw.println(" (null)");
9553 }
9554 needSep = true;
9555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009556
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009557 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009558 pw.println(" ");
Dianne Hackborn12527f92009-11-11 17:39:50 -08009559 pw.println(" Historical broadcasts:");
9560 for (int i=0; i<MAX_BROADCAST_HISTORY; i++) {
9561 BroadcastRecord r = mBroadcastHistory[i];
9562 if (r == null) {
9563 break;
9564 }
9565 pw.println(" Historical Broadcast #" + i + ":");
9566 r.dump(pw, " ");
9567 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009568 needSep = true;
9569 }
9570
9571 if (mStickyBroadcasts != null) {
Dianne Hackborn12527f92009-11-11 17:39:50 -08009572 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009573 pw.println(" Sticky broadcasts:");
9574 StringBuilder sb = new StringBuilder(128);
9575 for (Map.Entry<String, ArrayList<Intent>> ent
9576 : mStickyBroadcasts.entrySet()) {
9577 pw.print(" * Sticky action "); pw.print(ent.getKey());
9578 pw.println(":");
9579 ArrayList<Intent> intents = ent.getValue();
9580 final int N = intents.size();
9581 for (int i=0; i<N; i++) {
9582 sb.setLength(0);
9583 sb.append(" Intent: ");
9584 intents.get(i).toShortString(sb, true, false);
9585 pw.println(sb.toString());
9586 Bundle bundle = intents.get(i).getExtras();
9587 if (bundle != null) {
9588 pw.print(" ");
9589 pw.println(bundle.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009590 }
9591 }
9592 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009593 needSep = true;
9594 }
9595
9596 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009597 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009598 pw.println(" mBroadcastsScheduled=" + mBroadcastsScheduled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009599 pw.println(" mHandler:");
9600 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009601 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009602 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009603
9604 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009605 }
9606
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009607 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9608 int opti, boolean dumpAll) {
9609 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009610
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009611 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009612 if (mServices.size() > 0) {
9613 pw.println(" Active services:");
9614 Iterator<ServiceRecord> it = mServices.values().iterator();
9615 while (it.hasNext()) {
9616 ServiceRecord r = it.next();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009617 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009618 r.dump(pw, " ");
9619 }
9620 needSep = true;
9621 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009622 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009623
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009624 if (mPendingServices.size() > 0) {
9625 if (needSep) pw.println(" ");
9626 pw.println(" Pending services:");
9627 for (int i=0; i<mPendingServices.size(); i++) {
9628 ServiceRecord r = mPendingServices.get(i);
9629 pw.print(" * Pending "); pw.println(r);
9630 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009631 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009632 needSep = true;
9633 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009634
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009635 if (mRestartingServices.size() > 0) {
9636 if (needSep) pw.println(" ");
9637 pw.println(" Restarting services:");
9638 for (int i=0; i<mRestartingServices.size(); i++) {
9639 ServiceRecord r = mRestartingServices.get(i);
9640 pw.print(" * Restarting "); pw.println(r);
9641 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009642 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009643 needSep = true;
9644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009645
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009646 if (mStoppingServices.size() > 0) {
9647 if (needSep) pw.println(" ");
9648 pw.println(" Stopping services:");
9649 for (int i=0; i<mStoppingServices.size(); i++) {
9650 ServiceRecord r = mStoppingServices.get(i);
9651 pw.print(" * Stopping "); pw.println(r);
9652 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009653 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009654 needSep = true;
9655 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009656
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009657 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009658 if (mServiceConnections.size() > 0) {
9659 if (needSep) pw.println(" ");
9660 pw.println(" Connection bindings to services:");
9661 Iterator<ConnectionRecord> it
9662 = mServiceConnections.values().iterator();
9663 while (it.hasNext()) {
9664 ConnectionRecord r = it.next();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009665 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009666 r.dump(pw, " ");
9667 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009668 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009669 }
9670 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009671
9672 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009673 }
9674
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009675 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9676 int opti, boolean dumpAll) {
9677 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009678
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009679 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009680 if (mProvidersByClass.size() > 0) {
9681 if (needSep) pw.println(" ");
9682 pw.println(" Published content providers (by class):");
9683 Iterator it = mProvidersByClass.entrySet().iterator();
9684 while (it.hasNext()) {
9685 Map.Entry e = (Map.Entry)it.next();
9686 ContentProviderRecord r = (ContentProviderRecord)e.getValue();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009687 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009688 r.dump(pw, " ");
9689 }
9690 needSep = true;
9691 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009692
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009693 if (mProvidersByName.size() > 0) {
9694 pw.println(" ");
9695 pw.println(" Authority to provider mappings:");
9696 Iterator it = mProvidersByName.entrySet().iterator();
9697 while (it.hasNext()) {
9698 Map.Entry e = (Map.Entry)it.next();
9699 ContentProviderRecord r = (ContentProviderRecord)e.getValue();
9700 pw.print(" "); pw.print(e.getKey()); pw.print(": ");
9701 pw.println(r);
9702 }
9703 needSep = true;
9704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009705 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009706
9707 if (mLaunchingProviders.size() > 0) {
9708 if (needSep) pw.println(" ");
9709 pw.println(" Launching content providers:");
9710 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
9711 pw.print(" Launching #"); pw.print(i); pw.print(": ");
9712 pw.println(mLaunchingProviders.get(i));
9713 }
9714 needSep = true;
9715 }
9716
9717 if (mGrantedUriPermissions.size() > 0) {
9718 pw.println();
9719 pw.println("Granted Uri Permissions:");
9720 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9721 int uid = mGrantedUriPermissions.keyAt(i);
9722 HashMap<Uri, UriPermission> perms
9723 = mGrantedUriPermissions.valueAt(i);
9724 pw.print(" * UID "); pw.print(uid);
9725 pw.println(" holds:");
9726 for (UriPermission perm : perms.values()) {
9727 pw.print(" "); pw.println(perm);
9728 perm.dump(pw, " ");
9729 }
9730 }
9731 needSep = true;
9732 }
9733
9734 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009735 }
9736
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009737 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9738 int opti, boolean dumpAll) {
9739 boolean needSep = false;
9740
9741 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009742 if (this.mIntentSenderRecords.size() > 0) {
9743 Iterator<WeakReference<PendingIntentRecord>> it
9744 = mIntentSenderRecords.values().iterator();
9745 while (it.hasNext()) {
9746 WeakReference<PendingIntentRecord> ref = it.next();
9747 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009748 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009749 if (rec != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009750 pw.print(" * "); pw.println(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009751 rec.dump(pw, " ");
9752 } else {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009753 pw.print(" * "); pw.print(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009754 }
9755 }
9756 }
9757 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009758
9759 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009760 }
9761
9762 private static final void dumpHistoryList(PrintWriter pw, List list,
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009763 String prefix, String label, boolean complete) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009764 TaskRecord lastTask = null;
9765 for (int i=list.size()-1; i>=0; i--) {
9766 HistoryRecord r = (HistoryRecord)list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009767 final boolean full = complete || !r.inHistory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009768 if (lastTask != r.task) {
9769 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009770 pw.print(prefix);
9771 pw.print(full ? "* " : " ");
9772 pw.println(lastTask);
9773 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009774 lastTask.dump(pw, prefix + " ");
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009776 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009777 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9778 pw.print(" #"); pw.print(i); pw.print(": ");
9779 pw.println(r);
9780 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009781 r.dump(pw, prefix + " ");
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009782 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009783 }
9784 }
9785
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009786 private static String buildOomTag(String prefix, String space, int val, int base) {
9787 if (val == base) {
9788 if (space == null) return prefix;
9789 return prefix + " ";
9790 }
9791 return prefix + "+" + Integer.toString(val-base);
9792 }
9793
9794 private static final int dumpProcessList(PrintWriter pw,
9795 ActivityManagerService service, List list,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009796 String prefix, String normalLabel, String persistentLabel,
9797 boolean inclOomAdj) {
9798 int numPers = 0;
9799 for (int i=list.size()-1; i>=0; i--) {
9800 ProcessRecord r = (ProcessRecord)list.get(i);
9801 if (false) {
9802 pw.println(prefix + (r.persistent ? persistentLabel : normalLabel)
9803 + " #" + i + ":");
9804 r.dump(pw, prefix + " ");
9805 } else if (inclOomAdj) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009806 String oomAdj;
9807 if (r.setAdj >= EMPTY_APP_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08009808 oomAdj = buildOomTag("empty", null, r.setAdj, EMPTY_APP_ADJ);
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009809 } else if (r.setAdj >= HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08009810 oomAdj = buildOomTag("bak", " ", r.setAdj, HIDDEN_APP_MIN_ADJ);
9811 } else if (r.setAdj >= HOME_APP_ADJ) {
9812 oomAdj = buildOomTag("home ", null, r.setAdj, HOME_APP_ADJ);
9813 } else if (r.setAdj >= SECONDARY_SERVER_ADJ) {
9814 oomAdj = buildOomTag("svc", " ", r.setAdj, SECONDARY_SERVER_ADJ);
9815 } else if (r.setAdj >= BACKUP_APP_ADJ) {
9816 oomAdj = buildOomTag("bckup", null, r.setAdj, BACKUP_APP_ADJ);
9817 } else if (r.setAdj >= VISIBLE_APP_ADJ) {
9818 oomAdj = buildOomTag("vis ", null, r.setAdj, VISIBLE_APP_ADJ);
9819 } else if (r.setAdj >= FOREGROUND_APP_ADJ) {
9820 oomAdj = buildOomTag("fore ", null, r.setAdj, FOREGROUND_APP_ADJ);
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009821 } else if (r.setAdj >= CORE_SERVER_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08009822 oomAdj = buildOomTag("core ", null, r.setAdj, CORE_SERVER_ADJ);
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009823 } else if (r.setAdj >= SYSTEM_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08009824 oomAdj = buildOomTag("sys ", null, r.setAdj, SYSTEM_ADJ);
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009825 } else {
9826 oomAdj = Integer.toString(r.setAdj);
9827 }
9828 String schedGroup;
9829 switch (r.setSchedGroup) {
9830 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9831 schedGroup = "B";
9832 break;
9833 case Process.THREAD_GROUP_DEFAULT:
9834 schedGroup = "F";
9835 break;
9836 default:
9837 schedGroup = Integer.toString(r.setSchedGroup);
9838 break;
9839 }
9840 pw.println(String.format("%s%s #%2d: adj=%s/%s %s (%s)",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009841 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackborndd71fc82009-12-16 19:24:32 -08009842 i, oomAdj, schedGroup, r.toShortString(), r.adjType));
Dianne Hackbornde42bb62009-08-05 12:26:15 -07009843 if (r.adjSource != null || r.adjTarget != null) {
9844 pw.println(prefix + " " + r.adjTarget
Dianne Hackborndd71fc82009-12-16 19:24:32 -08009845 + "<=" + r.adjSource);
Dianne Hackbornde42bb62009-08-05 12:26:15 -07009846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009847 } else {
9848 pw.println(String.format("%s%s #%2d: %s",
9849 prefix, (r.persistent ? persistentLabel : normalLabel),
9850 i, r.toString()));
9851 }
9852 if (r.persistent) {
9853 numPers++;
9854 }
9855 }
9856 return numPers;
9857 }
9858
9859 private static final void dumpApplicationMemoryUsage(FileDescriptor fd,
9860 PrintWriter pw, List list, String prefix, String[] args) {
Dianne Hackborn6447ca32009-04-07 19:50:08 -07009861 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009862 long uptime = SystemClock.uptimeMillis();
9863 long realtime = SystemClock.elapsedRealtime();
9864
9865 if (isCheckinRequest) {
9866 // short checkin version
9867 pw.println(uptime + "," + realtime);
9868 pw.flush();
9869 } else {
9870 pw.println("Applications Memory Usage (kB):");
9871 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9872 }
9873 for (int i = list.size() - 1 ; i >= 0 ; i--) {
9874 ProcessRecord r = (ProcessRecord)list.get(i);
9875 if (r.thread != null) {
9876 if (!isCheckinRequest) {
9877 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
9878 pw.flush();
9879 }
9880 try {
9881 r.thread.asBinder().dump(fd, args);
9882 } catch (RemoteException e) {
9883 if (!isCheckinRequest) {
9884 pw.println("Got RemoteException!");
9885 pw.flush();
9886 }
9887 }
9888 }
9889 }
9890 }
9891
9892 /**
9893 * Searches array of arguments for the specified string
9894 * @param args array of argument strings
9895 * @param value value to search for
9896 * @return true if the value is contained in the array
9897 */
9898 private static boolean scanArgs(String[] args, String value) {
9899 if (args != null) {
9900 for (String arg : args) {
9901 if (value.equals(arg)) {
9902 return true;
9903 }
9904 }
9905 }
9906 return false;
9907 }
9908
Dianne Hackborn75b03852009-06-12 15:43:26 -07009909 private final int indexOfTokenLocked(IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009910 int count = mHistory.size();
9911
9912 // convert the token to an entry in the history.
9913 HistoryRecord r = null;
9914 int index = -1;
9915 for (int i=count-1; i>=0; i--) {
9916 Object o = mHistory.get(i);
9917 if (o == token) {
9918 r = (HistoryRecord)o;
9919 index = i;
9920 break;
9921 }
9922 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009923
9924 return index;
9925 }
9926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009927 private final void killServicesLocked(ProcessRecord app,
9928 boolean allowRestart) {
9929 // Report disconnected services.
9930 if (false) {
9931 // XXX we are letting the client link to the service for
9932 // death notifications.
9933 if (app.services.size() > 0) {
9934 Iterator it = app.services.iterator();
9935 while (it.hasNext()) {
9936 ServiceRecord r = (ServiceRecord)it.next();
9937 if (r.connections.size() > 0) {
9938 Iterator<ConnectionRecord> jt
9939 = r.connections.values().iterator();
9940 while (jt.hasNext()) {
9941 ConnectionRecord c = jt.next();
9942 if (c.binding.client != app) {
9943 try {
9944 //c.conn.connected(r.className, null);
9945 } catch (Exception e) {
9946 // todo: this should be asynchronous!
9947 Log.w(TAG, "Exception thrown disconnected servce "
9948 + r.shortName
9949 + " from app " + app.processName, e);
9950 }
9951 }
9952 }
9953 }
9954 }
9955 }
9956 }
9957
9958 // Clean up any connections this application has to other services.
9959 if (app.connections.size() > 0) {
9960 Iterator<ConnectionRecord> it = app.connections.iterator();
9961 while (it.hasNext()) {
9962 ConnectionRecord r = it.next();
9963 removeConnectionLocked(r, app, null);
9964 }
9965 }
9966 app.connections.clear();
9967
9968 if (app.services.size() != 0) {
9969 // Any services running in the application need to be placed
9970 // back in the pending list.
9971 Iterator it = app.services.iterator();
9972 while (it.hasNext()) {
9973 ServiceRecord sr = (ServiceRecord)it.next();
9974 synchronized (sr.stats.getBatteryStats()) {
9975 sr.stats.stopLaunchedLocked();
9976 }
9977 sr.app = null;
9978 sr.executeNesting = 0;
9979 mStoppingServices.remove(sr);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07009980
9981 boolean hasClients = sr.bindings.size() > 0;
9982 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009983 Iterator<IntentBindRecord> bindings
9984 = sr.bindings.values().iterator();
9985 while (bindings.hasNext()) {
9986 IntentBindRecord b = bindings.next();
9987 if (DEBUG_SERVICE) Log.v(TAG, "Killing binding " + b
9988 + ": shouldUnbind=" + b.hasBound);
9989 b.binder = null;
9990 b.requested = b.received = b.hasBound = false;
9991 }
9992 }
9993
9994 if (sr.crashCount >= 2) {
9995 Log.w(TAG, "Service crashed " + sr.crashCount
9996 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -08009997 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009998 sr.crashCount, sr.shortName, app.pid);
9999 bringDownServiceLocked(sr, true);
10000 } else if (!allowRestart) {
10001 bringDownServiceLocked(sr, true);
10002 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010003 boolean canceled = scheduleServiceRestartLocked(sr, true);
10004
10005 // Should the service remain running? Note that in the
10006 // extreme case of so many attempts to deliver a command
10007 // that it failed, that we also will stop it here.
10008 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10009 if (sr.pendingStarts.size() == 0) {
10010 sr.startRequested = false;
10011 if (!hasClients) {
10012 // Whoops, no reason to restart!
10013 bringDownServiceLocked(sr, true);
10014 }
10015 }
10016 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010017 }
10018 }
10019
10020 if (!allowRestart) {
10021 app.services.clear();
10022 }
10023 }
10024
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010025 // Make sure we have no more records on the stopping list.
10026 int i = mStoppingServices.size();
10027 while (i > 0) {
10028 i--;
10029 ServiceRecord sr = mStoppingServices.get(i);
10030 if (sr.app == app) {
10031 mStoppingServices.remove(i);
10032 }
10033 }
10034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010035 app.executingServices.clear();
10036 }
10037
10038 private final void removeDyingProviderLocked(ProcessRecord proc,
10039 ContentProviderRecord cpr) {
10040 synchronized (cpr) {
10041 cpr.launchingApp = null;
10042 cpr.notifyAll();
10043 }
10044
10045 mProvidersByClass.remove(cpr.info.name);
10046 String names[] = cpr.info.authority.split(";");
10047 for (int j = 0; j < names.length; j++) {
10048 mProvidersByName.remove(names[j]);
10049 }
10050
10051 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10052 while (cit.hasNext()) {
10053 ProcessRecord capp = cit.next();
10054 if (!capp.persistent && capp.thread != null
10055 && capp.pid != 0
10056 && capp.pid != MY_PID) {
10057 Log.i(TAG, "Killing app " + capp.processName
10058 + " (pid " + capp.pid
10059 + ") because provider " + cpr.info.name
10060 + " is in dying process " + proc.processName);
10061 Process.killProcess(capp.pid);
10062 }
10063 }
10064
10065 mLaunchingProviders.remove(cpr);
10066 }
10067
10068 /**
10069 * Main code for cleaning up a process when it has gone away. This is
10070 * called both as a result of the process dying, or directly when stopping
10071 * a process when running in single process mode.
10072 */
10073 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
10074 boolean restarting, int index) {
10075 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010076 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010077 }
10078
Dianne Hackborn36124872009-10-08 16:22:03 -070010079 mProcessesToGc.remove(app);
10080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010081 // Dismiss any open dialogs.
10082 if (app.crashDialog != null) {
10083 app.crashDialog.dismiss();
10084 app.crashDialog = null;
10085 }
10086 if (app.anrDialog != null) {
10087 app.anrDialog.dismiss();
10088 app.anrDialog = null;
10089 }
10090 if (app.waitDialog != null) {
10091 app.waitDialog.dismiss();
10092 app.waitDialog = null;
10093 }
10094
10095 app.crashing = false;
10096 app.notResponding = false;
10097
10098 app.resetPackageList();
10099 app.thread = null;
10100 app.forcingToForeground = null;
10101 app.foregroundServices = false;
10102
10103 killServicesLocked(app, true);
10104
10105 boolean restart = false;
10106
10107 int NL = mLaunchingProviders.size();
10108
10109 // Remove published content providers.
10110 if (!app.pubProviders.isEmpty()) {
10111 Iterator it = app.pubProviders.values().iterator();
10112 while (it.hasNext()) {
10113 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10114 cpr.provider = null;
10115 cpr.app = null;
10116
10117 // See if someone is waiting for this provider... in which
10118 // case we don't remove it, but just let it restart.
10119 int i = 0;
10120 if (!app.bad) {
10121 for (; i<NL; i++) {
10122 if (mLaunchingProviders.get(i) == cpr) {
10123 restart = true;
10124 break;
10125 }
10126 }
10127 } else {
10128 i = NL;
10129 }
10130
10131 if (i >= NL) {
10132 removeDyingProviderLocked(app, cpr);
10133 NL = mLaunchingProviders.size();
10134 }
10135 }
10136 app.pubProviders.clear();
10137 }
10138
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010139 // Take care of any launching providers waiting for this process.
10140 if (checkAppInLaunchingProvidersLocked(app, false)) {
10141 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010142 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010144 // Unregister from connected content providers.
10145 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010146 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010147 while (it.hasNext()) {
10148 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10149 cpr.clients.remove(app);
10150 }
10151 app.conProviders.clear();
10152 }
10153
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010154 // At this point there may be remaining entries in mLaunchingProviders
10155 // where we were the only one waiting, so they are no longer of use.
10156 // Look for these and clean up if found.
10157 // XXX Commented out for now. Trying to figure out a way to reproduce
10158 // the actual situation to identify what is actually going on.
10159 if (false) {
10160 for (int i=0; i<NL; i++) {
10161 ContentProviderRecord cpr = (ContentProviderRecord)
10162 mLaunchingProviders.get(i);
10163 if (cpr.clients.size() <= 0 && cpr.externals <= 0) {
10164 synchronized (cpr) {
10165 cpr.launchingApp = null;
10166 cpr.notifyAll();
10167 }
10168 }
10169 }
10170 }
10171
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010172 skipCurrentReceiverLocked(app);
10173
10174 // Unregister any receivers.
10175 if (app.receivers.size() > 0) {
10176 Iterator<ReceiverList> it = app.receivers.iterator();
10177 while (it.hasNext()) {
10178 removeReceiverLocked(it.next());
10179 }
10180 app.receivers.clear();
10181 }
10182
Christopher Tate181fafa2009-05-14 11:12:14 -070010183 // If the app is undergoing backup, tell the backup manager about it
10184 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
10185 if (DEBUG_BACKUP) Log.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
10186 try {
10187 IBackupManager bm = IBackupManager.Stub.asInterface(
10188 ServiceManager.getService(Context.BACKUP_SERVICE));
10189 bm.agentDisconnected(app.info.packageName);
10190 } catch (RemoteException e) {
10191 // can't happen; backup manager is local
10192 }
10193 }
10194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010195 // If the caller is restarting this app, then leave it in its
10196 // current lists and let the caller take care of it.
10197 if (restarting) {
10198 return;
10199 }
10200
10201 if (!app.persistent) {
10202 if (DEBUG_PROCESSES) Log.v(TAG,
10203 "Removing non-persistent process during cleanup: " + app);
10204 mProcessNames.remove(app.processName, app.info.uid);
10205 } else if (!app.removed) {
10206 // This app is persistent, so we need to keep its record around.
10207 // If it is not already on the pending app list, add it there
10208 // and start a new process for it.
10209 app.thread = null;
10210 app.forcingToForeground = null;
10211 app.foregroundServices = false;
10212 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10213 mPersistentStartingProcesses.add(app);
10214 restart = true;
10215 }
10216 }
10217 mProcessesOnHold.remove(app);
10218
The Android Open Source Project4df24232009-03-05 14:34:35 -080010219 if (app == mHomeProcess) {
10220 mHomeProcess = null;
10221 }
10222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010223 if (restart) {
10224 // We have components that still need to be running in the
10225 // process, so re-launch it.
10226 mProcessNames.put(app.processName, app.info.uid, app);
10227 startProcessLocked(app, "restart", app.processName);
10228 } else if (app.pid > 0 && app.pid != MY_PID) {
10229 // Goodbye!
10230 synchronized (mPidsSelfLocked) {
10231 mPidsSelfLocked.remove(app.pid);
10232 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10233 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010234 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010235 }
10236 }
10237
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010238 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10239 // Look through the content providers we are waiting to have launched,
10240 // and if any run in this process then either schedule a restart of
10241 // the process or kill the client waiting for it if this process has
10242 // gone bad.
10243 int NL = mLaunchingProviders.size();
10244 boolean restart = false;
10245 for (int i=0; i<NL; i++) {
10246 ContentProviderRecord cpr = (ContentProviderRecord)
10247 mLaunchingProviders.get(i);
10248 if (cpr.launchingApp == app) {
10249 if (!alwaysBad && !app.bad) {
10250 restart = true;
10251 } else {
10252 removeDyingProviderLocked(app, cpr);
10253 NL = mLaunchingProviders.size();
10254 }
10255 }
10256 }
10257 return restart;
10258 }
10259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010260 // =========================================================
10261 // SERVICES
10262 // =========================================================
10263
10264 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10265 ActivityManager.RunningServiceInfo info =
10266 new ActivityManager.RunningServiceInfo();
10267 info.service = r.name;
10268 if (r.app != null) {
10269 info.pid = r.app.pid;
10270 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010271 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010272 info.process = r.processName;
10273 info.foreground = r.isForeground;
10274 info.activeSince = r.createTime;
10275 info.started = r.startRequested;
10276 info.clientCount = r.connections.size();
10277 info.crashCount = r.crashCount;
10278 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010279 if (r.isForeground) {
10280 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10281 }
10282 if (r.startRequested) {
10283 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10284 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010285 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010286 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10287 }
10288 if (r.app != null && r.app.persistent) {
10289 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10290 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010291 for (ConnectionRecord conn : r.connections.values()) {
10292 if (conn.clientLabel != 0) {
10293 info.clientPackage = conn.binding.client.info.packageName;
10294 info.clientLabel = conn.clientLabel;
10295 break;
10296 }
10297 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010298 return info;
10299 }
10300
10301 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10302 int flags) {
10303 synchronized (this) {
10304 ArrayList<ActivityManager.RunningServiceInfo> res
10305 = new ArrayList<ActivityManager.RunningServiceInfo>();
10306
10307 if (mServices.size() > 0) {
10308 Iterator<ServiceRecord> it = mServices.values().iterator();
10309 while (it.hasNext() && res.size() < maxNum) {
10310 res.add(makeRunningServiceInfoLocked(it.next()));
10311 }
10312 }
10313
10314 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10315 ServiceRecord r = mRestartingServices.get(i);
10316 ActivityManager.RunningServiceInfo info =
10317 makeRunningServiceInfoLocked(r);
10318 info.restarting = r.nextRestartTime;
10319 res.add(info);
10320 }
10321
10322 return res;
10323 }
10324 }
10325
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010326 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
10327 synchronized (this) {
10328 ServiceRecord r = mServices.get(name);
10329 if (r != null) {
10330 for (ConnectionRecord conn : r.connections.values()) {
10331 if (conn.clientIntent != null) {
10332 return conn.clientIntent;
10333 }
10334 }
10335 }
10336 }
10337 return null;
10338 }
10339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010340 private final ServiceRecord findServiceLocked(ComponentName name,
10341 IBinder token) {
10342 ServiceRecord r = mServices.get(name);
10343 return r == token ? r : null;
10344 }
10345
10346 private final class ServiceLookupResult {
10347 final ServiceRecord record;
10348 final String permission;
10349
10350 ServiceLookupResult(ServiceRecord _record, String _permission) {
10351 record = _record;
10352 permission = _permission;
10353 }
10354 };
10355
10356 private ServiceLookupResult findServiceLocked(Intent service,
10357 String resolvedType) {
10358 ServiceRecord r = null;
10359 if (service.getComponent() != null) {
10360 r = mServices.get(service.getComponent());
10361 }
10362 if (r == null) {
10363 Intent.FilterComparison filter = new Intent.FilterComparison(service);
10364 r = mServicesByIntent.get(filter);
10365 }
10366
10367 if (r == null) {
10368 try {
10369 ResolveInfo rInfo =
10370 ActivityThread.getPackageManager().resolveService(
10371 service, resolvedType, 0);
10372 ServiceInfo sInfo =
10373 rInfo != null ? rInfo.serviceInfo : null;
10374 if (sInfo == null) {
10375 return null;
10376 }
10377
10378 ComponentName name = new ComponentName(
10379 sInfo.applicationInfo.packageName, sInfo.name);
10380 r = mServices.get(name);
10381 } catch (RemoteException ex) {
10382 // pm is in same process, this will never happen.
10383 }
10384 }
10385 if (r != null) {
10386 int callingPid = Binder.getCallingPid();
10387 int callingUid = Binder.getCallingUid();
10388 if (checkComponentPermission(r.permission,
10389 callingPid, callingUid, r.exported ? -1 : r.appInfo.uid)
10390 != PackageManager.PERMISSION_GRANTED) {
10391 Log.w(TAG, "Permission Denial: Accessing service " + r.name
10392 + " from pid=" + callingPid
10393 + ", uid=" + callingUid
10394 + " requires " + r.permission);
10395 return new ServiceLookupResult(null, r.permission);
10396 }
10397 return new ServiceLookupResult(r, null);
10398 }
10399 return null;
10400 }
10401
10402 private class ServiceRestarter implements Runnable {
10403 private ServiceRecord mService;
10404
10405 void setService(ServiceRecord service) {
10406 mService = service;
10407 }
10408
10409 public void run() {
10410 synchronized(ActivityManagerService.this) {
10411 performServiceRestartLocked(mService);
10412 }
10413 }
10414 }
10415
10416 private ServiceLookupResult retrieveServiceLocked(Intent service,
10417 String resolvedType, int callingPid, int callingUid) {
10418 ServiceRecord r = null;
10419 if (service.getComponent() != null) {
10420 r = mServices.get(service.getComponent());
10421 }
10422 Intent.FilterComparison filter = new Intent.FilterComparison(service);
10423 r = mServicesByIntent.get(filter);
10424 if (r == null) {
10425 try {
10426 ResolveInfo rInfo =
10427 ActivityThread.getPackageManager().resolveService(
Dianne Hackborn1655be42009-05-08 14:29:01 -070010428 service, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010429 ServiceInfo sInfo =
10430 rInfo != null ? rInfo.serviceInfo : null;
10431 if (sInfo == null) {
10432 Log.w(TAG, "Unable to start service " + service +
10433 ": not found");
10434 return null;
10435 }
10436
10437 ComponentName name = new ComponentName(
10438 sInfo.applicationInfo.packageName, sInfo.name);
10439 r = mServices.get(name);
10440 if (r == null) {
10441 filter = new Intent.FilterComparison(service.cloneFilter());
10442 ServiceRestarter res = new ServiceRestarter();
10443 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10444 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10445 synchronized (stats) {
10446 ss = stats.getServiceStatsLocked(
10447 sInfo.applicationInfo.uid, sInfo.packageName,
10448 sInfo.name);
10449 }
10450 r = new ServiceRecord(ss, name, filter, sInfo, res);
10451 res.setService(r);
10452 mServices.put(name, r);
10453 mServicesByIntent.put(filter, r);
10454
10455 // Make sure this component isn't in the pending list.
10456 int N = mPendingServices.size();
10457 for (int i=0; i<N; i++) {
10458 ServiceRecord pr = mPendingServices.get(i);
10459 if (pr.name.equals(name)) {
10460 mPendingServices.remove(i);
10461 i--;
10462 N--;
10463 }
10464 }
10465 }
10466 } catch (RemoteException ex) {
10467 // pm is in same process, this will never happen.
10468 }
10469 }
10470 if (r != null) {
10471 if (checkComponentPermission(r.permission,
10472 callingPid, callingUid, r.exported ? -1 : r.appInfo.uid)
10473 != PackageManager.PERMISSION_GRANTED) {
10474 Log.w(TAG, "Permission Denial: Accessing service " + r.name
10475 + " from pid=" + Binder.getCallingPid()
10476 + ", uid=" + Binder.getCallingUid()
10477 + " requires " + r.permission);
10478 return new ServiceLookupResult(null, r.permission);
10479 }
10480 return new ServiceLookupResult(r, null);
10481 }
10482 return null;
10483 }
10484
10485 private final void bumpServiceExecutingLocked(ServiceRecord r) {
10486 long now = SystemClock.uptimeMillis();
10487 if (r.executeNesting == 0 && r.app != null) {
10488 if (r.app.executingServices.size() == 0) {
10489 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10490 msg.obj = r.app;
10491 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
10492 }
10493 r.app.executingServices.add(r);
10494 }
10495 r.executeNesting++;
10496 r.executingStart = now;
10497 }
10498
10499 private final void sendServiceArgsLocked(ServiceRecord r,
10500 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010501 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010502 if (N == 0) {
10503 return;
10504 }
10505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010506 int i = 0;
10507 while (i < N) {
10508 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010509 ServiceRecord.StartItem si = r.pendingStarts.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010510 if (DEBUG_SERVICE) Log.v(TAG, "Sending arguments to service: "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010511 + r.name + " " + r.intent + " args=" + si.intent);
Dianne Hackbornfed534e2009-09-23 00:42:12 -070010512 if (si.intent == null && N > 1) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010513 // If somehow we got a dummy start at the front, then
10514 // just drop it here.
10515 i++;
10516 continue;
10517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010518 bumpServiceExecutingLocked(r);
10519 if (!oomAdjusted) {
10520 oomAdjusted = true;
10521 updateOomAdjLocked(r.app);
10522 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010523 int flags = 0;
10524 if (si.deliveryCount > 0) {
10525 flags |= Service.START_FLAG_RETRY;
10526 }
10527 if (si.doneExecutingCount > 0) {
10528 flags |= Service.START_FLAG_REDELIVERY;
10529 }
10530 r.app.thread.scheduleServiceArgs(r, si.id, flags, si.intent);
10531 si.deliveredTime = SystemClock.uptimeMillis();
10532 r.deliveredStarts.add(si);
10533 si.deliveryCount++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010534 i++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010535 } catch (RemoteException e) {
10536 // Remote process gone... we'll let the normal cleanup take
10537 // care of this.
10538 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010539 } catch (Exception e) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010540 Log.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010541 break;
10542 }
10543 }
10544 if (i == N) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010545 r.pendingStarts.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010546 } else {
10547 while (i > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010548 i--;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010549 r.pendingStarts.remove(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010550 }
10551 }
10552 }
10553
10554 private final boolean requestServiceBindingLocked(ServiceRecord r,
10555 IntentBindRecord i, boolean rebind) {
10556 if (r.app == null || r.app.thread == null) {
10557 // If service is not currently running, can't yet bind.
10558 return false;
10559 }
10560 if ((!i.requested || rebind) && i.apps.size() > 0) {
10561 try {
10562 bumpServiceExecutingLocked(r);
10563 if (DEBUG_SERVICE) Log.v(TAG, "Connecting binding " + i
10564 + ": shouldUnbind=" + i.hasBound);
10565 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
10566 if (!rebind) {
10567 i.requested = true;
10568 }
10569 i.hasBound = true;
10570 i.doRebind = false;
10571 } catch (RemoteException e) {
10572 return false;
10573 }
10574 }
10575 return true;
10576 }
10577
10578 private final void requestServiceBindingsLocked(ServiceRecord r) {
10579 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
10580 while (bindings.hasNext()) {
10581 IntentBindRecord i = bindings.next();
10582 if (!requestServiceBindingLocked(r, i, false)) {
10583 break;
10584 }
10585 }
10586 }
10587
10588 private final void realStartServiceLocked(ServiceRecord r,
10589 ProcessRecord app) throws RemoteException {
10590 if (app.thread == null) {
10591 throw new RemoteException();
10592 }
10593
10594 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070010595 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010596
10597 app.services.add(r);
10598 bumpServiceExecutingLocked(r);
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010599 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010600
10601 boolean created = false;
10602 try {
10603 if (DEBUG_SERVICE) Log.v(TAG, "Scheduling start service: "
10604 + r.name + " " + r.intent);
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010605 mStringBuilder.setLength(0);
10606 r.intent.getIntent().toShortString(mStringBuilder, false, true);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010607 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010608 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010609 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010610 synchronized (r.stats.getBatteryStats()) {
10611 r.stats.startLaunchedLocked();
10612 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070010613 ensurePackageDexOpt(r.serviceInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010614 app.thread.scheduleCreateService(r, r.serviceInfo);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010615 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010616 created = true;
10617 } finally {
10618 if (!created) {
10619 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010620 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010621 }
10622 }
10623
10624 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010625
10626 // If the service is in the started state, and there are no
10627 // pending arguments, then fake up one so its onStartCommand() will
10628 // be called.
10629 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
10630 r.lastStartId++;
10631 if (r.lastStartId < 1) {
10632 r.lastStartId = 1;
10633 }
10634 r.pendingStarts.add(new ServiceRecord.StartItem(r.lastStartId, null));
10635 }
10636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010637 sendServiceArgsLocked(r, true);
10638 }
10639
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010640 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
10641 boolean allowCancel) {
10642 boolean canceled = false;
10643
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010644 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010645 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070010646 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010647
10648 // Any delivered but not yet finished starts should be put back
10649 // on the pending list.
10650 final int N = r.deliveredStarts.size();
10651 if (N > 0) {
10652 for (int i=N-1; i>=0; i--) {
10653 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
10654 if (si.intent == null) {
10655 // We'll generate this again if needed.
10656 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
10657 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
10658 r.pendingStarts.add(0, si);
10659 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
10660 dur *= 2;
10661 if (minDuration < dur) minDuration = dur;
10662 if (resetTime < dur) resetTime = dur;
10663 } else {
10664 Log.w(TAG, "Canceling start item " + si.intent + " in service "
10665 + r.name);
10666 canceled = true;
10667 }
10668 }
10669 r.deliveredStarts.clear();
10670 }
10671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010672 r.totalRestartCount++;
10673 if (r.restartDelay == 0) {
10674 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010675 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010676 } else {
10677 // If it has been a "reasonably long time" since the service
10678 // was started, then reset our restart duration back to
10679 // the beginning, so we don't infinitely increase the duration
10680 // on a service that just occasionally gets killed (which is
10681 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010682 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010683 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010684 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010685 } else {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010686 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010687 if (r.restartDelay < minDuration) {
10688 r.restartDelay = minDuration;
10689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010690 }
10691 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010692
10693 r.nextRestartTime = now + r.restartDelay;
10694
10695 // Make sure that we don't end up restarting a bunch of services
10696 // all at the same time.
10697 boolean repeat;
10698 do {
10699 repeat = false;
10700 for (int i=mRestartingServices.size()-1; i>=0; i--) {
10701 ServiceRecord r2 = mRestartingServices.get(i);
10702 if (r2 != r && r.nextRestartTime
10703 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
10704 && r.nextRestartTime
10705 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
10706 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
10707 r.restartDelay = r.nextRestartTime - now;
10708 repeat = true;
10709 break;
10710 }
10711 }
10712 } while (repeat);
10713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010714 if (!mRestartingServices.contains(r)) {
10715 mRestartingServices.add(r);
10716 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010717
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010718 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010720 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010721 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010722 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
10723 Log.w(TAG, "Scheduling restart of crashed service "
10724 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080010725 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010726 r.shortName, r.restartDelay);
10727
10728 Message msg = Message.obtain();
10729 msg.what = SERVICE_ERROR_MSG;
10730 msg.obj = r;
10731 mHandler.sendMessage(msg);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010732
10733 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010734 }
10735
10736 final void performServiceRestartLocked(ServiceRecord r) {
10737 if (!mRestartingServices.contains(r)) {
10738 return;
10739 }
10740 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
10741 }
10742
10743 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
10744 if (r.restartDelay == 0) {
10745 return false;
10746 }
10747 r.resetRestartCounter();
10748 mRestartingServices.remove(r);
10749 mHandler.removeCallbacks(r.restarter);
10750 return true;
10751 }
10752
10753 private final boolean bringUpServiceLocked(ServiceRecord r,
10754 int intentFlags, boolean whileRestarting) {
10755 //Log.i(TAG, "Bring up service:");
10756 //r.dump(" ");
10757
Dianne Hackborn36124872009-10-08 16:22:03 -070010758 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010759 sendServiceArgsLocked(r, false);
10760 return true;
10761 }
10762
10763 if (!whileRestarting && r.restartDelay > 0) {
10764 // If waiting for a restart, then do nothing.
10765 return true;
10766 }
10767
10768 if (DEBUG_SERVICE) Log.v(TAG, "Bringing up service " + r.name
10769 + " " + r.intent);
10770
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010771 // We are now bringing the service up, so no longer in the
10772 // restarting state.
10773 mRestartingServices.remove(r);
10774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010775 final String appName = r.processName;
10776 ProcessRecord app = getProcessRecordLocked(appName, r.appInfo.uid);
10777 if (app != null && app.thread != null) {
10778 try {
10779 realStartServiceLocked(r, app);
10780 return true;
10781 } catch (RemoteException e) {
10782 Log.w(TAG, "Exception when starting service " + r.shortName, e);
10783 }
10784
10785 // If a dead object exception was thrown -- fall through to
10786 // restart the application.
10787 }
10788
Dianne Hackborn36124872009-10-08 16:22:03 -070010789 // Not running -- get it started, and enqueue this service record
10790 // to be executed when the app comes up.
10791 if (startProcessLocked(appName, r.appInfo, true, intentFlags,
10792 "service", r.name, false) == null) {
10793 Log.w(TAG, "Unable to launch app "
10794 + r.appInfo.packageName + "/"
10795 + r.appInfo.uid + " for service "
10796 + r.intent.getIntent() + ": process is bad");
10797 bringDownServiceLocked(r, true);
10798 return false;
10799 }
10800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010801 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010802 mPendingServices.add(r);
10803 }
Dianne Hackborn36124872009-10-08 16:22:03 -070010804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010805 return true;
10806 }
10807
10808 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
10809 //Log.i(TAG, "Bring down service:");
10810 //r.dump(" ");
10811
10812 // Does it still need to run?
10813 if (!force && r.startRequested) {
10814 return;
10815 }
10816 if (r.connections.size() > 0) {
10817 if (!force) {
10818 // XXX should probably keep a count of the number of auto-create
10819 // connections directly in the service.
10820 Iterator<ConnectionRecord> it = r.connections.values().iterator();
10821 while (it.hasNext()) {
10822 ConnectionRecord cr = it.next();
10823 if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
10824 return;
10825 }
10826 }
10827 }
10828
10829 // Report to all of the connections that the service is no longer
10830 // available.
10831 Iterator<ConnectionRecord> it = r.connections.values().iterator();
10832 while (it.hasNext()) {
10833 ConnectionRecord c = it.next();
10834 try {
10835 // todo: shouldn't be a synchronous call!
10836 c.conn.connected(r.name, null);
10837 } catch (Exception e) {
10838 Log.w(TAG, "Failure disconnecting service " + r.name +
10839 " to connection " + c.conn.asBinder() +
10840 " (in " + c.binding.client.processName + ")", e);
10841 }
10842 }
10843 }
10844
10845 // Tell the service that it has been unbound.
10846 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
10847 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
10848 while (it.hasNext()) {
10849 IntentBindRecord ibr = it.next();
10850 if (DEBUG_SERVICE) Log.v(TAG, "Bringing down binding " + ibr
10851 + ": hasBound=" + ibr.hasBound);
10852 if (r.app != null && r.app.thread != null && ibr.hasBound) {
10853 try {
10854 bumpServiceExecutingLocked(r);
10855 updateOomAdjLocked(r.app);
10856 ibr.hasBound = false;
10857 r.app.thread.scheduleUnbindService(r,
10858 ibr.intent.getIntent());
10859 } catch (Exception e) {
10860 Log.w(TAG, "Exception when unbinding service "
10861 + r.shortName, e);
10862 serviceDoneExecutingLocked(r, true);
10863 }
10864 }
10865 }
10866 }
10867
10868 if (DEBUG_SERVICE) Log.v(TAG, "Bringing down service " + r.name
10869 + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010870 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010871 System.identityHashCode(r), r.shortName,
10872 (r.app != null) ? r.app.pid : -1);
10873
10874 mServices.remove(r.name);
10875 mServicesByIntent.remove(r.intent);
10876 if (localLOGV) Log.v(TAG, "BRING DOWN SERVICE: " + r.shortName);
10877 r.totalRestartCount = 0;
10878 unscheduleServiceRestartLocked(r);
10879
10880 // Also make sure it is not on the pending list.
10881 int N = mPendingServices.size();
10882 for (int i=0; i<N; i++) {
10883 if (mPendingServices.get(i) == r) {
10884 mPendingServices.remove(i);
10885 if (DEBUG_SERVICE) Log.v(
10886 TAG, "Removed pending service: " + r.shortName);
10887 i--;
10888 N--;
10889 }
10890 }
10891
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010892 r.cancelNotification();
10893 r.isForeground = false;
10894 r.foregroundId = 0;
10895 r.foregroundNoti = null;
10896
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010897 // Clear start entries.
10898 r.deliveredStarts.clear();
10899 r.pendingStarts.clear();
10900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010901 if (r.app != null) {
10902 synchronized (r.stats.getBatteryStats()) {
10903 r.stats.stopLaunchedLocked();
10904 }
10905 r.app.services.remove(r);
10906 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010907 try {
Dianne Hackborna1e989b2009-09-01 19:54:29 -070010908 if (DEBUG_SERVICE) Log.v(TAG,
10909 "Stopping service: " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010910 bumpServiceExecutingLocked(r);
10911 mStoppingServices.add(r);
10912 updateOomAdjLocked(r.app);
10913 r.app.thread.scheduleStopService(r);
10914 } catch (Exception e) {
10915 Log.w(TAG, "Exception when stopping service "
10916 + r.shortName, e);
10917 serviceDoneExecutingLocked(r, true);
10918 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010919 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010920 } else {
10921 if (DEBUG_SERVICE) Log.v(
10922 TAG, "Removed service that has no process: " + r.shortName);
10923 }
10924 } else {
10925 if (DEBUG_SERVICE) Log.v(
10926 TAG, "Removed service that is not running: " + r.shortName);
10927 }
10928 }
10929
10930 ComponentName startServiceLocked(IApplicationThread caller,
10931 Intent service, String resolvedType,
10932 int callingPid, int callingUid) {
10933 synchronized(this) {
10934 if (DEBUG_SERVICE) Log.v(TAG, "startService: " + service
10935 + " type=" + resolvedType + " args=" + service.getExtras());
10936
10937 if (caller != null) {
10938 final ProcessRecord callerApp = getRecordForAppLocked(caller);
10939 if (callerApp == null) {
10940 throw new SecurityException(
10941 "Unable to find app for caller " + caller
10942 + " (pid=" + Binder.getCallingPid()
10943 + ") when starting service " + service);
10944 }
10945 }
10946
10947 ServiceLookupResult res =
10948 retrieveServiceLocked(service, resolvedType,
10949 callingPid, callingUid);
10950 if (res == null) {
10951 return null;
10952 }
10953 if (res.record == null) {
10954 return new ComponentName("!", res.permission != null
10955 ? res.permission : "private to package");
10956 }
10957 ServiceRecord r = res.record;
10958 if (unscheduleServiceRestartLocked(r)) {
10959 if (DEBUG_SERVICE) Log.v(TAG, "START SERVICE WHILE RESTART PENDING: "
10960 + r.shortName);
10961 }
10962 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010963 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010964 r.lastStartId++;
10965 if (r.lastStartId < 1) {
10966 r.lastStartId = 1;
10967 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010968 r.pendingStarts.add(new ServiceRecord.StartItem(r.lastStartId, service));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010969 r.lastActivity = SystemClock.uptimeMillis();
10970 synchronized (r.stats.getBatteryStats()) {
10971 r.stats.startRunningLocked();
10972 }
10973 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
10974 return new ComponentName("!", "Service process is bad");
10975 }
10976 return r.name;
10977 }
10978 }
10979
10980 public ComponentName startService(IApplicationThread caller, Intent service,
10981 String resolvedType) {
10982 // Refuse possible leaked file descriptors
10983 if (service != null && service.hasFileDescriptors() == true) {
10984 throw new IllegalArgumentException("File descriptors passed in Intent");
10985 }
10986
10987 synchronized(this) {
10988 final int callingPid = Binder.getCallingPid();
10989 final int callingUid = Binder.getCallingUid();
10990 final long origId = Binder.clearCallingIdentity();
10991 ComponentName res = startServiceLocked(caller, service,
10992 resolvedType, callingPid, callingUid);
10993 Binder.restoreCallingIdentity(origId);
10994 return res;
10995 }
10996 }
10997
10998 ComponentName startServiceInPackage(int uid,
10999 Intent service, String resolvedType) {
11000 synchronized(this) {
11001 final long origId = Binder.clearCallingIdentity();
11002 ComponentName res = startServiceLocked(null, service,
11003 resolvedType, -1, uid);
11004 Binder.restoreCallingIdentity(origId);
11005 return res;
11006 }
11007 }
11008
11009 public int stopService(IApplicationThread caller, Intent service,
11010 String resolvedType) {
11011 // Refuse possible leaked file descriptors
11012 if (service != null && service.hasFileDescriptors() == true) {
11013 throw new IllegalArgumentException("File descriptors passed in Intent");
11014 }
11015
11016 synchronized(this) {
11017 if (DEBUG_SERVICE) Log.v(TAG, "stopService: " + service
11018 + " type=" + resolvedType);
11019
11020 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11021 if (caller != null && callerApp == null) {
11022 throw new SecurityException(
11023 "Unable to find app for caller " + caller
11024 + " (pid=" + Binder.getCallingPid()
11025 + ") when stopping service " + service);
11026 }
11027
11028 // If this service is active, make sure it is stopped.
11029 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11030 if (r != null) {
11031 if (r.record != null) {
11032 synchronized (r.record.stats.getBatteryStats()) {
11033 r.record.stats.stopRunningLocked();
11034 }
11035 r.record.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011036 r.record.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011037 final long origId = Binder.clearCallingIdentity();
11038 bringDownServiceLocked(r.record, false);
11039 Binder.restoreCallingIdentity(origId);
11040 return 1;
11041 }
11042 return -1;
11043 }
11044 }
11045
11046 return 0;
11047 }
11048
11049 public IBinder peekService(Intent service, String resolvedType) {
11050 // Refuse possible leaked file descriptors
11051 if (service != null && service.hasFileDescriptors() == true) {
11052 throw new IllegalArgumentException("File descriptors passed in Intent");
11053 }
11054
11055 IBinder ret = null;
11056
11057 synchronized(this) {
11058 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11059
11060 if (r != null) {
11061 // r.record is null if findServiceLocked() failed the caller permission check
11062 if (r.record == null) {
11063 throw new SecurityException(
11064 "Permission Denial: Accessing service " + r.record.name
11065 + " from pid=" + Binder.getCallingPid()
11066 + ", uid=" + Binder.getCallingUid()
11067 + " requires " + r.permission);
11068 }
11069 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11070 if (ib != null) {
11071 ret = ib.binder;
11072 }
11073 }
11074 }
11075
11076 return ret;
11077 }
11078
11079 public boolean stopServiceToken(ComponentName className, IBinder token,
11080 int startId) {
11081 synchronized(this) {
11082 if (DEBUG_SERVICE) Log.v(TAG, "stopServiceToken: " + className
11083 + " " + token + " startId=" + startId);
11084 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011085 if (r != null) {
11086 if (startId >= 0) {
11087 // Asked to only stop if done with all work. Note that
11088 // to avoid leaks, we will take this as dropping all
11089 // start items up to and including this one.
11090 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11091 if (si != null) {
11092 while (r.deliveredStarts.size() > 0) {
11093 if (r.deliveredStarts.remove(0) == si) {
11094 break;
11095 }
11096 }
11097 }
11098
11099 if (r.lastStartId != startId) {
11100 return false;
11101 }
11102
11103 if (r.deliveredStarts.size() > 0) {
11104 Log.w(TAG, "stopServiceToken startId " + startId
11105 + " is last, but have " + r.deliveredStarts.size()
11106 + " remaining args");
11107 }
11108 }
11109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011110 synchronized (r.stats.getBatteryStats()) {
11111 r.stats.stopRunningLocked();
11112 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011113 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011114 }
11115 final long origId = Binder.clearCallingIdentity();
11116 bringDownServiceLocked(r, false);
11117 Binder.restoreCallingIdentity(origId);
11118 return true;
11119 }
11120 }
11121 return false;
11122 }
11123
11124 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011125 int id, Notification notification, boolean removeNotification) {
11126 final long origId = Binder.clearCallingIdentity();
11127 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011128 synchronized(this) {
11129 ServiceRecord r = findServiceLocked(className, token);
11130 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011131 if (id != 0) {
11132 if (notification == null) {
11133 throw new IllegalArgumentException("null notification");
11134 }
11135 if (r.foregroundId != id) {
11136 r.cancelNotification();
11137 r.foregroundId = id;
11138 }
11139 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11140 r.foregroundNoti = notification;
11141 r.isForeground = true;
11142 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011143 if (r.app != null) {
11144 updateServiceForegroundLocked(r.app, true);
11145 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011146 } else {
11147 if (r.isForeground) {
11148 r.isForeground = false;
11149 if (r.app != null) {
11150 updateServiceForegroundLocked(r.app, true);
11151 }
11152 }
11153 if (removeNotification) {
11154 r.cancelNotification();
11155 r.foregroundId = 0;
11156 r.foregroundNoti = null;
11157 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011158 }
11159 }
11160 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011161 } finally {
11162 Binder.restoreCallingIdentity(origId);
11163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011164 }
11165
11166 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11167 boolean anyForeground = false;
11168 for (ServiceRecord sr : (HashSet<ServiceRecord>)proc.services) {
11169 if (sr.isForeground) {
11170 anyForeground = true;
11171 break;
11172 }
11173 }
11174 if (anyForeground != proc.foregroundServices) {
11175 proc.foregroundServices = anyForeground;
11176 if (oomAdj) {
11177 updateOomAdjLocked();
11178 }
11179 }
11180 }
11181
11182 public int bindService(IApplicationThread caller, IBinder token,
11183 Intent service, String resolvedType,
11184 IServiceConnection connection, int flags) {
11185 // Refuse possible leaked file descriptors
11186 if (service != null && service.hasFileDescriptors() == true) {
11187 throw new IllegalArgumentException("File descriptors passed in Intent");
11188 }
11189
11190 synchronized(this) {
11191 if (DEBUG_SERVICE) Log.v(TAG, "bindService: " + service
11192 + " type=" + resolvedType + " conn=" + connection.asBinder()
11193 + " flags=0x" + Integer.toHexString(flags));
11194 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11195 if (callerApp == null) {
11196 throw new SecurityException(
11197 "Unable to find app for caller " + caller
11198 + " (pid=" + Binder.getCallingPid()
11199 + ") when binding service " + service);
11200 }
11201
11202 HistoryRecord activity = null;
11203 if (token != null) {
Dianne Hackborn75b03852009-06-12 15:43:26 -070011204 int aindex = indexOfTokenLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011205 if (aindex < 0) {
11206 Log.w(TAG, "Binding with unknown activity: " + token);
11207 return 0;
11208 }
11209 activity = (HistoryRecord)mHistory.get(aindex);
11210 }
11211
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011212 int clientLabel = 0;
11213 PendingIntent clientIntent = null;
11214
11215 if (callerApp.info.uid == Process.SYSTEM_UID) {
11216 // Hacky kind of thing -- allow system stuff to tell us
11217 // what they are, so we can report this elsewhere for
11218 // others to know why certain services are running.
11219 try {
11220 clientIntent = (PendingIntent)service.getParcelableExtra(
11221 Intent.EXTRA_CLIENT_INTENT);
11222 } catch (RuntimeException e) {
11223 }
11224 if (clientIntent != null) {
11225 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11226 if (clientLabel != 0) {
11227 // There are no useful extras in the intent, trash them.
11228 // System code calling with this stuff just needs to know
11229 // this will happen.
11230 service = service.cloneFilter();
11231 }
11232 }
11233 }
11234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011235 ServiceLookupResult res =
11236 retrieveServiceLocked(service, resolvedType,
11237 Binder.getCallingPid(), Binder.getCallingUid());
11238 if (res == null) {
11239 return 0;
11240 }
11241 if (res.record == null) {
11242 return -1;
11243 }
11244 ServiceRecord s = res.record;
11245
11246 final long origId = Binder.clearCallingIdentity();
11247
11248 if (unscheduleServiceRestartLocked(s)) {
11249 if (DEBUG_SERVICE) Log.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
11250 + s.shortName);
11251 }
11252
11253 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11254 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011255 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011256
11257 IBinder binder = connection.asBinder();
11258 s.connections.put(binder, c);
11259 b.connections.add(c);
11260 if (activity != null) {
11261 if (activity.connections == null) {
11262 activity.connections = new HashSet<ConnectionRecord>();
11263 }
11264 activity.connections.add(c);
11265 }
11266 b.client.connections.add(c);
11267 mServiceConnections.put(binder, c);
11268
11269 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11270 s.lastActivity = SystemClock.uptimeMillis();
11271 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11272 return 0;
11273 }
11274 }
11275
11276 if (s.app != null) {
11277 // This could have made the service more important.
11278 updateOomAdjLocked(s.app);
11279 }
11280
11281 if (DEBUG_SERVICE) Log.v(TAG, "Bind " + s + " with " + b
11282 + ": received=" + b.intent.received
11283 + " apps=" + b.intent.apps.size()
11284 + " doRebind=" + b.intent.doRebind);
11285
11286 if (s.app != null && b.intent.received) {
11287 // Service is already running, so we can immediately
11288 // publish the connection.
11289 try {
11290 c.conn.connected(s.name, b.intent.binder);
11291 } catch (Exception e) {
11292 Log.w(TAG, "Failure sending service " + s.shortName
11293 + " to connection " + c.conn.asBinder()
11294 + " (in " + c.binding.client.processName + ")", e);
11295 }
11296
11297 // If this is the first app connected back to this binding,
11298 // and the service had previously asked to be told when
11299 // rebound, then do so.
11300 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11301 requestServiceBindingLocked(s, b.intent, true);
11302 }
11303 } else if (!b.intent.requested) {
11304 requestServiceBindingLocked(s, b.intent, false);
11305 }
11306
11307 Binder.restoreCallingIdentity(origId);
11308 }
11309
11310 return 1;
11311 }
11312
11313 private void removeConnectionLocked(
11314 ConnectionRecord c, ProcessRecord skipApp, HistoryRecord skipAct) {
11315 IBinder binder = c.conn.asBinder();
11316 AppBindRecord b = c.binding;
11317 ServiceRecord s = b.service;
11318 s.connections.remove(binder);
11319 b.connections.remove(c);
11320 if (c.activity != null && c.activity != skipAct) {
11321 if (c.activity.connections != null) {
11322 c.activity.connections.remove(c);
11323 }
11324 }
11325 if (b.client != skipApp) {
11326 b.client.connections.remove(c);
11327 }
11328 mServiceConnections.remove(binder);
11329
11330 if (b.connections.size() == 0) {
11331 b.intent.apps.remove(b.client);
11332 }
11333
11334 if (DEBUG_SERVICE) Log.v(TAG, "Disconnecting binding " + b.intent
11335 + ": shouldUnbind=" + b.intent.hasBound);
11336 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11337 && b.intent.hasBound) {
11338 try {
11339 bumpServiceExecutingLocked(s);
11340 updateOomAdjLocked(s.app);
11341 b.intent.hasBound = false;
11342 // Assume the client doesn't want to know about a rebind;
11343 // we will deal with that later if it asks for one.
11344 b.intent.doRebind = false;
11345 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11346 } catch (Exception e) {
11347 Log.w(TAG, "Exception when unbinding service " + s.shortName, e);
11348 serviceDoneExecutingLocked(s, true);
11349 }
11350 }
11351
11352 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11353 bringDownServiceLocked(s, false);
11354 }
11355 }
11356
11357 public boolean unbindService(IServiceConnection connection) {
11358 synchronized (this) {
11359 IBinder binder = connection.asBinder();
11360 if (DEBUG_SERVICE) Log.v(TAG, "unbindService: conn=" + binder);
11361 ConnectionRecord r = mServiceConnections.get(binder);
11362 if (r == null) {
11363 Log.w(TAG, "Unbind failed: could not find connection for "
11364 + connection.asBinder());
11365 return false;
11366 }
11367
11368 final long origId = Binder.clearCallingIdentity();
11369
11370 removeConnectionLocked(r, null, null);
11371
11372 if (r.binding.service.app != null) {
11373 // This could have made the service less important.
11374 updateOomAdjLocked(r.binding.service.app);
11375 }
11376
11377 Binder.restoreCallingIdentity(origId);
11378 }
11379
11380 return true;
11381 }
11382
11383 public void publishService(IBinder token, Intent intent, IBinder service) {
11384 // Refuse possible leaked file descriptors
11385 if (intent != null && intent.hasFileDescriptors() == true) {
11386 throw new IllegalArgumentException("File descriptors passed in Intent");
11387 }
11388
11389 synchronized(this) {
11390 if (!(token instanceof ServiceRecord)) {
11391 throw new IllegalArgumentException("Invalid service token");
11392 }
11393 ServiceRecord r = (ServiceRecord)token;
11394
11395 final long origId = Binder.clearCallingIdentity();
11396
11397 if (DEBUG_SERVICE) Log.v(TAG, "PUBLISHING SERVICE " + r.name
11398 + " " + intent + ": " + service);
11399 if (r != null) {
11400 Intent.FilterComparison filter
11401 = new Intent.FilterComparison(intent);
11402 IntentBindRecord b = r.bindings.get(filter);
11403 if (b != null && !b.received) {
11404 b.binder = service;
11405 b.requested = true;
11406 b.received = true;
11407 if (r.connections.size() > 0) {
11408 Iterator<ConnectionRecord> it
11409 = r.connections.values().iterator();
11410 while (it.hasNext()) {
11411 ConnectionRecord c = it.next();
11412 if (!filter.equals(c.binding.intent.intent)) {
11413 if (DEBUG_SERVICE) Log.v(
11414 TAG, "Not publishing to: " + c);
11415 if (DEBUG_SERVICE) Log.v(
11416 TAG, "Bound intent: " + c.binding.intent.intent);
11417 if (DEBUG_SERVICE) Log.v(
11418 TAG, "Published intent: " + intent);
11419 continue;
11420 }
11421 if (DEBUG_SERVICE) Log.v(TAG, "Publishing to: " + c);
11422 try {
11423 c.conn.connected(r.name, service);
11424 } catch (Exception e) {
11425 Log.w(TAG, "Failure sending service " + r.name +
11426 " to connection " + c.conn.asBinder() +
11427 " (in " + c.binding.client.processName + ")", e);
11428 }
11429 }
11430 }
11431 }
11432
11433 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
11434
11435 Binder.restoreCallingIdentity(origId);
11436 }
11437 }
11438 }
11439
11440 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11441 // Refuse possible leaked file descriptors
11442 if (intent != null && intent.hasFileDescriptors() == true) {
11443 throw new IllegalArgumentException("File descriptors passed in Intent");
11444 }
11445
11446 synchronized(this) {
11447 if (!(token instanceof ServiceRecord)) {
11448 throw new IllegalArgumentException("Invalid service token");
11449 }
11450 ServiceRecord r = (ServiceRecord)token;
11451
11452 final long origId = Binder.clearCallingIdentity();
11453
11454 if (r != null) {
11455 Intent.FilterComparison filter
11456 = new Intent.FilterComparison(intent);
11457 IntentBindRecord b = r.bindings.get(filter);
11458 if (DEBUG_SERVICE) Log.v(TAG, "unbindFinished in " + r
11459 + " at " + b + ": apps="
11460 + (b != null ? b.apps.size() : 0));
11461 if (b != null) {
11462 if (b.apps.size() > 0) {
11463 // Applications have already bound since the last
11464 // unbind, so just rebind right here.
11465 requestServiceBindingLocked(r, b, true);
11466 } else {
11467 // Note to tell the service the next time there is
11468 // a new client.
11469 b.doRebind = true;
11470 }
11471 }
11472
11473 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
11474
11475 Binder.restoreCallingIdentity(origId);
11476 }
11477 }
11478 }
11479
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011480 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011481 synchronized(this) {
11482 if (!(token instanceof ServiceRecord)) {
11483 throw new IllegalArgumentException("Invalid service token");
11484 }
11485 ServiceRecord r = (ServiceRecord)token;
11486 boolean inStopping = mStoppingServices.contains(token);
11487 if (r != null) {
11488 if (DEBUG_SERVICE) Log.v(TAG, "DONE EXECUTING SERVICE " + r.name
11489 + ": nesting=" + r.executeNesting
11490 + ", inStopping=" + inStopping);
11491 if (r != token) {
11492 Log.w(TAG, "Done executing service " + r.name
11493 + " with incorrect token: given " + token
11494 + ", expected " + r);
11495 return;
11496 }
11497
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011498 if (type == 1) {
11499 // This is a call from a service start... take care of
11500 // book-keeping.
11501 r.callStart = true;
11502 switch (res) {
11503 case Service.START_STICKY_COMPATIBILITY:
11504 case Service.START_STICKY: {
11505 // We are done with the associated start arguments.
11506 r.findDeliveredStart(startId, true);
11507 // Don't stop if killed.
11508 r.stopIfKilled = false;
11509 break;
11510 }
11511 case Service.START_NOT_STICKY: {
11512 // We are done with the associated start arguments.
11513 r.findDeliveredStart(startId, true);
11514 if (r.lastStartId == startId) {
11515 // There is no more work, and this service
11516 // doesn't want to hang around if killed.
11517 r.stopIfKilled = true;
11518 }
11519 break;
11520 }
11521 case Service.START_REDELIVER_INTENT: {
11522 // We'll keep this item until they explicitly
11523 // call stop for it, but keep track of the fact
11524 // that it was delivered.
11525 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11526 if (si != null) {
11527 si.deliveryCount = 0;
11528 si.doneExecutingCount++;
11529 // Don't stop if killed.
11530 r.stopIfKilled = true;
11531 }
11532 break;
11533 }
11534 default:
11535 throw new IllegalArgumentException(
11536 "Unknown service start result: " + res);
11537 }
11538 if (res == Service.START_STICKY_COMPATIBILITY) {
11539 r.callStart = false;
11540 }
11541 }
11542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011543 final long origId = Binder.clearCallingIdentity();
11544 serviceDoneExecutingLocked(r, inStopping);
11545 Binder.restoreCallingIdentity(origId);
11546 } else {
11547 Log.w(TAG, "Done executing unknown service " + r.name
11548 + " with token " + token);
11549 }
11550 }
11551 }
11552
11553 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
11554 r.executeNesting--;
11555 if (r.executeNesting <= 0 && r.app != null) {
11556 r.app.executingServices.remove(r);
11557 if (r.app.executingServices.size() == 0) {
11558 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
11559 }
11560 if (inStopping) {
11561 mStoppingServices.remove(r);
11562 }
11563 updateOomAdjLocked(r.app);
11564 }
11565 }
11566
11567 void serviceTimeout(ProcessRecord proc) {
11568 synchronized(this) {
11569 if (proc.executingServices.size() == 0 || proc.thread == null) {
11570 return;
11571 }
11572 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
11573 Iterator<ServiceRecord> it = proc.executingServices.iterator();
11574 ServiceRecord timeout = null;
11575 long nextTime = 0;
11576 while (it.hasNext()) {
11577 ServiceRecord sr = it.next();
11578 if (sr.executingStart < maxTime) {
11579 timeout = sr;
11580 break;
11581 }
11582 if (sr.executingStart > nextTime) {
11583 nextTime = sr.executingStart;
11584 }
11585 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011586 if (timeout != null && mLruProcesses.contains(proc)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011587 Log.w(TAG, "Timeout executing service: " + timeout);
Dan Egnor42471dd2010-01-07 17:25:22 -080011588 appNotRespondingLocked(proc, null, null, "Executing service " + timeout.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011589 } else {
11590 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11591 msg.obj = proc;
11592 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
11593 }
11594 }
11595 }
11596
11597 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011598 // BACKUP AND RESTORE
11599 // =========================================================
11600
11601 // Cause the target app to be launched if necessary and its backup agent
11602 // instantiated. The backup agent will invoke backupAgentCreated() on the
11603 // activity manager to announce its creation.
11604 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
11605 if (DEBUG_BACKUP) Log.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
11606 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
11607
11608 synchronized(this) {
11609 // !!! TODO: currently no check here that we're already bound
11610 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11611 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11612 synchronized (stats) {
11613 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11614 }
11615
11616 BackupRecord r = new BackupRecord(ss, app, backupMode);
11617 ComponentName hostingName = new ComponentName(app.packageName, app.backupAgentName);
11618 // startProcessLocked() returns existing proc's record if it's already running
11619 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011620 false, 0, "backup", hostingName, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011621 if (proc == null) {
11622 Log.e(TAG, "Unable to start backup agent process " + r);
11623 return false;
11624 }
11625
11626 r.app = proc;
11627 mBackupTarget = r;
11628 mBackupAppName = app.packageName;
11629
Christopher Tate6fa95972009-06-05 18:43:55 -070011630 // Try not to kill the process during backup
11631 updateOomAdjLocked(proc);
11632
Christopher Tate181fafa2009-05-14 11:12:14 -070011633 // If the process is already attached, schedule the creation of the backup agent now.
11634 // If it is not yet live, this will be done when it attaches to the framework.
11635 if (proc.thread != null) {
11636 if (DEBUG_BACKUP) Log.v(TAG, "Agent proc already running: " + proc);
11637 try {
11638 proc.thread.scheduleCreateBackupAgent(app, backupMode);
11639 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011640 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011641 }
11642 } else {
11643 if (DEBUG_BACKUP) Log.v(TAG, "Agent proc not running, waiting for attach");
11644 }
11645 // Invariants: at this point, the target app process exists and the application
11646 // is either already running or in the process of coming up. mBackupTarget and
11647 // mBackupAppName describe the app, so that when it binds back to the AM we
11648 // know that it's scheduled for a backup-agent operation.
11649 }
11650
11651 return true;
11652 }
11653
11654 // A backup agent has just come up
11655 public void backupAgentCreated(String agentPackageName, IBinder agent) {
11656 if (DEBUG_BACKUP) Log.v(TAG, "backupAgentCreated: " + agentPackageName
11657 + " = " + agent);
11658
11659 synchronized(this) {
11660 if (!agentPackageName.equals(mBackupAppName)) {
11661 Log.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
11662 return;
11663 }
11664
Christopher Tate043dadc2009-06-02 16:11:00 -070011665 long oldIdent = Binder.clearCallingIdentity();
Christopher Tate181fafa2009-05-14 11:12:14 -070011666 try {
11667 IBackupManager bm = IBackupManager.Stub.asInterface(
11668 ServiceManager.getService(Context.BACKUP_SERVICE));
11669 bm.agentConnected(agentPackageName, agent);
11670 } catch (RemoteException e) {
11671 // can't happen; the backup manager service is local
11672 } catch (Exception e) {
11673 Log.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11674 e.printStackTrace();
Christopher Tate043dadc2009-06-02 16:11:00 -070011675 } finally {
11676 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011677 }
11678 }
11679 }
11680
11681 // done with this agent
11682 public void unbindBackupAgent(ApplicationInfo appInfo) {
11683 if (DEBUG_BACKUP) Log.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011684 if (appInfo == null) {
11685 Log.w(TAG, "unbind backup agent for null app");
11686 return;
11687 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011688
11689 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070011690 if (mBackupAppName == null) {
11691 Log.w(TAG, "Unbinding backup agent with no active backup");
11692 return;
11693 }
11694
Christopher Tate181fafa2009-05-14 11:12:14 -070011695 if (!mBackupAppName.equals(appInfo.packageName)) {
11696 Log.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
11697 return;
11698 }
11699
Christopher Tate6fa95972009-06-05 18:43:55 -070011700 ProcessRecord proc = mBackupTarget.app;
11701 mBackupTarget = null;
11702 mBackupAppName = null;
11703
11704 // Not backing this app up any more; reset its OOM adjustment
11705 updateOomAdjLocked(proc);
11706
Christopher Tatec7b31e32009-06-10 15:49:30 -070011707 // If the app crashed during backup, 'thread' will be null here
11708 if (proc.thread != null) {
11709 try {
11710 proc.thread.scheduleDestroyBackupAgent(appInfo);
11711 } catch (Exception e) {
11712 Log.e(TAG, "Exception when unbinding backup agent:");
11713 e.printStackTrace();
11714 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011715 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011716 }
11717 }
11718 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011719 // BROADCASTS
11720 // =========================================================
11721
11722 private final List getStickies(String action, IntentFilter filter,
11723 List cur) {
11724 final ContentResolver resolver = mContext.getContentResolver();
11725 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
11726 if (list == null) {
11727 return cur;
11728 }
11729 int N = list.size();
11730 for (int i=0; i<N; i++) {
11731 Intent intent = list.get(i);
11732 if (filter.match(resolver, intent, true, TAG) >= 0) {
11733 if (cur == null) {
11734 cur = new ArrayList<Intent>();
11735 }
11736 cur.add(intent);
11737 }
11738 }
11739 return cur;
11740 }
11741
11742 private final void scheduleBroadcastsLocked() {
11743 if (DEBUG_BROADCAST) Log.v(TAG, "Schedule broadcasts: current="
11744 + mBroadcastsScheduled);
11745
11746 if (mBroadcastsScheduled) {
11747 return;
11748 }
11749 mHandler.sendEmptyMessage(BROADCAST_INTENT_MSG);
11750 mBroadcastsScheduled = true;
11751 }
11752
11753 public Intent registerReceiver(IApplicationThread caller,
11754 IIntentReceiver receiver, IntentFilter filter, String permission) {
11755 synchronized(this) {
11756 ProcessRecord callerApp = null;
11757 if (caller != null) {
11758 callerApp = getRecordForAppLocked(caller);
11759 if (callerApp == null) {
11760 throw new SecurityException(
11761 "Unable to find app for caller " + caller
11762 + " (pid=" + Binder.getCallingPid()
11763 + ") when registering receiver " + receiver);
11764 }
11765 }
11766
11767 List allSticky = null;
11768
11769 // Look for any matching sticky broadcasts...
11770 Iterator actions = filter.actionsIterator();
11771 if (actions != null) {
11772 while (actions.hasNext()) {
11773 String action = (String)actions.next();
11774 allSticky = getStickies(action, filter, allSticky);
11775 }
11776 } else {
11777 allSticky = getStickies(null, filter, allSticky);
11778 }
11779
11780 // The first sticky in the list is returned directly back to
11781 // the client.
11782 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11783
11784 if (DEBUG_BROADCAST) Log.v(TAG, "Register receiver " + filter
11785 + ": " + sticky);
11786
11787 if (receiver == null) {
11788 return sticky;
11789 }
11790
11791 ReceiverList rl
11792 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11793 if (rl == null) {
11794 rl = new ReceiverList(this, callerApp,
11795 Binder.getCallingPid(),
11796 Binder.getCallingUid(), receiver);
11797 if (rl.app != null) {
11798 rl.app.receivers.add(rl);
11799 } else {
11800 try {
11801 receiver.asBinder().linkToDeath(rl, 0);
11802 } catch (RemoteException e) {
11803 return sticky;
11804 }
11805 rl.linkedToDeath = true;
11806 }
11807 mRegisteredReceivers.put(receiver.asBinder(), rl);
11808 }
11809 BroadcastFilter bf = new BroadcastFilter(filter, rl, permission);
11810 rl.add(bf);
11811 if (!bf.debugCheck()) {
11812 Log.w(TAG, "==> For Dynamic broadast");
11813 }
11814 mReceiverResolver.addFilter(bf);
11815
11816 // Enqueue broadcasts for all existing stickies that match
11817 // this filter.
11818 if (allSticky != null) {
11819 ArrayList receivers = new ArrayList();
11820 receivers.add(bf);
11821
11822 int N = allSticky.size();
11823 for (int i=0; i<N; i++) {
11824 Intent intent = (Intent)allSticky.get(i);
11825 BroadcastRecord r = new BroadcastRecord(intent, null,
11826 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011827 false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011828 if (mParallelBroadcasts.size() == 0) {
11829 scheduleBroadcastsLocked();
11830 }
11831 mParallelBroadcasts.add(r);
11832 }
11833 }
11834
11835 return sticky;
11836 }
11837 }
11838
11839 public void unregisterReceiver(IIntentReceiver receiver) {
11840 if (DEBUG_BROADCAST) Log.v(TAG, "Unregister receiver: " + receiver);
11841
11842 boolean doNext = false;
11843
11844 synchronized(this) {
11845 ReceiverList rl
11846 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11847 if (rl != null) {
11848 if (rl.curBroadcast != null) {
11849 BroadcastRecord r = rl.curBroadcast;
11850 doNext = finishReceiverLocked(
11851 receiver.asBinder(), r.resultCode, r.resultData,
11852 r.resultExtras, r.resultAbort, true);
11853 }
11854
11855 if (rl.app != null) {
11856 rl.app.receivers.remove(rl);
11857 }
11858 removeReceiverLocked(rl);
11859 if (rl.linkedToDeath) {
11860 rl.linkedToDeath = false;
11861 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11862 }
11863 }
11864 }
11865
11866 if (!doNext) {
11867 return;
11868 }
11869
11870 final long origId = Binder.clearCallingIdentity();
11871 processNextBroadcast(false);
11872 trimApplications();
11873 Binder.restoreCallingIdentity(origId);
11874 }
11875
11876 void removeReceiverLocked(ReceiverList rl) {
11877 mRegisteredReceivers.remove(rl.receiver.asBinder());
11878 int N = rl.size();
11879 for (int i=0; i<N; i++) {
11880 mReceiverResolver.removeFilter(rl.get(i));
11881 }
11882 }
11883
11884 private final int broadcastIntentLocked(ProcessRecord callerApp,
11885 String callerPackage, Intent intent, String resolvedType,
11886 IIntentReceiver resultTo, int resultCode, String resultData,
11887 Bundle map, String requiredPermission,
11888 boolean ordered, boolean sticky, int callingPid, int callingUid) {
11889 intent = new Intent(intent);
11890
Dianne Hackborn82f3f002009-06-16 18:49:05 -070011891 if (DEBUG_BROADCAST_LIGHT) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011892 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
11893 + " ordered=" + ordered);
11894 if ((resultTo != null) && !ordered) {
11895 Log.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
11896 }
11897
11898 // Handle special intents: if this broadcast is from the package
11899 // manager about a package being removed, we need to remove all of
11900 // its activities from the history stack.
11901 final boolean uidRemoved = intent.ACTION_UID_REMOVED.equals(
11902 intent.getAction());
11903 if (intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11904 || intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
11905 || uidRemoved) {
11906 if (checkComponentPermission(
11907 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
11908 callingPid, callingUid, -1)
11909 == PackageManager.PERMISSION_GRANTED) {
11910 if (uidRemoved) {
11911 final Bundle intentExtras = intent.getExtras();
11912 final int uid = intentExtras != null
11913 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11914 if (uid >= 0) {
11915 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11916 synchronized (bs) {
11917 bs.removeUidStatsLocked(uid);
11918 }
11919 }
11920 } else {
11921 Uri data = intent.getData();
11922 String ssp;
11923 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11924 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
Dianne Hackborn03abb812010-01-04 18:43:19 -080011925 forceStopPackageLocked(ssp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011926 intent.getIntExtra(Intent.EXTRA_UID, -1), false);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011927 AttributeCache ac = AttributeCache.instance();
11928 if (ac != null) {
11929 ac.removePackage(ssp);
11930 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011931 }
11932 }
11933 }
11934 } else {
11935 String msg = "Permission Denial: " + intent.getAction()
11936 + " broadcast from " + callerPackage + " (pid=" + callingPid
11937 + ", uid=" + callingUid + ")"
11938 + " requires "
11939 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
11940 Log.w(TAG, msg);
11941 throw new SecurityException(msg);
11942 }
11943 }
11944
11945 /*
11946 * If this is the time zone changed action, queue up a message that will reset the timezone
11947 * of all currently running processes. This message will get queued up before the broadcast
11948 * happens.
11949 */
11950 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11951 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11952 }
11953
Dianne Hackborn854060af2009-07-09 18:14:31 -070011954 /*
11955 * Prevent non-system code (defined here to be non-persistent
11956 * processes) from sending protected broadcasts.
11957 */
11958 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
11959 || callingUid == Process.SHELL_UID || callingUid == 0) {
11960 // Always okay.
11961 } else if (callerApp == null || !callerApp.persistent) {
11962 try {
11963 if (ActivityThread.getPackageManager().isProtectedBroadcast(
11964 intent.getAction())) {
11965 String msg = "Permission Denial: not allowed to send broadcast "
11966 + intent.getAction() + " from pid="
11967 + callingPid + ", uid=" + callingUid;
11968 Log.w(TAG, msg);
11969 throw new SecurityException(msg);
11970 }
11971 } catch (RemoteException e) {
11972 Log.w(TAG, "Remote exception", e);
11973 return BROADCAST_SUCCESS;
11974 }
11975 }
11976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011977 // Add to the sticky list if requested.
11978 if (sticky) {
11979 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11980 callingPid, callingUid)
11981 != PackageManager.PERMISSION_GRANTED) {
11982 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11983 + callingPid + ", uid=" + callingUid
11984 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
11985 Log.w(TAG, msg);
11986 throw new SecurityException(msg);
11987 }
11988 if (requiredPermission != null) {
11989 Log.w(TAG, "Can't broadcast sticky intent " + intent
11990 + " and enforce permission " + requiredPermission);
11991 return BROADCAST_STICKY_CANT_HAVE_PERMISSION;
11992 }
11993 if (intent.getComponent() != null) {
11994 throw new SecurityException(
11995 "Sticky broadcasts can't target a specific component");
11996 }
11997 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
11998 if (list == null) {
11999 list = new ArrayList<Intent>();
12000 mStickyBroadcasts.put(intent.getAction(), list);
12001 }
12002 int N = list.size();
12003 int i;
12004 for (i=0; i<N; i++) {
12005 if (intent.filterEquals(list.get(i))) {
12006 // This sticky already exists, replace it.
12007 list.set(i, new Intent(intent));
12008 break;
12009 }
12010 }
12011 if (i >= N) {
12012 list.add(new Intent(intent));
12013 }
12014 }
12015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012016 // Figure out who all will receive this broadcast.
12017 List receivers = null;
12018 List<BroadcastFilter> registeredReceivers = null;
12019 try {
12020 if (intent.getComponent() != null) {
12021 // Broadcast is going to one specific receiver class...
12022 ActivityInfo ai = ActivityThread.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -070012023 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012024 if (ai != null) {
12025 receivers = new ArrayList();
12026 ResolveInfo ri = new ResolveInfo();
12027 ri.activityInfo = ai;
12028 receivers.add(ri);
12029 }
12030 } else {
12031 // Need to resolve the intent to interested receivers...
12032 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12033 == 0) {
12034 receivers =
12035 ActivityThread.getPackageManager().queryIntentReceivers(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012036 intent, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012037 }
Mihai Preda074edef2009-05-18 17:13:31 +020012038 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012039 }
12040 } catch (RemoteException ex) {
12041 // pm is in same process, this will never happen.
12042 }
12043
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012044 final boolean replacePending =
12045 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12046
12047 if (DEBUG_BROADCAST) Log.v(TAG, "Enqueing broadcast: " + intent.getAction()
12048 + " replacePending=" + replacePending);
12049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012050 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12051 if (!ordered && NR > 0) {
12052 // If we are not serializing this broadcast, then send the
12053 // registered receivers separately so they don't wait for the
12054 // components to be launched.
12055 BroadcastRecord r = new BroadcastRecord(intent, callerApp,
12056 callerPackage, callingPid, callingUid, requiredPermission,
12057 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012058 ordered, sticky, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012059 if (DEBUG_BROADCAST) Log.v(
12060 TAG, "Enqueueing parallel broadcast " + r
12061 + ": prev had " + mParallelBroadcasts.size());
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012062 boolean replaced = false;
12063 if (replacePending) {
12064 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
12065 if (intent.filterEquals(mParallelBroadcasts.get(i).intent)) {
12066 if (DEBUG_BROADCAST) Log.v(TAG,
12067 "***** DROPPING PARALLEL: " + intent);
12068 mParallelBroadcasts.set(i, r);
12069 replaced = true;
12070 break;
12071 }
12072 }
12073 }
12074 if (!replaced) {
12075 mParallelBroadcasts.add(r);
12076 scheduleBroadcastsLocked();
12077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012078 registeredReceivers = null;
12079 NR = 0;
12080 }
12081
12082 // Merge into one list.
12083 int ir = 0;
12084 if (receivers != null) {
12085 // A special case for PACKAGE_ADDED: do not allow the package
12086 // being added to see this broadcast. This prevents them from
12087 // using this as a back door to get run as soon as they are
12088 // installed. Maybe in the future we want to have a special install
12089 // broadcast or such for apps, but we'd like to deliberately make
12090 // this decision.
The Android Open Source Project10592532009-03-18 17:39:46 -070012091 boolean skip = false;
12092 if (intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackbornf63220f2009-03-24 18:38:43 -070012093 skip = true;
The Android Open Source Project10592532009-03-18 17:39:46 -070012094 } else if (intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())) {
12095 skip = true;
12096 } else if (intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
12097 skip = true;
12098 }
12099 String skipPackage = (skip && intent.getData() != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012100 ? intent.getData().getSchemeSpecificPart()
12101 : null;
12102 if (skipPackage != null && receivers != null) {
12103 int NT = receivers.size();
12104 for (int it=0; it<NT; it++) {
12105 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12106 if (curt.activityInfo.packageName.equals(skipPackage)) {
12107 receivers.remove(it);
12108 it--;
12109 NT--;
12110 }
12111 }
12112 }
12113
12114 int NT = receivers != null ? receivers.size() : 0;
12115 int it = 0;
12116 ResolveInfo curt = null;
12117 BroadcastFilter curr = null;
12118 while (it < NT && ir < NR) {
12119 if (curt == null) {
12120 curt = (ResolveInfo)receivers.get(it);
12121 }
12122 if (curr == null) {
12123 curr = registeredReceivers.get(ir);
12124 }
12125 if (curr.getPriority() >= curt.priority) {
12126 // Insert this broadcast record into the final list.
12127 receivers.add(it, curr);
12128 ir++;
12129 curr = null;
12130 it++;
12131 NT++;
12132 } else {
12133 // Skip to the next ResolveInfo in the final list.
12134 it++;
12135 curt = null;
12136 }
12137 }
12138 }
12139 while (ir < NR) {
12140 if (receivers == null) {
12141 receivers = new ArrayList();
12142 }
12143 receivers.add(registeredReceivers.get(ir));
12144 ir++;
12145 }
12146
12147 if ((receivers != null && receivers.size() > 0)
12148 || resultTo != null) {
12149 BroadcastRecord r = new BroadcastRecord(intent, callerApp,
12150 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012151 receivers, resultTo, resultCode, resultData, map, ordered,
12152 sticky, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012153 if (DEBUG_BROADCAST) Log.v(
12154 TAG, "Enqueueing ordered broadcast " + r
12155 + ": prev had " + mOrderedBroadcasts.size());
12156 if (DEBUG_BROADCAST) {
12157 int seq = r.intent.getIntExtra("seq", -1);
12158 Log.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
12159 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012160 boolean replaced = false;
12161 if (replacePending) {
12162 for (int i=mOrderedBroadcasts.size()-1; i>=0; i--) {
12163 if (intent.filterEquals(mOrderedBroadcasts.get(i).intent)) {
12164 if (DEBUG_BROADCAST) Log.v(TAG,
12165 "***** DROPPING ORDERED: " + intent);
12166 mOrderedBroadcasts.set(i, r);
12167 replaced = true;
12168 break;
12169 }
12170 }
12171 }
12172 if (!replaced) {
12173 mOrderedBroadcasts.add(r);
12174 scheduleBroadcastsLocked();
12175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012176 }
12177
12178 return BROADCAST_SUCCESS;
12179 }
12180
12181 public final int broadcastIntent(IApplicationThread caller,
12182 Intent intent, String resolvedType, IIntentReceiver resultTo,
12183 int resultCode, String resultData, Bundle map,
12184 String requiredPermission, boolean serialized, boolean sticky) {
12185 // Refuse possible leaked file descriptors
12186 if (intent != null && intent.hasFileDescriptors() == true) {
12187 throw new IllegalArgumentException("File descriptors passed in Intent");
12188 }
12189
12190 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012191 int flags = intent.getFlags();
12192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012193 if (!mSystemReady) {
12194 // if the caller really truly claims to know what they're doing, go
12195 // ahead and allow the broadcast without launching any receivers
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012196 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12197 intent = new Intent(intent);
12198 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12199 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0){
12200 Log.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12201 + " before boot completion");
12202 throw new IllegalStateException("Cannot broadcast before boot completed");
12203 }
12204 }
12205
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012206 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12207 throw new IllegalArgumentException(
12208 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12209 }
12210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012211 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12212 final int callingPid = Binder.getCallingPid();
12213 final int callingUid = Binder.getCallingUid();
12214 final long origId = Binder.clearCallingIdentity();
12215 int res = broadcastIntentLocked(callerApp,
12216 callerApp != null ? callerApp.info.packageName : null,
12217 intent, resolvedType, resultTo,
12218 resultCode, resultData, map, requiredPermission, serialized,
12219 sticky, callingPid, callingUid);
12220 Binder.restoreCallingIdentity(origId);
12221 return res;
12222 }
12223 }
12224
12225 int broadcastIntentInPackage(String packageName, int uid,
12226 Intent intent, String resolvedType, IIntentReceiver resultTo,
12227 int resultCode, String resultData, Bundle map,
12228 String requiredPermission, boolean serialized, boolean sticky) {
12229 synchronized(this) {
12230 final long origId = Binder.clearCallingIdentity();
12231 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12232 resultTo, resultCode, resultData, map, requiredPermission,
12233 serialized, sticky, -1, uid);
12234 Binder.restoreCallingIdentity(origId);
12235 return res;
12236 }
12237 }
12238
12239 public final void unbroadcastIntent(IApplicationThread caller,
12240 Intent intent) {
12241 // Refuse possible leaked file descriptors
12242 if (intent != null && intent.hasFileDescriptors() == true) {
12243 throw new IllegalArgumentException("File descriptors passed in Intent");
12244 }
12245
12246 synchronized(this) {
12247 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12248 != PackageManager.PERMISSION_GRANTED) {
12249 String msg = "Permission Denial: unbroadcastIntent() from pid="
12250 + Binder.getCallingPid()
12251 + ", uid=" + Binder.getCallingUid()
12252 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
12253 Log.w(TAG, msg);
12254 throw new SecurityException(msg);
12255 }
12256 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12257 if (list != null) {
12258 int N = list.size();
12259 int i;
12260 for (i=0; i<N; i++) {
12261 if (intent.filterEquals(list.get(i))) {
12262 list.remove(i);
12263 break;
12264 }
12265 }
12266 }
12267 }
12268 }
12269
12270 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12271 String resultData, Bundle resultExtras, boolean resultAbort,
12272 boolean explicit) {
12273 if (mOrderedBroadcasts.size() == 0) {
12274 if (explicit) {
12275 Log.w(TAG, "finishReceiver called but no pending broadcasts");
12276 }
12277 return false;
12278 }
12279 BroadcastRecord r = mOrderedBroadcasts.get(0);
12280 if (r.receiver == null) {
12281 if (explicit) {
12282 Log.w(TAG, "finishReceiver called but none active");
12283 }
12284 return false;
12285 }
12286 if (r.receiver != receiver) {
12287 Log.w(TAG, "finishReceiver called but active receiver is different");
12288 return false;
12289 }
12290 int state = r.state;
12291 r.state = r.IDLE;
12292 if (state == r.IDLE) {
12293 if (explicit) {
12294 Log.w(TAG, "finishReceiver called but state is IDLE");
12295 }
12296 }
12297 r.receiver = null;
12298 r.intent.setComponent(null);
12299 if (r.curApp != null) {
12300 r.curApp.curReceiver = null;
12301 }
12302 if (r.curFilter != null) {
12303 r.curFilter.receiverList.curBroadcast = null;
12304 }
12305 r.curFilter = null;
12306 r.curApp = null;
12307 r.curComponent = null;
12308 r.curReceiver = null;
12309 mPendingBroadcast = null;
12310
12311 r.resultCode = resultCode;
12312 r.resultData = resultData;
12313 r.resultExtras = resultExtras;
12314 r.resultAbort = resultAbort;
12315
12316 // We will process the next receiver right now if this is finishing
12317 // an app receiver (which is always asynchronous) or after we have
12318 // come back from calling a receiver.
12319 return state == BroadcastRecord.APP_RECEIVE
12320 || state == BroadcastRecord.CALL_DONE_RECEIVE;
12321 }
12322
12323 public void finishReceiver(IBinder who, int resultCode, String resultData,
12324 Bundle resultExtras, boolean resultAbort) {
12325 if (DEBUG_BROADCAST) Log.v(TAG, "Finish receiver: " + who);
12326
12327 // Refuse possible leaked file descriptors
12328 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12329 throw new IllegalArgumentException("File descriptors passed in Bundle");
12330 }
12331
12332 boolean doNext;
12333
12334 final long origId = Binder.clearCallingIdentity();
12335
12336 synchronized(this) {
12337 doNext = finishReceiverLocked(
12338 who, resultCode, resultData, resultExtras, resultAbort, true);
12339 }
12340
12341 if (doNext) {
12342 processNextBroadcast(false);
12343 }
12344 trimApplications();
12345
12346 Binder.restoreCallingIdentity(origId);
12347 }
12348
12349 private final void logBroadcastReceiverDiscard(BroadcastRecord r) {
12350 if (r.nextReceiver > 0) {
12351 Object curReceiver = r.receivers.get(r.nextReceiver-1);
12352 if (curReceiver instanceof BroadcastFilter) {
12353 BroadcastFilter bf = (BroadcastFilter) curReceiver;
Doug Zongker2bec3d42009-12-04 12:52:44 -080012354 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012355 System.identityHashCode(r),
12356 r.intent.getAction(),
12357 r.nextReceiver - 1,
12358 System.identityHashCode(bf));
12359 } else {
Doug Zongker2bec3d42009-12-04 12:52:44 -080012360 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012361 System.identityHashCode(r),
12362 r.intent.getAction(),
12363 r.nextReceiver - 1,
12364 ((ResolveInfo)curReceiver).toString());
12365 }
12366 } else {
12367 Log.w(TAG, "Discarding broadcast before first receiver is invoked: "
12368 + r);
Doug Zongker2bec3d42009-12-04 12:52:44 -080012369 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012370 System.identityHashCode(r),
12371 r.intent.getAction(),
12372 r.nextReceiver,
12373 "NONE");
12374 }
12375 }
12376
12377 private final void broadcastTimeout() {
12378 synchronized (this) {
12379 if (mOrderedBroadcasts.size() == 0) {
12380 return;
12381 }
12382 long now = SystemClock.uptimeMillis();
12383 BroadcastRecord r = mOrderedBroadcasts.get(0);
Dianne Hackborn12527f92009-11-11 17:39:50 -080012384 if ((r.receiverTime+BROADCAST_TIMEOUT) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012385 if (DEBUG_BROADCAST) Log.v(TAG,
12386 "Premature timeout @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
Dianne Hackborn12527f92009-11-11 17:39:50 -080012387 + (r.receiverTime + BROADCAST_TIMEOUT));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012388 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG);
Dianne Hackborn12527f92009-11-11 17:39:50 -080012389 mHandler.sendMessageAtTime(msg, r.receiverTime+BROADCAST_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012390 return;
12391 }
12392
12393 Log.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r.receiver);
Dianne Hackborn12527f92009-11-11 17:39:50 -080012394 r.receiverTime = now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012395 r.anrCount++;
12396
12397 // Current receiver has passed its expiration date.
12398 if (r.nextReceiver <= 0) {
12399 Log.w(TAG, "Timeout on receiver with nextReceiver <= 0");
12400 return;
12401 }
12402
12403 ProcessRecord app = null;
12404
12405 Object curReceiver = r.receivers.get(r.nextReceiver-1);
12406 Log.w(TAG, "Receiver during timeout: " + curReceiver);
12407 logBroadcastReceiverDiscard(r);
12408 if (curReceiver instanceof BroadcastFilter) {
12409 BroadcastFilter bf = (BroadcastFilter)curReceiver;
12410 if (bf.receiverList.pid != 0
12411 && bf.receiverList.pid != MY_PID) {
12412 synchronized (this.mPidsSelfLocked) {
12413 app = this.mPidsSelfLocked.get(
12414 bf.receiverList.pid);
12415 }
12416 }
12417 } else {
12418 app = r.curApp;
12419 }
12420
12421 if (app != null) {
Dan Egnorb7f03672009-12-09 16:22:32 -080012422 appNotRespondingLocked(app, null, null, "Broadcast of " + r.intent.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012423 }
12424
12425 if (mPendingBroadcast == r) {
12426 mPendingBroadcast = null;
12427 }
12428
12429 // Move on to the next receiver.
12430 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
12431 r.resultExtras, r.resultAbort, true);
12432 scheduleBroadcastsLocked();
12433 }
12434 }
12435
12436 private final void processCurBroadcastLocked(BroadcastRecord r,
12437 ProcessRecord app) throws RemoteException {
12438 if (app.thread == null) {
12439 throw new RemoteException();
12440 }
12441 r.receiver = app.thread.asBinder();
12442 r.curApp = app;
12443 app.curReceiver = r;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012444 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012445
12446 // Tell the application to launch this receiver.
12447 r.intent.setComponent(r.curComponent);
12448
12449 boolean started = false;
12450 try {
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012451 if (DEBUG_BROADCAST_LIGHT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012452 "Delivering to component " + r.curComponent
12453 + ": " + r);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070012454 ensurePackageDexOpt(r.intent.getComponent().getPackageName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012455 app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
12456 r.resultCode, r.resultData, r.resultExtras, r.ordered);
12457 started = true;
12458 } finally {
12459 if (!started) {
12460 r.receiver = null;
12461 r.curApp = null;
12462 app.curReceiver = null;
12463 }
12464 }
12465
12466 }
12467
12468 static void performReceive(ProcessRecord app, IIntentReceiver receiver,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070012469 Intent intent, int resultCode, String data, Bundle extras,
12470 boolean ordered, boolean sticky) throws RemoteException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012471 if (app != null && app.thread != null) {
12472 // If we have an app thread, do the call through that so it is
12473 // correctly ordered with other one-way calls.
12474 app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070012475 data, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012476 } else {
Dianne Hackborn68d881c2009-10-05 13:58:17 -070012477 receiver.performReceive(intent, resultCode, data, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012478 }
12479 }
12480
12481 private final void deliverToRegisteredReceiver(BroadcastRecord r,
12482 BroadcastFilter filter, boolean ordered) {
12483 boolean skip = false;
12484 if (filter.requiredPermission != null) {
12485 int perm = checkComponentPermission(filter.requiredPermission,
12486 r.callingPid, r.callingUid, -1);
12487 if (perm != PackageManager.PERMISSION_GRANTED) {
12488 Log.w(TAG, "Permission Denial: broadcasting "
12489 + r.intent.toString()
12490 + " from " + r.callerPackage + " (pid="
12491 + r.callingPid + ", uid=" + r.callingUid + ")"
12492 + " requires " + filter.requiredPermission
12493 + " due to registered receiver " + filter);
12494 skip = true;
12495 }
12496 }
12497 if (r.requiredPermission != null) {
12498 int perm = checkComponentPermission(r.requiredPermission,
12499 filter.receiverList.pid, filter.receiverList.uid, -1);
12500 if (perm != PackageManager.PERMISSION_GRANTED) {
12501 Log.w(TAG, "Permission Denial: receiving "
12502 + r.intent.toString()
12503 + " to " + filter.receiverList.app
12504 + " (pid=" + filter.receiverList.pid
12505 + ", uid=" + filter.receiverList.uid + ")"
12506 + " requires " + r.requiredPermission
12507 + " due to sender " + r.callerPackage
12508 + " (uid " + r.callingUid + ")");
12509 skip = true;
12510 }
12511 }
12512
12513 if (!skip) {
12514 // If this is not being sent as an ordered broadcast, then we
12515 // don't want to touch the fields that keep track of the current
12516 // state of ordered broadcasts.
12517 if (ordered) {
12518 r.receiver = filter.receiverList.receiver.asBinder();
12519 r.curFilter = filter;
12520 filter.receiverList.curBroadcast = r;
12521 r.state = BroadcastRecord.CALL_IN_RECEIVE;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012522 if (filter.receiverList.app != null) {
12523 // Bump hosting application to no longer be in background
12524 // scheduling class. Note that we can't do that if there
12525 // isn't an app... but we can only be in that case for
12526 // things that directly call the IActivityManager API, which
12527 // are already core system stuff so don't matter for this.
12528 r.curApp = filter.receiverList.app;
12529 filter.receiverList.app.curReceiver = r;
12530 updateOomAdjLocked();
12531 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012532 }
12533 try {
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012534 if (DEBUG_BROADCAST_LIGHT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012535 int seq = r.intent.getIntExtra("seq", -1);
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012536 Log.i(TAG, "Delivering to " + filter.receiverList.app
12537 + " (seq=" + seq + "): " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012538 }
12539 performReceive(filter.receiverList.app, filter.receiverList.receiver,
12540 new Intent(r.intent), r.resultCode,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012541 r.resultData, r.resultExtras, r.ordered, r.initialSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012542 if (ordered) {
12543 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
12544 }
12545 } catch (RemoteException e) {
12546 Log.w(TAG, "Failure sending broadcast " + r.intent, e);
12547 if (ordered) {
12548 r.receiver = null;
12549 r.curFilter = null;
12550 filter.receiverList.curBroadcast = null;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012551 if (filter.receiverList.app != null) {
12552 filter.receiverList.app.curReceiver = null;
12553 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012554 }
12555 }
12556 }
12557 }
12558
Dianne Hackborn12527f92009-11-11 17:39:50 -080012559 private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
12560 if (r.callingUid < 0) {
12561 // This was from a registerReceiver() call; ignore it.
12562 return;
12563 }
12564 System.arraycopy(mBroadcastHistory, 0, mBroadcastHistory, 1,
12565 MAX_BROADCAST_HISTORY-1);
12566 r.finishTime = SystemClock.uptimeMillis();
12567 mBroadcastHistory[0] = r;
12568 }
12569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012570 private final void processNextBroadcast(boolean fromMsg) {
12571 synchronized(this) {
12572 BroadcastRecord r;
12573
12574 if (DEBUG_BROADCAST) Log.v(TAG, "processNextBroadcast: "
12575 + mParallelBroadcasts.size() + " broadcasts, "
12576 + mOrderedBroadcasts.size() + " serialized broadcasts");
12577
12578 updateCpuStats();
12579
12580 if (fromMsg) {
12581 mBroadcastsScheduled = false;
12582 }
12583
12584 // First, deliver any non-serialized broadcasts right away.
12585 while (mParallelBroadcasts.size() > 0) {
12586 r = mParallelBroadcasts.remove(0);
Dianne Hackborn12527f92009-11-11 17:39:50 -080012587 r.dispatchTime = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012588 final int N = r.receivers.size();
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012589 if (DEBUG_BROADCAST_LIGHT) Log.v(TAG, "Processing parallel broadcast "
12590 + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012591 for (int i=0; i<N; i++) {
12592 Object target = r.receivers.get(i);
12593 if (DEBUG_BROADCAST) Log.v(TAG,
12594 "Delivering non-serialized to registered "
12595 + target + ": " + r);
12596 deliverToRegisteredReceiver(r, (BroadcastFilter)target, false);
12597 }
Dianne Hackborn12527f92009-11-11 17:39:50 -080012598 addBroadcastToHistoryLocked(r);
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012599 if (DEBUG_BROADCAST_LIGHT) Log.v(TAG, "Done with parallel broadcast "
12600 + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012601 }
12602
12603 // Now take care of the next serialized one...
12604
12605 // If we are waiting for a process to come up to handle the next
12606 // broadcast, then do nothing at this point. Just in case, we
12607 // check that the process we're waiting for still exists.
12608 if (mPendingBroadcast != null) {
Dianne Hackbornbd0a81f2009-10-04 13:30:50 -070012609 if (DEBUG_BROADCAST_LIGHT) {
12610 Log.v(TAG, "processNextBroadcast: waiting for "
12611 + mPendingBroadcast.curApp);
12612 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012613
12614 boolean isDead;
12615 synchronized (mPidsSelfLocked) {
12616 isDead = (mPidsSelfLocked.get(mPendingBroadcast.curApp.pid) == null);
12617 }
12618 if (!isDead) {
12619 // It's still alive, so keep waiting
12620 return;
12621 } else {
12622 Log.w(TAG, "pending app " + mPendingBroadcast.curApp
12623 + " died before responding to broadcast");
12624 mPendingBroadcast = null;
12625 }
12626 }
12627
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012628 boolean looped = false;
12629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012630 do {
12631 if (mOrderedBroadcasts.size() == 0) {
12632 // No more broadcasts pending, so all done!
12633 scheduleAppGcsLocked();
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012634 if (looped) {
12635 // If we had finished the last ordered broadcast, then
12636 // make sure all processes have correct oom and sched
12637 // adjustments.
12638 updateOomAdjLocked();
12639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012640 return;
12641 }
12642 r = mOrderedBroadcasts.get(0);
12643 boolean forceReceive = false;
12644
12645 // Ensure that even if something goes awry with the timeout
12646 // detection, we catch "hung" broadcasts here, discard them,
12647 // and continue to make progress.
12648 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
12649 long now = SystemClock.uptimeMillis();
12650 if (r.dispatchTime > 0) {
12651 if ((numReceivers > 0) &&
12652 (now > r.dispatchTime + (2*BROADCAST_TIMEOUT*numReceivers))) {
12653 Log.w(TAG, "Hung broadcast discarded after timeout failure:"
12654 + " now=" + now
12655 + " dispatchTime=" + r.dispatchTime
Dianne Hackborn12527f92009-11-11 17:39:50 -080012656 + " startTime=" + r.receiverTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012657 + " intent=" + r.intent
12658 + " numReceivers=" + numReceivers
12659 + " nextReceiver=" + r.nextReceiver
12660 + " state=" + r.state);
12661 broadcastTimeout(); // forcibly finish this broadcast
12662 forceReceive = true;
12663 r.state = BroadcastRecord.IDLE;
12664 }
12665 }
12666
12667 if (r.state != BroadcastRecord.IDLE) {
12668 if (DEBUG_BROADCAST) Log.d(TAG,
12669 "processNextBroadcast() called when not idle (state="
12670 + r.state + ")");
12671 return;
12672 }
12673
12674 if (r.receivers == null || r.nextReceiver >= numReceivers
12675 || r.resultAbort || forceReceive) {
12676 // No more receivers for this broadcast! Send the final
12677 // result if requested...
12678 if (r.resultTo != null) {
12679 try {
12680 if (DEBUG_BROADCAST) {
12681 int seq = r.intent.getIntExtra("seq", -1);
12682 Log.i(TAG, "Finishing broadcast " + r.intent.getAction()
12683 + " seq=" + seq + " app=" + r.callerApp);
12684 }
12685 performReceive(r.callerApp, r.resultTo,
12686 new Intent(r.intent), r.resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -070012687 r.resultData, r.resultExtras, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012688 } catch (RemoteException e) {
12689 Log.w(TAG, "Failure sending broadcast result of " + r.intent, e);
12690 }
12691 }
12692
12693 if (DEBUG_BROADCAST) Log.v(TAG, "Cancelling BROADCAST_TIMEOUT_MSG");
12694 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG);
12695
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012696 if (DEBUG_BROADCAST_LIGHT) Log.v(TAG, "Finished with ordered broadcast "
12697 + r);
12698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012699 // ... and on to the next...
Dianne Hackborn12527f92009-11-11 17:39:50 -080012700 addBroadcastToHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012701 mOrderedBroadcasts.remove(0);
12702 r = null;
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012703 looped = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012704 continue;
12705 }
12706 } while (r == null);
12707
12708 // Get the next receiver...
12709 int recIdx = r.nextReceiver++;
12710
12711 // Keep track of when this receiver started, and make sure there
12712 // is a timeout message pending to kill it if need be.
Dianne Hackborn12527f92009-11-11 17:39:50 -080012713 r.receiverTime = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012714 if (recIdx == 0) {
Dianne Hackborn12527f92009-11-11 17:39:50 -080012715 r.dispatchTime = r.receiverTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012716
Dianne Hackborn82f3f002009-06-16 18:49:05 -070012717 if (DEBUG_BROADCAST_LIGHT) Log.v(TAG, "Processing ordered broadcast "
12718 + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012719 if (DEBUG_BROADCAST) Log.v(TAG,
12720 "Submitting BROADCAST_TIMEOUT_MSG for "
Dianne Hackborn12527f92009-11-11 17:39:50 -080012721 + (r.receiverTime + BROADCAST_TIMEOUT));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012722 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG);
Dianne Hackborn12527f92009-11-11 17:39:50 -080012723 mHandler.sendMessageAtTime(msg, r.receiverTime+BROADCAST_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012724 }
12725
12726 Object nextReceiver = r.receivers.get(recIdx);
12727 if (nextReceiver instanceof BroadcastFilter) {
12728 // Simple case: this is a registered receiver who gets
12729 // a direct call.
12730 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
12731 if (DEBUG_BROADCAST) Log.v(TAG,
12732 "Delivering serialized to registered "
12733 + filter + ": " + r);
12734 deliverToRegisteredReceiver(r, filter, r.ordered);
12735 if (r.receiver == null || !r.ordered) {
12736 // The receiver has already finished, so schedule to
12737 // process the next one.
12738 r.state = BroadcastRecord.IDLE;
12739 scheduleBroadcastsLocked();
12740 }
12741 return;
12742 }
12743
12744 // Hard case: need to instantiate the receiver, possibly
12745 // starting its application process to host it.
12746
12747 ResolveInfo info =
12748 (ResolveInfo)nextReceiver;
12749
12750 boolean skip = false;
12751 int perm = checkComponentPermission(info.activityInfo.permission,
12752 r.callingPid, r.callingUid,
12753 info.activityInfo.exported
12754 ? -1 : info.activityInfo.applicationInfo.uid);
12755 if (perm != PackageManager.PERMISSION_GRANTED) {
12756 Log.w(TAG, "Permission Denial: broadcasting "
12757 + r.intent.toString()
12758 + " from " + r.callerPackage + " (pid=" + r.callingPid
12759 + ", uid=" + r.callingUid + ")"
12760 + " requires " + info.activityInfo.permission
12761 + " due to receiver " + info.activityInfo.packageName
12762 + "/" + info.activityInfo.name);
12763 skip = true;
12764 }
12765 if (r.callingUid != Process.SYSTEM_UID &&
12766 r.requiredPermission != null) {
12767 try {
12768 perm = ActivityThread.getPackageManager().
12769 checkPermission(r.requiredPermission,
12770 info.activityInfo.applicationInfo.packageName);
12771 } catch (RemoteException e) {
12772 perm = PackageManager.PERMISSION_DENIED;
12773 }
12774 if (perm != PackageManager.PERMISSION_GRANTED) {
12775 Log.w(TAG, "Permission Denial: receiving "
12776 + r.intent + " to "
12777 + info.activityInfo.applicationInfo.packageName
12778 + " requires " + r.requiredPermission
12779 + " due to sender " + r.callerPackage
12780 + " (uid " + r.callingUid + ")");
12781 skip = true;
12782 }
12783 }
12784 if (r.curApp != null && r.curApp.crashing) {
12785 // If the target process is crashing, just skip it.
12786 skip = true;
12787 }
12788
12789 if (skip) {
12790 r.receiver = null;
12791 r.curFilter = null;
12792 r.state = BroadcastRecord.IDLE;
12793 scheduleBroadcastsLocked();
12794 return;
12795 }
12796
12797 r.state = BroadcastRecord.APP_RECEIVE;
12798 String targetProcess = info.activityInfo.processName;
12799 r.curComponent = new ComponentName(
12800 info.activityInfo.applicationInfo.packageName,
12801 info.activityInfo.name);
12802 r.curReceiver = info.activityInfo;
12803
12804 // Is this receiver's application already running?
12805 ProcessRecord app = getProcessRecordLocked(targetProcess,
12806 info.activityInfo.applicationInfo.uid);
12807 if (app != null && app.thread != null) {
12808 try {
12809 processCurBroadcastLocked(r, app);
12810 return;
12811 } catch (RemoteException e) {
12812 Log.w(TAG, "Exception when sending broadcast to "
12813 + r.curComponent, e);
12814 }
12815
12816 // If a dead object exception was thrown -- fall through to
12817 // restart the application.
12818 }
12819
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012820 // Not running -- get it started, to be executed when the app comes up.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012821 if ((r.curApp=startProcessLocked(targetProcess,
12822 info.activityInfo.applicationInfo, true,
12823 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012824 "broadcast", r.curComponent,
12825 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0))
12826 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012827 // Ah, this recipient is unavailable. Finish it if necessary,
12828 // and mark the broadcast record as ready for the next.
12829 Log.w(TAG, "Unable to launch app "
12830 + info.activityInfo.applicationInfo.packageName + "/"
12831 + info.activityInfo.applicationInfo.uid + " for broadcast "
12832 + r.intent + ": process is bad");
12833 logBroadcastReceiverDiscard(r);
12834 finishReceiverLocked(r.receiver, r.resultCode, r.resultData,
12835 r.resultExtras, r.resultAbort, true);
12836 scheduleBroadcastsLocked();
12837 r.state = BroadcastRecord.IDLE;
12838 return;
12839 }
12840
12841 mPendingBroadcast = r;
12842 }
12843 }
12844
12845 // =========================================================
12846 // INSTRUMENTATION
12847 // =========================================================
12848
12849 public boolean startInstrumentation(ComponentName className,
12850 String profileFile, int flags, Bundle arguments,
12851 IInstrumentationWatcher watcher) {
12852 // Refuse possible leaked file descriptors
12853 if (arguments != null && arguments.hasFileDescriptors()) {
12854 throw new IllegalArgumentException("File descriptors passed in Bundle");
12855 }
12856
12857 synchronized(this) {
12858 InstrumentationInfo ii = null;
12859 ApplicationInfo ai = null;
12860 try {
12861 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012862 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012863 ai = mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012864 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012865 } catch (PackageManager.NameNotFoundException e) {
12866 }
12867 if (ii == null) {
12868 reportStartInstrumentationFailure(watcher, className,
12869 "Unable to find instrumentation info for: " + className);
12870 return false;
12871 }
12872 if (ai == null) {
12873 reportStartInstrumentationFailure(watcher, className,
12874 "Unable to find instrumentation target package: " + ii.targetPackage);
12875 return false;
12876 }
12877
12878 int match = mContext.getPackageManager().checkSignatures(
12879 ii.targetPackage, ii.packageName);
12880 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12881 String msg = "Permission Denial: starting instrumentation "
12882 + className + " from pid="
12883 + Binder.getCallingPid()
12884 + ", uid=" + Binder.getCallingPid()
12885 + " not allowed because package " + ii.packageName
12886 + " does not have a signature matching the target "
12887 + ii.targetPackage;
12888 reportStartInstrumentationFailure(watcher, className, msg);
12889 throw new SecurityException(msg);
12890 }
12891
12892 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn03abb812010-01-04 18:43:19 -080012893 forceStopPackageLocked(ii.targetPackage, -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012894 ProcessRecord app = addAppLocked(ai);
12895 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012896 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012897 app.instrumentationProfileFile = profileFile;
12898 app.instrumentationArguments = arguments;
12899 app.instrumentationWatcher = watcher;
12900 app.instrumentationResultClass = className;
12901 Binder.restoreCallingIdentity(origId);
12902 }
12903
12904 return true;
12905 }
12906
12907 /**
12908 * Report errors that occur while attempting to start Instrumentation. Always writes the
12909 * error to the logs, but if somebody is watching, send the report there too. This enables
12910 * the "am" command to report errors with more information.
12911 *
12912 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12913 * @param cn The component name of the instrumentation.
12914 * @param report The error report.
12915 */
12916 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12917 ComponentName cn, String report) {
12918 Log.w(TAG, report);
12919 try {
12920 if (watcher != null) {
12921 Bundle results = new Bundle();
12922 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12923 results.putString("Error", report);
12924 watcher.instrumentationStatus(cn, -1, results);
12925 }
12926 } catch (RemoteException e) {
12927 Log.w(TAG, e);
12928 }
12929 }
12930
12931 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12932 if (app.instrumentationWatcher != null) {
12933 try {
12934 // NOTE: IInstrumentationWatcher *must* be oneway here
12935 app.instrumentationWatcher.instrumentationFinished(
12936 app.instrumentationClass,
12937 resultCode,
12938 results);
12939 } catch (RemoteException e) {
12940 }
12941 }
12942 app.instrumentationWatcher = null;
12943 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012944 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012945 app.instrumentationProfileFile = null;
12946 app.instrumentationArguments = null;
12947
Dianne Hackborn03abb812010-01-04 18:43:19 -080012948 forceStopPackageLocked(app.processName, -1, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012949 }
12950
12951 public void finishInstrumentation(IApplicationThread target,
12952 int resultCode, Bundle results) {
12953 // Refuse possible leaked file descriptors
12954 if (results != null && results.hasFileDescriptors()) {
12955 throw new IllegalArgumentException("File descriptors passed in Intent");
12956 }
12957
12958 synchronized(this) {
12959 ProcessRecord app = getRecordForAppLocked(target);
12960 if (app == null) {
12961 Log.w(TAG, "finishInstrumentation: no app for " + target);
12962 return;
12963 }
12964 final long origId = Binder.clearCallingIdentity();
12965 finishInstrumentationLocked(app, resultCode, results);
12966 Binder.restoreCallingIdentity(origId);
12967 }
12968 }
12969
12970 // =========================================================
12971 // CONFIGURATION
12972 // =========================================================
12973
12974 public ConfigurationInfo getDeviceConfigurationInfo() {
12975 ConfigurationInfo config = new ConfigurationInfo();
12976 synchronized (this) {
12977 config.reqTouchScreen = mConfiguration.touchscreen;
12978 config.reqKeyboardType = mConfiguration.keyboard;
12979 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012980 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12981 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012982 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12983 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012984 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12985 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012986 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12987 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012988 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012989 }
12990 return config;
12991 }
12992
12993 public Configuration getConfiguration() {
12994 Configuration ci;
12995 synchronized(this) {
12996 ci = new Configuration(mConfiguration);
12997 }
12998 return ci;
12999 }
13000
13001 public void updateConfiguration(Configuration values) {
13002 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13003 "updateConfiguration()");
13004
13005 synchronized(this) {
13006 if (values == null && mWindowManager != null) {
13007 // sentinel: fetch the current configuration from the window manager
13008 values = mWindowManager.computeNewConfiguration();
13009 }
13010
13011 final long origId = Binder.clearCallingIdentity();
13012 updateConfigurationLocked(values, null);
13013 Binder.restoreCallingIdentity(origId);
13014 }
13015 }
13016
13017 /**
13018 * Do either or both things: (1) change the current configuration, and (2)
13019 * make sure the given activity is running with the (now) current
13020 * configuration. Returns true if the activity has been left running, or
13021 * false if <var>starting</var> is being destroyed to match the new
13022 * configuration.
13023 */
13024 public boolean updateConfigurationLocked(Configuration values,
13025 HistoryRecord starting) {
13026 int changes = 0;
13027
13028 boolean kept = true;
13029
13030 if (values != null) {
13031 Configuration newConfig = new Configuration(mConfiguration);
13032 changes = newConfig.updateFrom(values);
13033 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013034 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013035 Log.i(TAG, "Updating configuration to: " + values);
13036 }
13037
Doug Zongker2bec3d42009-12-04 12:52:44 -080013038 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013039
13040 if (values.locale != null) {
13041 saveLocaleLocked(values.locale,
13042 !values.locale.equals(mConfiguration.locale),
13043 values.userSetLocale);
13044 }
13045
13046 mConfiguration = newConfig;
Dianne Hackborna8f60182009-09-01 19:01:50 -070013047 Log.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013048
13049 AttributeCache ac = AttributeCache.instance();
13050 if (ac != null) {
13051 ac.updateConfiguration(mConfiguration);
13052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013053
13054 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
13055 msg.obj = new Configuration(mConfiguration);
13056 mHandler.sendMessage(msg);
13057
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013058 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13059 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013060 try {
13061 if (app.thread != null) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013062 if (DEBUG_CONFIGURATION) Log.v(TAG, "Sending to proc "
13063 + app.processName + " new config " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013064 app.thread.scheduleConfigurationChanged(mConfiguration);
13065 }
13066 } catch (Exception e) {
13067 }
13068 }
13069 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013070 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13071 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013072 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
13073 null, false, false, MY_PID, Process.SYSTEM_UID);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013074 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13075 broadcastIntentLocked(null, null,
13076 new Intent(Intent.ACTION_LOCALE_CHANGED),
13077 null, null, 0, null, null,
13078 null, false, false, MY_PID, Process.SYSTEM_UID);
13079 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013080 }
13081 }
13082
13083 if (changes != 0 && starting == null) {
13084 // If the configuration changed, and the caller is not already
13085 // in the process of starting an activity, then find the top
13086 // activity to check if its configuration needs to change.
13087 starting = topRunningActivityLocked(null);
13088 }
13089
13090 if (starting != null) {
13091 kept = ensureActivityConfigurationLocked(starting, changes);
13092 if (kept) {
13093 // If this didn't result in the starting activity being
13094 // destroyed, then we need to make sure at this point that all
13095 // other activities are made visible.
13096 if (DEBUG_SWITCH) Log.i(TAG, "Config didn't destroy " + starting
13097 + ", ensuring others are correct.");
13098 ensureActivitiesVisibleLocked(starting, changes);
13099 }
13100 }
13101
13102 return kept;
13103 }
13104
13105 private final boolean relaunchActivityLocked(HistoryRecord r,
13106 int changes, boolean andResume) {
13107 List<ResultInfo> results = null;
13108 List<Intent> newIntents = null;
13109 if (andResume) {
13110 results = r.results;
13111 newIntents = r.newIntents;
13112 }
13113 if (DEBUG_SWITCH) Log.v(TAG, "Relaunching: " + r
13114 + " with results=" + results + " newIntents=" + newIntents
13115 + " andResume=" + andResume);
Doug Zongker2bec3d42009-12-04 12:52:44 -080013116 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
13117 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013118 r.task.taskId, r.shortComponentName);
13119
13120 r.startFreezingScreenLocked(r.app, 0);
13121
13122 try {
13123 if (DEBUG_SWITCH) Log.i(TAG, "Switch is restarting resumed " + r);
13124 r.app.thread.scheduleRelaunchActivity(r, results, newIntents,
Dianne Hackborn871ecdc2009-12-11 15:24:33 -080013125 changes, !andResume, mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013126 // Note: don't need to call pauseIfSleepingLocked() here, because
13127 // the caller will only pass in 'andResume' if this activity is
13128 // currently resumed, which implies we aren't sleeping.
13129 } catch (RemoteException e) {
13130 return false;
13131 }
13132
13133 if (andResume) {
13134 r.results = null;
13135 r.newIntents = null;
Dianne Hackborn1bcf5a82009-09-30 15:22:29 -070013136 reportResumedActivityLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013137 }
13138
13139 return true;
13140 }
13141
13142 /**
13143 * Make sure the given activity matches the current configuration. Returns
13144 * false if the activity had to be destroyed. Returns true if the
13145 * configuration is the same, or the activity will remain running as-is
13146 * for whatever reason. Ensures the HistoryRecord is updated with the
13147 * correct configuration and all other bookkeeping is handled.
13148 */
13149 private final boolean ensureActivityConfigurationLocked(HistoryRecord r,
13150 int globalChanges) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013151 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Log.v(TAG,
13152 "Ensuring correct configuration: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013153
13154 // Short circuit: if the two configurations are the exact same
13155 // object (the common case), then there is nothing to do.
13156 Configuration newConfig = mConfiguration;
13157 if (r.configuration == newConfig) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013158 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Log.v(TAG,
13159 "Configuration unchanged in " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013160 return true;
13161 }
13162
13163 // We don't worry about activities that are finishing.
13164 if (r.finishing) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013165 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013166 "Configuration doesn't matter in finishing " + r);
13167 r.stopFreezingScreenLocked(false);
13168 return true;
13169 }
13170
13171 // Okay we now are going to make this activity have the new config.
13172 // But then we need to figure out how it needs to deal with that.
13173 Configuration oldConfig = r.configuration;
13174 r.configuration = newConfig;
13175
13176 // If the activity isn't currently running, just leave the new
13177 // configuration and it will pick that up next time it starts.
13178 if (r.app == null || r.app.thread == null) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013179 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013180 "Configuration doesn't matter not running " + r);
13181 r.stopFreezingScreenLocked(false);
13182 return true;
13183 }
13184
13185 // If the activity isn't persistent, there is a chance we will
13186 // need to restart it.
13187 if (!r.persistent) {
13188
13189 // Figure out what has changed between the two configurations.
13190 int changes = oldConfig.diff(newConfig);
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013191 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
13192 Log.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013193 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013194 + Integer.toHexString(r.info.configChanges)
13195 + ", newConfig=" + newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013196 }
13197 if ((changes&(~r.info.configChanges)) != 0) {
13198 // Aha, the activity isn't handling the change, so DIE DIE DIE.
13199 r.configChangeFlags |= changes;
13200 r.startFreezingScreenLocked(r.app, globalChanges);
13201 if (r.app == null || r.app.thread == null) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013202 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Log.v(TAG,
13203 "Switch is destroying non-running " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013204 destroyActivityLocked(r, true);
13205 } else if (r.state == ActivityState.PAUSING) {
13206 // A little annoying: we are waiting for this activity to
13207 // finish pausing. Let's not do anything now, but just
13208 // flag that it needs to be restarted when done pausing.
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013209 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Log.v(TAG,
13210 "Switch is skipping already pausing " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013211 r.configDestroy = true;
13212 return true;
13213 } else if (r.state == ActivityState.RESUMED) {
13214 // Try to optimize this case: the configuration is changing
13215 // and we need to restart the top, resumed activity.
13216 // Instead of doing the normal handshaking, just say
13217 // "restart!".
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013218 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Log.v(TAG,
13219 "Switch is restarting resumed " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013220 relaunchActivityLocked(r, r.configChangeFlags, true);
13221 r.configChangeFlags = 0;
13222 } else {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013223 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Log.v(TAG,
13224 "Switch is restarting non-resumed " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013225 relaunchActivityLocked(r, r.configChangeFlags, false);
13226 r.configChangeFlags = 0;
13227 }
13228
13229 // All done... tell the caller we weren't able to keep this
13230 // activity around.
13231 return false;
13232 }
13233 }
13234
13235 // Default case: the activity can handle this new configuration, so
13236 // hand it over. Note that we don't need to give it the new
13237 // configuration, since we always send configuration changes to all
13238 // process when they happen so it can just use whatever configuration
13239 // it last got.
13240 if (r.app != null && r.app.thread != null) {
13241 try {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013242 if (DEBUG_CONFIGURATION) Log.v(TAG, "Sending new config to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013243 r.app.thread.scheduleActivityConfigurationChanged(r);
13244 } catch (RemoteException e) {
13245 // If process died, whatever.
13246 }
13247 }
13248 r.stopFreezingScreenLocked(false);
13249
13250 return true;
13251 }
13252
13253 /**
13254 * Save the locale. You must be inside a synchronized (this) block.
13255 */
13256 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13257 if(isDiff) {
13258 SystemProperties.set("user.language", l.getLanguage());
13259 SystemProperties.set("user.region", l.getCountry());
13260 }
13261
13262 if(isPersist) {
13263 SystemProperties.set("persist.sys.language", l.getLanguage());
13264 SystemProperties.set("persist.sys.country", l.getCountry());
13265 SystemProperties.set("persist.sys.localevar", l.getVariant());
13266 }
13267 }
13268
13269 // =========================================================
13270 // LIFETIME MANAGEMENT
13271 // =========================================================
13272
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013273 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
13274 ProcessRecord TOP_APP, boolean recursed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013275 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013276 // This adjustment has already been computed. If we are calling
13277 // from the top, we may have already computed our adjustment with
13278 // an earlier hidden adjustment that isn't really for us... if
13279 // so, use the new hidden adjustment.
13280 if (!recursed && app.hidden) {
13281 app.curAdj = hiddenAdj;
13282 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013283 return app.curAdj;
13284 }
13285
13286 if (app.thread == null) {
13287 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013288 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013289 return (app.curAdj=EMPTY_APP_ADJ);
13290 }
13291
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013292 if (app.maxAdj <= FOREGROUND_APP_ADJ) {
13293 // The max adjustment doesn't allow this app to be anything
13294 // below foreground, so it is not worth doing work for it.
13295 app.adjType = "fixed";
13296 app.adjSeq = mAdjSeq;
13297 app.curRawAdj = app.maxAdj;
13298 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
13299 return (app.curAdj=app.maxAdj);
13300 }
13301
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013302 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013303 app.adjSource = null;
13304 app.adjTarget = null;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013305 app.empty = false;
13306 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013307
The Android Open Source Project4df24232009-03-05 14:34:35 -080013308 // Determine the importance of the process, starting with most
13309 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013310 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013311 int schedGroup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013312 int N;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013313 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013314 // The last app on the list is the foreground app.
13315 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013316 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013317 app.adjType = "top-activity";
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013318 } else if (app.instrumentationClass != null) {
13319 // Don't want to kill running instrumentation.
13320 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013321 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013322 app.adjType = "instrumentation";
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013323 } else if (app.persistentActivities > 0) {
13324 // Special persistent activities... shouldn't be used these days.
13325 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013326 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013327 app.adjType = "persistent";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013328 } else if (app.curReceiver != null ||
13329 (mPendingBroadcast != null && mPendingBroadcast.curApp == app)) {
13330 // An app that is currently receiving a broadcast also
13331 // counts as being in the foreground.
13332 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013333 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013334 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013335 } else if (app.executingServices.size() > 0) {
13336 // An app that is currently executing a service callback also
13337 // counts as being in the foreground.
13338 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013339 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013340 app.adjType = "exec-service";
13341 } else if (app.foregroundServices) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013342 // The user is aware of this app, so make it visible.
13343 adj = VISIBLE_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013344 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013345 app.adjType = "foreground-service";
13346 } else if (app.forcingToForeground != null) {
13347 // The user is aware of this app, so make it visible.
13348 adj = VISIBLE_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013349 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013350 app.adjType = "force-foreground";
13351 app.adjSource = app.forcingToForeground;
The Android Open Source Project4df24232009-03-05 14:34:35 -080013352 } else if (app == mHomeProcess) {
13353 // This process is hosting what we currently consider to be the
13354 // home app, so we don't want to let it go into the background.
13355 adj = HOME_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013356 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013357 app.adjType = "home";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013358 } else if ((N=app.activities.size()) != 0) {
13359 // This app is in the background with paused activities.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013360 app.hidden = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013361 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013362 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013363 app.adjType = "bg-activities";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013364 N = app.activities.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013365 for (int j=0; j<N; j++) {
13366 if (((HistoryRecord)app.activities.get(j)).visible) {
13367 // This app has a visible activity!
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013368 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013369 adj = VISIBLE_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013370 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013371 app.adjType = "visible";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013372 break;
13373 }
13374 }
13375 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013376 // A very not-needed process. If this is lower in the lru list,
13377 // we will push it in to the empty bucket.
13378 app.hidden = true;
13379 app.empty = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013380 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013381 adj = hiddenAdj;
13382 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013383 }
13384
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013385 //Log.i(TAG, "OOM " + app + ": initial adj=" + adj);
13386
The Android Open Source Project4df24232009-03-05 14:34:35 -080013387 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013388 // there are applications dependent on our services or providers, but
13389 // this gives us a baseline and makes sure we don't get into an
13390 // infinite recursion.
13391 app.adjSeq = mAdjSeq;
13392 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013393
Christopher Tate6fa95972009-06-05 18:43:55 -070013394 if (mBackupTarget != null && app == mBackupTarget.app) {
13395 // If possible we want to avoid killing apps while they're being backed up
13396 if (adj > BACKUP_APP_ADJ) {
13397 if (DEBUG_BACKUP) Log.v(TAG, "oom BACKUP_APP_ADJ for " + app);
13398 adj = BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013399 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013400 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013401 }
13402 }
13403
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013404 if (app.services.size() != 0 && (adj > FOREGROUND_APP_ADJ
13405 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013406 final long now = SystemClock.uptimeMillis();
13407 // This process is more important if the top activity is
13408 // bound to the service.
13409 Iterator jt = app.services.iterator();
13410 while (jt.hasNext() && adj > FOREGROUND_APP_ADJ) {
13411 ServiceRecord s = (ServiceRecord)jt.next();
13412 if (s.startRequested) {
13413 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13414 // This service has seen some activity within
13415 // recent memory, so we will keep its process ahead
13416 // of the background processes.
13417 if (adj > SECONDARY_SERVER_ADJ) {
13418 adj = SECONDARY_SERVER_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013419 app.adjType = "started-services";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013420 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013421 }
13422 }
13423 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013424 if (s.connections.size() > 0 && (adj > FOREGROUND_APP_ADJ
13425 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013426 Iterator<ConnectionRecord> kt
13427 = s.connections.values().iterator();
13428 while (kt.hasNext() && adj > FOREGROUND_APP_ADJ) {
13429 // XXX should compute this based on the max of
13430 // all connected clients.
13431 ConnectionRecord cr = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013432 if (cr.binding.client == app) {
13433 // Binding to ourself is not interesting.
13434 continue;
13435 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013436 if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
13437 ProcessRecord client = cr.binding.client;
13438 int myHiddenAdj = hiddenAdj;
13439 if (myHiddenAdj > client.hiddenAdj) {
13440 if (client.hiddenAdj > VISIBLE_APP_ADJ) {
13441 myHiddenAdj = client.hiddenAdj;
13442 } else {
13443 myHiddenAdj = VISIBLE_APP_ADJ;
13444 }
13445 }
13446 int clientAdj = computeOomAdjLocked(
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013447 client, myHiddenAdj, TOP_APP, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013448 if (adj > clientAdj) {
13449 adj = clientAdj > VISIBLE_APP_ADJ
13450 ? clientAdj : VISIBLE_APP_ADJ;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013451 if (!client.hidden) {
13452 app.hidden = false;
13453 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013454 app.adjType = "service";
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013455 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13456 .REASON_SERVICE_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013457 app.adjSource = cr.binding.client;
13458 app.adjTarget = s.serviceInfo.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013459 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013460 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13461 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13462 schedGroup = Process.THREAD_GROUP_DEFAULT;
13463 }
13464 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013465 }
13466 HistoryRecord a = cr.activity;
13467 //if (a != null) {
13468 // Log.i(TAG, "Connection to " + a ": state=" + a.state);
13469 //}
13470 if (a != null && adj > FOREGROUND_APP_ADJ &&
13471 (a.state == ActivityState.RESUMED
13472 || a.state == ActivityState.PAUSING)) {
13473 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013474 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013475 app.hidden = false;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013476 app.adjType = "service";
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013477 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13478 .REASON_SERVICE_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013479 app.adjSource = a;
13480 app.adjTarget = s.serviceInfo.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013481 }
13482 }
13483 }
13484 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013485
13486 // Finally, f this process has active services running in it, we
13487 // would like to avoid killing it unless it would prevent the current
13488 // application from running. By default we put the process in
13489 // with the rest of the background processes; as we scan through
13490 // its services we may bump it up from there.
13491 if (adj > hiddenAdj) {
13492 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013493 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013494 app.adjType = "bg-services";
13495 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013496 }
13497
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013498 if (app.pubProviders.size() != 0 && (adj > FOREGROUND_APP_ADJ
13499 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013500 Iterator jt = app.pubProviders.values().iterator();
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013501 while (jt.hasNext() && (adj > FOREGROUND_APP_ADJ
13502 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013503 ContentProviderRecord cpr = (ContentProviderRecord)jt.next();
13504 if (cpr.clients.size() != 0) {
13505 Iterator<ProcessRecord> kt = cpr.clients.iterator();
13506 while (kt.hasNext() && adj > FOREGROUND_APP_ADJ) {
13507 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013508 if (client == app) {
13509 // Being our own client is not interesting.
13510 continue;
13511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013512 int myHiddenAdj = hiddenAdj;
13513 if (myHiddenAdj > client.hiddenAdj) {
13514 if (client.hiddenAdj > FOREGROUND_APP_ADJ) {
13515 myHiddenAdj = client.hiddenAdj;
13516 } else {
13517 myHiddenAdj = FOREGROUND_APP_ADJ;
13518 }
13519 }
13520 int clientAdj = computeOomAdjLocked(
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013521 client, myHiddenAdj, TOP_APP, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013522 if (adj > clientAdj) {
13523 adj = clientAdj > FOREGROUND_APP_ADJ
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013524 ? clientAdj : FOREGROUND_APP_ADJ;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013525 if (!client.hidden) {
13526 app.hidden = false;
13527 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013528 app.adjType = "provider";
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013529 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13530 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013531 app.adjSource = client;
13532 app.adjTarget = cpr.info.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013533 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013534 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13535 schedGroup = Process.THREAD_GROUP_DEFAULT;
13536 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013537 }
13538 }
13539 // If the provider has external (non-framework) process
13540 // dependencies, ensure that its adjustment is at least
13541 // FOREGROUND_APP_ADJ.
13542 if (cpr.externals != 0) {
13543 if (adj > FOREGROUND_APP_ADJ) {
13544 adj = FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013545 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013546 app.hidden = false;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013547 app.adjType = "provider";
13548 app.adjTarget = cpr.info.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013549 }
13550 }
13551 }
13552 }
13553
13554 app.curRawAdj = adj;
13555
13556 //Log.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
13557 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13558 if (adj > app.maxAdj) {
13559 adj = app.maxAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013560 if (app.maxAdj <= VISIBLE_APP_ADJ) {
13561 schedGroup = Process.THREAD_GROUP_DEFAULT;
13562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013563 }
13564
13565 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013566 app.curSchedGroup = schedGroup;
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013568 return adj;
13569 }
13570
13571 /**
13572 * Ask a given process to GC right now.
13573 */
13574 final void performAppGcLocked(ProcessRecord app) {
13575 try {
13576 app.lastRequestedGc = SystemClock.uptimeMillis();
13577 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013578 if (app.reportLowMemory) {
13579 app.reportLowMemory = false;
13580 app.thread.scheduleLowMemory();
13581 } else {
13582 app.thread.processInBackground();
13583 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013584 }
13585 } catch (Exception e) {
13586 // whatever.
13587 }
13588 }
13589
13590 /**
13591 * Returns true if things are idle enough to perform GCs.
13592 */
13593 private final boolean canGcNow() {
13594 return mParallelBroadcasts.size() == 0
13595 && mOrderedBroadcasts.size() == 0
13596 && (mSleeping || (mResumedActivity != null &&
13597 mResumedActivity.idle));
13598 }
13599
13600 /**
13601 * Perform GCs on all processes that are waiting for it, but only
13602 * if things are idle.
13603 */
13604 final void performAppGcsLocked() {
13605 final int N = mProcessesToGc.size();
13606 if (N <= 0) {
13607 return;
13608 }
13609 if (canGcNow()) {
13610 while (mProcessesToGc.size() > 0) {
13611 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013612 if (proc.curRawAdj > VISIBLE_APP_ADJ || proc.reportLowMemory) {
13613 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13614 <= SystemClock.uptimeMillis()) {
13615 // To avoid spamming the system, we will GC processes one
13616 // at a time, waiting a few seconds between each.
13617 performAppGcLocked(proc);
13618 scheduleAppGcsLocked();
13619 return;
13620 } else {
13621 // It hasn't been long enough since we last GCed this
13622 // process... put it in the list to wait for its time.
13623 addProcessToGcListLocked(proc);
13624 break;
13625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013626 }
13627 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013628
13629 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013630 }
13631 }
13632
13633 /**
13634 * If all looks good, perform GCs on all processes waiting for them.
13635 */
13636 final void performAppGcsIfAppropriateLocked() {
13637 if (canGcNow()) {
13638 performAppGcsLocked();
13639 return;
13640 }
13641 // Still not idle, wait some more.
13642 scheduleAppGcsLocked();
13643 }
13644
13645 /**
13646 * Schedule the execution of all pending app GCs.
13647 */
13648 final void scheduleAppGcsLocked() {
13649 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013650
13651 if (mProcessesToGc.size() > 0) {
13652 // Schedule a GC for the time to the next process.
13653 ProcessRecord proc = mProcessesToGc.get(0);
13654 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13655
13656 long when = mProcessesToGc.get(0).lastRequestedGc + GC_MIN_INTERVAL;
13657 long now = SystemClock.uptimeMillis();
13658 if (when < (now+GC_TIMEOUT)) {
13659 when = now + GC_TIMEOUT;
13660 }
13661 mHandler.sendMessageAtTime(msg, when);
13662 }
13663 }
13664
13665 /**
13666 * Add a process to the array of processes waiting to be GCed. Keeps the
13667 * list in sorted order by the last GC time. The process can't already be
13668 * on the list.
13669 */
13670 final void addProcessToGcListLocked(ProcessRecord proc) {
13671 boolean added = false;
13672 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13673 if (mProcessesToGc.get(i).lastRequestedGc <
13674 proc.lastRequestedGc) {
13675 added = true;
13676 mProcessesToGc.add(i+1, proc);
13677 break;
13678 }
13679 }
13680 if (!added) {
13681 mProcessesToGc.add(0, proc);
13682 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013683 }
13684
13685 /**
13686 * Set up to ask a process to GC itself. This will either do it
13687 * immediately, or put it on the list of processes to gc the next
13688 * time things are idle.
13689 */
13690 final void scheduleAppGcLocked(ProcessRecord app) {
13691 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013692 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013693 return;
13694 }
13695 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013696 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013697 scheduleAppGcsLocked();
13698 }
13699 }
13700
13701 private final boolean updateOomAdjLocked(
13702 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP) {
13703 app.hiddenAdj = hiddenAdj;
13704
13705 if (app.thread == null) {
13706 return true;
13707 }
13708
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013709 int adj = computeOomAdjLocked(app, hiddenAdj, TOP_APP, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013710
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013711 if ((app.pid != 0 && app.pid != MY_PID) || Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013712 if (app.curRawAdj != app.setRawAdj) {
13713 if (app.curRawAdj > FOREGROUND_APP_ADJ
13714 && app.setRawAdj <= FOREGROUND_APP_ADJ) {
13715 // If this app is transitioning from foreground to
13716 // non-foreground, have it do a gc.
13717 scheduleAppGcLocked(app);
13718 } else if (app.curRawAdj >= HIDDEN_APP_MIN_ADJ
13719 && app.setRawAdj < HIDDEN_APP_MIN_ADJ) {
13720 // Likewise do a gc when an app is moving in to the
13721 // background (such as a service stopping).
13722 scheduleAppGcLocked(app);
13723 }
13724 app.setRawAdj = app.curRawAdj;
13725 }
13726 if (adj != app.setAdj) {
13727 if (Process.setOomAdj(app.pid, adj)) {
13728 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Log.v(
13729 TAG, "Set app " + app.processName +
13730 " oom adj to " + adj);
13731 app.setAdj = adj;
13732 } else {
13733 return false;
13734 }
13735 }
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013736 if (app.setSchedGroup != app.curSchedGroup) {
13737 app.setSchedGroup = app.curSchedGroup;
13738 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Log.v(TAG,
13739 "Setting process group of " + app.processName
13740 + " to " + app.curSchedGroup);
13741 if (true) {
San Mehat9438de22009-06-10 09:11:28 -070013742 long oldId = Binder.clearCallingIdentity();
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013743 try {
13744 Process.setProcessGroup(app.pid, app.curSchedGroup);
13745 } catch (Exception e) {
13746 Log.w(TAG, "Failed setting process group of " + app.pid
13747 + " to " + app.curSchedGroup);
San Mehat9438de22009-06-10 09:11:28 -070013748 e.printStackTrace();
13749 } finally {
13750 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013751 }
13752 }
13753 if (false) {
13754 if (app.thread != null) {
13755 try {
13756 app.thread.setSchedulingGroup(app.curSchedGroup);
13757 } catch (RemoteException e) {
13758 }
13759 }
13760 }
13761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013762 }
13763
13764 return true;
13765 }
13766
13767 private final HistoryRecord resumedAppLocked() {
13768 HistoryRecord resumedActivity = mResumedActivity;
13769 if (resumedActivity == null || resumedActivity.app == null) {
13770 resumedActivity = mPausingActivity;
13771 if (resumedActivity == null || resumedActivity.app == null) {
13772 resumedActivity = topRunningActivityLocked(null);
13773 }
13774 }
13775 return resumedActivity;
13776 }
13777
13778 private final boolean updateOomAdjLocked(ProcessRecord app) {
13779 final HistoryRecord TOP_ACT = resumedAppLocked();
13780 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13781 int curAdj = app.curAdj;
13782 final boolean wasHidden = app.curAdj >= HIDDEN_APP_MIN_ADJ
13783 && app.curAdj <= HIDDEN_APP_MAX_ADJ;
13784
13785 mAdjSeq++;
13786
13787 final boolean res = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP);
13788 if (res) {
13789 final boolean nowHidden = app.curAdj >= HIDDEN_APP_MIN_ADJ
13790 && app.curAdj <= HIDDEN_APP_MAX_ADJ;
13791 if (nowHidden != wasHidden) {
13792 // Changed to/from hidden state, so apps after it in the LRU
13793 // list may also be changed.
13794 updateOomAdjLocked();
13795 }
13796 }
13797 return res;
13798 }
13799
13800 private final boolean updateOomAdjLocked() {
13801 boolean didOomAdj = true;
13802 final HistoryRecord TOP_ACT = resumedAppLocked();
13803 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13804
13805 if (false) {
13806 RuntimeException e = new RuntimeException();
13807 e.fillInStackTrace();
13808 Log.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
13809 }
13810
13811 mAdjSeq++;
13812
13813 // First try updating the OOM adjustment for each of the
13814 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013815 int i = mLruProcesses.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013816 int curHiddenAdj = HIDDEN_APP_MIN_ADJ;
13817 while (i > 0) {
13818 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013819 ProcessRecord app = mLruProcesses.get(i);
13820 //Log.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013821 if (updateOomAdjLocked(app, curHiddenAdj, TOP_APP)) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013822 if (curHiddenAdj < EMPTY_APP_ADJ
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013823 && app.curAdj == curHiddenAdj) {
13824 curHiddenAdj++;
13825 }
13826 } else {
13827 didOomAdj = false;
13828 }
13829 }
13830
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013831 // If we return false, we will fall back on killing processes to
13832 // have a fixed limit. Do this if a limit has been requested; else
13833 // only return false if one of the adjustments failed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013834 return ENFORCE_PROCESS_LIMIT || mProcessLimit > 0 ? false : didOomAdj;
13835 }
13836
13837 private final void trimApplications() {
13838 synchronized (this) {
13839 int i;
13840
13841 // First remove any unused application processes whose package
13842 // has been removed.
13843 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13844 final ProcessRecord app = mRemovedProcesses.get(i);
13845 if (app.activities.size() == 0
13846 && app.curReceiver == null && app.services.size() == 0) {
13847 Log.i(
13848 TAG, "Exiting empty application process "
13849 + app.processName + " ("
13850 + (app.thread != null ? app.thread.asBinder() : null)
13851 + ")\n");
13852 if (app.pid > 0 && app.pid != MY_PID) {
13853 Process.killProcess(app.pid);
13854 } else {
13855 try {
13856 app.thread.scheduleExit();
13857 } catch (Exception e) {
13858 // Ignore exceptions.
13859 }
13860 }
13861 cleanUpApplicationRecordLocked(app, false, -1);
13862 mRemovedProcesses.remove(i);
13863
13864 if (app.persistent) {
13865 if (app.persistent) {
13866 addAppLocked(app.info);
13867 }
13868 }
13869 }
13870 }
13871
13872 // Now try updating the OOM adjustment for each of the
13873 // application processes based on their current state.
13874 // If the setOomAdj() API is not supported, then go with our
13875 // back-up plan...
13876 if (!updateOomAdjLocked()) {
13877
13878 // Count how many processes are running services.
13879 int numServiceProcs = 0;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013880 for (i=mLruProcesses.size()-1; i>=0; i--) {
13881 final ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013882
13883 if (app.persistent || app.services.size() != 0
13884 || app.curReceiver != null
13885 || app.persistentActivities > 0) {
13886 // Don't count processes holding services against our
13887 // maximum process count.
13888 if (localLOGV) Log.v(
13889 TAG, "Not trimming app " + app + " with services: "
13890 + app.services);
13891 numServiceProcs++;
13892 }
13893 }
13894
13895 int curMaxProcs = mProcessLimit;
13896 if (curMaxProcs <= 0) curMaxProcs = MAX_PROCESSES;
13897 if (mAlwaysFinishActivities) {
13898 curMaxProcs = 1;
13899 }
13900 curMaxProcs += numServiceProcs;
13901
13902 // Quit as many processes as we can to get down to the desired
13903 // process count. First remove any processes that no longer
13904 // have activites running in them.
13905 for ( i=0;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013906 i<mLruProcesses.size()
13907 && mLruProcesses.size() > curMaxProcs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013908 i++) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013909 final ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013910 // Quit an application only if it is not currently
13911 // running any activities.
13912 if (!app.persistent && app.activities.size() == 0
13913 && app.curReceiver == null && app.services.size() == 0) {
13914 Log.i(
13915 TAG, "Exiting empty application process "
13916 + app.processName + " ("
13917 + (app.thread != null ? app.thread.asBinder() : null)
13918 + ")\n");
13919 if (app.pid > 0 && app.pid != MY_PID) {
13920 Process.killProcess(app.pid);
13921 } else {
13922 try {
13923 app.thread.scheduleExit();
13924 } catch (Exception e) {
13925 // Ignore exceptions.
13926 }
13927 }
13928 // todo: For now we assume the application is not buggy
13929 // or evil, and will quit as a result of our request.
13930 // Eventually we need to drive this off of the death
13931 // notification, and kill the process if it takes too long.
13932 cleanUpApplicationRecordLocked(app, false, i);
13933 i--;
13934 }
13935 }
13936
13937 // If we still have too many processes, now from the least
13938 // recently used process we start finishing activities.
13939 if (Config.LOGV) Log.v(
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013940 TAG, "*** NOW HAVE " + mLruProcesses.size() +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013941 " of " + curMaxProcs + " processes");
13942 for ( i=0;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013943 i<mLruProcesses.size()
13944 && mLruProcesses.size() > curMaxProcs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013945 i++) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013946 final ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013947 // Quit the application only if we have a state saved for
13948 // all of its activities.
13949 boolean canQuit = !app.persistent && app.curReceiver == null
13950 && app.services.size() == 0
13951 && app.persistentActivities == 0;
13952 int NUMA = app.activities.size();
13953 int j;
13954 if (Config.LOGV) Log.v(
13955 TAG, "Looking to quit " + app.processName);
13956 for (j=0; j<NUMA && canQuit; j++) {
13957 HistoryRecord r = (HistoryRecord)app.activities.get(j);
13958 if (Config.LOGV) Log.v(
13959 TAG, " " + r.intent.getComponent().flattenToShortString()
13960 + ": frozen=" + r.haveState + ", visible=" + r.visible);
13961 canQuit = (r.haveState || !r.stateNotNeeded)
13962 && !r.visible && r.stopped;
13963 }
13964 if (canQuit) {
13965 // Finish all of the activities, and then the app itself.
13966 for (j=0; j<NUMA; j++) {
13967 HistoryRecord r = (HistoryRecord)app.activities.get(j);
13968 if (!r.finishing) {
13969 destroyActivityLocked(r, false);
13970 }
13971 r.resultTo = null;
13972 }
13973 Log.i(TAG, "Exiting application process "
13974 + app.processName + " ("
13975 + (app.thread != null ? app.thread.asBinder() : null)
13976 + ")\n");
13977 if (app.pid > 0 && app.pid != MY_PID) {
13978 Process.killProcess(app.pid);
13979 } else {
13980 try {
13981 app.thread.scheduleExit();
13982 } catch (Exception e) {
13983 // Ignore exceptions.
13984 }
13985 }
13986 // todo: For now we assume the application is not buggy
13987 // or evil, and will quit as a result of our request.
13988 // Eventually we need to drive this off of the death
13989 // notification, and kill the process if it takes too long.
13990 cleanUpApplicationRecordLocked(app, false, i);
13991 i--;
13992 //dump();
13993 }
13994 }
13995
13996 }
13997
13998 int curMaxActivities = MAX_ACTIVITIES;
13999 if (mAlwaysFinishActivities) {
14000 curMaxActivities = 1;
14001 }
14002
14003 // Finally, if there are too many activities now running, try to
14004 // finish as many as we can to get back down to the limit.
14005 for ( i=0;
14006 i<mLRUActivities.size()
14007 && mLRUActivities.size() > curMaxActivities;
14008 i++) {
14009 final HistoryRecord r
14010 = (HistoryRecord)mLRUActivities.get(i);
14011
14012 // We can finish this one if we have its icicle saved and
14013 // it is not persistent.
14014 if ((r.haveState || !r.stateNotNeeded) && !r.visible
14015 && r.stopped && !r.persistent && !r.finishing) {
14016 final int origSize = mLRUActivities.size();
14017 destroyActivityLocked(r, true);
14018
14019 // This will remove it from the LRU list, so keep
14020 // our index at the same value. Note that this check to
14021 // see if the size changes is just paranoia -- if
14022 // something unexpected happens, we don't want to end up
14023 // in an infinite loop.
14024 if (origSize > mLRUActivities.size()) {
14025 i--;
14026 }
14027 }
14028 }
14029 }
14030 }
14031
14032 /** This method sends the specified signal to each of the persistent apps */
14033 public void signalPersistentProcesses(int sig) throws RemoteException {
14034 if (sig != Process.SIGNAL_USR1) {
14035 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14036 }
14037
14038 synchronized (this) {
14039 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14040 != PackageManager.PERMISSION_GRANTED) {
14041 throw new SecurityException("Requires permission "
14042 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14043 }
14044
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014045 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14046 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014047 if (r.thread != null && r.persistent) {
14048 Process.sendSignal(r.pid, sig);
14049 }
14050 }
14051 }
14052 }
14053
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014054 public boolean profileControl(String process, boolean start,
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014055 String path, ParcelFileDescriptor fd) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014056
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014057 try {
14058 synchronized (this) {
14059 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14060 // its own permission.
14061 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14062 != PackageManager.PERMISSION_GRANTED) {
14063 throw new SecurityException("Requires permission "
14064 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014065 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014066
14067 if (start && fd == null) {
14068 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014069 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014070
14071 ProcessRecord proc = null;
14072 try {
14073 int pid = Integer.parseInt(process);
14074 synchronized (mPidsSelfLocked) {
14075 proc = mPidsSelfLocked.get(pid);
14076 }
14077 } catch (NumberFormatException e) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014078 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014079
14080 if (proc == null) {
14081 HashMap<String, SparseArray<ProcessRecord>> all
14082 = mProcessNames.getMap();
14083 SparseArray<ProcessRecord> procs = all.get(process);
14084 if (procs != null && procs.size() > 0) {
14085 proc = procs.valueAt(0);
14086 }
14087 }
14088
14089 if (proc == null || proc.thread == null) {
14090 throw new IllegalArgumentException("Unknown process: " + process);
14091 }
14092
14093 boolean isSecure = "1".equals(SystemProperties.get(SYSTEM_SECURE, "0"));
14094 if (isSecure) {
14095 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14096 throw new SecurityException("Process not debuggable: " + proc);
14097 }
14098 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014099
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014100 proc.thread.profilerControl(start, path, fd);
14101 fd = null;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014102 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014103 }
14104 } catch (RemoteException e) {
14105 throw new IllegalStateException("Process disappeared");
14106 } finally {
14107 if (fd != null) {
14108 try {
14109 fd.close();
14110 } catch (IOException e) {
14111 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014112 }
14113 }
14114 }
14115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014116 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14117 public void monitor() {
14118 synchronized (this) { }
14119 }
14120}