blob: 718c6de9460e73b2507ae5cb1909a991c7285f86 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 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 android.app;
18
Christopher Tate45281862010-03-05 15:46:30 -080019import android.app.backup.BackupAgent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.content.BroadcastReceiver;
21import android.content.ComponentCallbacks;
22import android.content.ComponentName;
23import android.content.ContentProvider;
24import android.content.Context;
25import android.content.IContentProvider;
26import android.content.Intent;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070027import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.pm.ActivityInfo;
29import android.content.pm.ApplicationInfo;
30import android.content.pm.IPackageManager;
31import android.content.pm.InstrumentationInfo;
32import android.content.pm.PackageManager;
Sen Hubde75702010-05-28 01:54:03 -070033import android.content.pm.PackageManager.NameNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.content.pm.ProviderInfo;
35import android.content.pm.ServiceInfo;
36import android.content.res.AssetManager;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -070037import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.content.res.Configuration;
39import android.content.res.Resources;
40import android.database.sqlite.SQLiteDatabase;
41import android.database.sqlite.SQLiteDebug;
Vasu Noric3849202010-03-09 10:47:25 -080042import android.database.sqlite.SQLiteDebug.DbStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.graphics.Bitmap;
44import android.graphics.Canvas;
Robert Greenwalt434203a2010-10-11 16:00:27 -070045import android.net.IConnectivityManager;
46import android.net.Proxy;
47import android.net.ProxyProperties;
Joe Onoratod630f102011-03-17 18:42:26 -070048import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.os.Bundle;
50import android.os.Debug;
51import android.os.Handler;
52import android.os.IBinder;
53import android.os.Looper;
54import android.os.Message;
55import android.os.MessageQueue;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070056import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.os.Process;
58import android.os.RemoteException;
59import android.os.ServiceManager;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070060import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.os.SystemClock;
62import android.util.AndroidRuntimeException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.util.DisplayMetrics;
64import android.util.EventLog;
65import android.util.Log;
Dianne Hackborn287952c2010-09-22 22:34:31 -070066import android.util.LogPrinter;
Dianne Hackbornc9421ba2010-03-11 22:23:46 -080067import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.view.Display;
Romain Guy52339202010-09-03 16:04:46 -070069import android.view.HardwareRenderer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.view.View;
71import android.view.ViewDebug;
72import android.view.ViewManager;
Dianne Hackborn6dd005b2011-07-18 13:22:50 -070073import android.view.ViewRootImpl;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import android.view.Window;
75import android.view.WindowManager;
76import android.view.WindowManagerImpl;
77
78import com.android.internal.os.BinderInternal;
79import com.android.internal.os.RuntimeInit;
Bob Leee5408332009-09-04 18:31:17 -070080import com.android.internal.os.SamplingProfilerIntegration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081
82import org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl;
83
84import java.io.File;
85import java.io.FileDescriptor;
86import java.io.FileOutputStream;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070087import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import java.io.PrintWriter;
89import java.lang.ref.WeakReference;
Robert Greenwalt03595d02010-11-02 14:08:23 -070090import java.net.InetAddress;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import java.util.ArrayList;
92import java.util.HashMap;
93import java.util.Iterator;
94import java.util.List;
95import java.util.Locale;
96import java.util.Map;
97import java.util.TimeZone;
98import java.util.regex.Pattern;
99
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -0800100import dalvik.system.CloseGuard;
Bob Leee5408332009-09-04 18:31:17 -0700101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102final class SuperNotCalledException extends AndroidRuntimeException {
103 public SuperNotCalledException(String msg) {
104 super(msg);
105 }
106}
107
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700108final class RemoteServiceException extends AndroidRuntimeException {
109 public RemoteServiceException(String msg) {
110 super(msg);
111 }
112}
113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114/**
115 * This manages the execution of the main thread in an
116 * application process, scheduling and executing activities,
117 * broadcasts, and other operations on it as the activity
118 * manager requests.
119 *
120 * {@hide}
121 */
122public final class ActivityThread {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700123 /** @hide */
124 public static final String TAG = "ActivityThread";
Jim Miller0b2a6d02010-07-13 18:01:29 -0700125 private static final android.graphics.Bitmap.Config THUMBNAIL_FORMAT = Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 private static final boolean DEBUG = false;
Joe Onorato43a17652011-04-06 19:22:23 -0700127 static final boolean localLOGV = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700128 static final boolean DEBUG_MESSAGES = false;
Dianne Hackborne829fef2010-10-26 17:44:01 -0700129 /** @hide */
130 public static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700131 private static final boolean DEBUG_RESULTS = false;
Christopher Tate4a627c72011-04-01 14:43:32 -0700132 private static final boolean DEBUG_BACKUP = true;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700133 private static final boolean DEBUG_CONFIGURATION = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
135 private static final Pattern PATTERN_SEMICOLON = Pattern.compile(";");
136 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
137 private static final int LOG_ON_PAUSE_CALLED = 30021;
138 private static final int LOG_ON_RESUME_CALLED = 30022;
139
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700140 static ContextImpl mSystemContext = null;
Bob Leee5408332009-09-04 18:31:17 -0700141
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700142 static IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700144 final ApplicationThread mAppThread = new ApplicationThread();
145 final Looper mLooper = Looper.myLooper();
146 final H mH = new H();
147 final HashMap<IBinder, ActivityClientRecord> mActivities
148 = new HashMap<IBinder, ActivityClientRecord>();
149 // List of new activities (via ActivityRecord.nextIdle) that should
150 // be reported when next we idle.
151 ActivityClientRecord mNewActivities = null;
152 // Number of activities that are currently visible on-screen.
153 int mNumVisibleActivities = 0;
154 final HashMap<IBinder, Service> mServices
155 = new HashMap<IBinder, Service>();
156 AppBindData mBoundApplication;
157 Configuration mConfiguration;
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700158 Configuration mCompatConfiguration;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700159 Configuration mResConfiguration;
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700160 CompatibilityInfo mResCompatibilityInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700161 Application mInitialApplication;
162 final ArrayList<Application> mAllApplications
163 = new ArrayList<Application>();
164 // set of instantiated backup agents, keyed by package name
165 final HashMap<String, BackupAgent> mBackupAgents = new HashMap<String, BackupAgent>();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700166 static final ThreadLocal<ActivityThread> sThreadLocal = new ThreadLocal();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700167 Instrumentation mInstrumentation;
168 String mInstrumentationAppDir = null;
169 String mInstrumentationAppPackage = null;
170 String mInstrumentedAppDir = null;
171 boolean mSystemThread = false;
172 boolean mJitEnabled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700174 // These can be accessed by multiple threads; mPackages is the lock.
175 // XXX For now we keep around information about all packages we have
176 // seen, not removing entries from this map.
Dianne Hackborn2f0b1752011-05-31 17:59:49 -0700177 // NOTE: The activity manager in its process needs to call in to
178 // ActivityThread to do things like update resource configurations,
179 // which means this lock gets held while the activity manager holds its
180 // own lock. Thus you MUST NEVER call back into the activity manager
181 // or anything that depends on it while holding this lock.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700182 final HashMap<String, WeakReference<LoadedApk>> mPackages
183 = new HashMap<String, WeakReference<LoadedApk>>();
184 final HashMap<String, WeakReference<LoadedApk>> mResourcePackages
185 = new HashMap<String, WeakReference<LoadedApk>>();
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700186 final HashMap<CompatibilityInfo, DisplayMetrics> mDisplayMetrics
187 = new HashMap<CompatibilityInfo, DisplayMetrics>();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700188 final HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources
189 = new HashMap<ResourcesKey, WeakReference<Resources> >();
190 final ArrayList<ActivityClientRecord> mRelaunchingActivities
191 = new ArrayList<ActivityClientRecord>();
192 Configuration mPendingConfiguration = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700194 // The lock of mProviderMap protects the following variables.
195 final HashMap<String, ProviderClientRecord> mProviderMap
196 = new HashMap<String, ProviderClientRecord>();
197 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap
198 = new HashMap<IBinder, ProviderRefCount>();
199 final HashMap<IBinder, ProviderClientRecord> mLocalProviders
200 = new HashMap<IBinder, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Jeff Hamilton52d32032011-01-08 15:31:26 -0600202 final HashMap<Activity, ArrayList<OnActivityPausedListener>> mOnPauseListeners
203 = new HashMap<Activity, ArrayList<OnActivityPausedListener>>();
204
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700205 final GcIdler mGcIdler = new GcIdler();
206 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700208 static Handler sMainThreadHandler; // set once in main()
209
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800210 Bundle mCoreSettings = null;
211
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400212 static final class ActivityClientRecord {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700214 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 Intent intent;
216 Bundle state;
217 Activity activity;
218 Window window;
219 Activity parent;
220 String embeddedID;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700221 Activity.NonConfigurationInstances lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 boolean paused;
223 boolean stopped;
224 boolean hideForNow;
225 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700226 Configuration createdConfig;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700227 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228
229 ActivityInfo activityInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400230 CompatibilityInfo compatInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700231 LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232
233 List<ResultInfo> pendingResults;
234 List<Intent> pendingIntents;
235
236 boolean startsNotResumed;
237 boolean isForward;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800238 int pendingConfigChanges;
239 boolean onlyLocalRequest;
240
241 View mPendingRemoveWindow;
242 WindowManager mPendingRemoveWindowManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700244 ActivityClientRecord() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 parent = null;
246 embeddedID = null;
247 paused = false;
248 stopped = false;
249 hideForNow = false;
250 nextIdle = null;
251 }
252
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800253 public boolean isPreHoneycomb() {
254 if (activity != null) {
255 return activity.getApplicationInfo().targetSdkVersion
256 < android.os.Build.VERSION_CODES.HONEYCOMB;
257 }
258 return false;
259 }
260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261 public String toString() {
262 ComponentName componentName = intent.getComponent();
263 return "ActivityRecord{"
264 + Integer.toHexString(System.identityHashCode(this))
265 + " token=" + token + " " + (componentName == null
266 ? "no component name" : componentName.toShortString())
267 + "}";
268 }
269 }
270
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400271 final class ProviderClientRecord implements IBinder.DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272 final String mName;
273 final IContentProvider mProvider;
274 final ContentProvider mLocalProvider;
275
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700276 ProviderClientRecord(String name, IContentProvider provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277 ContentProvider localProvider) {
278 mName = name;
279 mProvider = provider;
280 mLocalProvider = localProvider;
281 }
282
283 public void binderDied() {
284 removeDeadProvider(mName, mProvider);
285 }
286 }
287
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400288 static final class NewIntentData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289 List<Intent> intents;
290 IBinder token;
291 public String toString() {
292 return "NewIntentData{intents=" + intents + " token=" + token + "}";
293 }
294 }
295
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400296 static final class ReceiverData extends BroadcastReceiver.PendingResult {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700297 public ReceiverData(Intent intent, int resultCode, String resultData, Bundle resultExtras,
298 boolean ordered, boolean sticky, IBinder token) {
299 super(resultCode, resultData, resultExtras, TYPE_COMPONENT, ordered, sticky, token);
300 this.intent = intent;
301 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303 Intent intent;
304 ActivityInfo info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400305 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800306 public String toString() {
307 return "ReceiverData{intent=" + intent + " packageName=" +
Dianne Hackborne829fef2010-10-26 17:44:01 -0700308 info.packageName + " resultCode=" + getResultCode()
309 + " resultData=" + getResultData() + " resultExtras="
310 + getResultExtras(false) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 }
312 }
313
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400314 static final class CreateBackupAgentData {
Christopher Tate181fafa2009-05-14 11:12:14 -0700315 ApplicationInfo appInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400316 CompatibilityInfo compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700317 int backupMode;
318 public String toString() {
319 return "CreateBackupAgentData{appInfo=" + appInfo
320 + " backupAgent=" + appInfo.backupAgentName
321 + " mode=" + backupMode + "}";
322 }
323 }
Bob Leee5408332009-09-04 18:31:17 -0700324
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400325 static final class CreateServiceData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326 IBinder token;
327 ServiceInfo info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400328 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 Intent intent;
330 public String toString() {
331 return "CreateServiceData{token=" + token + " className="
332 + info.name + " packageName=" + info.packageName
333 + " intent=" + intent + "}";
334 }
335 }
336
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400337 static final class BindServiceData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800338 IBinder token;
339 Intent intent;
340 boolean rebind;
341 public String toString() {
342 return "BindServiceData{token=" + token + " intent=" + intent + "}";
343 }
344 }
345
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400346 static final class ServiceArgsData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347 IBinder token;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700348 boolean taskRemoved;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700350 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800351 Intent args;
352 public String toString() {
353 return "ServiceArgsData{token=" + token + " startId=" + startId
354 + " args=" + args + "}";
355 }
356 }
357
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400358 static final class AppBindData {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700359 LoadedApk info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360 String processName;
361 ApplicationInfo appInfo;
362 List<ProviderInfo> providers;
363 ComponentName instrumentationName;
364 String profileFile;
365 Bundle instrumentationArgs;
366 IInstrumentationWatcher instrumentationWatcher;
367 int debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700368 boolean restrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 Configuration config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400370 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371 boolean handlingProfiling;
372 public String toString() {
373 return "AppBindData{appInfo=" + appInfo + "}";
374 }
375 }
376
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400377 static final class DumpComponentInfo {
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700378 ParcelFileDescriptor fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700379 IBinder token;
Dianne Hackborn30d71892010-12-11 10:37:55 -0800380 String prefix;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 String[] args;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382 }
383
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400384 static final class ResultData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 IBinder token;
386 List<ResultInfo> results;
387 public String toString() {
388 return "ResultData{token=" + token + " results" + results + "}";
389 }
390 }
391
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400392 static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800393 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800394 String what;
395 String who;
396 }
397
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400398 static final class ProfilerControlData {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700399 String path;
400 ParcelFileDescriptor fd;
401 }
402
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400403 static final class DumpHeapData {
Andy McFadden824c5102010-07-09 16:26:57 -0700404 String path;
405 ParcelFileDescriptor fd;
406 }
407
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400408 static final class UpdateCompatibilityData {
409 String pkg;
410 CompatibilityInfo info;
411 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -0700412
Chet Haase9c1e23b2011-03-24 10:51:31 -0700413 native private void dumpGraphicsInfo(FileDescriptor fd);
414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800415 private final class ApplicationThread extends ApplicationThreadNative {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700416 private static final String HEAP_COLUMN = "%13s %8s %8s %8s %8s %8s %8s";
417 private static final String ONE_COUNT_COLUMN = "%21s %8d";
418 private static final String TWO_COUNT_COLUMNS = "%21s %8d %21s %8d";
419 private static final String TWO_COUNT_COLUMNS_DB = "%21s %8d %21s %8d";
Vasu Nori3c7131f2010-09-21 14:36:57 -0700420 private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
Bob Leee5408332009-09-04 18:31:17 -0700421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422 // Formatting for checkin service - update version if row format changes
423 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;
Bob Leee5408332009-09-04 18:31:17 -0700424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 public final void schedulePauseActivity(IBinder token, boolean finished,
426 boolean userLeaving, int configChanges) {
427 queueOrSendMessage(
428 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
429 token,
430 (userLeaving ? 1 : 0),
431 configChanges);
432 }
433
434 public final void scheduleStopActivity(IBinder token, boolean showWindow,
435 int configChanges) {
436 queueOrSendMessage(
437 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
438 token, 0, configChanges);
439 }
440
441 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
442 queueOrSendMessage(
443 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
444 token);
445 }
446
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800447 public final void scheduleSleeping(IBinder token, boolean sleeping) {
448 queueOrSendMessage(H.SLEEPING, token, sleeping ? 1 : 0);
449 }
450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 public final void scheduleResumeActivity(IBinder token, boolean isForward) {
452 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
453 }
454
455 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
456 ResultData res = new ResultData();
457 res.token = token;
458 res.results = results;
459 queueOrSendMessage(H.SEND_RESULT, res);
460 }
461
462 // we use token to identify this activity without having to send the
463 // activity itself back to the activity manager. (matters more with ipc)
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700464 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400465 ActivityInfo info, CompatibilityInfo compatInfo, Bundle state,
466 List<ResultInfo> pendingResults,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700468 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469
470 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700471 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 r.intent = intent;
473 r.activityInfo = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400474 r.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475 r.state = state;
476
477 r.pendingResults = pendingResults;
478 r.pendingIntents = pendingNewIntents;
479
480 r.startsNotResumed = notResumed;
481 r.isForward = isForward;
482
483 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
484 }
485
486 public final void scheduleRelaunchActivity(IBinder token,
487 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800488 int configChanges, boolean notResumed, Configuration config) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800489 requestRelaunchActivity(token, pendingResults, pendingNewIntents,
490 configChanges, notResumed, config, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 }
492
493 public final void scheduleNewIntent(List<Intent> intents, IBinder token) {
494 NewIntentData data = new NewIntentData();
495 data.intents = intents;
496 data.token = token;
497
498 queueOrSendMessage(H.NEW_INTENT, data);
499 }
500
501 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
502 int configChanges) {
503 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
504 configChanges);
505 }
506
507 public final void scheduleReceiver(Intent intent, ActivityInfo info,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400508 CompatibilityInfo compatInfo, int resultCode, String data, Bundle extras,
509 boolean sync) {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700510 ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
511 sync, false, mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 r.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400513 r.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514 queueOrSendMessage(H.RECEIVER, r);
515 }
516
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400517 public final void scheduleCreateBackupAgent(ApplicationInfo app,
518 CompatibilityInfo compatInfo, int backupMode) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700519 CreateBackupAgentData d = new CreateBackupAgentData();
520 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400521 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700522 d.backupMode = backupMode;
523
524 queueOrSendMessage(H.CREATE_BACKUP_AGENT, d);
525 }
526
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400527 public final void scheduleDestroyBackupAgent(ApplicationInfo app,
528 CompatibilityInfo compatInfo) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700529 CreateBackupAgentData d = new CreateBackupAgentData();
530 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400531 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700532
533 queueOrSendMessage(H.DESTROY_BACKUP_AGENT, d);
534 }
535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 public final void scheduleCreateService(IBinder token,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400537 ServiceInfo info, CompatibilityInfo compatInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538 CreateServiceData s = new CreateServiceData();
539 s.token = token;
540 s.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400541 s.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542
543 queueOrSendMessage(H.CREATE_SERVICE, s);
544 }
545
546 public final void scheduleBindService(IBinder token, Intent intent,
547 boolean rebind) {
548 BindServiceData s = new BindServiceData();
549 s.token = token;
550 s.intent = intent;
551 s.rebind = rebind;
552
553 queueOrSendMessage(H.BIND_SERVICE, s);
554 }
555
556 public final void scheduleUnbindService(IBinder token, Intent intent) {
557 BindServiceData s = new BindServiceData();
558 s.token = token;
559 s.intent = intent;
560
561 queueOrSendMessage(H.UNBIND_SERVICE, s);
562 }
563
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700564 public final void scheduleServiceArgs(IBinder token, boolean taskRemoved, int startId,
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700565 int flags ,Intent args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566 ServiceArgsData s = new ServiceArgsData();
567 s.token = token;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700568 s.taskRemoved = taskRemoved;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569 s.startId = startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700570 s.flags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571 s.args = args;
572
573 queueOrSendMessage(H.SERVICE_ARGS, s);
574 }
575
576 public final void scheduleStopService(IBinder token) {
577 queueOrSendMessage(H.STOP_SERVICE, token);
578 }
579
580 public final void bindApplication(String processName,
581 ApplicationInfo appInfo, List<ProviderInfo> providers,
582 ComponentName instrumentationName, String profileFile,
583 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
Christopher Tate181fafa2009-05-14 11:12:14 -0700584 int debugMode, boolean isRestrictedBackupMode, Configuration config,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400585 CompatibilityInfo compatInfo, Map<String, IBinder> services,
586 Bundle coreSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587
588 if (services != null) {
589 // Setup the service cache in the ServiceManager
590 ServiceManager.initServiceCache(services);
591 }
592
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800593 setCoreSettings(coreSettings);
594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 AppBindData data = new AppBindData();
596 data.processName = processName;
597 data.appInfo = appInfo;
598 data.providers = providers;
599 data.instrumentationName = instrumentationName;
600 data.profileFile = profileFile;
601 data.instrumentationArgs = instrumentationArgs;
602 data.instrumentationWatcher = instrumentationWatcher;
603 data.debugMode = debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700604 data.restrictedBackupMode = isRestrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 data.config = config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400606 data.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 queueOrSendMessage(H.BIND_APPLICATION, data);
608 }
609
610 public final void scheduleExit() {
611 queueOrSendMessage(H.EXIT_APPLICATION, null);
612 }
613
Christopher Tate5e1ab332009-09-01 20:32:49 -0700614 public final void scheduleSuicide() {
615 queueOrSendMessage(H.SUICIDE, null);
616 }
617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 public void requestThumbnail(IBinder token) {
619 queueOrSendMessage(H.REQUEST_THUMBNAIL, token);
620 }
621
622 public void scheduleConfigurationChanged(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800623 synchronized (mPackages) {
624 if (mPendingConfiguration == null ||
625 mPendingConfiguration.isOtherSeqNewer(config)) {
626 mPendingConfiguration = config;
627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628 }
629 queueOrSendMessage(H.CONFIGURATION_CHANGED, config);
630 }
631
632 public void updateTimeZone() {
633 TimeZone.setDefault(null);
634 }
635
Robert Greenwalt03595d02010-11-02 14:08:23 -0700636 public void clearDnsCache() {
637 // a non-standard API to get this to libcore
638 InetAddress.clearDnsCache();
639 }
640
Robert Greenwalt434203a2010-10-11 16:00:27 -0700641 public void setHttpProxy(String host, String port, String exclList) {
642 Proxy.setHttpProxySystemProperty(host, port, exclList);
643 }
644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 public void processInBackground() {
646 mH.removeMessages(H.GC_WHEN_IDLE);
647 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
648 }
649
650 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700651 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700652 try {
653 data.fd = ParcelFileDescriptor.dup(fd);
654 data.token = servicetoken;
655 data.args = args;
656 queueOrSendMessage(H.DUMP_SERVICE, data);
657 } catch (IOException e) {
658 Slog.w(TAG, "dumpService failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 }
660 }
661
662 // This function exists to make sure all receiver dispatching is
663 // correctly ordered, since these are one-way calls and the binder driver
664 // applies transaction ordering per object for such calls.
665 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700666 int resultCode, String dataStr, Bundle extras, boolean ordered,
667 boolean sticky) throws RemoteException {
668 receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 }
Bob Leee5408332009-09-04 18:31:17 -0700670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 public void scheduleLowMemory() {
672 queueOrSendMessage(H.LOW_MEMORY, null);
673 }
674
675 public void scheduleActivityConfigurationChanged(IBinder token) {
676 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token);
677 }
678
Romain Guy7eabe552011-07-21 14:56:34 -0700679 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd,
680 int profileType) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700681 ProfilerControlData pcd = new ProfilerControlData();
682 pcd.path = path;
683 pcd.fd = fd;
Romain Guy7eabe552011-07-21 14:56:34 -0700684 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0, profileType);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800685 }
686
Andy McFadden824c5102010-07-09 16:26:57 -0700687 public void dumpHeap(boolean managed, String path, ParcelFileDescriptor fd) {
688 DumpHeapData dhd = new DumpHeapData();
689 dhd.path = path;
690 dhd.fd = fd;
691 queueOrSendMessage(H.DUMP_HEAP, dhd, managed ? 1 : 0);
692 }
693
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700694 public void setSchedulingGroup(int group) {
695 // Note: do this immediately, since going into the foreground
696 // should happen regardless of what pending work we have to do
697 // and the activity manager will wait for us to report back that
698 // we are done before sending us to the background.
699 try {
700 Process.setProcessGroup(Process.myPid(), group);
701 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800702 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700703 }
704 }
Bob Leee5408332009-09-04 18:31:17 -0700705
Dianne Hackborn3025ef32009-08-31 21:31:47 -0700706 public void getMemoryInfo(Debug.MemoryInfo outInfo) {
707 Debug.getMemoryInfo(outInfo);
708 }
Bob Leee5408332009-09-04 18:31:17 -0700709
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700710 public void dispatchPackageBroadcast(int cmd, String[] packages) {
711 queueOrSendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
712 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700713
714 public void scheduleCrash(String msg) {
715 queueOrSendMessage(H.SCHEDULE_CRASH, msg);
716 }
Dianne Hackborn625ac272010-09-17 18:29:22 -0700717
Dianne Hackborn30d71892010-12-11 10:37:55 -0800718 public void dumpActivity(FileDescriptor fd, IBinder activitytoken,
719 String prefix, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700720 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700721 try {
722 data.fd = ParcelFileDescriptor.dup(fd);
723 data.token = activitytoken;
724 data.prefix = prefix;
725 data.args = args;
726 queueOrSendMessage(H.DUMP_ACTIVITY, data);
727 } catch (IOException e) {
728 Slog.w(TAG, "dumpActivity failed", e);
Dianne Hackborn625ac272010-09-17 18:29:22 -0700729 }
730 }
Chet Haase9c1e23b2011-03-24 10:51:31 -0700731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 @Override
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700733 public Debug.MemoryInfo dumpMemInfo(FileDescriptor fd, String[] args) {
734 FileOutputStream fout = new FileOutputStream(fd);
735 PrintWriter pw = new PrintWriter(fout);
736 try {
737 return dumpMemInfo(fd, pw, args);
738 } finally {
Chet Haase9c1e23b2011-03-24 10:51:31 -0700739 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -0700740 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700741 }
742
743 private Debug.MemoryInfo dumpMemInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 long nativeMax = Debug.getNativeHeapSize() / 1024;
745 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
746 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
747
748 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
749 Debug.getMemoryInfo(memInfo);
750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 Runtime runtime = Runtime.getRuntime();
752
753 long dalvikMax = runtime.totalMemory() / 1024;
754 long dalvikFree = runtime.freeMemory() / 1024;
755 long dalvikAllocated = dalvikMax - dalvikFree;
756 long viewInstanceCount = ViewDebug.getViewInstanceCount();
Joe Onoratoc6cc0f82011-04-12 11:53:13 -0700757 long viewRootInstanceCount = ViewDebug.getViewAncestorInstanceCount();
Brian Carlstromc21550a2010-10-05 21:34:06 -0700758 long appContextInstanceCount = Debug.countInstancesOfClass(ContextImpl.class);
759 long activityInstanceCount = Debug.countInstancesOfClass(Activity.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 int globalAssetCount = AssetManager.getGlobalAssetCount();
761 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
762 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
763 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
764 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
Brian Carlstromc9d5b312010-10-05 22:23:41 -0700765 long openSslSocketCount = Debug.countInstancesOfClass(OpenSSLSocketImpl.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024;
Vasu Noric3849202010-03-09 10:47:25 -0800767 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -0700768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 // Check to see if we were called by checkin server. If so, print terse format.
770 boolean doCheckinFormat = false;
771 if (args != null) {
772 for (String arg : args) {
773 if ("-c".equals(arg)) doCheckinFormat = true;
774 }
775 }
Bob Leee5408332009-09-04 18:31:17 -0700776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 // For checkin, we print one long comma-separated list of values
778 if (doCheckinFormat) {
779 // NOTE: if you change anything significant below, also consider changing
780 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -0700781 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -0700783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 // Header
785 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
786 pw.print(Process.myPid()); pw.print(',');
787 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 // Heap info - max
790 pw.print(nativeMax); pw.print(',');
791 pw.print(dalvikMax); pw.print(',');
792 pw.print("N/A,");
793 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 // Heap info - allocated
796 pw.print(nativeAllocated); pw.print(',');
797 pw.print(dalvikAllocated); pw.print(',');
798 pw.print("N/A,");
799 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 // Heap info - free
802 pw.print(nativeFree); pw.print(',');
803 pw.print(dalvikFree); pw.print(',');
804 pw.print("N/A,");
805 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 // Heap info - proportional set size
808 pw.print(memInfo.nativePss); pw.print(',');
809 pw.print(memInfo.dalvikPss); pw.print(',');
810 pw.print(memInfo.otherPss); pw.print(',');
811 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813 // Heap info - shared
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700814 pw.print(memInfo.nativeSharedDirty); pw.print(',');
815 pw.print(memInfo.dalvikSharedDirty); pw.print(',');
816 pw.print(memInfo.otherSharedDirty); pw.print(',');
817 pw.print(memInfo.nativeSharedDirty + memInfo.dalvikSharedDirty
818 + memInfo.otherSharedDirty); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 // Heap info - private
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700821 pw.print(memInfo.nativePrivateDirty); pw.print(',');
822 pw.print(memInfo.dalvikPrivateDirty); pw.print(',');
823 pw.print(memInfo.otherPrivateDirty); pw.print(',');
824 pw.print(memInfo.nativePrivateDirty + memInfo.dalvikPrivateDirty
825 + memInfo.otherPrivateDirty); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 // Object counts
828 pw.print(viewInstanceCount); pw.print(',');
829 pw.print(viewRootInstanceCount); pw.print(',');
830 pw.print(appContextInstanceCount); pw.print(',');
831 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 pw.print(globalAssetCount); pw.print(',');
834 pw.print(globalAssetManagerCount); pw.print(',');
835 pw.print(binderLocalObjectCount); pw.print(',');
836 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 pw.print(binderDeathObjectCount); pw.print(',');
839 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 // SQL
842 pw.print(sqliteAllocated); pw.print(',');
Vasu Noric3849202010-03-09 10:47:25 -0800843 pw.print(stats.memoryUsed / 1024); pw.print(',');
844 pw.print(stats.pageCacheOverflo / 1024); pw.print(',');
845 pw.print(stats.largestMemAlloc / 1024); pw.print(',');
846 for (int i = 0; i < stats.dbStats.size(); i++) {
847 DbStats dbStats = stats.dbStats.get(i);
848 printRow(pw, DB_INFO_FORMAT, dbStats.pageSize, dbStats.dbSize,
Vasu Nori90a367262010-04-12 12:49:09 -0700849 dbStats.lookaside, dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -0800850 pw.print(',');
851 }
Bob Leee5408332009-09-04 18:31:17 -0700852
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700853 return memInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 }
Bob Leee5408332009-09-04 18:31:17 -0700855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 // otherwise, show human-readable format
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700857 printRow(pw, HEAP_COLUMN, "", "", "Shared", "Private", "Heap", "Heap", "Heap");
858 printRow(pw, HEAP_COLUMN, "", "Pss", "Dirty", "Dirty", "Size", "Alloc", "Free");
859 printRow(pw, HEAP_COLUMN, "", "------", "------", "------", "------", "------",
860 "------");
861 printRow(pw, HEAP_COLUMN, "Native", memInfo.nativePss, memInfo.nativeSharedDirty,
862 memInfo.nativePrivateDirty, nativeMax, nativeAllocated, nativeFree);
863 printRow(pw, HEAP_COLUMN, "Dalvik", memInfo.dalvikPss, memInfo.dalvikSharedDirty,
864 memInfo.dalvikPrivateDirty, dalvikMax, dalvikAllocated, dalvikFree);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700866 int otherPss = memInfo.otherPss;
867 int otherSharedDirty = memInfo.otherSharedDirty;
868 int otherPrivateDirty = memInfo.otherPrivateDirty;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700870 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
871 printRow(pw, HEAP_COLUMN, memInfo.getOtherLabel(i),
872 memInfo.getOtherPss(i), memInfo.getOtherSharedDirty(i),
873 memInfo.getOtherPrivateDirty(i), "", "", "");
874 otherPss -= memInfo.getOtherPss(i);
875 otherSharedDirty -= memInfo.getOtherSharedDirty(i);
876 otherPrivateDirty -= memInfo.getOtherPrivateDirty(i);
877 }
878
879 printRow(pw, HEAP_COLUMN, "Unknown", otherPss, otherSharedDirty,
880 otherPrivateDirty, "", "", "");
881 printRow(pw, HEAP_COLUMN, "TOTAL", memInfo.getTotalPss(),
882 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
883 nativeMax+dalvikMax, nativeAllocated+dalvikAllocated,
884 nativeFree+dalvikFree);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885
886 pw.println(" ");
887 pw.println(" Objects");
Joe Onoratoc6cc0f82011-04-12 11:53:13 -0700888 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewAncestors:",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 viewRootInstanceCount);
890
891 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
892 "Activities:", activityInstanceCount);
893
894 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
895 "AssetManagers:", globalAssetManagerCount);
896
897 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
898 "Proxy Binders:", binderProxyObjectCount);
899 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
900
901 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -0700902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 // SQLite mem info
904 pw.println(" ");
905 pw.println(" SQL");
Vasu Nori3c7131f2010-09-21 14:36:57 -0700906 printRow(pw, TWO_COUNT_COLUMNS_DB, "heap:", sqliteAllocated, "MEMORY_USED:",
Vasu Noric3849202010-03-09 10:47:25 -0800907 stats.memoryUsed / 1024);
Vasu Nori3c7131f2010-09-21 14:36:57 -0700908 printRow(pw, TWO_COUNT_COLUMNS_DB, "PAGECACHE_OVERFLOW:",
909 stats.pageCacheOverflo / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -0800910 pw.println(" ");
911 int N = stats.dbStats.size();
912 if (N > 0) {
913 pw.println(" DATABASES");
Vasu Nori3c7131f2010-09-21 14:36:57 -0700914 printRow(pw, " %8s %8s %14s %14s %s", "pgsz", "dbsz", "Lookaside(b)", "cache",
915 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -0800916 for (int i = 0; i < N; i++) {
917 DbStats dbStats = stats.dbStats.get(i);
Vasu Nori3c7131f2010-09-21 14:36:57 -0700918 printRow(pw, DB_INFO_FORMAT,
919 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
920 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
921 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
922 dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -0800923 }
924 }
Bob Leee5408332009-09-04 18:31:17 -0700925
Dianne Hackborn82e1ee92009-08-11 18:56:41 -0700926 // Asset details.
927 String assetAlloc = AssetManager.getAssetAllocations();
928 if (assetAlloc != null) {
929 pw.println(" ");
930 pw.println(" Asset Allocations");
931 pw.print(assetAlloc);
932 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700933
934 return memInfo;
935 }
936
937 @Override
938 public void dumpGfxInfo(FileDescriptor fd, String[] args) {
939 dumpGraphicsInfo(fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 }
941
942 private void printRow(PrintWriter pw, String format, Object...objs) {
943 pw.println(String.format(format, objs));
944 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800945
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800946 public void setCoreSettings(Bundle coreSettings) {
947 queueOrSendMessage(H.SET_CORE_SETTINGS, coreSettings);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800948 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400949
950 public void updatePackageCompatibilityInfo(String pkg, CompatibilityInfo info) {
951 UpdateCompatibilityData ucd = new UpdateCompatibilityData();
952 ucd.pkg = pkg;
953 ucd.info = info;
954 queueOrSendMessage(H.UPDATE_PACKAGE_COMPATIBILITY_INFO, ucd);
955 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700956
957 public void scheduleTrimMemory(int level) {
958 queueOrSendMessage(H.TRIM_MEMORY, level);
959 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 }
961
962 private final class H extends Handler {
963 public static final int LAUNCH_ACTIVITY = 100;
964 public static final int PAUSE_ACTIVITY = 101;
965 public static final int PAUSE_ACTIVITY_FINISHING= 102;
966 public static final int STOP_ACTIVITY_SHOW = 103;
967 public static final int STOP_ACTIVITY_HIDE = 104;
968 public static final int SHOW_WINDOW = 105;
969 public static final int HIDE_WINDOW = 106;
970 public static final int RESUME_ACTIVITY = 107;
971 public static final int SEND_RESULT = 108;
Brian Carlstromed7e0072011-03-24 13:27:57 -0700972 public static final int DESTROY_ACTIVITY = 109;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 public static final int BIND_APPLICATION = 110;
974 public static final int EXIT_APPLICATION = 111;
975 public static final int NEW_INTENT = 112;
976 public static final int RECEIVER = 113;
977 public static final int CREATE_SERVICE = 114;
978 public static final int SERVICE_ARGS = 115;
979 public static final int STOP_SERVICE = 116;
980 public static final int REQUEST_THUMBNAIL = 117;
981 public static final int CONFIGURATION_CHANGED = 118;
982 public static final int CLEAN_UP_CONTEXT = 119;
983 public static final int GC_WHEN_IDLE = 120;
984 public static final int BIND_SERVICE = 121;
985 public static final int UNBIND_SERVICE = 122;
986 public static final int DUMP_SERVICE = 123;
987 public static final int LOW_MEMORY = 124;
988 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
989 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800990 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -0700991 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -0700992 public static final int DESTROY_BACKUP_AGENT = 129;
993 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700994 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800995 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700996 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700997 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -0700998 public static final int DUMP_HEAP = 135;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700999 public static final int DUMP_ACTIVITY = 136;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001000 public static final int SLEEPING = 137;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001001 public static final int SET_CORE_SETTINGS = 138;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001002 public static final int UPDATE_PACKAGE_COMPATIBILITY_INFO = 139;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001003 public static final int TRIM_MEMORY = 140;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 String codeToString(int code) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001005 if (DEBUG_MESSAGES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 switch (code) {
1007 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
1008 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
1009 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
1010 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
1011 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
1012 case SHOW_WINDOW: return "SHOW_WINDOW";
1013 case HIDE_WINDOW: return "HIDE_WINDOW";
1014 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
1015 case SEND_RESULT: return "SEND_RESULT";
1016 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
1017 case BIND_APPLICATION: return "BIND_APPLICATION";
1018 case EXIT_APPLICATION: return "EXIT_APPLICATION";
1019 case NEW_INTENT: return "NEW_INTENT";
1020 case RECEIVER: return "RECEIVER";
1021 case CREATE_SERVICE: return "CREATE_SERVICE";
1022 case SERVICE_ARGS: return "SERVICE_ARGS";
1023 case STOP_SERVICE: return "STOP_SERVICE";
1024 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
1025 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
1026 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
1027 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
1028 case BIND_SERVICE: return "BIND_SERVICE";
1029 case UNBIND_SERVICE: return "UNBIND_SERVICE";
1030 case DUMP_SERVICE: return "DUMP_SERVICE";
1031 case LOW_MEMORY: return "LOW_MEMORY";
1032 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
1033 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001034 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -07001035 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
1036 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -07001037 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001038 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001039 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001040 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001041 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -07001042 case DUMP_HEAP: return "DUMP_HEAP";
Dianne Hackborn625ac272010-09-17 18:29:22 -07001043 case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001044 case SLEEPING: return "SLEEPING";
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001045 case SET_CORE_SETTINGS: return "SET_CORE_SETTINGS";
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001046 case UPDATE_PACKAGE_COMPATIBILITY_INFO: return "UPDATE_PACKAGE_COMPATIBILITY_INFO";
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001047 case TRIM_MEMORY: return "TRIM_MEMORY";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 }
1049 }
1050 return "(unknown)";
1051 }
1052 public void handleMessage(Message msg) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001053 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 switch (msg.what) {
1055 case LAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001056 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057
1058 r.packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001059 r.activityInfo.applicationInfo, r.compatInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001060 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 } break;
1062 case RELAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001063 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08001064 handleRelaunchActivity(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 } break;
1066 case PAUSE_ACTIVITY:
1067 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -07001068 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 break;
1070 case PAUSE_ACTIVITY_FINISHING:
1071 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
1072 break;
1073 case STOP_ACTIVITY_SHOW:
1074 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
1075 break;
1076 case STOP_ACTIVITY_HIDE:
1077 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
1078 break;
1079 case SHOW_WINDOW:
1080 handleWindowVisibility((IBinder)msg.obj, true);
1081 break;
1082 case HIDE_WINDOW:
1083 handleWindowVisibility((IBinder)msg.obj, false);
1084 break;
1085 case RESUME_ACTIVITY:
1086 handleResumeActivity((IBinder)msg.obj, true,
1087 msg.arg1 != 0);
1088 break;
1089 case SEND_RESULT:
1090 handleSendResult((ResultData)msg.obj);
1091 break;
1092 case DESTROY_ACTIVITY:
1093 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
1094 msg.arg2, false);
1095 break;
1096 case BIND_APPLICATION:
1097 AppBindData data = (AppBindData)msg.obj;
1098 handleBindApplication(data);
1099 break;
1100 case EXIT_APPLICATION:
1101 if (mInitialApplication != null) {
1102 mInitialApplication.onTerminate();
1103 }
1104 Looper.myLooper().quit();
1105 break;
1106 case NEW_INTENT:
1107 handleNewIntent((NewIntentData)msg.obj);
1108 break;
1109 case RECEIVER:
1110 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001111 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 break;
1113 case CREATE_SERVICE:
1114 handleCreateService((CreateServiceData)msg.obj);
1115 break;
1116 case BIND_SERVICE:
1117 handleBindService((BindServiceData)msg.obj);
1118 break;
1119 case UNBIND_SERVICE:
1120 handleUnbindService((BindServiceData)msg.obj);
1121 break;
1122 case SERVICE_ARGS:
1123 handleServiceArgs((ServiceArgsData)msg.obj);
1124 break;
1125 case STOP_SERVICE:
1126 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001127 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 break;
1129 case REQUEST_THUMBNAIL:
1130 handleRequestThumbnail((IBinder)msg.obj);
1131 break;
1132 case CONFIGURATION_CHANGED:
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001133 handleConfigurationChanged((Configuration)msg.obj, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 break;
1135 case CLEAN_UP_CONTEXT:
1136 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1137 cci.context.performFinalCleanup(cci.who, cci.what);
1138 break;
1139 case GC_WHEN_IDLE:
1140 scheduleGcIdler();
1141 break;
1142 case DUMP_SERVICE:
Dianne Hackborn625ac272010-09-17 18:29:22 -07001143 handleDumpService((DumpComponentInfo)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 break;
1145 case LOW_MEMORY:
1146 handleLowMemory();
1147 break;
1148 case ACTIVITY_CONFIGURATION_CHANGED:
1149 handleActivityConfigurationChanged((IBinder)msg.obj);
1150 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001151 case PROFILER_CONTROL:
Romain Guy7eabe552011-07-21 14:56:34 -07001152 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj, msg.arg2);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001153 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001154 case CREATE_BACKUP_AGENT:
1155 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1156 break;
1157 case DESTROY_BACKUP_AGENT:
1158 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1159 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001160 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001161 Process.killProcess(Process.myPid());
1162 break;
1163 case REMOVE_PROVIDER:
1164 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001165 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001166 case ENABLE_JIT:
1167 ensureJitEnabled();
1168 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001169 case DISPATCH_PACKAGE_BROADCAST:
1170 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
1171 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001172 case SCHEDULE_CRASH:
1173 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001174 case DUMP_HEAP:
1175 handleDumpHeap(msg.arg1 != 0, (DumpHeapData)msg.obj);
1176 break;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001177 case DUMP_ACTIVITY:
1178 handleDumpActivity((DumpComponentInfo)msg.obj);
1179 break;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001180 case SLEEPING:
1181 handleSleeping((IBinder)msg.obj, msg.arg1 != 0);
1182 break;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001183 case SET_CORE_SETTINGS:
1184 handleSetCoreSettings((Bundle) msg.obj);
1185 break;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001186 case UPDATE_PACKAGE_COMPATIBILITY_INFO:
1187 handleUpdatePackageCompatibilityInfo((UpdateCompatibilityData)msg.obj);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001188 case TRIM_MEMORY:
1189 handleTrimMemory(msg.arg1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07001191 if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 }
Bob Leee5408332009-09-04 18:31:17 -07001193
Brian Carlstromed7e0072011-03-24 13:27:57 -07001194 private void maybeSnapshot() {
1195 if (mBoundApplication != null && SamplingProfilerIntegration.isEnabled()) {
Sen Hubde75702010-05-28 01:54:03 -07001196 // convert the *private* ActivityThread.PackageInfo to *public* known
1197 // android.content.pm.PackageInfo
1198 String packageName = mBoundApplication.info.mPackageName;
1199 android.content.pm.PackageInfo packageInfo = null;
1200 try {
1201 Context context = getSystemContext();
1202 if(context == null) {
1203 Log.e(TAG, "cannot get a valid context");
1204 return;
1205 }
1206 PackageManager pm = context.getPackageManager();
1207 if(pm == null) {
1208 Log.e(TAG, "cannot get a valid PackageManager");
1209 return;
1210 }
1211 packageInfo = pm.getPackageInfo(
1212 packageName, PackageManager.GET_ACTIVITIES);
1213 } catch (NameNotFoundException e) {
1214 Log.e(TAG, "cannot get package info for " + packageName, e);
1215 }
1216 SamplingProfilerIntegration.writeSnapshot(mBoundApplication.processName, packageInfo);
Bob Leee5408332009-09-04 18:31:17 -07001217 }
1218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 }
1220
1221 private final class Idler implements MessageQueue.IdleHandler {
1222 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001223 ActivityClientRecord a = mNewActivities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 if (a != null) {
1225 mNewActivities = null;
1226 IActivityManager am = ActivityManagerNative.getDefault();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001227 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001229 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 TAG, "Reporting idle of " + a +
1231 " finished=" +
1232 (a.activity != null ? a.activity.mFinished : false));
1233 if (a.activity != null && !a.activity.mFinished) {
1234 try {
Dianne Hackborne88846e2009-09-30 21:34:25 -07001235 am.activityIdle(a.token, a.createdConfig);
1236 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 } catch (RemoteException ex) {
1238 }
1239 }
1240 prev = a;
1241 a = a.nextIdle;
1242 prev.nextIdle = null;
1243 } while (a != null);
1244 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001245 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 return false;
1247 }
1248 }
1249
1250 final class GcIdler implements MessageQueue.IdleHandler {
1251 public final boolean queueIdle() {
1252 doGcIfNeeded();
1253 return false;
1254 }
1255 }
1256
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001257 private final static class ResourcesKey {
1258 final private String mResDir;
1259 final private float mScale;
1260 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07001261
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001262 ResourcesKey(String resDir, float scale) {
1263 mResDir = resDir;
1264 mScale = scale;
1265 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
1266 }
Bob Leee5408332009-09-04 18:31:17 -07001267
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001268 @Override
1269 public int hashCode() {
1270 return mHash;
1271 }
1272
1273 @Override
1274 public boolean equals(Object obj) {
1275 if (!(obj instanceof ResourcesKey)) {
1276 return false;
1277 }
1278 ResourcesKey peer = (ResourcesKey) obj;
1279 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
1280 }
1281 }
1282
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001283 public static final ActivityThread currentActivityThread() {
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07001284 return sThreadLocal.get();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001285 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001287 public static final String currentPackageName() {
1288 ActivityThread am = currentActivityThread();
1289 return (am != null && am.mBoundApplication != null)
1290 ? am.mBoundApplication.processName : null;
1291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001293 public static final Application currentApplication() {
1294 ActivityThread am = currentActivityThread();
1295 return am != null ? am.mInitialApplication : null;
1296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001298 public static IPackageManager getPackageManager() {
1299 if (sPackageManager != null) {
1300 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1301 return sPackageManager;
1302 }
1303 IBinder b = ServiceManager.getService("package");
1304 //Slog.v("PackageManager", "default service binder = " + b);
1305 sPackageManager = IPackageManager.Stub.asInterface(b);
1306 //Slog.v("PackageManager", "default service = " + sPackageManager);
1307 return sPackageManager;
1308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001310 DisplayMetrics getDisplayMetricsLocked(CompatibilityInfo ci, boolean forceUpdate) {
1311 DisplayMetrics dm = mDisplayMetrics.get(ci);
1312 if (dm != null && !forceUpdate) {
1313 return dm;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001314 }
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001315 if (dm == null) {
1316 dm = new DisplayMetrics();
1317 mDisplayMetrics.put(ci, dm);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001318 }
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001319 Display d = WindowManagerImpl.getDefault(ci).getDefaultDisplay();
1320 d.getMetrics(dm);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001321 //Slog.i("foo", "New metrics: w=" + metrics.widthPixels + " h="
1322 // + metrics.heightPixels + " den=" + metrics.density
1323 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001324 return dm;
1325 }
1326
1327 static Configuration applyConfigCompat(Configuration config, CompatibilityInfo compat) {
1328 if (config == null) {
1329 return null;
1330 }
1331 if (compat != null && !compat.supportsScreen()) {
1332 config = new Configuration(config);
1333 compat.applyToConfiguration(config);
1334 }
1335 return config;
1336 }
1337
1338 private final Configuration mMainThreadConfig = new Configuration();
1339 Configuration applyConfigCompatMainThread(Configuration config, CompatibilityInfo compat) {
1340 if (config == null) {
1341 return null;
1342 }
1343 if (compat != null && !compat.supportsScreen()) {
1344 mMainThreadConfig.setTo(config);
1345 config = mMainThreadConfig;
1346 compat.applyToConfiguration(config);
1347 }
1348 return config;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001351 /**
1352 * Creates the top level Resources for applications with the given compatibility info.
1353 *
1354 * @param resDir the resource directory.
1355 * @param compInfo the compability info. It will use the default compatibility info when it's
1356 * null.
1357 */
1358 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
1359 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
1360 Resources r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001362 // Resources is app scale dependent.
1363 if (false) {
1364 Slog.w(TAG, "getTopLevelResources: " + resDir + " / "
1365 + compInfo.applicationScale);
1366 }
1367 WeakReference<Resources> wr = mActiveResources.get(key);
1368 r = wr != null ? wr.get() : null;
1369 //if (r != null) Slog.i(TAG, "isUpToDate " + resDir + ": " + r.getAssets().isUpToDate());
1370 if (r != null && r.getAssets().isUpToDate()) {
1371 if (false) {
1372 Slog.w(TAG, "Returning cached resources " + r + " " + resDir
1373 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
1374 }
1375 return r;
1376 }
1377 }
1378
1379 //if (r != null) {
1380 // Slog.w(TAG, "Throwing away out-of-date resources!!!! "
1381 // + r + " " + resDir);
1382 //}
1383
1384 AssetManager assets = new AssetManager();
1385 if (assets.addAssetPath(resDir) == 0) {
1386 return null;
1387 }
1388
1389 //Slog.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001390 DisplayMetrics metrics = getDisplayMetricsLocked(compInfo, false);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001391 r = new Resources(assets, metrics, getConfiguration(), compInfo);
1392 if (false) {
1393 Slog.i(TAG, "Created app resources " + resDir + " " + r + ": "
1394 + r.getConfiguration() + " appScale="
1395 + r.getCompatibilityInfo().applicationScale);
1396 }
1397
1398 synchronized (mPackages) {
1399 WeakReference<Resources> wr = mActiveResources.get(key);
1400 Resources existing = wr != null ? wr.get() : null;
1401 if (existing != null && existing.getAssets().isUpToDate()) {
1402 // Someone else already created the resources while we were
1403 // unlocked; go ahead and use theirs.
1404 r.getAssets().close();
1405 return existing;
1406 }
1407
1408 // XXX need to remove entries when weak references go away
1409 mActiveResources.put(key, new WeakReference<Resources>(r));
1410 return r;
1411 }
1412 }
1413
1414 /**
1415 * Creates the top level resources for the given package.
1416 */
1417 Resources getTopLevelResources(String resDir, LoadedApk pkgInfo) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001418 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo.get());
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001419 }
1420
1421 final Handler getHandler() {
1422 return mH;
1423 }
1424
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001425 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
1426 int flags) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001427 synchronized (mPackages) {
1428 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
1430 ref = mPackages.get(packageName);
1431 } else {
1432 ref = mResourcePackages.get(packageName);
1433 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001434 LoadedApk packageInfo = ref != null ? ref.get() : null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001435 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001436 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
1437 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 if (packageInfo != null && (packageInfo.mResources == null
1439 || packageInfo.mResources.getAssets().isUpToDate())) {
1440 if (packageInfo.isSecurityViolation()
1441 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
1442 throw new SecurityException(
1443 "Requesting code from " + packageName
1444 + " to be run in process "
1445 + mBoundApplication.processName
1446 + "/" + mBoundApplication.appInfo.uid);
1447 }
1448 return packageInfo;
1449 }
1450 }
1451
1452 ApplicationInfo ai = null;
1453 try {
1454 ai = getPackageManager().getApplicationInfo(packageName,
1455 PackageManager.GET_SHARED_LIBRARY_FILES);
1456 } catch (RemoteException e) {
1457 }
1458
1459 if (ai != null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001460 return getPackageInfo(ai, compatInfo, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 }
1462
1463 return null;
1464 }
1465
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001466 public final LoadedApk getPackageInfo(ApplicationInfo ai, CompatibilityInfo compatInfo,
1467 int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
1469 boolean securityViolation = includeCode && ai.uid != 0
1470 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
1471 ? ai.uid != mBoundApplication.appInfo.uid : true);
1472 if ((flags&(Context.CONTEXT_INCLUDE_CODE
1473 |Context.CONTEXT_IGNORE_SECURITY))
1474 == Context.CONTEXT_INCLUDE_CODE) {
1475 if (securityViolation) {
1476 String msg = "Requesting code from " + ai.packageName
1477 + " (with uid " + ai.uid + ")";
1478 if (mBoundApplication != null) {
1479 msg = msg + " to be run in process "
1480 + mBoundApplication.processName + " (with uid "
1481 + mBoundApplication.appInfo.uid + ")";
1482 }
1483 throw new SecurityException(msg);
1484 }
1485 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001486 return getPackageInfo(ai, compatInfo, null, securityViolation, includeCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 }
1488
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001489 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai,
1490 CompatibilityInfo compatInfo) {
1491 return getPackageInfo(ai, compatInfo, null, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 }
1493
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001494 public final LoadedApk peekPackageInfo(String packageName, boolean includeCode) {
1495 synchronized (mPackages) {
1496 WeakReference<LoadedApk> ref;
1497 if (includeCode) {
1498 ref = mPackages.get(packageName);
1499 } else {
1500 ref = mResourcePackages.get(packageName);
1501 }
1502 return ref != null ? ref.get() : null;
1503 }
1504 }
1505
1506 private final LoadedApk getPackageInfo(ApplicationInfo aInfo, CompatibilityInfo compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
1508 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001509 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 if (includeCode) {
1511 ref = mPackages.get(aInfo.packageName);
1512 } else {
1513 ref = mResourcePackages.get(aInfo.packageName);
1514 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001515 LoadedApk packageInfo = ref != null ? ref.get() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 if (packageInfo == null || (packageInfo.mResources != null
1517 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001518 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 : "Loading resource-only package ") + aInfo.packageName
1520 + " (in " + (mBoundApplication != null
1521 ? mBoundApplication.processName : null)
1522 + ")");
1523 packageInfo =
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001524 new LoadedApk(this, aInfo, compatInfo, this, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 securityViolation, includeCode &&
1526 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
1527 if (includeCode) {
1528 mPackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001529 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 } else {
1531 mResourcePackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001532 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 }
1534 }
1535 return packageInfo;
1536 }
1537 }
1538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 ActivityThread() {
1540 }
1541
1542 public ApplicationThread getApplicationThread()
1543 {
1544 return mAppThread;
1545 }
1546
1547 public Instrumentation getInstrumentation()
1548 {
1549 return mInstrumentation;
1550 }
1551
1552 public Configuration getConfiguration() {
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001553 return mResConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554 }
1555
1556 public boolean isProfiling() {
1557 return mBoundApplication != null && mBoundApplication.profileFile != null;
1558 }
1559
1560 public String getProfileFilePath() {
1561 return mBoundApplication.profileFile;
1562 }
1563
1564 public Looper getLooper() {
1565 return mLooper;
1566 }
1567
1568 public Application getApplication() {
1569 return mInitialApplication;
1570 }
Bob Leee5408332009-09-04 18:31:17 -07001571
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07001572 public String getProcessName() {
1573 return mBoundApplication.processName;
1574 }
Bob Leee5408332009-09-04 18:31:17 -07001575
Dianne Hackborn21556372010-02-04 16:34:40 -08001576 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 synchronized (this) {
1578 if (mSystemContext == null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001579 ContextImpl context =
1580 ContextImpl.createSystemContext(this);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001581 LoadedApk info = new LoadedApk(this, "android", context, null,
1582 CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 context.init(info, null, this);
1584 context.getResources().updateConfiguration(
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001585 getConfiguration(), getDisplayMetricsLocked(
1586 CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO, false));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 mSystemContext = context;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001588 //Slog.i(TAG, "Created system resources " + context.getResources()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 // + ": " + context.getResources().getConfiguration());
1590 }
1591 }
1592 return mSystemContext;
1593 }
1594
Mike Cleron432b7132009-09-24 15:28:29 -07001595 public void installSystemApplicationInfo(ApplicationInfo info) {
1596 synchronized (this) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001597 ContextImpl context = getSystemContext();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001598 context.init(new LoadedApk(this, "android", context, info,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001599 CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO), null, this);
Mike Cleron432b7132009-09-24 15:28:29 -07001600 }
1601 }
1602
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001603 void ensureJitEnabled() {
1604 if (!mJitEnabled) {
1605 mJitEnabled = true;
1606 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
1607 }
1608 }
1609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 void scheduleGcIdler() {
1611 if (!mGcIdlerScheduled) {
1612 mGcIdlerScheduled = true;
1613 Looper.myQueue().addIdleHandler(mGcIdler);
1614 }
1615 mH.removeMessages(H.GC_WHEN_IDLE);
1616 }
1617
1618 void unscheduleGcIdler() {
1619 if (mGcIdlerScheduled) {
1620 mGcIdlerScheduled = false;
1621 Looper.myQueue().removeIdleHandler(mGcIdler);
1622 }
1623 mH.removeMessages(H.GC_WHEN_IDLE);
1624 }
1625
1626 void doGcIfNeeded() {
1627 mGcIdlerScheduled = false;
1628 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001629 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 // + "m now=" + now);
1631 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001632 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 BinderInternal.forceGc("bg");
1634 }
1635 }
1636
Jeff Hamilton52d32032011-01-08 15:31:26 -06001637 public void registerOnActivityPausedListener(Activity activity,
1638 OnActivityPausedListener listener) {
1639 synchronized (mOnPauseListeners) {
1640 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
1641 if (list == null) {
1642 list = new ArrayList<OnActivityPausedListener>();
1643 mOnPauseListeners.put(activity, list);
1644 }
1645 list.add(listener);
1646 }
1647 }
1648
Jeff Hamiltonce3224c2011-01-17 11:05:03 -08001649 public void unregisterOnActivityPausedListener(Activity activity,
1650 OnActivityPausedListener listener) {
1651 synchronized (mOnPauseListeners) {
1652 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
1653 if (list != null) {
1654 list.remove(listener);
1655 }
1656 }
1657 }
1658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 public final ActivityInfo resolveActivityInfo(Intent intent) {
1660 ActivityInfo aInfo = intent.resolveActivityInfo(
1661 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
1662 if (aInfo == null) {
1663 // Throw an exception.
1664 Instrumentation.checkStartActivityResult(
1665 IActivityManager.START_CLASS_NOT_FOUND, intent);
1666 }
1667 return aInfo;
1668 }
Bob Leee5408332009-09-04 18:31:17 -07001669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001672 Activity.NonConfigurationInstances lastNonConfigurationInstances) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001673 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001675 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 r.intent = intent;
1677 r.state = state;
1678 r.parent = parent;
1679 r.embeddedID = id;
1680 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001681 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 if (localLOGV) {
1683 ComponentName compname = intent.getComponent();
1684 String name;
1685 if (compname != null) {
1686 name = compname.toShortString();
1687 } else {
1688 name = "(Intent " + intent + ").getComponent() returned null";
1689 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001690 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 + ", comp=" + name
1692 + ", token=" + token);
1693 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07001694 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 }
1696
1697 public final Activity getActivity(IBinder token) {
1698 return mActivities.get(token).activity;
1699 }
1700
1701 public final void sendActivityResult(
1702 IBinder token, String id, int requestCode,
1703 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001704 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07001705 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
1707 list.add(new ResultInfo(id, requestCode, resultCode, data));
1708 mAppThread.scheduleSendResult(token, list);
1709 }
1710
1711 // if the thread hasn't started yet, we don't have the handler, so just
1712 // save the messages until we're ready.
1713 private final void queueOrSendMessage(int what, Object obj) {
1714 queueOrSendMessage(what, obj, 0, 0);
1715 }
1716
1717 private final void queueOrSendMessage(int what, Object obj, int arg1) {
1718 queueOrSendMessage(what, obj, arg1, 0);
1719 }
1720
1721 private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
1722 synchronized (this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001723 if (DEBUG_MESSAGES) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
1725 + ": " + arg1 + " / " + obj);
1726 Message msg = Message.obtain();
1727 msg.what = what;
1728 msg.obj = obj;
1729 msg.arg1 = arg1;
1730 msg.arg2 = arg2;
1731 mH.sendMessage(msg);
1732 }
1733 }
1734
Dianne Hackborn21556372010-02-04 16:34:40 -08001735 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 String what) {
1737 ContextCleanupInfo cci = new ContextCleanupInfo();
1738 cci.context = context;
1739 cci.who = who;
1740 cci.what = what;
1741 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
1742 }
1743
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001744 private final Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
1746
1747 ActivityInfo aInfo = r.activityInfo;
1748 if (r.packageInfo == null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001749 r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 Context.CONTEXT_INCLUDE_CODE);
1751 }
Bob Leee5408332009-09-04 18:31:17 -07001752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 ComponentName component = r.intent.getComponent();
1754 if (component == null) {
1755 component = r.intent.resolveActivity(
1756 mInitialApplication.getPackageManager());
1757 r.intent.setComponent(component);
1758 }
1759
1760 if (r.activityInfo.targetActivity != null) {
1761 component = new ComponentName(r.activityInfo.packageName,
1762 r.activityInfo.targetActivity);
1763 }
1764
1765 Activity activity = null;
1766 try {
1767 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
1768 activity = mInstrumentation.newActivity(
1769 cl, component.getClassName(), r.intent);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08001770 StrictMode.incrementExpectedActivityCount(activity.getClass());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 r.intent.setExtrasClassLoader(cl);
1772 if (r.state != null) {
1773 r.state.setClassLoader(cl);
1774 }
1775 } catch (Exception e) {
1776 if (!mInstrumentation.onException(activity, e)) {
1777 throw new RuntimeException(
1778 "Unable to instantiate activity " + component
1779 + ": " + e.toString(), e);
1780 }
1781 }
1782
1783 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001784 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001785
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001786 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
1787 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 TAG, r + ": app=" + app
1789 + ", appName=" + app.getPackageName()
1790 + ", pkg=" + r.packageInfo.getPackageName()
1791 + ", comp=" + r.intent.getComponent().toShortString()
1792 + ", dir=" + r.packageInfo.getAppDir());
1793
1794 if (activity != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001795 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 appContext.init(r.packageInfo, r.token, this);
1797 appContext.setOuterContext(activity);
1798 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001799 Configuration config = new Configuration(mCompatConfiguration);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001800 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07001801 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001802 activity.attach(appContext, this, getInstrumentation(), r.token,
1803 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001804 r.embeddedID, r.lastNonConfigurationInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07001805
Christopher Tateb70f3df2009-04-07 16:07:59 -07001806 if (customIntent != null) {
1807 activity.mIntent = customIntent;
1808 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001809 r.lastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 activity.mStartedActivity = false;
1811 int theme = r.activityInfo.getThemeResource();
1812 if (theme != 0) {
1813 activity.setTheme(theme);
1814 }
1815
1816 activity.mCalled = false;
1817 mInstrumentation.callActivityOnCreate(activity, r.state);
1818 if (!activity.mCalled) {
1819 throw new SuperNotCalledException(
1820 "Activity " + r.intent.getComponent().toShortString() +
1821 " did not call through to super.onCreate()");
1822 }
1823 r.activity = activity;
1824 r.stopped = true;
1825 if (!r.activity.mFinished) {
1826 activity.performStart();
1827 r.stopped = false;
1828 }
1829 if (!r.activity.mFinished) {
1830 if (r.state != null) {
1831 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
1832 }
1833 }
1834 if (!r.activity.mFinished) {
1835 activity.mCalled = false;
1836 mInstrumentation.callActivityOnPostCreate(activity, r.state);
1837 if (!activity.mCalled) {
1838 throw new SuperNotCalledException(
1839 "Activity " + r.intent.getComponent().toShortString() +
1840 " did not call through to super.onPostCreate()");
1841 }
1842 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 }
1844 r.paused = true;
1845
1846 mActivities.put(r.token, r);
1847
1848 } catch (SuperNotCalledException e) {
1849 throw e;
1850
1851 } catch (Exception e) {
1852 if (!mInstrumentation.onException(activity, e)) {
1853 throw new RuntimeException(
1854 "Unable to start activity " + component
1855 + ": " + e.toString(), e);
1856 }
1857 }
1858
1859 return activity;
1860 }
1861
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001862 private final void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 // If we are getting ready to gc after going to the background, well
1864 // we are back active so skip it.
1865 unscheduleGcIdler();
1866
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001867 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001868 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001869 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870
1871 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08001872 r.createdConfig = new Configuration(mConfiguration);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001873 Bundle oldState = r.state;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001874 handleResumeActivity(r.token, false, r.isForward);
1875
1876 if (!r.activity.mFinished && r.startsNotResumed) {
1877 // The activity manager actually wants this one to start out
1878 // paused, because it needs to be visible but isn't in the
1879 // foreground. We accomplish this by going through the
1880 // normal startup (because activities expect to go through
1881 // onResume() the first time they run, before their window
1882 // is displayed), and then pausing it. However, in this case
1883 // we do -not- need to do the full pause cycle (of freezing
1884 // and such) because the activity manager assumes it can just
1885 // retain the current state it has.
1886 try {
1887 r.activity.mCalled = false;
1888 mInstrumentation.callActivityOnPause(r.activity);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001889 // We need to keep around the original state, in case
1890 // we need to be created again.
1891 r.state = oldState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 if (!r.activity.mCalled) {
1893 throw new SuperNotCalledException(
1894 "Activity " + r.intent.getComponent().toShortString() +
1895 " did not call through to super.onPause()");
1896 }
1897
1898 } catch (SuperNotCalledException e) {
1899 throw e;
1900
1901 } catch (Exception e) {
1902 if (!mInstrumentation.onException(r.activity, e)) {
1903 throw new RuntimeException(
1904 "Unable to pause activity "
1905 + r.intent.getComponent().toShortString()
1906 + ": " + e.toString(), e);
1907 }
1908 }
1909 r.paused = true;
1910 }
1911 } else {
1912 // If there was an error, for any reason, tell the activity
1913 // manager to stop us.
1914 try {
1915 ActivityManagerNative.getDefault()
1916 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
1917 } catch (RemoteException ex) {
1918 }
1919 }
1920 }
1921
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001922 private final void deliverNewIntents(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 List<Intent> intents) {
1924 final int N = intents.size();
1925 for (int i=0; i<N; i++) {
1926 Intent intent = intents.get(i);
1927 intent.setExtrasClassLoader(r.activity.getClassLoader());
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001928 r.activity.mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
1930 }
1931 }
1932
1933 public final void performNewIntents(IBinder token,
1934 List<Intent> intents) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001935 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 if (r != null) {
1937 final boolean resumed = !r.paused;
1938 if (resumed) {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001939 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 mInstrumentation.callActivityOnPause(r.activity);
1941 }
1942 deliverNewIntents(r, intents);
1943 if (resumed) {
Dianne Hackbornb46ed762011-06-02 18:33:15 -07001944 r.activity.performResume();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001945 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 }
1947 }
1948 }
Bob Leee5408332009-09-04 18:31:17 -07001949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 private final void handleNewIntent(NewIntentData data) {
1951 performNewIntents(data.token, data.intents);
1952 }
1953
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07001954 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
1955
1956 /**
1957 * Return the Intent that's currently being handled by a
1958 * BroadcastReceiver on this thread, or null if none.
1959 * @hide
1960 */
1961 public static Intent getIntentBeingBroadcast() {
1962 return sCurrentBroadcastIntent.get();
1963 }
1964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 private final void handleReceiver(ReceiverData data) {
1966 // If we are getting ready to gc after going to the background, well
1967 // we are back active so skip it.
1968 unscheduleGcIdler();
1969
1970 String component = data.intent.getComponent().getClassName();
1971
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001972 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001973 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974
1975 IActivityManager mgr = ActivityManagerNative.getDefault();
1976
1977 BroadcastReceiver receiver = null;
1978 try {
1979 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1980 data.intent.setExtrasClassLoader(cl);
Dianne Hackborne829fef2010-10-26 17:44:01 -07001981 data.setExtrasClassLoader(cl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
1983 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07001984 if (DEBUG_BROADCAST) Slog.i(TAG,
1985 "Finishing failed broadcast to " + data.intent.getComponent());
1986 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 throw new RuntimeException(
1988 "Unable to instantiate receiver " + component
1989 + ": " + e.toString(), e);
1990 }
1991
1992 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001993 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001994
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001995 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 TAG, "Performing receive of " + data.intent
1997 + ": app=" + app
1998 + ", appName=" + app.getPackageName()
1999 + ", pkg=" + packageInfo.getPackageName()
2000 + ", comp=" + data.intent.getComponent().toShortString()
2001 + ", dir=" + packageInfo.getAppDir());
2002
Dianne Hackborn21556372010-02-04 16:34:40 -08002003 ContextImpl context = (ContextImpl)app.getBaseContext();
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002004 sCurrentBroadcastIntent.set(data.intent);
Dianne Hackborne829fef2010-10-26 17:44:01 -07002005 receiver.setPendingResult(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002006 receiver.onReceive(context.getReceiverRestrictedContext(),
2007 data.intent);
2008 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07002009 if (DEBUG_BROADCAST) Slog.i(TAG,
2010 "Finishing failed broadcast to " + data.intent.getComponent());
2011 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 if (!mInstrumentation.onException(receiver, e)) {
2013 throw new RuntimeException(
2014 "Unable to start receiver " + component
2015 + ": " + e.toString(), e);
2016 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002017 } finally {
2018 sCurrentBroadcastIntent.set(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 }
2020
Dianne Hackborne829fef2010-10-26 17:44:01 -07002021 if (receiver.getPendingResult() != null) {
2022 data.finish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 }
2024 }
2025
Christopher Tate181fafa2009-05-14 11:12:14 -07002026 // Instantiate a BackupAgent and tell it that it's alive
2027 private final void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002028 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07002029
2030 // no longer idle; we have backup work to do
2031 unscheduleGcIdler();
2032
2033 // instantiate the BackupAgent class named in the manifest
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002034 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07002035 String packageName = packageInfo.mPackageName;
2036 if (mBackupAgents.get(packageName) != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002037 Slog.d(TAG, "BackupAgent " + " for " + packageName
Christopher Tate181fafa2009-05-14 11:12:14 -07002038 + " already exists");
2039 return;
2040 }
Bob Leee5408332009-09-04 18:31:17 -07002041
Christopher Tate181fafa2009-05-14 11:12:14 -07002042 BackupAgent agent = null;
2043 String classname = data.appInfo.backupAgentName;
Christopher Tate4a627c72011-04-01 14:43:32 -07002044
Christopher Tate79ec80d2011-06-24 14:58:49 -07002045 // full backup operation but no app-supplied agent? use the default implementation
2046 if (classname == null && (data.backupMode == IApplicationThread.BACKUP_MODE_FULL
2047 || data.backupMode == IApplicationThread.BACKUP_MODE_RESTORE_FULL)) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002048 classname = "android.app.backup.FullBackupAgent";
Christopher Tate181fafa2009-05-14 11:12:14 -07002049 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002050
Christopher Tate181fafa2009-05-14 11:12:14 -07002051 try {
Christopher Tated1475e02009-07-09 15:36:17 -07002052 IBinder binder = null;
2053 try {
Christopher Tate4a627c72011-04-01 14:43:32 -07002054 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing agent class " + classname);
2055
Christopher Tated1475e02009-07-09 15:36:17 -07002056 java.lang.ClassLoader cl = packageInfo.getClassLoader();
Christopher Tate4a627c72011-04-01 14:43:32 -07002057 agent = (BackupAgent) cl.loadClass(classname).newInstance();
Christopher Tated1475e02009-07-09 15:36:17 -07002058
2059 // set up the agent's context
Dianne Hackborn21556372010-02-04 16:34:40 -08002060 ContextImpl context = new ContextImpl();
Christopher Tated1475e02009-07-09 15:36:17 -07002061 context.init(packageInfo, null, this);
2062 context.setOuterContext(agent);
2063 agent.attach(context);
2064
2065 agent.onCreate();
2066 binder = agent.onBind();
2067 mBackupAgents.put(packageName, agent);
2068 } catch (Exception e) {
2069 // If this is during restore, fail silently; otherwise go
2070 // ahead and let the user see the crash.
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002071 Slog.e(TAG, "Agent threw during creation: " + e);
Christopher Tate75a99702011-05-18 16:28:19 -07002072 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE
2073 && data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE_FULL) {
Christopher Tated1475e02009-07-09 15:36:17 -07002074 throw e;
2075 }
2076 // falling through with 'binder' still null
2077 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002078
2079 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07002080 try {
2081 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
2082 } catch (RemoteException e) {
2083 // nothing to do.
2084 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002085 } catch (Exception e) {
2086 throw new RuntimeException("Unable to create BackupAgent "
Christopher Tate4a627c72011-04-01 14:43:32 -07002087 + classname + ": " + e.toString(), e);
Christopher Tate181fafa2009-05-14 11:12:14 -07002088 }
2089 }
2090
2091 // Tear down a BackupAgent
2092 private final void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002093 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07002094
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002095 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07002096 String packageName = packageInfo.mPackageName;
2097 BackupAgent agent = mBackupAgents.get(packageName);
2098 if (agent != null) {
2099 try {
2100 agent.onDestroy();
2101 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002102 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07002103 e.printStackTrace();
2104 }
2105 mBackupAgents.remove(packageName);
2106 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002107 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07002108 }
2109 }
2110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 private final void handleCreateService(CreateServiceData data) {
2112 // If we are getting ready to gc after going to the background, well
2113 // we are back active so skip it.
2114 unscheduleGcIdler();
2115
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002116 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002117 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 Service service = null;
2119 try {
2120 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2121 service = (Service) cl.loadClass(data.info.name).newInstance();
2122 } catch (Exception e) {
2123 if (!mInstrumentation.onException(service, e)) {
2124 throw new RuntimeException(
2125 "Unable to instantiate service " + data.info.name
2126 + ": " + e.toString(), e);
2127 }
2128 }
2129
2130 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002131 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132
Dianne Hackborn21556372010-02-04 16:34:40 -08002133 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134 context.init(packageInfo, null, this);
2135
Dianne Hackborn0be1f782009-11-09 12:30:12 -08002136 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002137 context.setOuterContext(service);
2138 service.attach(context, this, data.info.name, data.token, app,
2139 ActivityManagerNative.getDefault());
2140 service.onCreate();
2141 mServices.put(data.token, service);
2142 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002143 ActivityManagerNative.getDefault().serviceDoneExecuting(
2144 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002145 } catch (RemoteException e) {
2146 // nothing to do.
2147 }
2148 } catch (Exception e) {
2149 if (!mInstrumentation.onException(service, e)) {
2150 throw new RuntimeException(
2151 "Unable to create service " + data.info.name
2152 + ": " + e.toString(), e);
2153 }
2154 }
2155 }
2156
2157 private final void handleBindService(BindServiceData data) {
2158 Service s = mServices.get(data.token);
2159 if (s != null) {
2160 try {
2161 data.intent.setExtrasClassLoader(s.getClassLoader());
2162 try {
2163 if (!data.rebind) {
2164 IBinder binder = s.onBind(data.intent);
2165 ActivityManagerNative.getDefault().publishService(
2166 data.token, data.intent, binder);
2167 } else {
2168 s.onRebind(data.intent);
2169 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002170 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002171 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002172 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173 } catch (RemoteException ex) {
2174 }
2175 } catch (Exception e) {
2176 if (!mInstrumentation.onException(s, e)) {
2177 throw new RuntimeException(
2178 "Unable to bind to service " + s
2179 + " with " + data.intent + ": " + e.toString(), e);
2180 }
2181 }
2182 }
2183 }
2184
2185 private final void handleUnbindService(BindServiceData data) {
2186 Service s = mServices.get(data.token);
2187 if (s != null) {
2188 try {
2189 data.intent.setExtrasClassLoader(s.getClassLoader());
2190 boolean doRebind = s.onUnbind(data.intent);
2191 try {
2192 if (doRebind) {
2193 ActivityManagerNative.getDefault().unbindFinished(
2194 data.token, data.intent, doRebind);
2195 } else {
2196 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002197 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002198 }
2199 } catch (RemoteException ex) {
2200 }
2201 } catch (Exception e) {
2202 if (!mInstrumentation.onException(s, e)) {
2203 throw new RuntimeException(
2204 "Unable to unbind to service " + s
2205 + " with " + data.intent + ": " + e.toString(), e);
2206 }
2207 }
2208 }
2209 }
2210
Dianne Hackborn625ac272010-09-17 18:29:22 -07002211 private void handleDumpService(DumpComponentInfo info) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07002212 Service s = mServices.get(info.token);
2213 if (s != null) {
2214 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
2215 s.dump(info.fd.getFileDescriptor(), pw, info.args);
2216 pw.flush();
2217 try {
2218 info.fd.close();
2219 } catch (IOException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002220 }
2221 }
2222 }
2223
Dianne Hackborn625ac272010-09-17 18:29:22 -07002224 private void handleDumpActivity(DumpComponentInfo info) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07002225 ActivityClientRecord r = mActivities.get(info.token);
2226 if (r != null && r.activity != null) {
2227 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
2228 r.activity.dump(info.prefix, info.fd.getFileDescriptor(), pw, info.args);
2229 pw.flush();
2230 try {
2231 info.fd.close();
2232 } catch (IOException e) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07002233 }
2234 }
2235 }
2236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002237 private final void handleServiceArgs(ServiceArgsData data) {
2238 Service s = mServices.get(data.token);
2239 if (s != null) {
2240 try {
2241 if (data.args != null) {
2242 data.args.setExtrasClassLoader(s.getClassLoader());
2243 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002244 int res;
2245 if (!data.taskRemoved) {
2246 res = s.onStartCommand(data.args, data.flags, data.startId);
2247 } else {
2248 s.onTaskRemoved(data.args);
2249 res = Service.START_TASK_REMOVED_COMPLETE;
2250 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002251
2252 QueuedWork.waitToFinish();
2253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002254 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002255 ActivityManagerNative.getDefault().serviceDoneExecuting(
2256 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002257 } catch (RemoteException e) {
2258 // nothing to do.
2259 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002260 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 } catch (Exception e) {
2262 if (!mInstrumentation.onException(s, e)) {
2263 throw new RuntimeException(
2264 "Unable to start service " + s
2265 + " with " + data.args + ": " + e.toString(), e);
2266 }
2267 }
2268 }
2269 }
2270
2271 private final void handleStopService(IBinder token) {
2272 Service s = mServices.remove(token);
2273 if (s != null) {
2274 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002275 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002276 s.onDestroy();
2277 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002278 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08002280 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002281 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002282
2283 QueuedWork.waitToFinish();
2284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002286 ActivityManagerNative.getDefault().serviceDoneExecuting(
2287 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002288 } catch (RemoteException e) {
2289 // nothing to do.
2290 }
2291 } catch (Exception e) {
2292 if (!mInstrumentation.onException(s, e)) {
2293 throw new RuntimeException(
2294 "Unable to stop service " + s
2295 + ": " + e.toString(), e);
2296 }
2297 }
2298 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002299 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002300 }
2301
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002302 public final ActivityClientRecord performResumeActivity(IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002303 boolean clearHide) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002304 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002305 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002306 + " finished=" + r.activity.mFinished);
2307 if (r != null && !r.activity.mFinished) {
2308 if (clearHide) {
2309 r.hideForNow = false;
2310 r.activity.mStartedActivity = false;
2311 }
2312 try {
2313 if (r.pendingIntents != null) {
2314 deliverNewIntents(r, r.pendingIntents);
2315 r.pendingIntents = null;
2316 }
2317 if (r.pendingResults != null) {
2318 deliverResults(r, r.pendingResults);
2319 r.pendingResults = null;
2320 }
2321 r.activity.performResume();
2322
Bob Leee5408332009-09-04 18:31:17 -07002323 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002324 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002326 r.paused = false;
2327 r.stopped = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002328 r.state = null;
2329 } catch (Exception e) {
2330 if (!mInstrumentation.onException(r.activity, e)) {
2331 throw new RuntimeException(
2332 "Unable to resume activity "
2333 + r.intent.getComponent().toShortString()
2334 + ": " + e.toString(), e);
2335 }
2336 }
2337 }
2338 return r;
2339 }
2340
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002341 final void cleanUpPendingRemoveWindows(ActivityClientRecord r) {
2342 if (r.mPendingRemoveWindow != null) {
2343 r.mPendingRemoveWindowManager.removeViewImmediate(r.mPendingRemoveWindow);
2344 IBinder wtoken = r.mPendingRemoveWindow.getWindowToken();
2345 if (wtoken != null) {
2346 WindowManagerImpl.getDefault().closeAll(wtoken,
2347 r.activity.getClass().getName(), "Activity");
2348 }
2349 }
2350 r.mPendingRemoveWindow = null;
2351 r.mPendingRemoveWindowManager = null;
2352 }
2353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002354 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2355 // If we are getting ready to gc after going to the background, well
2356 // we are back active so skip it.
2357 unscheduleGcIdler();
2358
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002359 ActivityClientRecord r = performResumeActivity(token, clearHide);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360
2361 if (r != null) {
2362 final Activity a = r.activity;
2363
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002364 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 TAG, "Resume " + r + " started activity: " +
2366 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2367 + ", finished: " + a.mFinished);
2368
2369 final int forwardBit = isForward ?
2370 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002372 // If the window hasn't yet been added to the window manager,
2373 // and this guy didn't finish itself or start another activity,
2374 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002375 boolean willBeVisible = !a.mStartedActivity;
2376 if (!willBeVisible) {
2377 try {
2378 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
2379 a.getActivityToken());
2380 } catch (RemoteException e) {
2381 }
2382 }
2383 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002384 r.window = r.activity.getWindow();
2385 View decor = r.window.getDecorView();
2386 decor.setVisibility(View.INVISIBLE);
2387 ViewManager wm = a.getWindowManager();
2388 WindowManager.LayoutParams l = r.window.getAttributes();
2389 a.mDecor = decor;
2390 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2391 l.softInputMode |= forwardBit;
2392 if (a.mVisibleFromClient) {
2393 a.mWindowAdded = true;
2394 wm.addView(decor, l);
2395 }
2396
2397 // If the window has already been added, but during resume
2398 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002399 // window visible.
2400 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002401 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002402 TAG, "Launch " + r + " mStartedActivity set");
2403 r.hideForNow = true;
2404 }
2405
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002406 // Get rid of anything left hanging around.
2407 cleanUpPendingRemoveWindows(r);
2408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002409 // The window is now visible if it has been added, we are not
2410 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002411 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002412 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002413 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002414 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002415 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002416 performConfigurationChanged(r.activity, r.newConfig);
2417 r.newConfig = null;
2418 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002419 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002420 + isForward);
2421 WindowManager.LayoutParams l = r.window.getAttributes();
2422 if ((l.softInputMode
2423 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2424 != forwardBit) {
2425 l.softInputMode = (l.softInputMode
2426 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2427 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002428 if (r.activity.mVisibleFromClient) {
2429 ViewManager wm = a.getWindowManager();
2430 View decor = r.window.getDecorView();
2431 wm.updateViewLayout(decor, l);
2432 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002433 }
2434 r.activity.mVisibleFromServer = true;
2435 mNumVisibleActivities++;
2436 if (r.activity.mVisibleFromClient) {
2437 r.activity.makeVisible();
2438 }
2439 }
2440
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002441 if (!r.onlyLocalRequest) {
2442 r.nextIdle = mNewActivities;
2443 mNewActivities = r;
2444 if (localLOGV) Slog.v(
2445 TAG, "Scheduling idle handler for " + r);
2446 Looper.myQueue().addIdleHandler(new Idler());
2447 }
2448 r.onlyLocalRequest = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002449
2450 } else {
2451 // If an exception was thrown when trying to resume, then
2452 // just end this activity.
2453 try {
2454 ActivityManagerNative.getDefault()
2455 .finishActivity(token, Activity.RESULT_CANCELED, null);
2456 } catch (RemoteException ex) {
2457 }
2458 }
2459 }
2460
2461 private int mThumbnailWidth = -1;
2462 private int mThumbnailHeight = -1;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002463 private Bitmap mAvailThumbnailBitmap = null;
2464 private Canvas mThumbnailCanvas = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002465
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002466 private final Bitmap createThumbnailBitmap(ActivityClientRecord r) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002467 Bitmap thumbnail = mAvailThumbnailBitmap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002468 try {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002469 if (thumbnail == null) {
2470 int w = mThumbnailWidth;
2471 int h;
2472 if (w < 0) {
2473 Resources res = r.activity.getResources();
2474 mThumbnailHeight = h =
2475 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002477 mThumbnailWidth = w =
2478 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
2479 } else {
2480 h = mThumbnailHeight;
2481 }
2482
2483 // On platforms where we don't want thumbnails, set dims to (0,0)
2484 if ((w > 0) && (h > 0)) {
2485 thumbnail = Bitmap.createBitmap(w, h, THUMBNAIL_FORMAT);
2486 thumbnail.eraseColor(0);
2487 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 }
2489
Dianne Hackbornfb3806d2010-12-09 13:14:12 -08002490 if (thumbnail != null) {
2491 Canvas cv = mThumbnailCanvas;
2492 if (cv == null) {
2493 mThumbnailCanvas = cv = new Canvas();
2494 }
2495
2496 cv.setBitmap(thumbnail);
2497 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
2498 mAvailThumbnailBitmap = thumbnail;
2499 thumbnail = null;
2500 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002501 }
Jim Miller0b2a6d02010-07-13 18:01:29 -07002502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 } catch (Exception e) {
2504 if (!mInstrumentation.onException(r.activity, e)) {
2505 throw new RuntimeException(
2506 "Unable to create thumbnail of "
2507 + r.intent.getComponent().toShortString()
2508 + ": " + e.toString(), e);
2509 }
2510 thumbnail = null;
2511 }
2512
2513 return thumbnail;
2514 }
2515
2516 private final void handlePauseActivity(IBinder token, boolean finished,
2517 boolean userLeaving, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002518 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002520 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002521 if (userLeaving) {
2522 performUserLeavingActivity(r);
2523 }
Bob Leee5408332009-09-04 18:31:17 -07002524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 r.activity.mConfigChangeFlags |= configChanges;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002526 performPauseActivity(token, finished, r.isPreHoneycomb());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07002528 // Make sure any pending writes are now committed.
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002529 if (r.isPreHoneycomb()) {
2530 QueuedWork.waitToFinish();
2531 }
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07002532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002533 // Tell the activity manager we have paused.
2534 try {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002535 ActivityManagerNative.getDefault().activityPaused(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 } catch (RemoteException ex) {
2537 }
2538 }
2539 }
2540
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002541 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 mInstrumentation.callActivityOnUserLeaving(r.activity);
2543 }
2544
2545 final Bundle performPauseActivity(IBinder token, boolean finished,
2546 boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002547 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002548 return r != null ? performPauseActivity(r, finished, saveState) : null;
2549 }
2550
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002551 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002552 boolean saveState) {
2553 if (r.paused) {
2554 if (r.activity.mFinished) {
2555 // If we are finishing, we won't call onResume() in certain cases.
2556 // So here we likewise don't want to call onPause() if the activity
2557 // isn't resumed.
2558 return null;
2559 }
2560 RuntimeException e = new RuntimeException(
2561 "Performing pause of activity that is not resumed: "
2562 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002563 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 }
2565 Bundle state = null;
2566 if (finished) {
2567 r.activity.mFinished = true;
2568 }
2569 try {
2570 // Next have the activity save its current state and managed dialogs...
2571 if (!r.activity.mFinished && saveState) {
2572 state = new Bundle();
2573 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2574 r.state = state;
2575 }
2576 // Now we are idle.
2577 r.activity.mCalled = false;
2578 mInstrumentation.callActivityOnPause(r.activity);
2579 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
2580 if (!r.activity.mCalled) {
2581 throw new SuperNotCalledException(
2582 "Activity " + r.intent.getComponent().toShortString() +
2583 " did not call through to super.onPause()");
2584 }
2585
2586 } catch (SuperNotCalledException e) {
2587 throw e;
2588
2589 } catch (Exception e) {
2590 if (!mInstrumentation.onException(r.activity, e)) {
2591 throw new RuntimeException(
2592 "Unable to pause activity "
2593 + r.intent.getComponent().toShortString()
2594 + ": " + e.toString(), e);
2595 }
2596 }
2597 r.paused = true;
Jeff Hamilton52d32032011-01-08 15:31:26 -06002598
2599 // Notify any outstanding on paused listeners
2600 ArrayList<OnActivityPausedListener> listeners;
2601 synchronized (mOnPauseListeners) {
2602 listeners = mOnPauseListeners.remove(r.activity);
2603 }
2604 int size = (listeners != null ? listeners.size() : 0);
2605 for (int i = 0; i < size; i++) {
2606 listeners.get(i).onPaused(r.activity);
2607 }
2608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609 return state;
2610 }
2611
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002612 final void performStopActivity(IBinder token, boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002613 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002614 performStopActivityInner(r, null, false, saveState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 }
2616
2617 private static class StopInfo {
2618 Bitmap thumbnail;
2619 CharSequence description;
2620 }
2621
2622 private final class ProviderRefCount {
2623 public int count;
2624 ProviderRefCount(int pCount) {
2625 count = pCount;
2626 }
2627 }
2628
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002629 /**
2630 * Core implementation of stopping an activity. Note this is a little
2631 * tricky because the server's meaning of stop is slightly different
2632 * than our client -- for the server, stop means to save state and give
2633 * it the result when it is done, but the window may still be visible.
2634 * For the client, we want to call onStop()/onStart() to indicate when
2635 * the activity's UI visibillity changes.
2636 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002637 private final void performStopActivityInner(ActivityClientRecord r,
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002638 StopInfo info, boolean keepShown, boolean saveState) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002639 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002640 Bundle state = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641 if (r != null) {
2642 if (!keepShown && r.stopped) {
2643 if (r.activity.mFinished) {
2644 // If we are finishing, we won't call onResume() in certain
2645 // cases. So here we likewise don't want to call onStop()
2646 // if the activity isn't resumed.
2647 return;
2648 }
2649 RuntimeException e = new RuntimeException(
2650 "Performing stop of activity that is not resumed: "
2651 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002652 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653 }
2654
2655 if (info != null) {
2656 try {
2657 // First create a thumbnail for the activity...
Jim Miller0b2a6d02010-07-13 18:01:29 -07002658 info.thumbnail = createThumbnailBitmap(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002659 info.description = r.activity.onCreateDescription();
2660 } catch (Exception e) {
2661 if (!mInstrumentation.onException(r.activity, e)) {
2662 throw new RuntimeException(
2663 "Unable to save state of activity "
2664 + r.intent.getComponent().toShortString()
2665 + ": " + e.toString(), e);
2666 }
2667 }
2668 }
2669
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002670 // Next have the activity save its current state and managed dialogs...
2671 if (!r.activity.mFinished && saveState) {
2672 if (r.state == null) {
2673 state = new Bundle();
2674 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2675 r.state = state;
2676 } else {
2677 state = r.state;
2678 }
2679 }
2680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002681 if (!keepShown) {
2682 try {
2683 // Now we are idle.
2684 r.activity.performStop();
2685 } catch (Exception e) {
2686 if (!mInstrumentation.onException(r.activity, e)) {
2687 throw new RuntimeException(
2688 "Unable to stop activity "
2689 + r.intent.getComponent().toShortString()
2690 + ": " + e.toString(), e);
2691 }
2692 }
2693 r.stopped = true;
2694 }
2695
2696 r.paused = true;
2697 }
2698 }
2699
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002700 private final void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002701 View v = r.activity.mDecor;
2702 if (v != null) {
2703 if (show) {
2704 if (!r.activity.mVisibleFromServer) {
2705 r.activity.mVisibleFromServer = true;
2706 mNumVisibleActivities++;
2707 if (r.activity.mVisibleFromClient) {
2708 r.activity.makeVisible();
2709 }
2710 }
2711 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002712 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002713 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002714 performConfigurationChanged(r.activity, r.newConfig);
2715 r.newConfig = null;
2716 }
2717 } else {
2718 if (r.activity.mVisibleFromServer) {
2719 r.activity.mVisibleFromServer = false;
2720 mNumVisibleActivities--;
2721 v.setVisibility(View.INVISIBLE);
2722 }
2723 }
2724 }
2725 }
2726
2727 private final void handleStopActivity(IBinder token, boolean show, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002728 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 r.activity.mConfigChangeFlags |= configChanges;
2730
2731 StopInfo info = new StopInfo();
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002732 performStopActivityInner(r, info, show, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002733
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002734 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002735 TAG, "Finishing stop of " + r + ": show=" + show
2736 + " win=" + r.window);
2737
2738 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07002739
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002740 // Make sure any pending writes are now committed.
2741 if (!r.isPreHoneycomb()) {
2742 QueuedWork.waitToFinish();
2743 }
2744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002745 // Tell activity manager we have been stopped.
2746 try {
2747 ActivityManagerNative.getDefault().activityStopped(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002748 r.token, r.state, info.thumbnail, info.description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002749 } catch (RemoteException ex) {
2750 }
2751 }
2752
2753 final void performRestartActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002754 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002755 if (r.stopped) {
2756 r.activity.performRestart();
2757 r.stopped = false;
2758 }
2759 }
2760
2761 private final void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002762 ActivityClientRecord r = mActivities.get(token);
Dianne Hackbornbfddc0f2010-12-14 11:28:01 -08002763
2764 if (r == null) {
2765 Log.w(TAG, "handleWindowVisibility: no activity for token " + token);
2766 return;
2767 }
2768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 if (!show && !r.stopped) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002770 performStopActivityInner(r, null, show, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002771 } else if (show && r.stopped) {
2772 // If we are getting ready to gc after going to the background, well
2773 // we are back active so skip it.
2774 unscheduleGcIdler();
2775
2776 r.activity.performRestart();
2777 r.stopped = false;
2778 }
2779 if (r.activity.mDecor != null) {
Joe Onorato43a17652011-04-06 19:22:23 -07002780 if (false) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781 TAG, "Handle window " + r + " visibility: " + show);
2782 updateVisibility(r, show);
2783 }
2784 }
2785
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002786 private final void handleSleeping(IBinder token, boolean sleeping) {
2787 ActivityClientRecord r = mActivities.get(token);
2788
2789 if (r == null) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08002790 Log.w(TAG, "handleSleeping: no activity for token " + token);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002791 return;
2792 }
2793
2794 if (sleeping) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08002795 if (!r.stopped && !r.isPreHoneycomb()) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002796 try {
2797 // Now we are idle.
2798 r.activity.performStop();
2799 } catch (Exception e) {
2800 if (!mInstrumentation.onException(r.activity, e)) {
2801 throw new RuntimeException(
2802 "Unable to stop activity "
2803 + r.intent.getComponent().toShortString()
2804 + ": " + e.toString(), e);
2805 }
2806 }
2807 r.stopped = true;
2808 }
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002809
2810 // Make sure any pending writes are now committed.
2811 if (!r.isPreHoneycomb()) {
2812 QueuedWork.waitToFinish();
2813 }
2814
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002815 // Tell activity manager we slept.
2816 try {
2817 ActivityManagerNative.getDefault().activitySlept(r.token);
2818 } catch (RemoteException ex) {
2819 }
2820 } else {
2821 if (r.stopped && r.activity.mVisibleFromServer) {
2822 r.activity.performRestart();
2823 r.stopped = false;
2824 }
2825 }
2826 }
2827
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08002828 private void handleSetCoreSettings(Bundle coreSettings) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08002829 synchronized (mPackages) {
2830 mCoreSettings = coreSettings;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08002831 }
2832 }
2833
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002834 private void handleUpdatePackageCompatibilityInfo(UpdateCompatibilityData data) {
2835 LoadedApk apk = peekPackageInfo(data.pkg, false);
2836 if (apk != null) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002837 apk.mCompatibilityInfo.set(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002838 }
2839 apk = peekPackageInfo(data.pkg, true);
2840 if (apk != null) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002841 apk.mCompatibilityInfo.set(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002842 }
2843 handleConfigurationChanged(mConfiguration, data.info);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002844 WindowManagerImpl.getDefault().reportNewConfiguration(mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002845 }
2846
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002847 private final void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 final int N = results.size();
2849 for (int i=0; i<N; i++) {
2850 ResultInfo ri = results.get(i);
2851 try {
2852 if (ri.mData != null) {
2853 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
2854 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002855 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07002856 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 r.activity.dispatchActivityResult(ri.mResultWho,
2858 ri.mRequestCode, ri.mResultCode, ri.mData);
2859 } catch (Exception e) {
2860 if (!mInstrumentation.onException(r.activity, e)) {
2861 throw new RuntimeException(
2862 "Failure delivering result " + ri + " to activity "
2863 + r.intent.getComponent().toShortString()
2864 + ": " + e.toString(), e);
2865 }
2866 }
2867 }
2868 }
2869
2870 private final void handleSendResult(ResultData res) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002871 ActivityClientRecord r = mActivities.get(res.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002872 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 if (r != null) {
2874 final boolean resumed = !r.paused;
2875 if (!r.activity.mFinished && r.activity.mDecor != null
2876 && r.hideForNow && resumed) {
2877 // We had hidden the activity because it started another
2878 // one... we have gotten a result back and we are not
2879 // paused, so make sure our window is visible.
2880 updateVisibility(r, true);
2881 }
2882 if (resumed) {
2883 try {
2884 // Now we are idle.
2885 r.activity.mCalled = false;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002886 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002887 mInstrumentation.callActivityOnPause(r.activity);
2888 if (!r.activity.mCalled) {
2889 throw new SuperNotCalledException(
2890 "Activity " + r.intent.getComponent().toShortString()
2891 + " did not call through to super.onPause()");
2892 }
2893 } catch (SuperNotCalledException e) {
2894 throw e;
2895 } catch (Exception e) {
2896 if (!mInstrumentation.onException(r.activity, e)) {
2897 throw new RuntimeException(
2898 "Unable to pause activity "
2899 + r.intent.getComponent().toShortString()
2900 + ": " + e.toString(), e);
2901 }
2902 }
2903 }
2904 deliverResults(r, res.results);
2905 if (resumed) {
Dianne Hackbornb46ed762011-06-02 18:33:15 -07002906 r.activity.performResume();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002907 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002908 }
2909 }
2910 }
2911
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002912 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 return performDestroyActivity(token, finishing, 0, false);
2914 }
2915
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002916 private final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002918 ActivityClientRecord r = mActivities.get(token);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002919 Class activityClass = null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002920 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002921 if (r != null) {
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002922 activityClass = r.activity.getClass();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002923 r.activity.mConfigChangeFlags |= configChanges;
2924 if (finishing) {
2925 r.activity.mFinished = true;
2926 }
2927 if (!r.paused) {
2928 try {
2929 r.activity.mCalled = false;
2930 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07002931 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 r.activity.getComponentName().getClassName());
2933 if (!r.activity.mCalled) {
2934 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002935 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936 + " did not call through to super.onPause()");
2937 }
2938 } catch (SuperNotCalledException e) {
2939 throw e;
2940 } catch (Exception e) {
2941 if (!mInstrumentation.onException(r.activity, e)) {
2942 throw new RuntimeException(
2943 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002944 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002945 + ": " + e.toString(), e);
2946 }
2947 }
2948 r.paused = true;
2949 }
2950 if (!r.stopped) {
2951 try {
2952 r.activity.performStop();
2953 } catch (SuperNotCalledException e) {
2954 throw e;
2955 } catch (Exception e) {
2956 if (!mInstrumentation.onException(r.activity, e)) {
2957 throw new RuntimeException(
2958 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002959 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002960 + ": " + e.toString(), e);
2961 }
2962 }
2963 r.stopped = true;
2964 }
2965 if (getNonConfigInstance) {
2966 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002967 r.lastNonConfigurationInstances
2968 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002969 } catch (Exception e) {
2970 if (!mInstrumentation.onException(r.activity, e)) {
2971 throw new RuntimeException(
2972 "Unable to retain activity "
2973 + r.intent.getComponent().toShortString()
2974 + ": " + e.toString(), e);
2975 }
2976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002977 }
2978 try {
2979 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07002980 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002981 if (!r.activity.mCalled) {
2982 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002983 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002984 " did not call through to super.onDestroy()");
2985 }
2986 if (r.window != null) {
2987 r.window.closeAllPanels();
2988 }
2989 } catch (SuperNotCalledException e) {
2990 throw e;
2991 } catch (Exception e) {
2992 if (!mInstrumentation.onException(r.activity, e)) {
2993 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002994 "Unable to destroy activity " + safeToComponentShortString(r.intent)
2995 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002996 }
2997 }
2998 }
2999 mActivities.remove(token);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003000 StrictMode.decrementExpectedActivityCount(activityClass);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003001 return r;
3002 }
3003
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003004 private static String safeToComponentShortString(Intent intent) {
3005 ComponentName component = intent.getComponent();
3006 return component == null ? "[Unknown]" : component.toShortString();
3007 }
3008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003009 private final void handleDestroyActivity(IBinder token, boolean finishing,
3010 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003011 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003012 configChanges, getNonConfigInstance);
3013 if (r != null) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003014 cleanUpPendingRemoveWindows(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003015 WindowManager wm = r.activity.getWindowManager();
3016 View v = r.activity.mDecor;
3017 if (v != null) {
3018 if (r.activity.mVisibleFromServer) {
3019 mNumVisibleActivities--;
3020 }
3021 IBinder wtoken = v.getWindowToken();
3022 if (r.activity.mWindowAdded) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003023 if (r.onlyLocalRequest) {
3024 // Hold off on removing this until the new activity's
3025 // window is being added.
3026 r.mPendingRemoveWindow = v;
3027 r.mPendingRemoveWindowManager = wm;
3028 } else {
3029 wm.removeViewImmediate(v);
3030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003032 if (wtoken != null && r.mPendingRemoveWindow == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033 WindowManagerImpl.getDefault().closeAll(wtoken,
3034 r.activity.getClass().getName(), "Activity");
3035 }
3036 r.activity.mDecor = null;
3037 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003038 if (r.mPendingRemoveWindow == null) {
3039 // If we are delaying the removal of the activity window, then
3040 // we can't clean up all windows here. Note that we can't do
3041 // so later either, which means any windows that aren't closed
3042 // by the app will leak. Well we try to warning them a lot
3043 // about leaking windows, because that is a bug, so if they are
3044 // using this recreate facility then they get to live with leaks.
3045 WindowManagerImpl.getDefault().closeAll(token,
3046 r.activity.getClass().getName(), "Activity");
3047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003048
3049 // Mocked out contexts won't be participating in the normal
3050 // process lifecycle, but if we're running with a proper
3051 // ApplicationContext we need to have it tear down things
3052 // cleanly.
3053 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08003054 if (c instanceof ContextImpl) {
3055 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003056 r.activity.getClass().getName(), "Activity");
3057 }
3058 }
3059 if (finishing) {
3060 try {
3061 ActivityManagerNative.getDefault().activityDestroyed(token);
3062 } catch (RemoteException ex) {
3063 // If the system process has died, it's game over for everyone.
3064 }
3065 }
3066 }
3067
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003068 public final void requestRelaunchActivity(IBinder token,
3069 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
3070 int configChanges, boolean notResumed, Configuration config,
3071 boolean fromServer) {
3072 ActivityClientRecord target = null;
3073
3074 synchronized (mPackages) {
3075 for (int i=0; i<mRelaunchingActivities.size(); i++) {
3076 ActivityClientRecord r = mRelaunchingActivities.get(i);
3077 if (r.token == token) {
3078 target = r;
3079 if (pendingResults != null) {
3080 if (r.pendingResults != null) {
3081 r.pendingResults.addAll(pendingResults);
3082 } else {
3083 r.pendingResults = pendingResults;
3084 }
3085 }
3086 if (pendingNewIntents != null) {
3087 if (r.pendingIntents != null) {
3088 r.pendingIntents.addAll(pendingNewIntents);
3089 } else {
3090 r.pendingIntents = pendingNewIntents;
3091 }
3092 }
3093 break;
3094 }
3095 }
3096
3097 if (target == null) {
3098 target = new ActivityClientRecord();
3099 target.token = token;
3100 target.pendingResults = pendingResults;
3101 target.pendingIntents = pendingNewIntents;
3102 if (!fromServer) {
3103 ActivityClientRecord existing = mActivities.get(token);
3104 if (existing != null) {
3105 target.startsNotResumed = existing.paused;
3106 }
3107 target.onlyLocalRequest = true;
3108 }
3109 mRelaunchingActivities.add(target);
3110 queueOrSendMessage(H.RELAUNCH_ACTIVITY, target);
3111 }
3112
3113 if (fromServer) {
3114 target.startsNotResumed = notResumed;
3115 target.onlyLocalRequest = false;
3116 }
3117 if (config != null) {
3118 target.createdConfig = config;
3119 }
3120 target.pendingConfigChanges |= configChanges;
3121 }
3122 }
3123
3124 private final void handleRelaunchActivity(ActivityClientRecord tmp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003125 // If we are getting ready to gc after going to the background, well
3126 // we are back active so skip it.
3127 unscheduleGcIdler();
3128
3129 Configuration changedConfig = null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003130 int configChanges = 0;
Bob Leee5408332009-09-04 18:31:17 -07003131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003132 // First: make sure we have the most recent configuration and most
3133 // recent version of the activity, or skip it if some previous call
3134 // had taken a more recent version.
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003135 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 int N = mRelaunchingActivities.size();
3137 IBinder token = tmp.token;
3138 tmp = null;
3139 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003140 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003141 if (r.token == token) {
3142 tmp = r;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003143 configChanges |= tmp.pendingConfigChanges;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003144 mRelaunchingActivities.remove(i);
3145 i--;
3146 N--;
3147 }
3148 }
Bob Leee5408332009-09-04 18:31:17 -07003149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003150 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003151 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003152 return;
3153 }
Bob Leee5408332009-09-04 18:31:17 -07003154
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003155 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
3156 + tmp.token + " with configChanges=0x"
3157 + Integer.toHexString(configChanges));
3158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003159 if (mPendingConfiguration != null) {
3160 changedConfig = mPendingConfiguration;
3161 mPendingConfiguration = null;
3162 }
3163 }
Bob Leee5408332009-09-04 18:31:17 -07003164
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003165 if (tmp.createdConfig != null) {
3166 // If the activity manager is passing us its current config,
3167 // assume that is really what we want regardless of what we
3168 // may have pending.
3169 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003170 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
3171 && mConfiguration.diff(tmp.createdConfig) != 0)) {
3172 if (changedConfig == null
3173 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
3174 changedConfig = tmp.createdConfig;
3175 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003176 }
3177 }
3178
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003179 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003180 + tmp.token + ": changedConfig=" + changedConfig);
3181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182 // If there was a pending configuration change, execute it first.
3183 if (changedConfig != null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003184 handleConfigurationChanged(changedConfig, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003185 }
Bob Leee5408332009-09-04 18:31:17 -07003186
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003187 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003188 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003189 if (r == null) {
3190 return;
3191 }
Bob Leee5408332009-09-04 18:31:17 -07003192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003193 r.activity.mConfigChangeFlags |= configChanges;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003194 r.onlyLocalRequest = tmp.onlyLocalRequest;
Christopher Tateb70f3df2009-04-07 16:07:59 -07003195 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07003196
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003197 r.activity.mChangingConfigurations = true;
3198
Dianne Hackborne2b04802010-12-09 09:24:55 -08003199 // Need to ensure state is saved.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003200 if (!r.paused) {
Dianne Hackborne2b04802010-12-09 09:24:55 -08003201 performPauseActivity(r.token, false, r.isPreHoneycomb());
3202 }
3203 if (r.state == null && !r.stopped && !r.isPreHoneycomb()) {
3204 r.state = new Bundle();
3205 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003206 }
Bob Leee5408332009-09-04 18:31:17 -07003207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003208 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07003209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 r.activity = null;
3211 r.window = null;
3212 r.hideForNow = false;
3213 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07003214 // Merge any pending results and pending intents; don't just replace them
3215 if (tmp.pendingResults != null) {
3216 if (r.pendingResults == null) {
3217 r.pendingResults = tmp.pendingResults;
3218 } else {
3219 r.pendingResults.addAll(tmp.pendingResults);
3220 }
3221 }
3222 if (tmp.pendingIntents != null) {
3223 if (r.pendingIntents == null) {
3224 r.pendingIntents = tmp.pendingIntents;
3225 } else {
3226 r.pendingIntents.addAll(tmp.pendingIntents);
3227 }
3228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003229 r.startsNotResumed = tmp.startsNotResumed;
Bob Leee5408332009-09-04 18:31:17 -07003230
Christopher Tateb70f3df2009-04-07 16:07:59 -07003231 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003232 }
3233
3234 private final void handleRequestThumbnail(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003235 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003236 Bitmap thumbnail = createThumbnailBitmap(r);
3237 CharSequence description = null;
3238 try {
3239 description = r.activity.onCreateDescription();
3240 } catch (Exception e) {
3241 if (!mInstrumentation.onException(r.activity, e)) {
3242 throw new RuntimeException(
3243 "Unable to create description of activity "
3244 + r.intent.getComponent().toShortString()
3245 + ": " + e.toString(), e);
3246 }
3247 }
3248 //System.out.println("Reporting top thumbnail " + thumbnail);
3249 try {
3250 ActivityManagerNative.getDefault().reportThumbnail(
3251 token, thumbnail, description);
3252 } catch (RemoteException ex) {
3253 }
3254 }
3255
3256 ArrayList<ComponentCallbacks> collectComponentCallbacksLocked(
3257 boolean allActivities, Configuration newConfig) {
3258 ArrayList<ComponentCallbacks> callbacks
3259 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07003260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003261 if (mActivities.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003262 Iterator<ActivityClientRecord> it = mActivities.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003263 while (it.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003264 ActivityClientRecord ar = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003265 Activity a = ar.activity;
3266 if (a != null) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003267 Configuration thisConfig = applyConfigCompatMainThread(newConfig,
3268 ar.packageInfo.mCompatibilityInfo.getIfNeeded());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003269 if (!ar.activity.mFinished && (allActivities ||
3270 (a != null && !ar.paused))) {
3271 // If the activity is currently resumed, its configuration
3272 // needs to change right now.
3273 callbacks.add(a);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003274 } else if (thisConfig != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003275 // Otherwise, we will tell it about the change
3276 // the next time it is resumed or shown. Note that
3277 // the activity manager may, before then, decide the
3278 // activity needs to be destroyed to handle its new
3279 // configuration.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003280 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Setting activity "
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003281 + ar.activityInfo.name + " newConfig=" + thisConfig);
3282 ar.newConfig = thisConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003283 }
3284 }
3285 }
3286 }
3287 if (mServices.size() > 0) {
3288 Iterator<Service> it = mServices.values().iterator();
3289 while (it.hasNext()) {
3290 callbacks.add(it.next());
3291 }
3292 }
3293 synchronized (mProviderMap) {
3294 if (mLocalProviders.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003295 Iterator<ProviderClientRecord> it = mLocalProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003296 while (it.hasNext()) {
3297 callbacks.add(it.next().mLocalProvider);
3298 }
3299 }
3300 }
3301 final int N = mAllApplications.size();
3302 for (int i=0; i<N; i++) {
3303 callbacks.add(mAllApplications.get(i));
3304 }
Bob Leee5408332009-09-04 18:31:17 -07003305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306 return callbacks;
3307 }
Bob Leee5408332009-09-04 18:31:17 -07003308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 private final void performConfigurationChanged(
3310 ComponentCallbacks cb, Configuration config) {
3311 // Only for Activity objects, check that they actually call up to their
3312 // superclass implementation. ComponentCallbacks is an interface, so
3313 // we check the runtime type and act accordingly.
3314 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
3315 if (activity != null) {
3316 activity.mCalled = false;
3317 }
Bob Leee5408332009-09-04 18:31:17 -07003318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 boolean shouldChangeConfig = false;
3320 if ((activity == null) || (activity.mCurrentConfig == null)) {
3321 shouldChangeConfig = true;
3322 } else {
Bob Leee5408332009-09-04 18:31:17 -07003323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003324 // If the new config is the same as the config this Activity
3325 // is already running with then don't bother calling
3326 // onConfigurationChanged
3327 int diff = activity.mCurrentConfig.diff(config);
3328 if (diff != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329 // If this activity doesn't handle any of the config changes
3330 // then don't bother calling onConfigurationChanged as we're
3331 // going to destroy it.
Dianne Hackborne6676352011-06-01 16:51:20 -07003332 if ((~activity.mActivityInfo.getRealConfigChanged() & diff) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003333 shouldChangeConfig = true;
3334 }
3335 }
3336 }
Bob Leee5408332009-09-04 18:31:17 -07003337
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003338 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003339 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003340 if (shouldChangeConfig) {
3341 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07003342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003343 if (activity != null) {
3344 if (!activity.mCalled) {
3345 throw new SuperNotCalledException(
3346 "Activity " + activity.getLocalClassName() +
3347 " did not call through to super.onConfigurationChanged()");
3348 }
3349 activity.mConfigChangeFlags = 0;
3350 activity.mCurrentConfig = new Configuration(config);
3351 }
3352 }
3353 }
3354
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07003355 public final void applyConfigurationToResources(Configuration config) {
3356 synchronized (mPackages) {
3357 applyConfigurationToResourcesLocked(config, null);
3358 }
3359 }
3360
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003361 final boolean applyConfigurationToResourcesLocked(Configuration config,
3362 CompatibilityInfo compat) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003363 if (mResConfiguration == null) {
3364 mResConfiguration = new Configuration();
3365 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003366 if (!mResConfiguration.isOtherSeqNewer(config) && compat == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003367 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq="
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003368 + mResConfiguration.seq + ", newSeq=" + config.seq);
Dianne Hackbornae078162010-03-18 11:29:37 -07003369 return false;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003370 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003371 int changes = mResConfiguration.updateFrom(config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003372 DisplayMetrics dm = getDisplayMetricsLocked(compat, true);
3373
3374 if (compat != null && (mResCompatibilityInfo == null ||
3375 !mResCompatibilityInfo.equals(compat))) {
3376 mResCompatibilityInfo = compat;
3377 changes |= ActivityInfo.CONFIG_SCREEN_LAYOUT
3378 | ActivityInfo.CONFIG_SCREEN_SIZE
3379 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3380 }
Bob Leee5408332009-09-04 18:31:17 -07003381
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003382 // set it for java, this also affects newly created Resources
3383 if (config.locale != null) {
3384 Locale.setDefault(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003385 }
Bob Leee5408332009-09-04 18:31:17 -07003386
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003387 Resources.updateSystemConfiguration(config, dm, compat);
Bob Leee5408332009-09-04 18:31:17 -07003388
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003389 ApplicationPackageManager.configurationChanged();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003390 //Slog.i(TAG, "Configuration changed in " + currentPackageName());
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003391
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003392 Iterator<WeakReference<Resources>> it =
3393 mActiveResources.values().iterator();
3394 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
3395 // mActiveResources.entrySet().iterator();
3396 while (it.hasNext()) {
3397 WeakReference<Resources> v = it.next();
3398 Resources r = v.get();
3399 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003400 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources "
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003401 + r + " config to: " + config);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003402 r.updateConfiguration(config, dm, compat);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003403 //Slog.i(TAG, "Updated app resources " + v.getKey()
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003404 // + " " + r + ": " + r.getConfiguration());
3405 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003406 //Slog.i(TAG, "Removing old resources " + v.getKey());
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003407 it.remove();
3408 }
3409 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003410
3411 return changes != 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003412 }
3413
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003414 final void handleConfigurationChanged(Configuration config, CompatibilityInfo compat) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003415
3416 ArrayList<ComponentCallbacks> callbacks = null;
3417
3418 synchronized (mPackages) {
3419 if (mPendingConfiguration != null) {
3420 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
3421 config = mPendingConfiguration;
3422 }
3423 mPendingConfiguration = null;
3424 }
3425
3426 if (config == null) {
3427 return;
3428 }
3429
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003430 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003431 + config);
3432
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003433 applyConfigurationToResourcesLocked(config, compat);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 if (mConfiguration == null) {
3436 mConfiguration = new Configuration();
3437 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003438 if (!mConfiguration.isOtherSeqNewer(config) && compat == null) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003439 return;
3440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003441 mConfiguration.updateFrom(config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003442 if (mCompatConfiguration == null) {
3443 mCompatConfiguration = new Configuration();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003444 }
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003445 mCompatConfiguration.setTo(mConfiguration);
3446 if (mResCompatibilityInfo != null && !mResCompatibilityInfo.supportsScreen()) {
3447 mResCompatibilityInfo.applyToConfiguration(mCompatConfiguration);
3448 config = mCompatConfiguration;
3449 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003450 callbacks = collectComponentCallbacksLocked(false, config);
3451 }
Bob Leee5408332009-09-04 18:31:17 -07003452
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003453 if (callbacks != null) {
3454 final int N = callbacks.size();
3455 for (int i=0; i<N; i++) {
3456 performConfigurationChanged(callbacks.get(i), config);
3457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003458 }
3459 }
3460
3461 final void handleActivityConfigurationChanged(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003462 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003463 if (r == null || r.activity == null) {
3464 return;
3465 }
Bob Leee5408332009-09-04 18:31:17 -07003466
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003467 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003468 + r.activityInfo.name);
3469
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003470 performConfigurationChanged(r.activity, mCompatConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003471 }
3472
Romain Guy7eabe552011-07-21 14:56:34 -07003473 final void handleProfilerControl(boolean start, ProfilerControlData pcd, int profileType) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003474 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003475 try {
Romain Guy7eabe552011-07-21 14:56:34 -07003476 switch (profileType) {
3477 case 1:
3478 ViewDebug.startLooperProfiling(pcd.path, pcd.fd.getFileDescriptor());
3479 break;
3480 default:
3481 Debug.startMethodTracing(pcd.path, pcd.fd.getFileDescriptor(),
3482 8 * 1024 * 1024, 0);
3483 break;
3484 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003485 } catch (RuntimeException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003486 Slog.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003487 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003488 } finally {
3489 try {
3490 pcd.fd.close();
3491 } catch (IOException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003492 Slog.w(TAG, "Failure closing profile fd", e);
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003493 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003494 }
3495 } else {
Romain Guy7eabe552011-07-21 14:56:34 -07003496 switch (profileType) {
3497 case 1:
3498 ViewDebug.stopLooperProfiling();
3499 break;
3500 default:
3501 Debug.stopMethodTracing();
3502 break;
3503
3504 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003505 }
3506 }
Bob Leee5408332009-09-04 18:31:17 -07003507
Andy McFadden824c5102010-07-09 16:26:57 -07003508 final void handleDumpHeap(boolean managed, DumpHeapData dhd) {
3509 if (managed) {
3510 try {
3511 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor());
3512 } catch (IOException e) {
3513 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
3514 + " -- can the process access this path?");
3515 } finally {
3516 try {
3517 dhd.fd.close();
3518 } catch (IOException e) {
3519 Slog.w(TAG, "Failure closing profile fd", e);
3520 }
3521 }
3522 } else {
Andy McFadden06a6b552010-07-13 16:28:09 -07003523 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07003524 }
3525 }
3526
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003527 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
3528 boolean hasPkgInfo = false;
3529 if (packages != null) {
3530 for (int i=packages.length-1; i>=0; i--) {
3531 //Slog.i(TAG, "Cleaning old package: " + packages[i]);
3532 if (!hasPkgInfo) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003533 WeakReference<LoadedApk> ref;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003534 ref = mPackages.get(packages[i]);
3535 if (ref != null && ref.get() != null) {
3536 hasPkgInfo = true;
3537 } else {
3538 ref = mResourcePackages.get(packages[i]);
3539 if (ref != null && ref.get() != null) {
3540 hasPkgInfo = true;
3541 }
3542 }
3543 }
3544 mPackages.remove(packages[i]);
3545 mResourcePackages.remove(packages[i]);
3546 }
3547 }
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003548 ApplicationPackageManager.handlePackageBroadcast(cmd, packages,
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003549 hasPkgInfo);
3550 }
3551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003552 final void handleLowMemory() {
Brian Carlstromed7e0072011-03-24 13:27:57 -07003553 ArrayList<ComponentCallbacks> callbacks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003554
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003555 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003556 callbacks = collectComponentCallbacksLocked(true, null);
3557 }
Bob Leee5408332009-09-04 18:31:17 -07003558
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003559 final int N = callbacks.size();
3560 for (int i=0; i<N; i++) {
3561 callbacks.get(i).onLowMemory();
3562 }
3563
Chris Tatece229052009-03-25 16:44:52 -07003564 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3565 if (Process.myUid() != Process.SYSTEM_UID) {
3566 int sqliteReleased = SQLiteDatabase.releaseMemory();
3567 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3568 }
Bob Leee5408332009-09-04 18:31:17 -07003569
Mike Reedcaf0df12009-04-27 14:32:05 -04003570 // Ask graphics to free up as much as possible (font/image caches)
3571 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003572
3573 BinderInternal.forceGc("mem");
3574 }
3575
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003576 final void handleTrimMemory(int level) {
Romain Guybdf76092011-07-18 15:00:43 -07003577 WindowManagerImpl.getDefault().trimMemory(level);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003578 }
3579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003580 private final void handleBindApplication(AppBindData data) {
3581 mBoundApplication = data;
3582 mConfiguration = new Configuration(data.config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003583 mCompatConfiguration = new Configuration(data.config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003585 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003586 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003587 android.ddm.DdmHandleAppName.setAppName(data.processName);
3588
Joe Onoratod630f102011-03-17 18:42:26 -07003589 // If the app is Honeycomb MR1 or earlier, switch its AsyncTask
3590 // implementation to use the pool executor. Normally, we use the
3591 // serialized executor as the default. This has to happen in the
3592 // main thread so the main looper is set right.
3593 if (data.appInfo.targetSdkVersion <= 12) {
3594 AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
3595 }
3596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003597 /*
3598 * Before spawning a new process, reset the time zone to be the system time zone.
3599 * This needs to be done because the system time zone could have changed after the
3600 * the spawning of this process. Without doing this this process would have the incorrect
3601 * system time zone.
3602 */
3603 TimeZone.setDefault(null);
3604
3605 /*
3606 * Initialize the default locale in this process for the reasons we set the time zone.
3607 */
3608 Locale.setDefault(data.config.locale);
3609
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003610 /*
3611 * Update the system configuration since its preloaded and might not
3612 * reflect configuration changes. The configuration object passed
3613 * in AppBindData can be safely assumed to be up to date
3614 */
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07003615 applyConfigurationToResourcesLocked(data.config, data.compatInfo);
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003616
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003617 data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003618
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003619 /**
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003620 * For system applications on userdebug/eng builds, log stack
3621 * traces of disk and network access to dropbox for analysis.
3622 */
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07003623 if ((data.appInfo.flags &
3624 (ApplicationInfo.FLAG_SYSTEM |
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07003625 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0) {
3626 StrictMode.conditionallyEnableDebugLogging();
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003627 }
3628
3629 /**
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07003630 * For apps targetting SDK Honeycomb or later, we don't allow
3631 * network usage on the main event loop / UI thread.
3632 *
3633 * Note to those grepping: this is what ultimately throws
3634 * NetworkOnMainThreadException ...
3635 */
3636 if (data.appInfo.targetSdkVersion > 9) {
3637 StrictMode.enableDeathOnNetwork();
3638 }
3639
3640 /**
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003641 * Switch this process to density compatibility mode if needed.
3642 */
3643 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3644 == 0) {
3645 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3646 }
Bob Leee5408332009-09-04 18:31:17 -07003647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003648 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3649 // XXX should have option to change the port.
3650 Debug.changeDebugPort(8100);
3651 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003652 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003653 + " is waiting for the debugger on port 8100...");
3654
3655 IActivityManager mgr = ActivityManagerNative.getDefault();
3656 try {
3657 mgr.showWaitingForDebugger(mAppThread, true);
3658 } catch (RemoteException ex) {
3659 }
3660
3661 Debug.waitForDebugger();
3662
3663 try {
3664 mgr.showWaitingForDebugger(mAppThread, false);
3665 } catch (RemoteException ex) {
3666 }
3667
3668 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003669 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003670 + " can be debugged on port 8100...");
3671 }
3672 }
3673
Robert Greenwalt434203a2010-10-11 16:00:27 -07003674 /**
3675 * Initialize the default http proxy in this process for the reasons we set the time zone.
3676 */
3677 IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
3678 IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
3679 try {
3680 ProxyProperties proxyProperties = service.getProxy();
3681 Proxy.setHttpProxySystemProperty(proxyProperties);
3682 } catch (RemoteException e) {}
3683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003684 if (data.instrumentationName != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08003685 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003686 appContext.init(data.info, null, this);
3687 InstrumentationInfo ii = null;
3688 try {
3689 ii = appContext.getPackageManager().
3690 getInstrumentationInfo(data.instrumentationName, 0);
3691 } catch (PackageManager.NameNotFoundException e) {
3692 }
3693 if (ii == null) {
3694 throw new RuntimeException(
3695 "Unable to find instrumentation info for: "
3696 + data.instrumentationName);
3697 }
3698
3699 mInstrumentationAppDir = ii.sourceDir;
3700 mInstrumentationAppPackage = ii.packageName;
3701 mInstrumentedAppDir = data.info.getAppDir();
3702
3703 ApplicationInfo instrApp = new ApplicationInfo();
3704 instrApp.packageName = ii.packageName;
3705 instrApp.sourceDir = ii.sourceDir;
3706 instrApp.publicSourceDir = ii.publicSourceDir;
3707 instrApp.dataDir = ii.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003708 instrApp.nativeLibraryDir = ii.nativeLibraryDir;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003709 LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003710 appContext.getClassLoader(), false, true);
Dianne Hackborn21556372010-02-04 16:34:40 -08003711 ContextImpl instrContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003712 instrContext.init(pi, null, this);
3713
3714 try {
3715 java.lang.ClassLoader cl = instrContext.getClassLoader();
3716 mInstrumentation = (Instrumentation)
3717 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3718 } catch (Exception e) {
3719 throw new RuntimeException(
3720 "Unable to instantiate instrumentation "
3721 + data.instrumentationName + ": " + e.toString(), e);
3722 }
3723
3724 mInstrumentation.init(this, instrContext, appContext,
3725 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3726
3727 if (data.profileFile != null && !ii.handleProfiling) {
3728 data.handlingProfiling = true;
3729 File file = new File(data.profileFile);
3730 file.getParentFile().mkdirs();
3731 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3732 }
3733
3734 try {
3735 mInstrumentation.onCreate(data.instrumentationArgs);
3736 }
3737 catch (Exception e) {
3738 throw new RuntimeException(
3739 "Exception thrown in onCreate() of "
3740 + data.instrumentationName + ": " + e.toString(), e);
3741 }
3742
3743 } else {
3744 mInstrumentation = new Instrumentation();
3745 }
3746
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08003747 if ((data.appInfo.flags&ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
Dianne Hackbornde398512011-01-18 18:45:21 -08003748 dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08003749 }
3750
Christopher Tate181fafa2009-05-14 11:12:14 -07003751 // If the app is being launched for full backup or restore, bring it up in
3752 // a restricted environment with the base application class.
Dianne Hackborn0be1f782009-11-09 12:30:12 -08003753 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003754 mInitialApplication = app;
3755
Christopher Tate75a99702011-05-18 16:28:19 -07003756 // don't bring up providers in restricted mode; they may depend on the
3757 // app's custom Application class
3758 if (!data.restrictedBackupMode){
3759 List<ProviderInfo> providers = data.providers;
3760 if (providers != null) {
3761 installContentProviders(app, providers);
3762 // For process that contains content providers, we want to
3763 // ensure that the JIT is enabled "at some point".
3764 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
3765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003766 }
3767
3768 try {
3769 mInstrumentation.callApplicationOnCreate(app);
3770 } catch (Exception e) {
3771 if (!mInstrumentation.onException(app, e)) {
3772 throw new RuntimeException(
3773 "Unable to create application " + app.getClass().getName()
3774 + ": " + e.toString(), e);
3775 }
3776 }
3777 }
3778
3779 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
3780 IActivityManager am = ActivityManagerNative.getDefault();
3781 if (mBoundApplication.profileFile != null && mBoundApplication.handlingProfiling) {
3782 Debug.stopMethodTracing();
3783 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003784 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003785 // + ", app thr: " + mAppThread);
3786 try {
3787 am.finishInstrumentation(mAppThread, resultCode, results);
3788 } catch (RemoteException ex) {
3789 }
3790 }
3791
3792 private final void installContentProviders(
3793 Context context, List<ProviderInfo> providers) {
3794 final ArrayList<IActivityManager.ContentProviderHolder> results =
3795 new ArrayList<IActivityManager.ContentProviderHolder>();
3796
3797 Iterator<ProviderInfo> i = providers.iterator();
3798 while (i.hasNext()) {
3799 ProviderInfo cpi = i.next();
3800 StringBuilder buf = new StringBuilder(128);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07003801 buf.append("Pub ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003802 buf.append(cpi.authority);
3803 buf.append(": ");
3804 buf.append(cpi.name);
3805 Log.i(TAG, buf.toString());
3806 IContentProvider cp = installProvider(context, null, cpi, false);
3807 if (cp != null) {
3808 IActivityManager.ContentProviderHolder cph =
3809 new IActivityManager.ContentProviderHolder(cpi);
3810 cph.provider = cp;
3811 results.add(cph);
3812 // Don't ever unload this provider from the process.
3813 synchronized(mProviderMap) {
3814 mProviderRefCountMap.put(cp.asBinder(), new ProviderRefCount(10000));
3815 }
3816 }
3817 }
3818
3819 try {
3820 ActivityManagerNative.getDefault().publishContentProviders(
3821 getApplicationThread(), results);
3822 } catch (RemoteException ex) {
3823 }
3824 }
3825
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003826 private final IContentProvider getExistingProvider(Context context, String name) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003827 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003828 final ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003829 if (pr != null) {
3830 return pr.mProvider;
3831 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003832 return null;
3833 }
3834 }
3835
3836 private final IContentProvider getProvider(Context context, String name) {
3837 IContentProvider existing = getExistingProvider(context, name);
3838 if (existing != null) {
3839 return existing;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003840 }
3841
3842 IActivityManager.ContentProviderHolder holder = null;
3843 try {
3844 holder = ActivityManagerNative.getDefault().getContentProvider(
3845 getApplicationThread(), name);
3846 } catch (RemoteException ex) {
3847 }
3848 if (holder == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003849 Slog.e(TAG, "Failed to find provider info for " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003850 return null;
3851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003852
3853 IContentProvider prov = installProvider(context, holder.provider,
3854 holder.info, true);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003855 //Slog.i(TAG, "noReleaseNeeded=" + holder.noReleaseNeeded);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003856 if (holder.noReleaseNeeded || holder.provider == null) {
3857 // We are not going to release the provider if it is an external
3858 // provider that doesn't care about being released, or if it is
3859 // a local provider running in this process.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003860 //Slog.i(TAG, "*** NO RELEASE NEEDED");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003861 synchronized(mProviderMap) {
3862 mProviderRefCountMap.put(prov.asBinder(), new ProviderRefCount(10000));
3863 }
3864 }
3865 return prov;
3866 }
3867
3868 public final IContentProvider acquireProvider(Context c, String name) {
3869 IContentProvider provider = getProvider(c, name);
3870 if(provider == null)
3871 return null;
3872 IBinder jBinder = provider.asBinder();
3873 synchronized(mProviderMap) {
3874 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3875 if(prc == null) {
3876 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3877 } else {
3878 prc.count++;
3879 } //end else
3880 } //end synchronized
3881 return provider;
3882 }
3883
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003884 public final IContentProvider acquireExistingProvider(Context c, String name) {
3885 IContentProvider provider = getExistingProvider(c, name);
3886 if(provider == null)
3887 return null;
3888 IBinder jBinder = provider.asBinder();
3889 synchronized(mProviderMap) {
3890 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3891 if(prc == null) {
3892 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3893 } else {
3894 prc.count++;
3895 } //end else
3896 } //end synchronized
3897 return provider;
3898 }
3899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 public final boolean releaseProvider(IContentProvider provider) {
3901 if(provider == null) {
3902 return false;
3903 }
3904 IBinder jBinder = provider.asBinder();
3905 synchronized(mProviderMap) {
3906 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3907 if(prc == null) {
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003908 if(localLOGV) Slog.v(TAG, "releaseProvider::Weird shouldn't be here");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003909 return false;
3910 } else {
3911 prc.count--;
3912 if(prc.count == 0) {
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003913 // Schedule the actual remove asynchronously, since we
3914 // don't know the context this will be called in.
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003915 // TODO: it would be nice to post a delayed message, so
3916 // if we come back and need the same provider quickly
3917 // we will still have it available.
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003918 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
3919 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 } //end if
3921 } //end else
3922 } //end synchronized
3923 return true;
3924 }
3925
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003926 final void completeRemoveProvider(IContentProvider provider) {
3927 IBinder jBinder = provider.asBinder();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003928 String name = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003929 synchronized(mProviderMap) {
3930 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3931 if(prc != null && prc.count == 0) {
3932 mProviderRefCountMap.remove(jBinder);
3933 //invoke removeProvider to dereference provider
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003934 name = removeProviderLocked(provider);
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003935 }
3936 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003937
3938 if (name != null) {
3939 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003940 if(localLOGV) Slog.v(TAG, "removeProvider::Invoking " +
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003941 "ActivityManagerNative.removeContentProvider(" + name);
3942 ActivityManagerNative.getDefault().removeContentProvider(
3943 getApplicationThread(), name);
3944 } catch (RemoteException e) {
3945 //do nothing content provider object is dead any way
3946 } //end catch
3947 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003948 }
3949
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003950 public final String removeProviderLocked(IContentProvider provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003951 if (provider == null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003952 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003953 }
3954 IBinder providerBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003956 String name = null;
3957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003958 // remove the provider from mProviderMap
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003959 Iterator<ProviderClientRecord> iter = mProviderMap.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003960 while (iter.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003961 ProviderClientRecord pr = iter.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962 IBinder myBinder = pr.mProvider.asBinder();
3963 if (myBinder == providerBinder) {
3964 //find if its published by this process itself
3965 if(pr.mLocalProvider != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003966 if(localLOGV) Slog.i(TAG, "removeProvider::found local provider returning");
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003967 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003968 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003969 if(localLOGV) Slog.v(TAG, "removeProvider::Not local provider Unlinking " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003970 "death recipient");
3971 //content provider is in another process
3972 myBinder.unlinkToDeath(pr, 0);
3973 iter.remove();
3974 //invoke remove only once for the very first name seen
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003975 if(name == null) {
3976 name = pr.mName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003977 }
3978 } //end if myBinder
3979 } //end while iter
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003980
3981 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982 }
3983
3984 final void removeDeadProvider(String name, IContentProvider provider) {
3985 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003986 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003988 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003989 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003990 if (removed != null) {
3991 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003993 }
3994 }
3995 }
3996
3997 final void removeDeadProviderLocked(String name, IContentProvider provider) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003998 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004000 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004001 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07004002 if (removed != null) {
4003 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
4004 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004005 }
4006 }
4007
4008 private final IContentProvider installProvider(Context context,
4009 IContentProvider provider, ProviderInfo info, boolean noisy) {
4010 ContentProvider localProvider = null;
4011 if (provider == null) {
4012 if (noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004013 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004014 + info.name);
4015 }
4016 Context c = null;
4017 ApplicationInfo ai = info.applicationInfo;
4018 if (context.getPackageName().equals(ai.packageName)) {
4019 c = context;
4020 } else if (mInitialApplication != null &&
4021 mInitialApplication.getPackageName().equals(ai.packageName)) {
4022 c = mInitialApplication;
4023 } else {
4024 try {
4025 c = context.createPackageContext(ai.packageName,
4026 Context.CONTEXT_INCLUDE_CODE);
4027 } catch (PackageManager.NameNotFoundException e) {
4028 }
4029 }
4030 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004031 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032 ai.packageName +
4033 " while loading content provider " +
4034 info.name);
4035 return null;
4036 }
4037 try {
4038 final java.lang.ClassLoader cl = c.getClassLoader();
4039 localProvider = (ContentProvider)cl.
4040 loadClass(info.name).newInstance();
4041 provider = localProvider.getIContentProvider();
4042 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004043 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004044 info.name + " from sourceDir " +
4045 info.applicationInfo.sourceDir);
4046 return null;
4047 }
Joe Onorato43a17652011-04-06 19:22:23 -07004048 if (false) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004049 TAG, "Instantiating local provider " + info.name);
4050 // XXX Need to create the correct context for this provider.
4051 localProvider.attachInfo(c, info);
4052 } catch (java.lang.Exception e) {
4053 if (!mInstrumentation.onException(null, e)) {
4054 throw new RuntimeException(
4055 "Unable to get provider " + info.name
4056 + ": " + e.toString(), e);
4057 }
4058 return null;
4059 }
4060 } else if (localLOGV) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004061 Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004062 + info.name);
4063 }
4064
4065 synchronized (mProviderMap) {
4066 // Cache the pointer for the remote provider.
4067 String names[] = PATTERN_SEMICOLON.split(info.authority);
4068 for (int i=0; i<names.length; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004069 ProviderClientRecord pr = new ProviderClientRecord(names[i], provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004070 localProvider);
4071 try {
4072 provider.asBinder().linkToDeath(pr, 0);
4073 mProviderMap.put(names[i], pr);
4074 } catch (RemoteException e) {
4075 return null;
4076 }
4077 }
4078 if (localProvider != null) {
4079 mLocalProviders.put(provider.asBinder(),
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004080 new ProviderClientRecord(null, provider, localProvider));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004081 }
4082 }
4083
4084 return provider;
4085 }
4086
4087 private final void attach(boolean system) {
4088 sThreadLocal.set(this);
4089 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004090 if (!system) {
Dianne Hackborn6dd005b2011-07-18 13:22:50 -07004091 ViewRootImpl.addFirstDrawHandler(new Runnable() {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08004092 public void run() {
4093 ensureJitEnabled();
4094 }
4095 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004096 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
4097 RuntimeInit.setApplicationObject(mAppThread.asBinder());
4098 IActivityManager mgr = ActivityManagerNative.getDefault();
4099 try {
4100 mgr.attachApplication(mAppThread);
4101 } catch (RemoteException ex) {
4102 }
4103 } else {
4104 // Don't set application object here -- if the system crashes,
4105 // we can't display an alert, we just want to die die die.
4106 android.ddm.DdmHandleAppName.setAppName("system_process");
4107 try {
4108 mInstrumentation = new Instrumentation();
Dianne Hackborn21556372010-02-04 16:34:40 -08004109 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004110 context.init(getSystemContext().mPackageInfo, null, this);
4111 Application app = Instrumentation.newApplication(Application.class, context);
4112 mAllApplications.add(app);
4113 mInitialApplication = app;
4114 app.onCreate();
4115 } catch (Exception e) {
4116 throw new RuntimeException(
4117 "Unable to instantiate Application():" + e.toString(), e);
4118 }
4119 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004120
Dianne Hackborn6dd005b2011-07-18 13:22:50 -07004121 ViewRootImpl.addConfigCallback(new ComponentCallbacks() {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004122 public void onConfigurationChanged(Configuration newConfig) {
4123 synchronized (mPackages) {
Dianne Hackbornae078162010-03-18 11:29:37 -07004124 // We need to apply this change to the resources
4125 // immediately, because upon returning the view
4126 // hierarchy will be informed about it.
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004127 if (applyConfigurationToResourcesLocked(newConfig, null)) {
Dianne Hackbornae078162010-03-18 11:29:37 -07004128 // This actually changed the resources! Tell
4129 // everyone about it.
4130 if (mPendingConfiguration == null ||
4131 mPendingConfiguration.isOtherSeqNewer(newConfig)) {
4132 mPendingConfiguration = newConfig;
4133
4134 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
4135 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004136 }
4137 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004138 }
4139 public void onLowMemory() {
4140 }
4141 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004142 }
4143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004144 public static final ActivityThread systemMain() {
Romain Guy52339202010-09-03 16:04:46 -07004145 HardwareRenderer.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004146 ActivityThread thread = new ActivityThread();
4147 thread.attach(true);
4148 return thread;
4149 }
4150
Jeff Brown10e89712011-07-08 18:52:57 -07004151 public final void installSystemProviders(List<ProviderInfo> providers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004152 if (providers != null) {
Jeff Brown10e89712011-07-08 18:52:57 -07004153 installContentProviders(mInitialApplication, providers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004154 }
4155 }
4156
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004157 public int getIntCoreSetting(String key, int defaultValue) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08004158 synchronized (mPackages) {
4159 if (mCoreSettings != null) {
4160 return mCoreSettings.getInt(key, defaultValue);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004161 } else {
4162 return defaultValue;
4163 }
4164 }
4165 }
4166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004167 public static final void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07004168 SamplingProfilerIntegration.start();
4169
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -08004170 // CloseGuard defaults to true and can be quite spammy. We
4171 // disable it here, but selectively enable it later (via
4172 // StrictMode) on debug builds, but using DropBox, not logs.
4173 CloseGuard.setEnabled(false);
4174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004175 Process.setArgV0("<pre-initialized>");
4176
4177 Looper.prepareMainLooper();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07004178 if (sMainThreadHandler == null) {
4179 sMainThreadHandler = new Handler();
4180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004181
4182 ActivityThread thread = new ActivityThread();
4183 thread.attach(false);
4184
Dianne Hackborn287952c2010-09-22 22:34:31 -07004185 if (false) {
4186 Looper.myLooper().setMessageLogging(new
4187 LogPrinter(Log.DEBUG, "ActivityThread"));
4188 }
4189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004190 Looper.loop();
4191
Jeff Brown10e89712011-07-08 18:52:57 -07004192 throw new RuntimeException("Main thread loop unexpectedly exited");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004193 }
4194}