blob: 2610d8772de6b82761e6406fc6b2a672d90d09e6 [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;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070021import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import 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;
Romain Guya9582652011-11-10 14:20:10 -080048import android.opengl.GLUtils;
Joe Onoratod630f102011-03-17 18:42:26 -070049import android.os.AsyncTask;
Amith Yamasani742a6712011-05-04 14:49:28 -070050import android.os.Binder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.os.Bundle;
52import android.os.Debug;
53import android.os.Handler;
54import android.os.IBinder;
55import android.os.Looper;
56import android.os.Message;
57import android.os.MessageQueue;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070058import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.os.Process;
60import android.os.RemoteException;
61import android.os.ServiceManager;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070062import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.os.SystemClock;
Amith Yamasani742a6712011-05-04 14:49:28 -070064import android.os.UserId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.util.AndroidRuntimeException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.util.DisplayMetrics;
67import android.util.EventLog;
68import android.util.Log;
Dianne Hackborn287952c2010-09-22 22:34:31 -070069import android.util.LogPrinter;
Jeff Brown6754ba22011-12-14 20:20:01 -080070import android.util.PrintWriterPrinter;
Dianne Hackbornc9421ba2010-03-11 22:23:46 -080071import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.view.Display;
Romain Guy52339202010-09-03 16:04:46 -070073import android.view.HardwareRenderer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import android.view.View;
75import android.view.ViewDebug;
76import android.view.ViewManager;
Dianne Hackborn6dd005b2011-07-18 13:22:50 -070077import android.view.ViewRootImpl;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import android.view.Window;
79import android.view.WindowManager;
80import android.view.WindowManagerImpl;
Jason Samsa6f338c2012-02-24 16:22:16 -080081import android.renderscript.RenderScript;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082
83import com.android.internal.os.BinderInternal;
84import com.android.internal.os.RuntimeInit;
Bob Leee5408332009-09-04 18:31:17 -070085import com.android.internal.os.SamplingProfilerIntegration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086
87import org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl;
88
89import java.io.File;
90import java.io.FileDescriptor;
91import java.io.FileOutputStream;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070092import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093import java.io.PrintWriter;
94import java.lang.ref.WeakReference;
Robert Greenwalt03595d02010-11-02 14:08:23 -070095import java.net.InetAddress;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096import java.util.ArrayList;
97import java.util.HashMap;
98import java.util.Iterator;
99import java.util.List;
100import java.util.Locale;
101import java.util.Map;
102import java.util.TimeZone;
103import java.util.regex.Pattern;
104
Jeff Sharkeye861b422012-03-01 20:59:22 -0800105import libcore.io.IoUtils;
106
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -0800107import dalvik.system.CloseGuard;
Bob Leee5408332009-09-04 18:31:17 -0700108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109final class SuperNotCalledException extends AndroidRuntimeException {
110 public SuperNotCalledException(String msg) {
111 super(msg);
112 }
113}
114
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700115final class RemoteServiceException extends AndroidRuntimeException {
116 public RemoteServiceException(String msg) {
117 super(msg);
118 }
119}
120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121/**
122 * This manages the execution of the main thread in an
123 * application process, scheduling and executing activities,
124 * broadcasts, and other operations on it as the activity
125 * manager requests.
126 *
127 * {@hide}
128 */
129public final class ActivityThread {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700130 /** @hide */
131 public static final String TAG = "ActivityThread";
Jim Miller0b2a6d02010-07-13 18:01:29 -0700132 private static final android.graphics.Bitmap.Config THUMBNAIL_FORMAT = Bitmap.Config.RGB_565;
Joe Onorato43a17652011-04-06 19:22:23 -0700133 static final boolean localLOGV = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700134 static final boolean DEBUG_MESSAGES = false;
Dianne Hackborne829fef2010-10-26 17:44:01 -0700135 /** @hide */
136 public static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700137 private static final boolean DEBUG_RESULTS = false;
Christopher Tate4a627c72011-04-01 14:43:32 -0700138 private static final boolean DEBUG_BACKUP = true;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700139 private static final boolean DEBUG_CONFIGURATION = false;
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800140 private static final boolean DEBUG_SERVICE = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
142 private static final Pattern PATTERN_SEMICOLON = Pattern.compile(";");
143 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
144 private static final int LOG_ON_PAUSE_CALLED = 30021;
145 private static final int LOG_ON_RESUME_CALLED = 30022;
146
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700147 static ContextImpl mSystemContext = null;
Bob Leee5408332009-09-04 18:31:17 -0700148
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700149 static IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700151 final ApplicationThread mAppThread = new ApplicationThread();
152 final Looper mLooper = Looper.myLooper();
153 final H mH = new H();
154 final HashMap<IBinder, ActivityClientRecord> mActivities
155 = new HashMap<IBinder, ActivityClientRecord>();
156 // List of new activities (via ActivityRecord.nextIdle) that should
157 // be reported when next we idle.
158 ActivityClientRecord mNewActivities = null;
159 // Number of activities that are currently visible on-screen.
160 int mNumVisibleActivities = 0;
161 final HashMap<IBinder, Service> mServices
162 = new HashMap<IBinder, Service>();
163 AppBindData mBoundApplication;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700164 Profiler mProfiler;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700165 Configuration mConfiguration;
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700166 Configuration mCompatConfiguration;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700167 Configuration mResConfiguration;
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700168 CompatibilityInfo mResCompatibilityInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700169 Application mInitialApplication;
170 final ArrayList<Application> mAllApplications
171 = new ArrayList<Application>();
172 // set of instantiated backup agents, keyed by package name
173 final HashMap<String, BackupAgent> mBackupAgents = new HashMap<String, BackupAgent>();
Romain Guy65b345f2011-07-27 18:51:50 -0700174 static final ThreadLocal<ActivityThread> sThreadLocal = new ThreadLocal<ActivityThread>();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700175 Instrumentation mInstrumentation;
176 String mInstrumentationAppDir = null;
177 String mInstrumentationAppPackage = null;
178 String mInstrumentedAppDir = null;
179 boolean mSystemThread = false;
180 boolean mJitEnabled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700182 // These can be accessed by multiple threads; mPackages is the lock.
183 // XXX For now we keep around information about all packages we have
184 // seen, not removing entries from this map.
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800185 // NOTE: The activity and window managers need to call in to
Dianne Hackborn2f0b1752011-05-31 17:59:49 -0700186 // ActivityThread to do things like update resource configurations,
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800187 // which means this lock gets held while the activity and window managers
188 // holds their own lock. Thus you MUST NEVER call back into the activity manager
189 // or window manager or anything that depends on them while holding this lock.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700190 final HashMap<String, WeakReference<LoadedApk>> mPackages
191 = new HashMap<String, WeakReference<LoadedApk>>();
192 final HashMap<String, WeakReference<LoadedApk>> mResourcePackages
193 = new HashMap<String, WeakReference<LoadedApk>>();
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700194 final HashMap<CompatibilityInfo, DisplayMetrics> mDisplayMetrics
195 = new HashMap<CompatibilityInfo, DisplayMetrics>();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700196 final HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources
197 = new HashMap<ResourcesKey, WeakReference<Resources> >();
198 final ArrayList<ActivityClientRecord> mRelaunchingActivities
199 = new ArrayList<ActivityClientRecord>();
200 Configuration mPendingConfiguration = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700202 // The lock of mProviderMap protects the following variables.
203 final HashMap<String, ProviderClientRecord> mProviderMap
204 = new HashMap<String, ProviderClientRecord>();
205 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap
206 = new HashMap<IBinder, ProviderRefCount>();
207 final HashMap<IBinder, ProviderClientRecord> mLocalProviders
208 = new HashMap<IBinder, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209
Jeff Hamilton52d32032011-01-08 15:31:26 -0600210 final HashMap<Activity, ArrayList<OnActivityPausedListener>> mOnPauseListeners
211 = new HashMap<Activity, ArrayList<OnActivityPausedListener>>();
212
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700213 final GcIdler mGcIdler = new GcIdler();
214 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700216 static Handler sMainThreadHandler; // set once in main()
217
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800218 Bundle mCoreSettings = null;
219
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400220 static final class ActivityClientRecord {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700222 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 Intent intent;
224 Bundle state;
225 Activity activity;
226 Window window;
227 Activity parent;
228 String embeddedID;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700229 Activity.NonConfigurationInstances lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 boolean paused;
231 boolean stopped;
232 boolean hideForNow;
233 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700234 Configuration createdConfig;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700235 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700237 String profileFile;
238 ParcelFileDescriptor profileFd;
239 boolean autoStopProfiler;
240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 ActivityInfo activityInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400242 CompatibilityInfo compatInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700243 LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244
245 List<ResultInfo> pendingResults;
246 List<Intent> pendingIntents;
247
248 boolean startsNotResumed;
249 boolean isForward;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800250 int pendingConfigChanges;
251 boolean onlyLocalRequest;
252
253 View mPendingRemoveWindow;
254 WindowManager mPendingRemoveWindowManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700256 ActivityClientRecord() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257 parent = null;
258 embeddedID = null;
259 paused = false;
260 stopped = false;
261 hideForNow = false;
262 nextIdle = null;
263 }
264
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800265 public boolean isPreHoneycomb() {
266 if (activity != null) {
267 return activity.getApplicationInfo().targetSdkVersion
268 < android.os.Build.VERSION_CODES.HONEYCOMB;
269 }
270 return false;
271 }
272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 public String toString() {
274 ComponentName componentName = intent.getComponent();
275 return "ActivityRecord{"
276 + Integer.toHexString(System.identityHashCode(this))
277 + " token=" + token + " " + (componentName == null
278 ? "no component name" : componentName.toShortString())
279 + "}";
280 }
281 }
282
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400283 final class ProviderClientRecord implements IBinder.DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284 final String mName;
285 final IContentProvider mProvider;
286 final ContentProvider mLocalProvider;
287
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700288 ProviderClientRecord(String name, IContentProvider provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289 ContentProvider localProvider) {
290 mName = name;
291 mProvider = provider;
292 mLocalProvider = localProvider;
293 }
294
295 public void binderDied() {
296 removeDeadProvider(mName, mProvider);
297 }
298 }
299
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400300 static final class NewIntentData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301 List<Intent> intents;
302 IBinder token;
303 public String toString() {
304 return "NewIntentData{intents=" + intents + " token=" + token + "}";
305 }
306 }
307
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400308 static final class ReceiverData extends BroadcastReceiver.PendingResult {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700309 public ReceiverData(Intent intent, int resultCode, String resultData, Bundle resultExtras,
310 boolean ordered, boolean sticky, IBinder token) {
311 super(resultCode, resultData, resultExtras, TYPE_COMPONENT, ordered, sticky, token);
312 this.intent = intent;
313 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 Intent intent;
316 ActivityInfo info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400317 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 public String toString() {
319 return "ReceiverData{intent=" + intent + " packageName=" +
Dianne Hackborne829fef2010-10-26 17:44:01 -0700320 info.packageName + " resultCode=" + getResultCode()
321 + " resultData=" + getResultData() + " resultExtras="
322 + getResultExtras(false) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 }
324 }
325
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400326 static final class CreateBackupAgentData {
Christopher Tate181fafa2009-05-14 11:12:14 -0700327 ApplicationInfo appInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400328 CompatibilityInfo compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700329 int backupMode;
330 public String toString() {
331 return "CreateBackupAgentData{appInfo=" + appInfo
332 + " backupAgent=" + appInfo.backupAgentName
333 + " mode=" + backupMode + "}";
334 }
335 }
Bob Leee5408332009-09-04 18:31:17 -0700336
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400337 static final class CreateServiceData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800338 IBinder token;
339 ServiceInfo info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400340 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800341 Intent intent;
342 public String toString() {
343 return "CreateServiceData{token=" + token + " className="
344 + info.name + " packageName=" + info.packageName
345 + " intent=" + intent + "}";
346 }
347 }
348
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400349 static final class BindServiceData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800350 IBinder token;
351 Intent intent;
352 boolean rebind;
353 public String toString() {
354 return "BindServiceData{token=" + token + " intent=" + intent + "}";
355 }
356 }
357
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400358 static final class ServiceArgsData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800359 IBinder token;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700360 boolean taskRemoved;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700362 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363 Intent args;
364 public String toString() {
365 return "ServiceArgsData{token=" + token + " startId=" + startId
366 + " args=" + args + "}";
367 }
368 }
369
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400370 static final class AppBindData {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700371 LoadedApk info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800372 String processName;
373 ApplicationInfo appInfo;
374 List<ProviderInfo> providers;
375 ComponentName instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376 Bundle instrumentationArgs;
377 IInstrumentationWatcher instrumentationWatcher;
378 int debugMode;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800379 boolean enableOpenGlTrace;
Christopher Tate181fafa2009-05-14 11:12:14 -0700380 boolean restrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700381 boolean persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382 Configuration config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400383 CompatibilityInfo compatInfo;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700384
385 /** Initial values for {@link Profiler}. */
386 String initProfileFile;
387 ParcelFileDescriptor initProfileFd;
388 boolean initAutoStopProfiler;
389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800390 public String toString() {
391 return "AppBindData{appInfo=" + appInfo + "}";
392 }
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700393 }
394
395 static final class Profiler {
396 String profileFile;
397 ParcelFileDescriptor profileFd;
398 boolean autoStopProfiler;
399 boolean profiling;
400 boolean handlingProfiling;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700401 public void setProfiler(String file, ParcelFileDescriptor fd) {
402 if (profiling) {
403 if (fd != null) {
404 try {
405 fd.close();
406 } catch (IOException e) {
407 }
408 }
409 return;
410 }
411 if (profileFd != null) {
412 try {
413 profileFd.close();
414 } catch (IOException e) {
415 }
416 }
417 profileFile = file;
418 profileFd = fd;
419 }
420 public void startProfiling() {
421 if (profileFd == null || profiling) {
422 return;
423 }
424 try {
425 Debug.startMethodTracing(profileFile, profileFd.getFileDescriptor(),
426 8 * 1024 * 1024, 0);
427 profiling = true;
428 } catch (RuntimeException e) {
429 Slog.w(TAG, "Profiling failed on path " + profileFile);
430 try {
431 profileFd.close();
432 profileFd = null;
433 } catch (IOException e2) {
434 Slog.w(TAG, "Failure closing profile fd", e2);
435 }
436 }
437 }
438 public void stopProfiling() {
439 if (profiling) {
440 profiling = false;
441 Debug.stopMethodTracing();
442 if (profileFd != null) {
443 try {
444 profileFd.close();
445 } catch (IOException e) {
446 }
447 }
448 profileFd = null;
449 profileFile = null;
450 }
451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 }
453
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400454 static final class DumpComponentInfo {
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700455 ParcelFileDescriptor fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700456 IBinder token;
Dianne Hackborn30d71892010-12-11 10:37:55 -0800457 String prefix;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458 String[] args;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800459 }
460
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400461 static final class ResultData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 IBinder token;
463 List<ResultInfo> results;
464 public String toString() {
465 return "ResultData{token=" + token + " results" + results + "}";
466 }
467 }
468
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400469 static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800470 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 String what;
472 String who;
473 }
474
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400475 static final class ProfilerControlData {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700476 String path;
477 ParcelFileDescriptor fd;
478 }
479
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400480 static final class DumpHeapData {
Andy McFadden824c5102010-07-09 16:26:57 -0700481 String path;
482 ParcelFileDescriptor fd;
483 }
484
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400485 static final class UpdateCompatibilityData {
486 String pkg;
487 CompatibilityInfo info;
488 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -0700489
Romain Guy65b345f2011-07-27 18:51:50 -0700490 private native void dumpGraphicsInfo(FileDescriptor fd);
Chet Haase9c1e23b2011-03-24 10:51:31 -0700491
Romain Guy65b345f2011-07-27 18:51:50 -0700492 private class ApplicationThread extends ApplicationThreadNative {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700493 private static final String HEAP_COLUMN = "%13s %8s %8s %8s %8s %8s %8s";
494 private static final String ONE_COUNT_COLUMN = "%21s %8d";
495 private static final String TWO_COUNT_COLUMNS = "%21s %8d %21s %8d";
Vasu Nori3c7131f2010-09-21 14:36:57 -0700496 private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
Bob Leee5408332009-09-04 18:31:17 -0700497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800498 // Formatting for checkin service - update version if row format changes
499 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;
Bob Leee5408332009-09-04 18:31:17 -0700500
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700501 private void updatePendingConfiguration(Configuration config) {
502 synchronized (mPackages) {
503 if (mPendingConfiguration == null ||
504 mPendingConfiguration.isOtherSeqNewer(config)) {
505 mPendingConfiguration = config;
506 }
507 }
508 }
509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510 public final void schedulePauseActivity(IBinder token, boolean finished,
511 boolean userLeaving, int configChanges) {
512 queueOrSendMessage(
513 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
514 token,
515 (userLeaving ? 1 : 0),
516 configChanges);
517 }
518
519 public final void scheduleStopActivity(IBinder token, boolean showWindow,
520 int configChanges) {
521 queueOrSendMessage(
522 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
523 token, 0, configChanges);
524 }
525
526 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
527 queueOrSendMessage(
528 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
529 token);
530 }
531
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800532 public final void scheduleSleeping(IBinder token, boolean sleeping) {
533 queueOrSendMessage(H.SLEEPING, token, sleeping ? 1 : 0);
534 }
535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 public final void scheduleResumeActivity(IBinder token, boolean isForward) {
537 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
538 }
539
540 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
541 ResultData res = new ResultData();
542 res.token = token;
543 res.results = results;
544 queueOrSendMessage(H.SEND_RESULT, res);
545 }
546
547 // we use token to identify this activity without having to send the
548 // activity itself back to the activity manager. (matters more with ipc)
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700549 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700550 ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
551 Bundle state, List<ResultInfo> pendingResults,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700552 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward,
553 String profileName, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700554 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555
556 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700557 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558 r.intent = intent;
559 r.activityInfo = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400560 r.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561 r.state = state;
562
563 r.pendingResults = pendingResults;
564 r.pendingIntents = pendingNewIntents;
565
566 r.startsNotResumed = notResumed;
567 r.isForward = isForward;
568
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700569 r.profileFile = profileName;
570 r.profileFd = profileFd;
571 r.autoStopProfiler = autoStopProfiler;
572
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700573 updatePendingConfiguration(curConfig);
574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
576 }
577
578 public final void scheduleRelaunchActivity(IBinder token,
579 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800580 int configChanges, boolean notResumed, Configuration config) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800581 requestRelaunchActivity(token, pendingResults, pendingNewIntents,
582 configChanges, notResumed, config, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 }
584
585 public final void scheduleNewIntent(List<Intent> intents, IBinder token) {
586 NewIntentData data = new NewIntentData();
587 data.intents = intents;
588 data.token = token;
589
590 queueOrSendMessage(H.NEW_INTENT, data);
591 }
592
593 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
594 int configChanges) {
595 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
596 configChanges);
597 }
598
599 public final void scheduleReceiver(Intent intent, ActivityInfo info,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400600 CompatibilityInfo compatInfo, int resultCode, String data, Bundle extras,
601 boolean sync) {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700602 ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
603 sync, false, mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 r.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400605 r.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 queueOrSendMessage(H.RECEIVER, r);
607 }
608
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400609 public final void scheduleCreateBackupAgent(ApplicationInfo app,
610 CompatibilityInfo compatInfo, int backupMode) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700611 CreateBackupAgentData d = new CreateBackupAgentData();
612 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400613 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700614 d.backupMode = backupMode;
615
616 queueOrSendMessage(H.CREATE_BACKUP_AGENT, d);
617 }
618
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400619 public final void scheduleDestroyBackupAgent(ApplicationInfo app,
620 CompatibilityInfo compatInfo) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700621 CreateBackupAgentData d = new CreateBackupAgentData();
622 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400623 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700624
625 queueOrSendMessage(H.DESTROY_BACKUP_AGENT, d);
626 }
627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628 public final void scheduleCreateService(IBinder token,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400629 ServiceInfo info, CompatibilityInfo compatInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 CreateServiceData s = new CreateServiceData();
631 s.token = token;
632 s.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400633 s.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634
635 queueOrSendMessage(H.CREATE_SERVICE, s);
636 }
637
638 public final void scheduleBindService(IBinder token, Intent intent,
639 boolean rebind) {
640 BindServiceData s = new BindServiceData();
641 s.token = token;
642 s.intent = intent;
643 s.rebind = rebind;
644
Amith Yamasani742a6712011-05-04 14:49:28 -0700645 if (DEBUG_SERVICE)
646 Slog.v(TAG, "scheduleBindService token=" + token + " intent=" + intent + " uid="
647 + Binder.getCallingUid() + " pid=" + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 queueOrSendMessage(H.BIND_SERVICE, s);
649 }
650
651 public final void scheduleUnbindService(IBinder token, Intent intent) {
652 BindServiceData s = new BindServiceData();
653 s.token = token;
654 s.intent = intent;
655
656 queueOrSendMessage(H.UNBIND_SERVICE, s);
657 }
658
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700659 public final void scheduleServiceArgs(IBinder token, boolean taskRemoved, int startId,
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700660 int flags ,Intent args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 ServiceArgsData s = new ServiceArgsData();
662 s.token = token;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700663 s.taskRemoved = taskRemoved;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 s.startId = startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700665 s.flags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 s.args = args;
667
668 queueOrSendMessage(H.SERVICE_ARGS, s);
669 }
670
671 public final void scheduleStopService(IBinder token) {
672 queueOrSendMessage(H.STOP_SERVICE, token);
673 }
674
675 public final void bindApplication(String processName,
676 ApplicationInfo appInfo, List<ProviderInfo> providers,
677 ComponentName instrumentationName, String profileFile,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700678 ParcelFileDescriptor profileFd, boolean autoStopProfiler,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
Siva Velusamy92a8b222012-03-09 16:24:04 -0800680 int debugMode, boolean enableOpenGlTrace, boolean isRestrictedBackupMode,
681 boolean persistent, Configuration config, CompatibilityInfo compatInfo,
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700682 Map<String, IBinder> services, Bundle coreSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683
684 if (services != null) {
685 // Setup the service cache in the ServiceManager
686 ServiceManager.initServiceCache(services);
687 }
688
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800689 setCoreSettings(coreSettings);
690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 AppBindData data = new AppBindData();
692 data.processName = processName;
693 data.appInfo = appInfo;
694 data.providers = providers;
695 data.instrumentationName = instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 data.instrumentationArgs = instrumentationArgs;
697 data.instrumentationWatcher = instrumentationWatcher;
698 data.debugMode = debugMode;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800699 data.enableOpenGlTrace = enableOpenGlTrace;
Christopher Tate181fafa2009-05-14 11:12:14 -0700700 data.restrictedBackupMode = isRestrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700701 data.persistent = persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 data.config = config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400703 data.compatInfo = compatInfo;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700704 data.initProfileFile = profileFile;
705 data.initProfileFd = profileFd;
706 data.initAutoStopProfiler = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 queueOrSendMessage(H.BIND_APPLICATION, data);
708 }
709
710 public final void scheduleExit() {
711 queueOrSendMessage(H.EXIT_APPLICATION, null);
712 }
713
Christopher Tate5e1ab332009-09-01 20:32:49 -0700714 public final void scheduleSuicide() {
715 queueOrSendMessage(H.SUICIDE, null);
716 }
717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 public void requestThumbnail(IBinder token) {
719 queueOrSendMessage(H.REQUEST_THUMBNAIL, token);
720 }
721
722 public void scheduleConfigurationChanged(Configuration config) {
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700723 updatePendingConfiguration(config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 queueOrSendMessage(H.CONFIGURATION_CHANGED, config);
725 }
726
727 public void updateTimeZone() {
728 TimeZone.setDefault(null);
729 }
730
Robert Greenwalt03595d02010-11-02 14:08:23 -0700731 public void clearDnsCache() {
732 // a non-standard API to get this to libcore
733 InetAddress.clearDnsCache();
734 }
735
Robert Greenwalt434203a2010-10-11 16:00:27 -0700736 public void setHttpProxy(String host, String port, String exclList) {
737 Proxy.setHttpProxySystemProperty(host, port, exclList);
738 }
739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 public void processInBackground() {
741 mH.removeMessages(H.GC_WHEN_IDLE);
742 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
743 }
744
745 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700746 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700747 try {
748 data.fd = ParcelFileDescriptor.dup(fd);
749 data.token = servicetoken;
750 data.args = args;
751 queueOrSendMessage(H.DUMP_SERVICE, data);
752 } catch (IOException e) {
753 Slog.w(TAG, "dumpService failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 }
755 }
756
757 // This function exists to make sure all receiver dispatching is
758 // correctly ordered, since these are one-way calls and the binder driver
759 // applies transaction ordering per object for such calls.
760 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700761 int resultCode, String dataStr, Bundle extras, boolean ordered,
762 boolean sticky) throws RemoteException {
763 receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 }
Bob Leee5408332009-09-04 18:31:17 -0700765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 public void scheduleLowMemory() {
767 queueOrSendMessage(H.LOW_MEMORY, null);
768 }
769
770 public void scheduleActivityConfigurationChanged(IBinder token) {
771 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token);
772 }
773
Romain Guy7eabe552011-07-21 14:56:34 -0700774 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd,
775 int profileType) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700776 ProfilerControlData pcd = new ProfilerControlData();
777 pcd.path = path;
778 pcd.fd = fd;
Romain Guy7eabe552011-07-21 14:56:34 -0700779 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0, profileType);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800780 }
781
Andy McFadden824c5102010-07-09 16:26:57 -0700782 public void dumpHeap(boolean managed, String path, ParcelFileDescriptor fd) {
783 DumpHeapData dhd = new DumpHeapData();
784 dhd.path = path;
785 dhd.fd = fd;
786 queueOrSendMessage(H.DUMP_HEAP, dhd, managed ? 1 : 0);
787 }
788
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700789 public void setSchedulingGroup(int group) {
790 // Note: do this immediately, since going into the foreground
791 // should happen regardless of what pending work we have to do
792 // and the activity manager will wait for us to report back that
793 // we are done before sending us to the background.
794 try {
795 Process.setProcessGroup(Process.myPid(), group);
796 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800797 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700798 }
799 }
Bob Leee5408332009-09-04 18:31:17 -0700800
Dianne Hackborn3025ef32009-08-31 21:31:47 -0700801 public void getMemoryInfo(Debug.MemoryInfo outInfo) {
802 Debug.getMemoryInfo(outInfo);
803 }
Bob Leee5408332009-09-04 18:31:17 -0700804
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700805 public void dispatchPackageBroadcast(int cmd, String[] packages) {
806 queueOrSendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
807 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700808
809 public void scheduleCrash(String msg) {
810 queueOrSendMessage(H.SCHEDULE_CRASH, msg);
811 }
Dianne Hackborn625ac272010-09-17 18:29:22 -0700812
Dianne Hackborn30d71892010-12-11 10:37:55 -0800813 public void dumpActivity(FileDescriptor fd, IBinder activitytoken,
814 String prefix, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700815 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700816 try {
817 data.fd = ParcelFileDescriptor.dup(fd);
818 data.token = activitytoken;
819 data.prefix = prefix;
820 data.args = args;
821 queueOrSendMessage(H.DUMP_ACTIVITY, data);
822 } catch (IOException e) {
823 Slog.w(TAG, "dumpActivity failed", e);
Dianne Hackborn625ac272010-09-17 18:29:22 -0700824 }
825 }
Chet Haase9c1e23b2011-03-24 10:51:31 -0700826
Marco Nelissen18cb2872011-11-15 11:19:53 -0800827 public void dumpProvider(FileDescriptor fd, IBinder providertoken,
828 String[] args) {
829 DumpComponentInfo data = new DumpComponentInfo();
830 try {
831 data.fd = ParcelFileDescriptor.dup(fd);
832 data.token = providertoken;
833 data.args = args;
834 queueOrSendMessage(H.DUMP_PROVIDER, data);
835 } catch (IOException e) {
836 Slog.w(TAG, "dumpProvider failed", e);
837 }
838 }
839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 @Override
Dianne Hackbornb437e092011-08-05 17:50:29 -0700841 public Debug.MemoryInfo dumpMemInfo(FileDescriptor fd, boolean checkin,
842 boolean all, String[] args) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700843 FileOutputStream fout = new FileOutputStream(fd);
844 PrintWriter pw = new PrintWriter(fout);
845 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -0700846 return dumpMemInfo(pw, checkin, all, args);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700847 } finally {
Chet Haase9c1e23b2011-03-24 10:51:31 -0700848 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -0700849 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700850 }
851
Dianne Hackbornb437e092011-08-05 17:50:29 -0700852 private Debug.MemoryInfo dumpMemInfo(PrintWriter pw, boolean checkin, boolean all,
853 String[] args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 long nativeMax = Debug.getNativeHeapSize() / 1024;
855 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
856 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
857
858 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
859 Debug.getMemoryInfo(memInfo);
860
Dianne Hackbornb437e092011-08-05 17:50:29 -0700861 if (!all) {
862 return memInfo;
863 }
864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 Runtime runtime = Runtime.getRuntime();
866
867 long dalvikMax = runtime.totalMemory() / 1024;
868 long dalvikFree = runtime.freeMemory() / 1024;
869 long dalvikAllocated = dalvikMax - dalvikFree;
870 long viewInstanceCount = ViewDebug.getViewInstanceCount();
Romain Guy65b345f2011-07-27 18:51:50 -0700871 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
Brian Carlstromc21550a2010-10-05 21:34:06 -0700872 long appContextInstanceCount = Debug.countInstancesOfClass(ContextImpl.class);
873 long activityInstanceCount = Debug.countInstancesOfClass(Activity.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 int globalAssetCount = AssetManager.getGlobalAssetCount();
875 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
876 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
877 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
878 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
Brian Carlstromc9d5b312010-10-05 22:23:41 -0700879 long openSslSocketCount = Debug.countInstancesOfClass(OpenSSLSocketImpl.class);
Vasu Noric3849202010-03-09 10:47:25 -0800880 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -0700881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 // For checkin, we print one long comma-separated list of values
Dianne Hackbornb437e092011-08-05 17:50:29 -0700883 if (checkin) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 // NOTE: if you change anything significant below, also consider changing
885 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -0700886 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -0700888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 // Header
890 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
891 pw.print(Process.myPid()); pw.print(',');
892 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 // Heap info - max
895 pw.print(nativeMax); pw.print(',');
896 pw.print(dalvikMax); pw.print(',');
897 pw.print("N/A,");
898 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 // Heap info - allocated
901 pw.print(nativeAllocated); pw.print(',');
902 pw.print(dalvikAllocated); pw.print(',');
903 pw.print("N/A,");
904 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 // Heap info - free
907 pw.print(nativeFree); pw.print(',');
908 pw.print(dalvikFree); pw.print(',');
909 pw.print("N/A,");
910 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 // Heap info - proportional set size
913 pw.print(memInfo.nativePss); pw.print(',');
914 pw.print(memInfo.dalvikPss); pw.print(',');
915 pw.print(memInfo.otherPss); pw.print(',');
916 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 // Heap info - shared
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700919 pw.print(memInfo.nativeSharedDirty); pw.print(',');
920 pw.print(memInfo.dalvikSharedDirty); pw.print(',');
921 pw.print(memInfo.otherSharedDirty); pw.print(',');
922 pw.print(memInfo.nativeSharedDirty + memInfo.dalvikSharedDirty
923 + memInfo.otherSharedDirty); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 // Heap info - private
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700926 pw.print(memInfo.nativePrivateDirty); pw.print(',');
927 pw.print(memInfo.dalvikPrivateDirty); pw.print(',');
928 pw.print(memInfo.otherPrivateDirty); pw.print(',');
929 pw.print(memInfo.nativePrivateDirty + memInfo.dalvikPrivateDirty
930 + memInfo.otherPrivateDirty); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 // Object counts
933 pw.print(viewInstanceCount); pw.print(',');
934 pw.print(viewRootInstanceCount); pw.print(',');
935 pw.print(appContextInstanceCount); pw.print(',');
936 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 pw.print(globalAssetCount); pw.print(',');
939 pw.print(globalAssetManagerCount); pw.print(',');
940 pw.print(binderLocalObjectCount); pw.print(',');
941 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943 pw.print(binderDeathObjectCount); pw.print(',');
944 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 // SQL
Vasu Noric3849202010-03-09 10:47:25 -0800947 pw.print(stats.memoryUsed / 1024); pw.print(',');
Jeff Brown2a293b62012-01-19 14:02:22 -0800948 pw.print(stats.memoryUsed / 1024); pw.print(',');
949 pw.print(stats.pageCacheOverflow / 1024); pw.print(',');
Dianne Hackbornb437e092011-08-05 17:50:29 -0700950 pw.print(stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -0800951 for (int i = 0; i < stats.dbStats.size(); i++) {
952 DbStats dbStats = stats.dbStats.get(i);
Dianne Hackbornb437e092011-08-05 17:50:29 -0700953 pw.print(','); pw.print(dbStats.dbName);
954 pw.print(','); pw.print(dbStats.pageSize);
955 pw.print(','); pw.print(dbStats.dbSize);
956 pw.print(','); pw.print(dbStats.lookaside);
957 pw.print(','); pw.print(dbStats.cache);
958 pw.print(','); pw.print(dbStats.cache);
Vasu Noric3849202010-03-09 10:47:25 -0800959 }
Dianne Hackbornb437e092011-08-05 17:50:29 -0700960 pw.println();
Bob Leee5408332009-09-04 18:31:17 -0700961
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700962 return memInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 }
Bob Leee5408332009-09-04 18:31:17 -0700964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 // otherwise, show human-readable format
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700966 printRow(pw, HEAP_COLUMN, "", "", "Shared", "Private", "Heap", "Heap", "Heap");
967 printRow(pw, HEAP_COLUMN, "", "Pss", "Dirty", "Dirty", "Size", "Alloc", "Free");
968 printRow(pw, HEAP_COLUMN, "", "------", "------", "------", "------", "------",
969 "------");
970 printRow(pw, HEAP_COLUMN, "Native", memInfo.nativePss, memInfo.nativeSharedDirty,
971 memInfo.nativePrivateDirty, nativeMax, nativeAllocated, nativeFree);
972 printRow(pw, HEAP_COLUMN, "Dalvik", memInfo.dalvikPss, memInfo.dalvikSharedDirty,
973 memInfo.dalvikPrivateDirty, dalvikMax, dalvikAllocated, dalvikFree);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700975 int otherPss = memInfo.otherPss;
976 int otherSharedDirty = memInfo.otherSharedDirty;
977 int otherPrivateDirty = memInfo.otherPrivateDirty;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700979 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
Romain Guy65b345f2011-07-27 18:51:50 -0700980 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700981 memInfo.getOtherPss(i), memInfo.getOtherSharedDirty(i),
982 memInfo.getOtherPrivateDirty(i), "", "", "");
983 otherPss -= memInfo.getOtherPss(i);
984 otherSharedDirty -= memInfo.getOtherSharedDirty(i);
985 otherPrivateDirty -= memInfo.getOtherPrivateDirty(i);
986 }
987
988 printRow(pw, HEAP_COLUMN, "Unknown", otherPss, otherSharedDirty,
989 otherPrivateDirty, "", "", "");
990 printRow(pw, HEAP_COLUMN, "TOTAL", memInfo.getTotalPss(),
991 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
992 nativeMax+dalvikMax, nativeAllocated+dalvikAllocated,
993 nativeFree+dalvikFree);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994
995 pw.println(" ");
996 pw.println(" Objects");
Romain Guy65b345f2011-07-27 18:51:50 -0700997 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRootImpl:",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 viewRootInstanceCount);
999
1000 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
1001 "Activities:", activityInstanceCount);
1002
1003 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
1004 "AssetManagers:", globalAssetManagerCount);
1005
1006 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
1007 "Proxy Binders:", binderProxyObjectCount);
1008 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
1009
1010 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -07001011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 // SQLite mem info
1013 pw.println(" ");
1014 pw.println(" SQL");
Jeff Brown2a293b62012-01-19 14:02:22 -08001015 printRow(pw, ONE_COUNT_COLUMN, "MEMORY_USED:", stats.memoryUsed / 1024);
1016 printRow(pw, TWO_COUNT_COLUMNS, "PAGECACHE_OVERFLOW:",
1017 stats.pageCacheOverflow / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -08001018 pw.println(" ");
1019 int N = stats.dbStats.size();
1020 if (N > 0) {
1021 pw.println(" DATABASES");
Vasu Nori3c7131f2010-09-21 14:36:57 -07001022 printRow(pw, " %8s %8s %14s %14s %s", "pgsz", "dbsz", "Lookaside(b)", "cache",
1023 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -08001024 for (int i = 0; i < N; i++) {
1025 DbStats dbStats = stats.dbStats.get(i);
Vasu Nori3c7131f2010-09-21 14:36:57 -07001026 printRow(pw, DB_INFO_FORMAT,
1027 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
1028 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
1029 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
1030 dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -08001031 }
1032 }
Bob Leee5408332009-09-04 18:31:17 -07001033
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07001034 // Asset details.
1035 String assetAlloc = AssetManager.getAssetAllocations();
1036 if (assetAlloc != null) {
1037 pw.println(" ");
1038 pw.println(" Asset Allocations");
1039 pw.print(assetAlloc);
1040 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001041
1042 return memInfo;
1043 }
1044
1045 @Override
1046 public void dumpGfxInfo(FileDescriptor fd, String[] args) {
1047 dumpGraphicsInfo(fd);
Romain Guy65b345f2011-07-27 18:51:50 -07001048 WindowManagerImpl.getDefault().dumpGfxInfo(fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 }
1050
Jeff Brown6754ba22011-12-14 20:20:01 -08001051 @Override
1052 public void dumpDbInfo(FileDescriptor fd, String[] args) {
1053 PrintWriter pw = new PrintWriter(new FileOutputStream(fd));
1054 PrintWriterPrinter printer = new PrintWriterPrinter(pw);
1055 SQLiteDebug.dump(printer, args);
1056 pw.flush();
1057 }
1058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 private void printRow(PrintWriter pw, String format, Object...objs) {
1060 pw.println(String.format(format, objs));
1061 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001062
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08001063 public void setCoreSettings(Bundle coreSettings) {
1064 queueOrSendMessage(H.SET_CORE_SETTINGS, coreSettings);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001065 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001066
1067 public void updatePackageCompatibilityInfo(String pkg, CompatibilityInfo info) {
1068 UpdateCompatibilityData ucd = new UpdateCompatibilityData();
1069 ucd.pkg = pkg;
1070 ucd.info = info;
1071 queueOrSendMessage(H.UPDATE_PACKAGE_COMPATIBILITY_INFO, ucd);
1072 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001073
1074 public void scheduleTrimMemory(int level) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001075 queueOrSendMessage(H.TRIM_MEMORY, null, level);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001076 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 }
1079
Romain Guy65b345f2011-07-27 18:51:50 -07001080 private class H extends Handler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 public static final int LAUNCH_ACTIVITY = 100;
1082 public static final int PAUSE_ACTIVITY = 101;
1083 public static final int PAUSE_ACTIVITY_FINISHING= 102;
1084 public static final int STOP_ACTIVITY_SHOW = 103;
1085 public static final int STOP_ACTIVITY_HIDE = 104;
1086 public static final int SHOW_WINDOW = 105;
1087 public static final int HIDE_WINDOW = 106;
1088 public static final int RESUME_ACTIVITY = 107;
1089 public static final int SEND_RESULT = 108;
Brian Carlstromed7e0072011-03-24 13:27:57 -07001090 public static final int DESTROY_ACTIVITY = 109;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 public static final int BIND_APPLICATION = 110;
1092 public static final int EXIT_APPLICATION = 111;
1093 public static final int NEW_INTENT = 112;
1094 public static final int RECEIVER = 113;
1095 public static final int CREATE_SERVICE = 114;
1096 public static final int SERVICE_ARGS = 115;
1097 public static final int STOP_SERVICE = 116;
1098 public static final int REQUEST_THUMBNAIL = 117;
1099 public static final int CONFIGURATION_CHANGED = 118;
1100 public static final int CLEAN_UP_CONTEXT = 119;
1101 public static final int GC_WHEN_IDLE = 120;
1102 public static final int BIND_SERVICE = 121;
1103 public static final int UNBIND_SERVICE = 122;
1104 public static final int DUMP_SERVICE = 123;
1105 public static final int LOW_MEMORY = 124;
1106 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
1107 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001108 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -07001109 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001110 public static final int DESTROY_BACKUP_AGENT = 129;
1111 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001112 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001113 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001114 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001115 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -07001116 public static final int DUMP_HEAP = 135;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001117 public static final int DUMP_ACTIVITY = 136;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001118 public static final int SLEEPING = 137;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001119 public static final int SET_CORE_SETTINGS = 138;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001120 public static final int UPDATE_PACKAGE_COMPATIBILITY_INFO = 139;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001121 public static final int TRIM_MEMORY = 140;
Marco Nelissen18cb2872011-11-15 11:19:53 -08001122 public static final int DUMP_PROVIDER = 141;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 String codeToString(int code) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001124 if (DEBUG_MESSAGES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 switch (code) {
1126 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
1127 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
1128 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
1129 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
1130 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
1131 case SHOW_WINDOW: return "SHOW_WINDOW";
1132 case HIDE_WINDOW: return "HIDE_WINDOW";
1133 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
1134 case SEND_RESULT: return "SEND_RESULT";
1135 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
1136 case BIND_APPLICATION: return "BIND_APPLICATION";
1137 case EXIT_APPLICATION: return "EXIT_APPLICATION";
1138 case NEW_INTENT: return "NEW_INTENT";
1139 case RECEIVER: return "RECEIVER";
1140 case CREATE_SERVICE: return "CREATE_SERVICE";
1141 case SERVICE_ARGS: return "SERVICE_ARGS";
1142 case STOP_SERVICE: return "STOP_SERVICE";
1143 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
1144 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
1145 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
1146 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
1147 case BIND_SERVICE: return "BIND_SERVICE";
1148 case UNBIND_SERVICE: return "UNBIND_SERVICE";
1149 case DUMP_SERVICE: return "DUMP_SERVICE";
1150 case LOW_MEMORY: return "LOW_MEMORY";
1151 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
1152 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001153 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -07001154 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
1155 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -07001156 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001157 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001158 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001159 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001160 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -07001161 case DUMP_HEAP: return "DUMP_HEAP";
Dianne Hackborn625ac272010-09-17 18:29:22 -07001162 case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001163 case SLEEPING: return "SLEEPING";
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001164 case SET_CORE_SETTINGS: return "SET_CORE_SETTINGS";
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001165 case UPDATE_PACKAGE_COMPATIBILITY_INFO: return "UPDATE_PACKAGE_COMPATIBILITY_INFO";
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001166 case TRIM_MEMORY: return "TRIM_MEMORY";
Marco Nelissen18cb2872011-11-15 11:19:53 -08001167 case DUMP_PROVIDER: return "DUMP_PROVIDER";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 }
1169 }
1170 return "(unknown)";
1171 }
1172 public void handleMessage(Message msg) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001173 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 switch (msg.what) {
1175 case LAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001176 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177
1178 r.packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001179 r.activityInfo.applicationInfo, r.compatInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001180 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 } break;
1182 case RELAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001183 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08001184 handleRelaunchActivity(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 } break;
1186 case PAUSE_ACTIVITY:
1187 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -07001188 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 break;
1190 case PAUSE_ACTIVITY_FINISHING:
1191 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
1192 break;
1193 case STOP_ACTIVITY_SHOW:
1194 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
1195 break;
1196 case STOP_ACTIVITY_HIDE:
1197 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
1198 break;
1199 case SHOW_WINDOW:
1200 handleWindowVisibility((IBinder)msg.obj, true);
1201 break;
1202 case HIDE_WINDOW:
1203 handleWindowVisibility((IBinder)msg.obj, false);
1204 break;
1205 case RESUME_ACTIVITY:
1206 handleResumeActivity((IBinder)msg.obj, true,
1207 msg.arg1 != 0);
1208 break;
1209 case SEND_RESULT:
1210 handleSendResult((ResultData)msg.obj);
1211 break;
1212 case DESTROY_ACTIVITY:
1213 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
1214 msg.arg2, false);
1215 break;
1216 case BIND_APPLICATION:
1217 AppBindData data = (AppBindData)msg.obj;
1218 handleBindApplication(data);
1219 break;
1220 case EXIT_APPLICATION:
1221 if (mInitialApplication != null) {
1222 mInitialApplication.onTerminate();
1223 }
1224 Looper.myLooper().quit();
1225 break;
1226 case NEW_INTENT:
1227 handleNewIntent((NewIntentData)msg.obj);
1228 break;
1229 case RECEIVER:
1230 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001231 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 break;
1233 case CREATE_SERVICE:
1234 handleCreateService((CreateServiceData)msg.obj);
1235 break;
1236 case BIND_SERVICE:
1237 handleBindService((BindServiceData)msg.obj);
1238 break;
1239 case UNBIND_SERVICE:
1240 handleUnbindService((BindServiceData)msg.obj);
1241 break;
1242 case SERVICE_ARGS:
1243 handleServiceArgs((ServiceArgsData)msg.obj);
1244 break;
1245 case STOP_SERVICE:
1246 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001247 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 break;
1249 case REQUEST_THUMBNAIL:
1250 handleRequestThumbnail((IBinder)msg.obj);
1251 break;
1252 case CONFIGURATION_CHANGED:
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001253 handleConfigurationChanged((Configuration)msg.obj, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254 break;
1255 case CLEAN_UP_CONTEXT:
1256 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1257 cci.context.performFinalCleanup(cci.who, cci.what);
1258 break;
1259 case GC_WHEN_IDLE:
1260 scheduleGcIdler();
1261 break;
1262 case DUMP_SERVICE:
Dianne Hackborn625ac272010-09-17 18:29:22 -07001263 handleDumpService((DumpComponentInfo)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 break;
1265 case LOW_MEMORY:
1266 handleLowMemory();
1267 break;
1268 case ACTIVITY_CONFIGURATION_CHANGED:
1269 handleActivityConfigurationChanged((IBinder)msg.obj);
1270 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001271 case PROFILER_CONTROL:
Romain Guy7eabe552011-07-21 14:56:34 -07001272 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj, msg.arg2);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001273 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001274 case CREATE_BACKUP_AGENT:
1275 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1276 break;
1277 case DESTROY_BACKUP_AGENT:
1278 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1279 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001280 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001281 Process.killProcess(Process.myPid());
1282 break;
1283 case REMOVE_PROVIDER:
1284 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001285 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001286 case ENABLE_JIT:
1287 ensureJitEnabled();
1288 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001289 case DISPATCH_PACKAGE_BROADCAST:
1290 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
1291 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001292 case SCHEDULE_CRASH:
1293 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001294 case DUMP_HEAP:
1295 handleDumpHeap(msg.arg1 != 0, (DumpHeapData)msg.obj);
1296 break;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001297 case DUMP_ACTIVITY:
1298 handleDumpActivity((DumpComponentInfo)msg.obj);
1299 break;
Marco Nelissen18cb2872011-11-15 11:19:53 -08001300 case DUMP_PROVIDER:
1301 handleDumpProvider((DumpComponentInfo)msg.obj);
1302 break;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001303 case SLEEPING:
1304 handleSleeping((IBinder)msg.obj, msg.arg1 != 0);
1305 break;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001306 case SET_CORE_SETTINGS:
1307 handleSetCoreSettings((Bundle) msg.obj);
1308 break;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001309 case UPDATE_PACKAGE_COMPATIBILITY_INFO:
1310 handleUpdatePackageCompatibilityInfo((UpdateCompatibilityData)msg.obj);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001311 break;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001312 case TRIM_MEMORY:
1313 handleTrimMemory(msg.arg1);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001314 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07001316 if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 }
Bob Leee5408332009-09-04 18:31:17 -07001318
Brian Carlstromed7e0072011-03-24 13:27:57 -07001319 private void maybeSnapshot() {
1320 if (mBoundApplication != null && SamplingProfilerIntegration.isEnabled()) {
Sen Hubde75702010-05-28 01:54:03 -07001321 // convert the *private* ActivityThread.PackageInfo to *public* known
1322 // android.content.pm.PackageInfo
1323 String packageName = mBoundApplication.info.mPackageName;
1324 android.content.pm.PackageInfo packageInfo = null;
1325 try {
1326 Context context = getSystemContext();
1327 if(context == null) {
1328 Log.e(TAG, "cannot get a valid context");
1329 return;
1330 }
1331 PackageManager pm = context.getPackageManager();
1332 if(pm == null) {
1333 Log.e(TAG, "cannot get a valid PackageManager");
1334 return;
1335 }
1336 packageInfo = pm.getPackageInfo(
1337 packageName, PackageManager.GET_ACTIVITIES);
1338 } catch (NameNotFoundException e) {
1339 Log.e(TAG, "cannot get package info for " + packageName, e);
1340 }
1341 SamplingProfilerIntegration.writeSnapshot(mBoundApplication.processName, packageInfo);
Bob Leee5408332009-09-04 18:31:17 -07001342 }
1343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 }
1345
Romain Guy65b345f2011-07-27 18:51:50 -07001346 private class Idler implements MessageQueue.IdleHandler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001348 ActivityClientRecord a = mNewActivities;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001349 boolean stopProfiling = false;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001350 if (mBoundApplication != null && mProfiler.profileFd != null
1351 && mProfiler.autoStopProfiler) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001352 stopProfiling = true;
1353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 if (a != null) {
1355 mNewActivities = null;
1356 IActivityManager am = ActivityManagerNative.getDefault();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001357 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001359 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 TAG, "Reporting idle of " + a +
1361 " finished=" +
Romain Guy65b345f2011-07-27 18:51:50 -07001362 (a.activity != null && a.activity.mFinished));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 if (a.activity != null && !a.activity.mFinished) {
1364 try {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001365 am.activityIdle(a.token, a.createdConfig, stopProfiling);
Dianne Hackborne88846e2009-09-30 21:34:25 -07001366 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 } catch (RemoteException ex) {
Romain Guy65b345f2011-07-27 18:51:50 -07001368 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 }
1370 }
1371 prev = a;
1372 a = a.nextIdle;
1373 prev.nextIdle = null;
1374 } while (a != null);
1375 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001376 if (stopProfiling) {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001377 mProfiler.stopProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001378 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001379 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 return false;
1381 }
1382 }
1383
1384 final class GcIdler implements MessageQueue.IdleHandler {
1385 public final boolean queueIdle() {
1386 doGcIfNeeded();
1387 return false;
1388 }
1389 }
1390
Romain Guy65b345f2011-07-27 18:51:50 -07001391 private static class ResourcesKey {
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001392 final private String mResDir;
1393 final private float mScale;
1394 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07001395
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001396 ResourcesKey(String resDir, float scale) {
1397 mResDir = resDir;
1398 mScale = scale;
1399 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
1400 }
Bob Leee5408332009-09-04 18:31:17 -07001401
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001402 @Override
1403 public int hashCode() {
1404 return mHash;
1405 }
1406
1407 @Override
1408 public boolean equals(Object obj) {
1409 if (!(obj instanceof ResourcesKey)) {
1410 return false;
1411 }
1412 ResourcesKey peer = (ResourcesKey) obj;
1413 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
1414 }
1415 }
1416
Romain Guy65b345f2011-07-27 18:51:50 -07001417 public static ActivityThread currentActivityThread() {
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07001418 return sThreadLocal.get();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420
Romain Guy65b345f2011-07-27 18:51:50 -07001421 public static String currentPackageName() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001422 ActivityThread am = currentActivityThread();
1423 return (am != null && am.mBoundApplication != null)
1424 ? am.mBoundApplication.processName : null;
1425 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426
Romain Guy65b345f2011-07-27 18:51:50 -07001427 public static Application currentApplication() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001428 ActivityThread am = currentActivityThread();
1429 return am != null ? am.mInitialApplication : null;
1430 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001432 public static IPackageManager getPackageManager() {
1433 if (sPackageManager != null) {
1434 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1435 return sPackageManager;
1436 }
1437 IBinder b = ServiceManager.getService("package");
1438 //Slog.v("PackageManager", "default service binder = " + b);
1439 sPackageManager = IPackageManager.Stub.asInterface(b);
1440 //Slog.v("PackageManager", "default service = " + sPackageManager);
1441 return sPackageManager;
1442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001444 DisplayMetrics getDisplayMetricsLocked(CompatibilityInfo ci, boolean forceUpdate) {
1445 DisplayMetrics dm = mDisplayMetrics.get(ci);
1446 if (dm != null && !forceUpdate) {
1447 return dm;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001448 }
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001449 if (dm == null) {
1450 dm = new DisplayMetrics();
1451 mDisplayMetrics.put(ci, dm);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001452 }
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001453 Display d = WindowManagerImpl.getDefault(ci).getDefaultDisplay();
1454 d.getMetrics(dm);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001455 //Slog.i("foo", "New metrics: w=" + metrics.widthPixels + " h="
1456 // + metrics.heightPixels + " den=" + metrics.density
1457 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001458 return dm;
1459 }
1460
1461 static Configuration applyConfigCompat(Configuration config, CompatibilityInfo compat) {
1462 if (config == null) {
1463 return null;
1464 }
1465 if (compat != null && !compat.supportsScreen()) {
1466 config = new Configuration(config);
1467 compat.applyToConfiguration(config);
1468 }
1469 return config;
1470 }
1471
Romain Guy65b345f2011-07-27 18:51:50 -07001472 private Configuration mMainThreadConfig = new Configuration();
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001473 Configuration applyConfigCompatMainThread(Configuration config, CompatibilityInfo compat) {
1474 if (config == null) {
1475 return null;
1476 }
1477 if (compat != null && !compat.supportsScreen()) {
1478 mMainThreadConfig.setTo(config);
1479 config = mMainThreadConfig;
1480 compat.applyToConfiguration(config);
1481 }
1482 return config;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001483 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001485 /**
1486 * Creates the top level Resources for applications with the given compatibility info.
1487 *
1488 * @param resDir the resource directory.
1489 * @param compInfo the compability info. It will use the default compatibility info when it's
1490 * null.
1491 */
1492 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
1493 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
1494 Resources r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001496 // Resources is app scale dependent.
1497 if (false) {
1498 Slog.w(TAG, "getTopLevelResources: " + resDir + " / "
1499 + compInfo.applicationScale);
1500 }
1501 WeakReference<Resources> wr = mActiveResources.get(key);
1502 r = wr != null ? wr.get() : null;
1503 //if (r != null) Slog.i(TAG, "isUpToDate " + resDir + ": " + r.getAssets().isUpToDate());
1504 if (r != null && r.getAssets().isUpToDate()) {
1505 if (false) {
1506 Slog.w(TAG, "Returning cached resources " + r + " " + resDir
1507 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
1508 }
1509 return r;
1510 }
1511 }
1512
1513 //if (r != null) {
1514 // Slog.w(TAG, "Throwing away out-of-date resources!!!! "
1515 // + r + " " + resDir);
1516 //}
1517
1518 AssetManager assets = new AssetManager();
1519 if (assets.addAssetPath(resDir) == 0) {
1520 return null;
1521 }
1522
1523 //Slog.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
Dianne Hackborn836e2622011-10-04 18:32:39 -07001524 DisplayMetrics metrics = getDisplayMetricsLocked(null, false);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001525 r = new Resources(assets, metrics, getConfiguration(), compInfo);
1526 if (false) {
1527 Slog.i(TAG, "Created app resources " + resDir + " " + r + ": "
1528 + r.getConfiguration() + " appScale="
1529 + r.getCompatibilityInfo().applicationScale);
1530 }
1531
1532 synchronized (mPackages) {
1533 WeakReference<Resources> wr = mActiveResources.get(key);
1534 Resources existing = wr != null ? wr.get() : null;
1535 if (existing != null && existing.getAssets().isUpToDate()) {
1536 // Someone else already created the resources while we were
1537 // unlocked; go ahead and use theirs.
1538 r.getAssets().close();
1539 return existing;
1540 }
1541
1542 // XXX need to remove entries when weak references go away
1543 mActiveResources.put(key, new WeakReference<Resources>(r));
1544 return r;
1545 }
1546 }
1547
1548 /**
1549 * Creates the top level resources for the given package.
1550 */
1551 Resources getTopLevelResources(String resDir, LoadedApk pkgInfo) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001552 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo.get());
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001553 }
1554
1555 final Handler getHandler() {
1556 return mH;
1557 }
1558
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001559 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
1560 int flags) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001561 synchronized (mPackages) {
1562 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
1564 ref = mPackages.get(packageName);
1565 } else {
1566 ref = mResourcePackages.get(packageName);
1567 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001568 LoadedApk packageInfo = ref != null ? ref.get() : null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001569 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001570 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
1571 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 if (packageInfo != null && (packageInfo.mResources == null
1573 || packageInfo.mResources.getAssets().isUpToDate())) {
1574 if (packageInfo.isSecurityViolation()
1575 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
1576 throw new SecurityException(
1577 "Requesting code from " + packageName
1578 + " to be run in process "
1579 + mBoundApplication.processName
1580 + "/" + mBoundApplication.appInfo.uid);
1581 }
1582 return packageInfo;
1583 }
1584 }
1585
1586 ApplicationInfo ai = null;
1587 try {
1588 ai = getPackageManager().getApplicationInfo(packageName,
1589 PackageManager.GET_SHARED_LIBRARY_FILES);
1590 } catch (RemoteException e) {
Romain Guy65b345f2011-07-27 18:51:50 -07001591 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 }
1593
1594 if (ai != null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001595 return getPackageInfo(ai, compatInfo, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 }
1597
1598 return null;
1599 }
1600
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001601 public final LoadedApk getPackageInfo(ApplicationInfo ai, CompatibilityInfo compatInfo,
1602 int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
1604 boolean securityViolation = includeCode && ai.uid != 0
1605 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
Amith Yamasani742a6712011-05-04 14:49:28 -07001606 ? !UserId.isSameApp(ai.uid, mBoundApplication.appInfo.uid)
1607 : true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608 if ((flags&(Context.CONTEXT_INCLUDE_CODE
1609 |Context.CONTEXT_IGNORE_SECURITY))
1610 == Context.CONTEXT_INCLUDE_CODE) {
1611 if (securityViolation) {
1612 String msg = "Requesting code from " + ai.packageName
1613 + " (with uid " + ai.uid + ")";
1614 if (mBoundApplication != null) {
1615 msg = msg + " to be run in process "
1616 + mBoundApplication.processName + " (with uid "
1617 + mBoundApplication.appInfo.uid + ")";
1618 }
1619 throw new SecurityException(msg);
1620 }
1621 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001622 return getPackageInfo(ai, compatInfo, null, securityViolation, includeCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 }
1624
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001625 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai,
1626 CompatibilityInfo compatInfo) {
1627 return getPackageInfo(ai, compatInfo, null, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 }
1629
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001630 public final LoadedApk peekPackageInfo(String packageName, boolean includeCode) {
1631 synchronized (mPackages) {
1632 WeakReference<LoadedApk> ref;
1633 if (includeCode) {
1634 ref = mPackages.get(packageName);
1635 } else {
1636 ref = mResourcePackages.get(packageName);
1637 }
1638 return ref != null ? ref.get() : null;
1639 }
1640 }
1641
Romain Guy65b345f2011-07-27 18:51:50 -07001642 private LoadedApk getPackageInfo(ApplicationInfo aInfo, CompatibilityInfo compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
1644 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001645 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 if (includeCode) {
1647 ref = mPackages.get(aInfo.packageName);
1648 } else {
1649 ref = mResourcePackages.get(aInfo.packageName);
1650 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001651 LoadedApk packageInfo = ref != null ? ref.get() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 if (packageInfo == null || (packageInfo.mResources != null
1653 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001654 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 : "Loading resource-only package ") + aInfo.packageName
1656 + " (in " + (mBoundApplication != null
1657 ? mBoundApplication.processName : null)
1658 + ")");
1659 packageInfo =
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001660 new LoadedApk(this, aInfo, compatInfo, this, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 securityViolation, includeCode &&
1662 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
1663 if (includeCode) {
1664 mPackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001665 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 } else {
1667 mResourcePackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001668 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 }
1670 }
1671 return packageInfo;
1672 }
1673 }
1674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 ActivityThread() {
1676 }
1677
1678 public ApplicationThread getApplicationThread()
1679 {
1680 return mAppThread;
1681 }
1682
1683 public Instrumentation getInstrumentation()
1684 {
1685 return mInstrumentation;
1686 }
1687
1688 public Configuration getConfiguration() {
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001689 return mResConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690 }
1691
1692 public boolean isProfiling() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001693 return mProfiler != null && mProfiler.profileFile != null
1694 && mProfiler.profileFd == null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 }
1696
1697 public String getProfileFilePath() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001698 return mProfiler.profileFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 }
1700
1701 public Looper getLooper() {
1702 return mLooper;
1703 }
1704
1705 public Application getApplication() {
1706 return mInitialApplication;
1707 }
Bob Leee5408332009-09-04 18:31:17 -07001708
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07001709 public String getProcessName() {
1710 return mBoundApplication.processName;
1711 }
Bob Leee5408332009-09-04 18:31:17 -07001712
Dianne Hackborn21556372010-02-04 16:34:40 -08001713 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 synchronized (this) {
1715 if (mSystemContext == null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001716 ContextImpl context =
1717 ContextImpl.createSystemContext(this);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001718 LoadedApk info = new LoadedApk(this, "android", context, null,
1719 CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 context.init(info, null, this);
1721 context.getResources().updateConfiguration(
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001722 getConfiguration(), getDisplayMetricsLocked(
1723 CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO, false));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 mSystemContext = context;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001725 //Slog.i(TAG, "Created system resources " + context.getResources()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 // + ": " + context.getResources().getConfiguration());
1727 }
1728 }
1729 return mSystemContext;
1730 }
1731
Mike Cleron432b7132009-09-24 15:28:29 -07001732 public void installSystemApplicationInfo(ApplicationInfo info) {
1733 synchronized (this) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001734 ContextImpl context = getSystemContext();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001735 context.init(new LoadedApk(this, "android", context, info,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001736 CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO), null, this);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001737
1738 // give ourselves a default profiler
1739 mProfiler = new Profiler();
Mike Cleron432b7132009-09-24 15:28:29 -07001740 }
1741 }
1742
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001743 void ensureJitEnabled() {
1744 if (!mJitEnabled) {
1745 mJitEnabled = true;
1746 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
1747 }
1748 }
1749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 void scheduleGcIdler() {
1751 if (!mGcIdlerScheduled) {
1752 mGcIdlerScheduled = true;
1753 Looper.myQueue().addIdleHandler(mGcIdler);
1754 }
1755 mH.removeMessages(H.GC_WHEN_IDLE);
1756 }
1757
1758 void unscheduleGcIdler() {
1759 if (mGcIdlerScheduled) {
1760 mGcIdlerScheduled = false;
1761 Looper.myQueue().removeIdleHandler(mGcIdler);
1762 }
1763 mH.removeMessages(H.GC_WHEN_IDLE);
1764 }
1765
1766 void doGcIfNeeded() {
1767 mGcIdlerScheduled = false;
1768 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001769 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 // + "m now=" + now);
1771 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001772 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 BinderInternal.forceGc("bg");
1774 }
1775 }
1776
Jeff Hamilton52d32032011-01-08 15:31:26 -06001777 public void registerOnActivityPausedListener(Activity activity,
1778 OnActivityPausedListener listener) {
1779 synchronized (mOnPauseListeners) {
1780 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
1781 if (list == null) {
1782 list = new ArrayList<OnActivityPausedListener>();
1783 mOnPauseListeners.put(activity, list);
1784 }
1785 list.add(listener);
1786 }
1787 }
1788
Jeff Hamiltonce3224c2011-01-17 11:05:03 -08001789 public void unregisterOnActivityPausedListener(Activity activity,
1790 OnActivityPausedListener listener) {
1791 synchronized (mOnPauseListeners) {
1792 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
1793 if (list != null) {
1794 list.remove(listener);
1795 }
1796 }
1797 }
1798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001799 public final ActivityInfo resolveActivityInfo(Intent intent) {
1800 ActivityInfo aInfo = intent.resolveActivityInfo(
1801 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
1802 if (aInfo == null) {
1803 // Throw an exception.
1804 Instrumentation.checkStartActivityResult(
1805 IActivityManager.START_CLASS_NOT_FOUND, intent);
1806 }
1807 return aInfo;
1808 }
Bob Leee5408332009-09-04 18:31:17 -07001809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001812 Activity.NonConfigurationInstances lastNonConfigurationInstances) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001813 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001815 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001816 r.intent = intent;
1817 r.state = state;
1818 r.parent = parent;
1819 r.embeddedID = id;
1820 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001821 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 if (localLOGV) {
1823 ComponentName compname = intent.getComponent();
1824 String name;
1825 if (compname != null) {
1826 name = compname.toShortString();
1827 } else {
1828 name = "(Intent " + intent + ").getComponent() returned null";
1829 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001830 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 + ", comp=" + name
1832 + ", token=" + token);
1833 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07001834 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 }
1836
1837 public final Activity getActivity(IBinder token) {
1838 return mActivities.get(token).activity;
1839 }
1840
1841 public final void sendActivityResult(
1842 IBinder token, String id, int requestCode,
1843 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001844 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07001845 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
1847 list.add(new ResultInfo(id, requestCode, resultCode, data));
1848 mAppThread.scheduleSendResult(token, list);
1849 }
1850
1851 // if the thread hasn't started yet, we don't have the handler, so just
1852 // save the messages until we're ready.
Romain Guy65b345f2011-07-27 18:51:50 -07001853 private void queueOrSendMessage(int what, Object obj) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 queueOrSendMessage(what, obj, 0, 0);
1855 }
1856
Romain Guy65b345f2011-07-27 18:51:50 -07001857 private void queueOrSendMessage(int what, Object obj, int arg1) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 queueOrSendMessage(what, obj, arg1, 0);
1859 }
1860
Romain Guy65b345f2011-07-27 18:51:50 -07001861 private void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 synchronized (this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001863 if (DEBUG_MESSAGES) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
1865 + ": " + arg1 + " / " + obj);
1866 Message msg = Message.obtain();
1867 msg.what = what;
1868 msg.obj = obj;
1869 msg.arg1 = arg1;
1870 msg.arg2 = arg2;
1871 mH.sendMessage(msg);
1872 }
1873 }
1874
Dianne Hackborn21556372010-02-04 16:34:40 -08001875 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 String what) {
1877 ContextCleanupInfo cci = new ContextCleanupInfo();
1878 cci.context = context;
1879 cci.who = who;
1880 cci.what = what;
1881 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
1882 }
1883
Romain Guy65b345f2011-07-27 18:51:50 -07001884 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
1886
1887 ActivityInfo aInfo = r.activityInfo;
1888 if (r.packageInfo == null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001889 r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 Context.CONTEXT_INCLUDE_CODE);
1891 }
Bob Leee5408332009-09-04 18:31:17 -07001892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 ComponentName component = r.intent.getComponent();
1894 if (component == null) {
1895 component = r.intent.resolveActivity(
1896 mInitialApplication.getPackageManager());
1897 r.intent.setComponent(component);
1898 }
1899
1900 if (r.activityInfo.targetActivity != null) {
1901 component = new ComponentName(r.activityInfo.packageName,
1902 r.activityInfo.targetActivity);
1903 }
1904
1905 Activity activity = null;
1906 try {
1907 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
1908 activity = mInstrumentation.newActivity(
1909 cl, component.getClassName(), r.intent);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08001910 StrictMode.incrementExpectedActivityCount(activity.getClass());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 r.intent.setExtrasClassLoader(cl);
1912 if (r.state != null) {
1913 r.state.setClassLoader(cl);
1914 }
1915 } catch (Exception e) {
1916 if (!mInstrumentation.onException(activity, e)) {
1917 throw new RuntimeException(
1918 "Unable to instantiate activity " + component
1919 + ": " + e.toString(), e);
1920 }
1921 }
1922
1923 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001924 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001925
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001926 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
1927 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 TAG, r + ": app=" + app
1929 + ", appName=" + app.getPackageName()
1930 + ", pkg=" + r.packageInfo.getPackageName()
1931 + ", comp=" + r.intent.getComponent().toShortString()
1932 + ", dir=" + r.packageInfo.getAppDir());
1933
1934 if (activity != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001935 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 appContext.init(r.packageInfo, r.token, this);
1937 appContext.setOuterContext(activity);
1938 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001939 Configuration config = new Configuration(mCompatConfiguration);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001940 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07001941 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001942 activity.attach(appContext, this, getInstrumentation(), r.token,
1943 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001944 r.embeddedID, r.lastNonConfigurationInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07001945
Christopher Tateb70f3df2009-04-07 16:07:59 -07001946 if (customIntent != null) {
1947 activity.mIntent = customIntent;
1948 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001949 r.lastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 activity.mStartedActivity = false;
1951 int theme = r.activityInfo.getThemeResource();
1952 if (theme != 0) {
1953 activity.setTheme(theme);
1954 }
1955
1956 activity.mCalled = false;
1957 mInstrumentation.callActivityOnCreate(activity, r.state);
1958 if (!activity.mCalled) {
1959 throw new SuperNotCalledException(
1960 "Activity " + r.intent.getComponent().toShortString() +
1961 " did not call through to super.onCreate()");
1962 }
1963 r.activity = activity;
1964 r.stopped = true;
1965 if (!r.activity.mFinished) {
1966 activity.performStart();
1967 r.stopped = false;
1968 }
1969 if (!r.activity.mFinished) {
1970 if (r.state != null) {
1971 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
1972 }
1973 }
1974 if (!r.activity.mFinished) {
1975 activity.mCalled = false;
1976 mInstrumentation.callActivityOnPostCreate(activity, r.state);
1977 if (!activity.mCalled) {
1978 throw new SuperNotCalledException(
1979 "Activity " + r.intent.getComponent().toShortString() +
1980 " did not call through to super.onPostCreate()");
1981 }
1982 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001983 }
1984 r.paused = true;
1985
1986 mActivities.put(r.token, r);
1987
1988 } catch (SuperNotCalledException e) {
1989 throw e;
1990
1991 } catch (Exception e) {
1992 if (!mInstrumentation.onException(activity, e)) {
1993 throw new RuntimeException(
1994 "Unable to start activity " + component
1995 + ": " + e.toString(), e);
1996 }
1997 }
1998
1999 return activity;
2000 }
2001
Romain Guy65b345f2011-07-27 18:51:50 -07002002 private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 // If we are getting ready to gc after going to the background, well
2004 // we are back active so skip it.
2005 unscheduleGcIdler();
2006
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002007 if (r.profileFd != null) {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002008 mProfiler.setProfiler(r.profileFile, r.profileFd);
2009 mProfiler.startProfiling();
2010 mProfiler.autoStopProfiler = r.autoStopProfiler;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002011 }
2012
Dianne Hackborn58f42a52011-10-10 13:46:34 -07002013 // Make sure we are running with the most recent config.
2014 handleConfigurationChanged(null, null);
2015
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002016 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07002018 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019
2020 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002021 r.createdConfig = new Configuration(mConfiguration);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08002022 Bundle oldState = r.state;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 handleResumeActivity(r.token, false, r.isForward);
2024
2025 if (!r.activity.mFinished && r.startsNotResumed) {
2026 // The activity manager actually wants this one to start out
2027 // paused, because it needs to be visible but isn't in the
2028 // foreground. We accomplish this by going through the
2029 // normal startup (because activities expect to go through
2030 // onResume() the first time they run, before their window
2031 // is displayed), and then pausing it. However, in this case
2032 // we do -not- need to do the full pause cycle (of freezing
2033 // and such) because the activity manager assumes it can just
2034 // retain the current state it has.
2035 try {
2036 r.activity.mCalled = false;
2037 mInstrumentation.callActivityOnPause(r.activity);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08002038 // We need to keep around the original state, in case
2039 // we need to be created again.
2040 r.state = oldState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 if (!r.activity.mCalled) {
2042 throw new SuperNotCalledException(
2043 "Activity " + r.intent.getComponent().toShortString() +
2044 " did not call through to super.onPause()");
2045 }
2046
2047 } catch (SuperNotCalledException e) {
2048 throw e;
2049
2050 } catch (Exception e) {
2051 if (!mInstrumentation.onException(r.activity, e)) {
2052 throw new RuntimeException(
2053 "Unable to pause activity "
2054 + r.intent.getComponent().toShortString()
2055 + ": " + e.toString(), e);
2056 }
2057 }
2058 r.paused = true;
2059 }
2060 } else {
2061 // If there was an error, for any reason, tell the activity
2062 // manager to stop us.
2063 try {
2064 ActivityManagerNative.getDefault()
2065 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
2066 } catch (RemoteException ex) {
Romain Guy65b345f2011-07-27 18:51:50 -07002067 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002068 }
2069 }
2070 }
2071
Romain Guy65b345f2011-07-27 18:51:50 -07002072 private void deliverNewIntents(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002073 List<Intent> intents) {
2074 final int N = intents.size();
2075 for (int i=0; i<N; i++) {
2076 Intent intent = intents.get(i);
2077 intent.setExtrasClassLoader(r.activity.getClassLoader());
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002078 r.activity.mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
2080 }
2081 }
2082
2083 public final void performNewIntents(IBinder token,
2084 List<Intent> intents) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002085 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086 if (r != null) {
2087 final boolean resumed = !r.paused;
2088 if (resumed) {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002089 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 mInstrumentation.callActivityOnPause(r.activity);
2091 }
2092 deliverNewIntents(r, intents);
2093 if (resumed) {
Dianne Hackbornb46ed762011-06-02 18:33:15 -07002094 r.activity.performResume();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002095 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002096 }
2097 }
2098 }
Bob Leee5408332009-09-04 18:31:17 -07002099
Romain Guy65b345f2011-07-27 18:51:50 -07002100 private void handleNewIntent(NewIntentData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002101 performNewIntents(data.token, data.intents);
2102 }
2103
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002104 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
2105
2106 /**
2107 * Return the Intent that's currently being handled by a
2108 * BroadcastReceiver on this thread, or null if none.
2109 * @hide
2110 */
2111 public static Intent getIntentBeingBroadcast() {
2112 return sCurrentBroadcastIntent.get();
2113 }
2114
Romain Guy65b345f2011-07-27 18:51:50 -07002115 private void handleReceiver(ReceiverData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002116 // If we are getting ready to gc after going to the background, well
2117 // we are back active so skip it.
2118 unscheduleGcIdler();
2119
2120 String component = data.intent.getComponent().getClassName();
2121
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002122 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002123 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124
2125 IActivityManager mgr = ActivityManagerNative.getDefault();
2126
Romain Guy65b345f2011-07-27 18:51:50 -07002127 BroadcastReceiver receiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002128 try {
2129 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2130 data.intent.setExtrasClassLoader(cl);
Dianne Hackborne829fef2010-10-26 17:44:01 -07002131 data.setExtrasClassLoader(cl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
2133 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07002134 if (DEBUG_BROADCAST) Slog.i(TAG,
2135 "Finishing failed broadcast to " + data.intent.getComponent());
2136 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002137 throw new RuntimeException(
2138 "Unable to instantiate receiver " + component
2139 + ": " + e.toString(), e);
2140 }
2141
2142 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08002143 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07002144
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002145 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002146 TAG, "Performing receive of " + data.intent
2147 + ": app=" + app
2148 + ", appName=" + app.getPackageName()
2149 + ", pkg=" + packageInfo.getPackageName()
2150 + ", comp=" + data.intent.getComponent().toShortString()
2151 + ", dir=" + packageInfo.getAppDir());
2152
Dianne Hackborn21556372010-02-04 16:34:40 -08002153 ContextImpl context = (ContextImpl)app.getBaseContext();
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002154 sCurrentBroadcastIntent.set(data.intent);
Dianne Hackborne829fef2010-10-26 17:44:01 -07002155 receiver.setPendingResult(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002156 receiver.onReceive(context.getReceiverRestrictedContext(),
2157 data.intent);
2158 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07002159 if (DEBUG_BROADCAST) Slog.i(TAG,
2160 "Finishing failed broadcast to " + data.intent.getComponent());
2161 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002162 if (!mInstrumentation.onException(receiver, e)) {
2163 throw new RuntimeException(
2164 "Unable to start receiver " + component
2165 + ": " + e.toString(), e);
2166 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002167 } finally {
2168 sCurrentBroadcastIntent.set(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002169 }
2170
Dianne Hackborne829fef2010-10-26 17:44:01 -07002171 if (receiver.getPendingResult() != null) {
2172 data.finish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173 }
2174 }
2175
Christopher Tate181fafa2009-05-14 11:12:14 -07002176 // Instantiate a BackupAgent and tell it that it's alive
Romain Guy65b345f2011-07-27 18:51:50 -07002177 private void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002178 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07002179
2180 // no longer idle; we have backup work to do
2181 unscheduleGcIdler();
2182
2183 // instantiate the BackupAgent class named in the manifest
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002184 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07002185 String packageName = packageInfo.mPackageName;
2186 if (mBackupAgents.get(packageName) != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002187 Slog.d(TAG, "BackupAgent " + " for " + packageName
Christopher Tate181fafa2009-05-14 11:12:14 -07002188 + " already exists");
2189 return;
2190 }
Bob Leee5408332009-09-04 18:31:17 -07002191
Christopher Tate181fafa2009-05-14 11:12:14 -07002192 BackupAgent agent = null;
2193 String classname = data.appInfo.backupAgentName;
Christopher Tate4a627c72011-04-01 14:43:32 -07002194
Christopher Tate79ec80d2011-06-24 14:58:49 -07002195 // full backup operation but no app-supplied agent? use the default implementation
2196 if (classname == null && (data.backupMode == IApplicationThread.BACKUP_MODE_FULL
2197 || data.backupMode == IApplicationThread.BACKUP_MODE_RESTORE_FULL)) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002198 classname = "android.app.backup.FullBackupAgent";
Christopher Tate181fafa2009-05-14 11:12:14 -07002199 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002200
Christopher Tate181fafa2009-05-14 11:12:14 -07002201 try {
Christopher Tated1475e02009-07-09 15:36:17 -07002202 IBinder binder = null;
2203 try {
Christopher Tate4a627c72011-04-01 14:43:32 -07002204 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing agent class " + classname);
2205
Christopher Tated1475e02009-07-09 15:36:17 -07002206 java.lang.ClassLoader cl = packageInfo.getClassLoader();
Christopher Tate4a627c72011-04-01 14:43:32 -07002207 agent = (BackupAgent) cl.loadClass(classname).newInstance();
Christopher Tated1475e02009-07-09 15:36:17 -07002208
2209 // set up the agent's context
Dianne Hackborn21556372010-02-04 16:34:40 -08002210 ContextImpl context = new ContextImpl();
Christopher Tated1475e02009-07-09 15:36:17 -07002211 context.init(packageInfo, null, this);
2212 context.setOuterContext(agent);
2213 agent.attach(context);
2214
2215 agent.onCreate();
2216 binder = agent.onBind();
2217 mBackupAgents.put(packageName, agent);
2218 } catch (Exception e) {
2219 // If this is during restore, fail silently; otherwise go
2220 // ahead and let the user see the crash.
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002221 Slog.e(TAG, "Agent threw during creation: " + e);
Christopher Tate75a99702011-05-18 16:28:19 -07002222 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE
2223 && data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE_FULL) {
Christopher Tated1475e02009-07-09 15:36:17 -07002224 throw e;
2225 }
2226 // falling through with 'binder' still null
2227 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002228
2229 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07002230 try {
2231 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
2232 } catch (RemoteException e) {
2233 // nothing to do.
2234 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002235 } catch (Exception e) {
2236 throw new RuntimeException("Unable to create BackupAgent "
Christopher Tate4a627c72011-04-01 14:43:32 -07002237 + classname + ": " + e.toString(), e);
Christopher Tate181fafa2009-05-14 11:12:14 -07002238 }
2239 }
2240
2241 // Tear down a BackupAgent
Romain Guy65b345f2011-07-27 18:51:50 -07002242 private void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002243 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07002244
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002245 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07002246 String packageName = packageInfo.mPackageName;
2247 BackupAgent agent = mBackupAgents.get(packageName);
2248 if (agent != null) {
2249 try {
2250 agent.onDestroy();
2251 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002252 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07002253 e.printStackTrace();
2254 }
2255 mBackupAgents.remove(packageName);
2256 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002257 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07002258 }
2259 }
2260
Romain Guy65b345f2011-07-27 18:51:50 -07002261 private void handleCreateService(CreateServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002262 // If we are getting ready to gc after going to the background, well
2263 // we are back active so skip it.
2264 unscheduleGcIdler();
2265
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002266 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002267 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002268 Service service = null;
2269 try {
2270 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2271 service = (Service) cl.loadClass(data.info.name).newInstance();
2272 } catch (Exception e) {
2273 if (!mInstrumentation.onException(service, e)) {
2274 throw new RuntimeException(
2275 "Unable to instantiate service " + data.info.name
2276 + ": " + e.toString(), e);
2277 }
2278 }
2279
2280 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002281 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002282
Dianne Hackborn21556372010-02-04 16:34:40 -08002283 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002284 context.init(packageInfo, null, this);
2285
Dianne Hackborn0be1f782009-11-09 12:30:12 -08002286 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002287 context.setOuterContext(service);
2288 service.attach(context, this, data.info.name, data.token, app,
2289 ActivityManagerNative.getDefault());
2290 service.onCreate();
2291 mServices.put(data.token, service);
2292 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002293 ActivityManagerNative.getDefault().serviceDoneExecuting(
2294 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002295 } catch (RemoteException e) {
2296 // nothing to do.
2297 }
2298 } catch (Exception e) {
2299 if (!mInstrumentation.onException(service, e)) {
2300 throw new RuntimeException(
2301 "Unable to create service " + data.info.name
2302 + ": " + e.toString(), e);
2303 }
2304 }
2305 }
2306
Romain Guy65b345f2011-07-27 18:51:50 -07002307 private void handleBindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002308 Service s = mServices.get(data.token);
Amith Yamasani742a6712011-05-04 14:49:28 -07002309 if (DEBUG_SERVICE)
2310 Slog.v(TAG, "handleBindService s=" + s + " rebind=" + data.rebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002311 if (s != null) {
2312 try {
2313 data.intent.setExtrasClassLoader(s.getClassLoader());
2314 try {
2315 if (!data.rebind) {
2316 IBinder binder = s.onBind(data.intent);
2317 ActivityManagerNative.getDefault().publishService(
2318 data.token, data.intent, binder);
2319 } else {
2320 s.onRebind(data.intent);
2321 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002322 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002323 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002324 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 } catch (RemoteException ex) {
2326 }
2327 } catch (Exception e) {
2328 if (!mInstrumentation.onException(s, e)) {
2329 throw new RuntimeException(
2330 "Unable to bind to service " + s
2331 + " with " + data.intent + ": " + e.toString(), e);
2332 }
2333 }
2334 }
2335 }
2336
Romain Guy65b345f2011-07-27 18:51:50 -07002337 private void handleUnbindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002338 Service s = mServices.get(data.token);
2339 if (s != null) {
2340 try {
2341 data.intent.setExtrasClassLoader(s.getClassLoader());
2342 boolean doRebind = s.onUnbind(data.intent);
2343 try {
2344 if (doRebind) {
2345 ActivityManagerNative.getDefault().unbindFinished(
2346 data.token, data.intent, doRebind);
2347 } else {
2348 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002349 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002350 }
2351 } catch (RemoteException ex) {
2352 }
2353 } catch (Exception e) {
2354 if (!mInstrumentation.onException(s, e)) {
2355 throw new RuntimeException(
2356 "Unable to unbind to service " + s
2357 + " with " + data.intent + ": " + e.toString(), e);
2358 }
2359 }
2360 }
2361 }
2362
Dianne Hackborn625ac272010-09-17 18:29:22 -07002363 private void handleDumpService(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08002364 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
2365 try {
2366 Service s = mServices.get(info.token);
2367 if (s != null) {
2368 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
2369 s.dump(info.fd.getFileDescriptor(), pw, info.args);
2370 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002371 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08002372 } finally {
2373 IoUtils.closeQuietly(info.fd);
2374 StrictMode.setThreadPolicy(oldPolicy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375 }
2376 }
2377
Dianne Hackborn625ac272010-09-17 18:29:22 -07002378 private void handleDumpActivity(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08002379 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
2380 try {
2381 ActivityClientRecord r = mActivities.get(info.token);
2382 if (r != null && r.activity != null) {
2383 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
2384 r.activity.dump(info.prefix, info.fd.getFileDescriptor(), pw, info.args);
2385 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07002386 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08002387 } finally {
2388 IoUtils.closeQuietly(info.fd);
2389 StrictMode.setThreadPolicy(oldPolicy);
Dianne Hackborn625ac272010-09-17 18:29:22 -07002390 }
2391 }
2392
Marco Nelissen18cb2872011-11-15 11:19:53 -08002393 private void handleDumpProvider(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08002394 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
2395 try {
2396 ProviderClientRecord r = mLocalProviders.get(info.token);
2397 if (r != null && r.mLocalProvider != null) {
2398 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
2399 r.mLocalProvider.dump(info.fd.getFileDescriptor(), pw, info.args);
2400 pw.flush();
Marco Nelissen18cb2872011-11-15 11:19:53 -08002401 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08002402 } finally {
2403 IoUtils.closeQuietly(info.fd);
2404 StrictMode.setThreadPolicy(oldPolicy);
Marco Nelissen18cb2872011-11-15 11:19:53 -08002405 }
2406 }
2407
Romain Guy65b345f2011-07-27 18:51:50 -07002408 private void handleServiceArgs(ServiceArgsData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002409 Service s = mServices.get(data.token);
2410 if (s != null) {
2411 try {
2412 if (data.args != null) {
2413 data.args.setExtrasClassLoader(s.getClassLoader());
2414 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002415 int res;
2416 if (!data.taskRemoved) {
2417 res = s.onStartCommand(data.args, data.flags, data.startId);
2418 } else {
2419 s.onTaskRemoved(data.args);
2420 res = Service.START_TASK_REMOVED_COMPLETE;
2421 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002422
2423 QueuedWork.waitToFinish();
2424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002425 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002426 ActivityManagerNative.getDefault().serviceDoneExecuting(
2427 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002428 } catch (RemoteException e) {
2429 // nothing to do.
2430 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002431 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 } catch (Exception e) {
2433 if (!mInstrumentation.onException(s, e)) {
2434 throw new RuntimeException(
2435 "Unable to start service " + s
2436 + " with " + data.args + ": " + e.toString(), e);
2437 }
2438 }
2439 }
2440 }
2441
Romain Guy65b345f2011-07-27 18:51:50 -07002442 private void handleStopService(IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 Service s = mServices.remove(token);
2444 if (s != null) {
2445 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002446 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002447 s.onDestroy();
2448 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002449 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08002451 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002452 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002453
2454 QueuedWork.waitToFinish();
2455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002457 ActivityManagerNative.getDefault().serviceDoneExecuting(
2458 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002459 } catch (RemoteException e) {
2460 // nothing to do.
2461 }
2462 } catch (Exception e) {
2463 if (!mInstrumentation.onException(s, e)) {
2464 throw new RuntimeException(
2465 "Unable to stop service " + s
2466 + ": " + e.toString(), e);
2467 }
2468 }
2469 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002470 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002471 }
2472
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002473 public final ActivityClientRecord performResumeActivity(IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002474 boolean clearHide) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002475 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002476 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002477 + " finished=" + r.activity.mFinished);
2478 if (r != null && !r.activity.mFinished) {
2479 if (clearHide) {
2480 r.hideForNow = false;
2481 r.activity.mStartedActivity = false;
2482 }
2483 try {
2484 if (r.pendingIntents != null) {
2485 deliverNewIntents(r, r.pendingIntents);
2486 r.pendingIntents = null;
2487 }
2488 if (r.pendingResults != null) {
2489 deliverResults(r, r.pendingResults);
2490 r.pendingResults = null;
2491 }
2492 r.activity.performResume();
2493
Bob Leee5408332009-09-04 18:31:17 -07002494 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002497 r.paused = false;
2498 r.stopped = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 r.state = null;
2500 } catch (Exception e) {
2501 if (!mInstrumentation.onException(r.activity, e)) {
2502 throw new RuntimeException(
2503 "Unable to resume activity "
2504 + r.intent.getComponent().toShortString()
2505 + ": " + e.toString(), e);
2506 }
2507 }
2508 }
2509 return r;
2510 }
2511
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002512 final void cleanUpPendingRemoveWindows(ActivityClientRecord r) {
2513 if (r.mPendingRemoveWindow != null) {
2514 r.mPendingRemoveWindowManager.removeViewImmediate(r.mPendingRemoveWindow);
2515 IBinder wtoken = r.mPendingRemoveWindow.getWindowToken();
2516 if (wtoken != null) {
2517 WindowManagerImpl.getDefault().closeAll(wtoken,
2518 r.activity.getClass().getName(), "Activity");
2519 }
2520 }
2521 r.mPendingRemoveWindow = null;
2522 r.mPendingRemoveWindowManager = null;
2523 }
2524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2526 // If we are getting ready to gc after going to the background, well
2527 // we are back active so skip it.
2528 unscheduleGcIdler();
2529
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002530 ActivityClientRecord r = performResumeActivity(token, clearHide);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002531
2532 if (r != null) {
2533 final Activity a = r.activity;
2534
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002535 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 TAG, "Resume " + r + " started activity: " +
2537 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2538 + ", finished: " + a.mFinished);
2539
2540 final int forwardBit = isForward ?
2541 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543 // If the window hasn't yet been added to the window manager,
2544 // and this guy didn't finish itself or start another activity,
2545 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002546 boolean willBeVisible = !a.mStartedActivity;
2547 if (!willBeVisible) {
2548 try {
2549 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
2550 a.getActivityToken());
2551 } catch (RemoteException e) {
2552 }
2553 }
2554 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 r.window = r.activity.getWindow();
2556 View decor = r.window.getDecorView();
2557 decor.setVisibility(View.INVISIBLE);
2558 ViewManager wm = a.getWindowManager();
2559 WindowManager.LayoutParams l = r.window.getAttributes();
2560 a.mDecor = decor;
2561 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2562 l.softInputMode |= forwardBit;
2563 if (a.mVisibleFromClient) {
2564 a.mWindowAdded = true;
2565 wm.addView(decor, l);
2566 }
2567
2568 // If the window has already been added, but during resume
2569 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002570 // window visible.
2571 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002572 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 TAG, "Launch " + r + " mStartedActivity set");
2574 r.hideForNow = true;
2575 }
2576
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002577 // Get rid of anything left hanging around.
2578 cleanUpPendingRemoveWindows(r);
2579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 // The window is now visible if it has been added, we are not
2581 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002582 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002583 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002585 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002586 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 performConfigurationChanged(r.activity, r.newConfig);
2588 r.newConfig = null;
2589 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002590 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 + isForward);
2592 WindowManager.LayoutParams l = r.window.getAttributes();
2593 if ((l.softInputMode
2594 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2595 != forwardBit) {
2596 l.softInputMode = (l.softInputMode
2597 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2598 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002599 if (r.activity.mVisibleFromClient) {
2600 ViewManager wm = a.getWindowManager();
2601 View decor = r.window.getDecorView();
2602 wm.updateViewLayout(decor, l);
2603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 }
2605 r.activity.mVisibleFromServer = true;
2606 mNumVisibleActivities++;
2607 if (r.activity.mVisibleFromClient) {
2608 r.activity.makeVisible();
2609 }
2610 }
2611
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002612 if (!r.onlyLocalRequest) {
2613 r.nextIdle = mNewActivities;
2614 mNewActivities = r;
2615 if (localLOGV) Slog.v(
2616 TAG, "Scheduling idle handler for " + r);
2617 Looper.myQueue().addIdleHandler(new Idler());
2618 }
2619 r.onlyLocalRequest = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002620
2621 } else {
2622 // If an exception was thrown when trying to resume, then
2623 // just end this activity.
2624 try {
2625 ActivityManagerNative.getDefault()
2626 .finishActivity(token, Activity.RESULT_CANCELED, null);
2627 } catch (RemoteException ex) {
2628 }
2629 }
2630 }
2631
2632 private int mThumbnailWidth = -1;
2633 private int mThumbnailHeight = -1;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002634 private Bitmap mAvailThumbnailBitmap = null;
2635 private Canvas mThumbnailCanvas = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636
Romain Guy65b345f2011-07-27 18:51:50 -07002637 private Bitmap createThumbnailBitmap(ActivityClientRecord r) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002638 Bitmap thumbnail = mAvailThumbnailBitmap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002639 try {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002640 if (thumbnail == null) {
2641 int w = mThumbnailWidth;
2642 int h;
2643 if (w < 0) {
2644 Resources res = r.activity.getResources();
2645 mThumbnailHeight = h =
2646 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002647
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002648 mThumbnailWidth = w =
2649 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
2650 } else {
2651 h = mThumbnailHeight;
2652 }
2653
2654 // On platforms where we don't want thumbnails, set dims to (0,0)
2655 if ((w > 0) && (h > 0)) {
2656 thumbnail = Bitmap.createBitmap(w, h, THUMBNAIL_FORMAT);
2657 thumbnail.eraseColor(0);
2658 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002659 }
2660
Dianne Hackbornfb3806d2010-12-09 13:14:12 -08002661 if (thumbnail != null) {
2662 Canvas cv = mThumbnailCanvas;
2663 if (cv == null) {
2664 mThumbnailCanvas = cv = new Canvas();
2665 }
2666
2667 cv.setBitmap(thumbnail);
2668 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
2669 mAvailThumbnailBitmap = thumbnail;
2670 thumbnail = null;
2671 }
Dianne Hackborn6311d0a2011-08-02 16:37:58 -07002672 cv.setBitmap(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 }
Jim Miller0b2a6d02010-07-13 18:01:29 -07002674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 } catch (Exception e) {
2676 if (!mInstrumentation.onException(r.activity, e)) {
2677 throw new RuntimeException(
2678 "Unable to create thumbnail of "
2679 + r.intent.getComponent().toShortString()
2680 + ": " + e.toString(), e);
2681 }
2682 thumbnail = null;
2683 }
2684
2685 return thumbnail;
2686 }
2687
Romain Guy65b345f2011-07-27 18:51:50 -07002688 private void handlePauseActivity(IBinder token, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002689 boolean userLeaving, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002690 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002691 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002692 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693 if (userLeaving) {
2694 performUserLeavingActivity(r);
2695 }
Bob Leee5408332009-09-04 18:31:17 -07002696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002697 r.activity.mConfigChangeFlags |= configChanges;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002698 performPauseActivity(token, finished, r.isPreHoneycomb());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07002700 // Make sure any pending writes are now committed.
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002701 if (r.isPreHoneycomb()) {
2702 QueuedWork.waitToFinish();
2703 }
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07002704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002705 // Tell the activity manager we have paused.
2706 try {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002707 ActivityManagerNative.getDefault().activityPaused(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002708 } catch (RemoteException ex) {
2709 }
2710 }
2711 }
2712
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002713 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002714 mInstrumentation.callActivityOnUserLeaving(r.activity);
2715 }
2716
2717 final Bundle performPauseActivity(IBinder token, boolean finished,
2718 boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002719 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 return r != null ? performPauseActivity(r, finished, saveState) : null;
2721 }
2722
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002723 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 boolean saveState) {
2725 if (r.paused) {
2726 if (r.activity.mFinished) {
2727 // If we are finishing, we won't call onResume() in certain cases.
2728 // So here we likewise don't want to call onPause() if the activity
2729 // isn't resumed.
2730 return null;
2731 }
2732 RuntimeException e = new RuntimeException(
2733 "Performing pause of activity that is not resumed: "
2734 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002735 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002736 }
2737 Bundle state = null;
2738 if (finished) {
2739 r.activity.mFinished = true;
2740 }
2741 try {
2742 // Next have the activity save its current state and managed dialogs...
2743 if (!r.activity.mFinished && saveState) {
2744 state = new Bundle();
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04002745 state.setAllowFds(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002746 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2747 r.state = state;
2748 }
2749 // Now we are idle.
2750 r.activity.mCalled = false;
2751 mInstrumentation.callActivityOnPause(r.activity);
2752 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
2753 if (!r.activity.mCalled) {
2754 throw new SuperNotCalledException(
2755 "Activity " + r.intent.getComponent().toShortString() +
2756 " did not call through to super.onPause()");
2757 }
2758
2759 } catch (SuperNotCalledException e) {
2760 throw e;
2761
2762 } catch (Exception e) {
2763 if (!mInstrumentation.onException(r.activity, e)) {
2764 throw new RuntimeException(
2765 "Unable to pause activity "
2766 + r.intent.getComponent().toShortString()
2767 + ": " + e.toString(), e);
2768 }
2769 }
2770 r.paused = true;
Jeff Hamilton52d32032011-01-08 15:31:26 -06002771
2772 // Notify any outstanding on paused listeners
2773 ArrayList<OnActivityPausedListener> listeners;
2774 synchronized (mOnPauseListeners) {
2775 listeners = mOnPauseListeners.remove(r.activity);
2776 }
2777 int size = (listeners != null ? listeners.size() : 0);
2778 for (int i = 0; i < size; i++) {
2779 listeners.get(i).onPaused(r.activity);
2780 }
2781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 return state;
2783 }
2784
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002785 final void performStopActivity(IBinder token, boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002786 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002787 performStopActivityInner(r, null, false, saveState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002788 }
2789
2790 private static class StopInfo {
2791 Bitmap thumbnail;
2792 CharSequence description;
2793 }
2794
Jeff Brownddaa9ac2011-11-11 20:16:14 -08002795 private static final class ProviderRefCount {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 public int count;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08002797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002798 ProviderRefCount(int pCount) {
2799 count = pCount;
2800 }
2801 }
2802
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002803 /**
2804 * Core implementation of stopping an activity. Note this is a little
2805 * tricky because the server's meaning of stop is slightly different
2806 * than our client -- for the server, stop means to save state and give
2807 * it the result when it is done, but the window may still be visible.
2808 * For the client, we want to call onStop()/onStart() to indicate when
2809 * the activity's UI visibillity changes.
2810 */
Romain Guy65b345f2011-07-27 18:51:50 -07002811 private void performStopActivityInner(ActivityClientRecord r,
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002812 StopInfo info, boolean keepShown, boolean saveState) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002813 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002814 Bundle state = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 if (r != null) {
2816 if (!keepShown && r.stopped) {
2817 if (r.activity.mFinished) {
2818 // If we are finishing, we won't call onResume() in certain
2819 // cases. So here we likewise don't want to call onStop()
2820 // if the activity isn't resumed.
2821 return;
2822 }
2823 RuntimeException e = new RuntimeException(
2824 "Performing stop of activity that is not resumed: "
2825 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002826 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 }
2828
2829 if (info != null) {
2830 try {
2831 // First create a thumbnail for the activity...
Dianne Hackborn0500b3c2011-11-01 15:28:43 -07002832 // For now, don't create the thumbnail here; we are
2833 // doing that by doing a screen snapshot.
2834 info.thumbnail = null; //createThumbnailBitmap(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 info.description = r.activity.onCreateDescription();
2836 } catch (Exception e) {
2837 if (!mInstrumentation.onException(r.activity, e)) {
2838 throw new RuntimeException(
2839 "Unable to save state of activity "
2840 + r.intent.getComponent().toShortString()
2841 + ": " + e.toString(), e);
2842 }
2843 }
2844 }
2845
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002846 // Next have the activity save its current state and managed dialogs...
2847 if (!r.activity.mFinished && saveState) {
2848 if (r.state == null) {
2849 state = new Bundle();
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04002850 state.setAllowFds(false);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002851 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2852 r.state = state;
2853 } else {
2854 state = r.state;
2855 }
2856 }
2857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002858 if (!keepShown) {
2859 try {
2860 // Now we are idle.
2861 r.activity.performStop();
2862 } catch (Exception e) {
2863 if (!mInstrumentation.onException(r.activity, e)) {
2864 throw new RuntimeException(
2865 "Unable to stop activity "
2866 + r.intent.getComponent().toShortString()
2867 + ": " + e.toString(), e);
2868 }
2869 }
2870 r.stopped = true;
2871 }
2872
2873 r.paused = true;
2874 }
2875 }
2876
Romain Guy65b345f2011-07-27 18:51:50 -07002877 private void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002878 View v = r.activity.mDecor;
2879 if (v != null) {
2880 if (show) {
2881 if (!r.activity.mVisibleFromServer) {
2882 r.activity.mVisibleFromServer = true;
2883 mNumVisibleActivities++;
2884 if (r.activity.mVisibleFromClient) {
2885 r.activity.makeVisible();
2886 }
2887 }
2888 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002889 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002890 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002891 performConfigurationChanged(r.activity, r.newConfig);
2892 r.newConfig = null;
2893 }
2894 } else {
2895 if (r.activity.mVisibleFromServer) {
2896 r.activity.mVisibleFromServer = false;
2897 mNumVisibleActivities--;
2898 v.setVisibility(View.INVISIBLE);
2899 }
2900 }
2901 }
2902 }
2903
Romain Guy65b345f2011-07-27 18:51:50 -07002904 private void handleStopActivity(IBinder token, boolean show, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002905 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002906 r.activity.mConfigChangeFlags |= configChanges;
2907
2908 StopInfo info = new StopInfo();
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002909 performStopActivityInner(r, info, show, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002910
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002911 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002912 TAG, "Finishing stop of " + r + ": show=" + show
2913 + " win=" + r.window);
2914
2915 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07002916
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002917 // Make sure any pending writes are now committed.
2918 if (!r.isPreHoneycomb()) {
2919 QueuedWork.waitToFinish();
2920 }
2921
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002922 // Tell activity manager we have been stopped.
2923 try {
2924 ActivityManagerNative.getDefault().activityStopped(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002925 r.token, r.state, info.thumbnail, info.description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002926 } catch (RemoteException ex) {
2927 }
2928 }
2929
2930 final void performRestartActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002931 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 if (r.stopped) {
2933 r.activity.performRestart();
2934 r.stopped = false;
2935 }
2936 }
2937
Romain Guy65b345f2011-07-27 18:51:50 -07002938 private void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002939 ActivityClientRecord r = mActivities.get(token);
Dianne Hackbornbfddc0f2010-12-14 11:28:01 -08002940
2941 if (r == null) {
2942 Log.w(TAG, "handleWindowVisibility: no activity for token " + token);
2943 return;
2944 }
2945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002946 if (!show && !r.stopped) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002947 performStopActivityInner(r, null, show, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002948 } else if (show && r.stopped) {
2949 // If we are getting ready to gc after going to the background, well
2950 // we are back active so skip it.
2951 unscheduleGcIdler();
2952
2953 r.activity.performRestart();
2954 r.stopped = false;
2955 }
2956 if (r.activity.mDecor != null) {
Joe Onorato43a17652011-04-06 19:22:23 -07002957 if (false) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002958 TAG, "Handle window " + r + " visibility: " + show);
2959 updateVisibility(r, show);
2960 }
2961 }
2962
Romain Guy65b345f2011-07-27 18:51:50 -07002963 private void handleSleeping(IBinder token, boolean sleeping) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002964 ActivityClientRecord r = mActivities.get(token);
2965
2966 if (r == null) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08002967 Log.w(TAG, "handleSleeping: no activity for token " + token);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002968 return;
2969 }
2970
2971 if (sleeping) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08002972 if (!r.stopped && !r.isPreHoneycomb()) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002973 try {
2974 // Now we are idle.
2975 r.activity.performStop();
2976 } catch (Exception e) {
2977 if (!mInstrumentation.onException(r.activity, e)) {
2978 throw new RuntimeException(
2979 "Unable to stop activity "
2980 + r.intent.getComponent().toShortString()
2981 + ": " + e.toString(), e);
2982 }
2983 }
2984 r.stopped = true;
2985 }
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002986
2987 // Make sure any pending writes are now committed.
2988 if (!r.isPreHoneycomb()) {
2989 QueuedWork.waitToFinish();
2990 }
2991
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002992 // Tell activity manager we slept.
2993 try {
2994 ActivityManagerNative.getDefault().activitySlept(r.token);
2995 } catch (RemoteException ex) {
2996 }
2997 } else {
2998 if (r.stopped && r.activity.mVisibleFromServer) {
2999 r.activity.performRestart();
3000 r.stopped = false;
3001 }
3002 }
3003 }
3004
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003005 private void handleSetCoreSettings(Bundle coreSettings) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08003006 synchronized (mPackages) {
3007 mCoreSettings = coreSettings;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003008 }
3009 }
3010
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003011 private void handleUpdatePackageCompatibilityInfo(UpdateCompatibilityData data) {
3012 LoadedApk apk = peekPackageInfo(data.pkg, false);
3013 if (apk != null) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003014 apk.mCompatibilityInfo.set(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003015 }
3016 apk = peekPackageInfo(data.pkg, true);
3017 if (apk != null) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003018 apk.mCompatibilityInfo.set(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003019 }
3020 handleConfigurationChanged(mConfiguration, data.info);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003021 WindowManagerImpl.getDefault().reportNewConfiguration(mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003022 }
3023
Romain Guy65b345f2011-07-27 18:51:50 -07003024 private void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003025 final int N = results.size();
3026 for (int i=0; i<N; i++) {
3027 ResultInfo ri = results.get(i);
3028 try {
3029 if (ri.mData != null) {
3030 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
3031 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003032 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07003033 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003034 r.activity.dispatchActivityResult(ri.mResultWho,
3035 ri.mRequestCode, ri.mResultCode, ri.mData);
3036 } catch (Exception e) {
3037 if (!mInstrumentation.onException(r.activity, e)) {
3038 throw new RuntimeException(
3039 "Failure delivering result " + ri + " to activity "
3040 + r.intent.getComponent().toShortString()
3041 + ": " + e.toString(), e);
3042 }
3043 }
3044 }
3045 }
3046
Romain Guy65b345f2011-07-27 18:51:50 -07003047 private void handleSendResult(ResultData res) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003048 ActivityClientRecord r = mActivities.get(res.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003049 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003050 if (r != null) {
3051 final boolean resumed = !r.paused;
3052 if (!r.activity.mFinished && r.activity.mDecor != null
3053 && r.hideForNow && resumed) {
3054 // We had hidden the activity because it started another
3055 // one... we have gotten a result back and we are not
3056 // paused, so make sure our window is visible.
3057 updateVisibility(r, true);
3058 }
3059 if (resumed) {
3060 try {
3061 // Now we are idle.
3062 r.activity.mCalled = false;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07003063 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003064 mInstrumentation.callActivityOnPause(r.activity);
3065 if (!r.activity.mCalled) {
3066 throw new SuperNotCalledException(
3067 "Activity " + r.intent.getComponent().toShortString()
3068 + " did not call through to super.onPause()");
3069 }
3070 } catch (SuperNotCalledException e) {
3071 throw e;
3072 } catch (Exception e) {
3073 if (!mInstrumentation.onException(r.activity, e)) {
3074 throw new RuntimeException(
3075 "Unable to pause activity "
3076 + r.intent.getComponent().toShortString()
3077 + ": " + e.toString(), e);
3078 }
3079 }
3080 }
3081 deliverResults(r, res.results);
3082 if (resumed) {
Dianne Hackbornb46ed762011-06-02 18:33:15 -07003083 r.activity.performResume();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07003084 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003085 }
3086 }
3087 }
3088
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003089 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003090 return performDestroyActivity(token, finishing, 0, false);
3091 }
3092
Romain Guy65b345f2011-07-27 18:51:50 -07003093 private ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003094 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003095 ActivityClientRecord r = mActivities.get(token);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003096 Class activityClass = null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003097 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098 if (r != null) {
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003099 activityClass = r.activity.getClass();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003100 r.activity.mConfigChangeFlags |= configChanges;
3101 if (finishing) {
3102 r.activity.mFinished = true;
3103 }
3104 if (!r.paused) {
3105 try {
3106 r.activity.mCalled = false;
3107 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07003108 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003109 r.activity.getComponentName().getClassName());
3110 if (!r.activity.mCalled) {
3111 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003112 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003113 + " did not call through to super.onPause()");
3114 }
3115 } catch (SuperNotCalledException e) {
3116 throw e;
3117 } catch (Exception e) {
3118 if (!mInstrumentation.onException(r.activity, e)) {
3119 throw new RuntimeException(
3120 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003121 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003122 + ": " + e.toString(), e);
3123 }
3124 }
3125 r.paused = true;
3126 }
3127 if (!r.stopped) {
3128 try {
3129 r.activity.performStop();
3130 } catch (SuperNotCalledException e) {
3131 throw e;
3132 } catch (Exception e) {
3133 if (!mInstrumentation.onException(r.activity, e)) {
3134 throw new RuntimeException(
3135 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003136 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003137 + ": " + e.toString(), e);
3138 }
3139 }
3140 r.stopped = true;
3141 }
3142 if (getNonConfigInstance) {
3143 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003144 r.lastNonConfigurationInstances
3145 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003146 } catch (Exception e) {
3147 if (!mInstrumentation.onException(r.activity, e)) {
3148 throw new RuntimeException(
3149 "Unable to retain activity "
3150 + r.intent.getComponent().toShortString()
3151 + ": " + e.toString(), e);
3152 }
3153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003154 }
3155 try {
3156 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07003157 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003158 if (!r.activity.mCalled) {
3159 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003160 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003161 " did not call through to super.onDestroy()");
3162 }
3163 if (r.window != null) {
3164 r.window.closeAllPanels();
3165 }
3166 } catch (SuperNotCalledException e) {
3167 throw e;
3168 } catch (Exception e) {
3169 if (!mInstrumentation.onException(r.activity, e)) {
3170 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003171 "Unable to destroy activity " + safeToComponentShortString(r.intent)
3172 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003173 }
3174 }
3175 }
3176 mActivities.remove(token);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003177 StrictMode.decrementExpectedActivityCount(activityClass);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003178 return r;
3179 }
3180
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003181 private static String safeToComponentShortString(Intent intent) {
3182 ComponentName component = intent.getComponent();
3183 return component == null ? "[Unknown]" : component.toShortString();
3184 }
3185
Romain Guy65b345f2011-07-27 18:51:50 -07003186 private void handleDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003187 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003188 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003189 configChanges, getNonConfigInstance);
3190 if (r != null) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003191 cleanUpPendingRemoveWindows(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003192 WindowManager wm = r.activity.getWindowManager();
3193 View v = r.activity.mDecor;
3194 if (v != null) {
3195 if (r.activity.mVisibleFromServer) {
3196 mNumVisibleActivities--;
3197 }
3198 IBinder wtoken = v.getWindowToken();
3199 if (r.activity.mWindowAdded) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003200 if (r.onlyLocalRequest) {
3201 // Hold off on removing this until the new activity's
3202 // window is being added.
3203 r.mPendingRemoveWindow = v;
3204 r.mPendingRemoveWindowManager = wm;
3205 } else {
3206 wm.removeViewImmediate(v);
3207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003208 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003209 if (wtoken != null && r.mPendingRemoveWindow == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 WindowManagerImpl.getDefault().closeAll(wtoken,
3211 r.activity.getClass().getName(), "Activity");
3212 }
3213 r.activity.mDecor = null;
3214 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003215 if (r.mPendingRemoveWindow == null) {
3216 // If we are delaying the removal of the activity window, then
3217 // we can't clean up all windows here. Note that we can't do
3218 // so later either, which means any windows that aren't closed
3219 // by the app will leak. Well we try to warning them a lot
3220 // about leaking windows, because that is a bug, so if they are
3221 // using this recreate facility then they get to live with leaks.
3222 WindowManagerImpl.getDefault().closeAll(token,
3223 r.activity.getClass().getName(), "Activity");
3224 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225
3226 // Mocked out contexts won't be participating in the normal
3227 // process lifecycle, but if we're running with a proper
3228 // ApplicationContext we need to have it tear down things
3229 // cleanly.
3230 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08003231 if (c instanceof ContextImpl) {
3232 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003233 r.activity.getClass().getName(), "Activity");
3234 }
3235 }
3236 if (finishing) {
3237 try {
3238 ActivityManagerNative.getDefault().activityDestroyed(token);
3239 } catch (RemoteException ex) {
3240 // If the system process has died, it's game over for everyone.
3241 }
3242 }
3243 }
3244
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003245 public final void requestRelaunchActivity(IBinder token,
3246 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
3247 int configChanges, boolean notResumed, Configuration config,
3248 boolean fromServer) {
3249 ActivityClientRecord target = null;
3250
3251 synchronized (mPackages) {
3252 for (int i=0; i<mRelaunchingActivities.size(); i++) {
3253 ActivityClientRecord r = mRelaunchingActivities.get(i);
3254 if (r.token == token) {
3255 target = r;
3256 if (pendingResults != null) {
3257 if (r.pendingResults != null) {
3258 r.pendingResults.addAll(pendingResults);
3259 } else {
3260 r.pendingResults = pendingResults;
3261 }
3262 }
3263 if (pendingNewIntents != null) {
3264 if (r.pendingIntents != null) {
3265 r.pendingIntents.addAll(pendingNewIntents);
3266 } else {
3267 r.pendingIntents = pendingNewIntents;
3268 }
3269 }
3270 break;
3271 }
3272 }
3273
3274 if (target == null) {
3275 target = new ActivityClientRecord();
3276 target.token = token;
3277 target.pendingResults = pendingResults;
3278 target.pendingIntents = pendingNewIntents;
3279 if (!fromServer) {
3280 ActivityClientRecord existing = mActivities.get(token);
3281 if (existing != null) {
3282 target.startsNotResumed = existing.paused;
3283 }
3284 target.onlyLocalRequest = true;
3285 }
3286 mRelaunchingActivities.add(target);
3287 queueOrSendMessage(H.RELAUNCH_ACTIVITY, target);
3288 }
3289
3290 if (fromServer) {
3291 target.startsNotResumed = notResumed;
3292 target.onlyLocalRequest = false;
3293 }
3294 if (config != null) {
3295 target.createdConfig = config;
3296 }
3297 target.pendingConfigChanges |= configChanges;
3298 }
3299 }
3300
Romain Guy65b345f2011-07-27 18:51:50 -07003301 private void handleRelaunchActivity(ActivityClientRecord tmp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003302 // If we are getting ready to gc after going to the background, well
3303 // we are back active so skip it.
3304 unscheduleGcIdler();
3305
3306 Configuration changedConfig = null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003307 int configChanges = 0;
Bob Leee5408332009-09-04 18:31:17 -07003308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 // First: make sure we have the most recent configuration and most
3310 // recent version of the activity, or skip it if some previous call
3311 // had taken a more recent version.
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003312 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313 int N = mRelaunchingActivities.size();
3314 IBinder token = tmp.token;
3315 tmp = null;
3316 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003317 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003318 if (r.token == token) {
3319 tmp = r;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003320 configChanges |= tmp.pendingConfigChanges;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 mRelaunchingActivities.remove(i);
3322 i--;
3323 N--;
3324 }
3325 }
Bob Leee5408332009-09-04 18:31:17 -07003326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003327 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003328 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329 return;
3330 }
Bob Leee5408332009-09-04 18:31:17 -07003331
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003332 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
3333 + tmp.token + " with configChanges=0x"
3334 + Integer.toHexString(configChanges));
3335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003336 if (mPendingConfiguration != null) {
3337 changedConfig = mPendingConfiguration;
3338 mPendingConfiguration = null;
3339 }
3340 }
Bob Leee5408332009-09-04 18:31:17 -07003341
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003342 if (tmp.createdConfig != null) {
3343 // If the activity manager is passing us its current config,
3344 // assume that is really what we want regardless of what we
3345 // may have pending.
3346 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003347 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
3348 && mConfiguration.diff(tmp.createdConfig) != 0)) {
3349 if (changedConfig == null
3350 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
3351 changedConfig = tmp.createdConfig;
3352 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003353 }
3354 }
3355
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003356 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003357 + tmp.token + ": changedConfig=" + changedConfig);
3358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003359 // If there was a pending configuration change, execute it first.
3360 if (changedConfig != null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003361 handleConfigurationChanged(changedConfig, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003362 }
Bob Leee5408332009-09-04 18:31:17 -07003363
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003364 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003365 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366 if (r == null) {
3367 return;
3368 }
Bob Leee5408332009-09-04 18:31:17 -07003369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370 r.activity.mConfigChangeFlags |= configChanges;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003371 r.onlyLocalRequest = tmp.onlyLocalRequest;
Christopher Tateb70f3df2009-04-07 16:07:59 -07003372 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07003373
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003374 r.activity.mChangingConfigurations = true;
3375
Dianne Hackborne2b04802010-12-09 09:24:55 -08003376 // Need to ensure state is saved.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003377 if (!r.paused) {
Dianne Hackborne2b04802010-12-09 09:24:55 -08003378 performPauseActivity(r.token, false, r.isPreHoneycomb());
3379 }
3380 if (r.state == null && !r.stopped && !r.isPreHoneycomb()) {
3381 r.state = new Bundle();
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04003382 r.state.setAllowFds(false);
Dianne Hackborne2b04802010-12-09 09:24:55 -08003383 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003384 }
Bob Leee5408332009-09-04 18:31:17 -07003385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003386 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07003387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003388 r.activity = null;
3389 r.window = null;
3390 r.hideForNow = false;
3391 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07003392 // Merge any pending results and pending intents; don't just replace them
3393 if (tmp.pendingResults != null) {
3394 if (r.pendingResults == null) {
3395 r.pendingResults = tmp.pendingResults;
3396 } else {
3397 r.pendingResults.addAll(tmp.pendingResults);
3398 }
3399 }
3400 if (tmp.pendingIntents != null) {
3401 if (r.pendingIntents == null) {
3402 r.pendingIntents = tmp.pendingIntents;
3403 } else {
3404 r.pendingIntents.addAll(tmp.pendingIntents);
3405 }
3406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003407 r.startsNotResumed = tmp.startsNotResumed;
Bob Leee5408332009-09-04 18:31:17 -07003408
Christopher Tateb70f3df2009-04-07 16:07:59 -07003409 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003410 }
3411
Romain Guy65b345f2011-07-27 18:51:50 -07003412 private void handleRequestThumbnail(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003413 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003414 Bitmap thumbnail = createThumbnailBitmap(r);
3415 CharSequence description = null;
3416 try {
3417 description = r.activity.onCreateDescription();
3418 } catch (Exception e) {
3419 if (!mInstrumentation.onException(r.activity, e)) {
3420 throw new RuntimeException(
3421 "Unable to create description of activity "
3422 + r.intent.getComponent().toShortString()
3423 + ": " + e.toString(), e);
3424 }
3425 }
3426 //System.out.println("Reporting top thumbnail " + thumbnail);
3427 try {
3428 ActivityManagerNative.getDefault().reportThumbnail(
3429 token, thumbnail, description);
3430 } catch (RemoteException ex) {
3431 }
3432 }
3433
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003434 ArrayList<ComponentCallbacks2> collectComponentCallbacksLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 boolean allActivities, Configuration newConfig) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003436 ArrayList<ComponentCallbacks2> callbacks
3437 = new ArrayList<ComponentCallbacks2>();
Bob Leee5408332009-09-04 18:31:17 -07003438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003439 if (mActivities.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003440 Iterator<ActivityClientRecord> it = mActivities.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003441 while (it.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003442 ActivityClientRecord ar = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443 Activity a = ar.activity;
3444 if (a != null) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003445 Configuration thisConfig = applyConfigCompatMainThread(newConfig,
3446 ar.packageInfo.mCompatibilityInfo.getIfNeeded());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003447 if (!ar.activity.mFinished && (allActivities ||
3448 (a != null && !ar.paused))) {
3449 // If the activity is currently resumed, its configuration
3450 // needs to change right now.
3451 callbacks.add(a);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003452 } else if (thisConfig != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003453 // Otherwise, we will tell it about the change
3454 // the next time it is resumed or shown. Note that
3455 // the activity manager may, before then, decide the
3456 // activity needs to be destroyed to handle its new
3457 // configuration.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003458 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Setting activity "
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003459 + ar.activityInfo.name + " newConfig=" + thisConfig);
3460 ar.newConfig = thisConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003461 }
3462 }
3463 }
3464 }
3465 if (mServices.size() > 0) {
3466 Iterator<Service> it = mServices.values().iterator();
3467 while (it.hasNext()) {
3468 callbacks.add(it.next());
3469 }
3470 }
3471 synchronized (mProviderMap) {
3472 if (mLocalProviders.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003473 Iterator<ProviderClientRecord> it = mLocalProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003474 while (it.hasNext()) {
3475 callbacks.add(it.next().mLocalProvider);
3476 }
3477 }
3478 }
3479 final int N = mAllApplications.size();
3480 for (int i=0; i<N; i++) {
3481 callbacks.add(mAllApplications.get(i));
3482 }
Bob Leee5408332009-09-04 18:31:17 -07003483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484 return callbacks;
3485 }
Bob Leee5408332009-09-04 18:31:17 -07003486
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003487 private final void performConfigurationChanged(
3488 ComponentCallbacks2 cb, Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003489 // Only for Activity objects, check that they actually call up to their
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003490 // superclass implementation. ComponentCallbacks2 is an interface, so
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003491 // we check the runtime type and act accordingly.
3492 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
3493 if (activity != null) {
3494 activity.mCalled = false;
3495 }
Bob Leee5408332009-09-04 18:31:17 -07003496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003497 boolean shouldChangeConfig = false;
3498 if ((activity == null) || (activity.mCurrentConfig == null)) {
3499 shouldChangeConfig = true;
3500 } else {
Bob Leee5408332009-09-04 18:31:17 -07003501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003502 // If the new config is the same as the config this Activity
3503 // is already running with then don't bother calling
3504 // onConfigurationChanged
3505 int diff = activity.mCurrentConfig.diff(config);
3506 if (diff != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003507 // If this activity doesn't handle any of the config changes
3508 // then don't bother calling onConfigurationChanged as we're
3509 // going to destroy it.
Dianne Hackborne6676352011-06-01 16:51:20 -07003510 if ((~activity.mActivityInfo.getRealConfigChanged() & diff) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003511 shouldChangeConfig = true;
3512 }
3513 }
3514 }
Bob Leee5408332009-09-04 18:31:17 -07003515
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003516 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003517 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518 if (shouldChangeConfig) {
3519 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07003520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003521 if (activity != null) {
3522 if (!activity.mCalled) {
3523 throw new SuperNotCalledException(
3524 "Activity " + activity.getLocalClassName() +
3525 " did not call through to super.onConfigurationChanged()");
3526 }
3527 activity.mConfigChangeFlags = 0;
3528 activity.mCurrentConfig = new Configuration(config);
3529 }
3530 }
3531 }
3532
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07003533 public final void applyConfigurationToResources(Configuration config) {
3534 synchronized (mPackages) {
3535 applyConfigurationToResourcesLocked(config, null);
3536 }
3537 }
3538
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003539 final boolean applyConfigurationToResourcesLocked(Configuration config,
3540 CompatibilityInfo compat) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003541 if (mResConfiguration == null) {
3542 mResConfiguration = new Configuration();
3543 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003544 if (!mResConfiguration.isOtherSeqNewer(config) && compat == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003545 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq="
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003546 + mResConfiguration.seq + ", newSeq=" + config.seq);
Dianne Hackbornae078162010-03-18 11:29:37 -07003547 return false;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003548 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003549 int changes = mResConfiguration.updateFrom(config);
Dianne Hackborn836e2622011-10-04 18:32:39 -07003550 DisplayMetrics dm = getDisplayMetricsLocked(null, true);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003551
3552 if (compat != null && (mResCompatibilityInfo == null ||
3553 !mResCompatibilityInfo.equals(compat))) {
3554 mResCompatibilityInfo = compat;
3555 changes |= ActivityInfo.CONFIG_SCREEN_LAYOUT
3556 | ActivityInfo.CONFIG_SCREEN_SIZE
3557 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3558 }
Bob Leee5408332009-09-04 18:31:17 -07003559
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003560 // set it for java, this also affects newly created Resources
3561 if (config.locale != null) {
3562 Locale.setDefault(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003563 }
Bob Leee5408332009-09-04 18:31:17 -07003564
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003565 Resources.updateSystemConfiguration(config, dm, compat);
Bob Leee5408332009-09-04 18:31:17 -07003566
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003567 ApplicationPackageManager.configurationChanged();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003568 //Slog.i(TAG, "Configuration changed in " + currentPackageName());
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003569
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003570 Iterator<WeakReference<Resources>> it =
3571 mActiveResources.values().iterator();
3572 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
3573 // mActiveResources.entrySet().iterator();
3574 while (it.hasNext()) {
3575 WeakReference<Resources> v = it.next();
3576 Resources r = v.get();
3577 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003578 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources "
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003579 + r + " config to: " + config);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003580 r.updateConfiguration(config, dm, compat);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003581 //Slog.i(TAG, "Updated app resources " + v.getKey()
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003582 // + " " + r + ": " + r.getConfiguration());
3583 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003584 //Slog.i(TAG, "Removing old resources " + v.getKey());
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003585 it.remove();
3586 }
3587 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003588
3589 return changes != 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003590 }
Dianne Hackborn836e2622011-10-04 18:32:39 -07003591
3592 final Configuration applyCompatConfiguration() {
3593 Configuration config = mConfiguration;
3594 if (mCompatConfiguration == null) {
3595 mCompatConfiguration = new Configuration();
3596 }
3597 mCompatConfiguration.setTo(mConfiguration);
3598 if (mResCompatibilityInfo != null && !mResCompatibilityInfo.supportsScreen()) {
3599 mResCompatibilityInfo.applyToConfiguration(mCompatConfiguration);
3600 config = mCompatConfiguration;
3601 }
3602 return config;
3603 }
3604
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003605 final void handleConfigurationChanged(Configuration config, CompatibilityInfo compat) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003606
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003607 ArrayList<ComponentCallbacks2> callbacks = null;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003608
3609 synchronized (mPackages) {
3610 if (mPendingConfiguration != null) {
3611 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
3612 config = mPendingConfiguration;
3613 }
3614 mPendingConfiguration = null;
3615 }
3616
3617 if (config == null) {
3618 return;
3619 }
3620
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003621 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003622 + config);
3623
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003624 applyConfigurationToResourcesLocked(config, compat);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626 if (mConfiguration == null) {
3627 mConfiguration = new Configuration();
3628 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003629 if (!mConfiguration.isOtherSeqNewer(config) && compat == null) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003630 return;
3631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003632 mConfiguration.updateFrom(config);
Dianne Hackborn836e2622011-10-04 18:32:39 -07003633 config = applyCompatConfiguration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003634 callbacks = collectComponentCallbacksLocked(false, config);
3635 }
Romain Guy65b345f2011-07-27 18:51:50 -07003636
3637 // Cleanup hardware accelerated stuff
3638 WindowManagerImpl.getDefault().trimLocalMemory();
Bob Leee5408332009-09-04 18:31:17 -07003639
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003640 if (callbacks != null) {
3641 final int N = callbacks.size();
3642 for (int i=0; i<N; i++) {
3643 performConfigurationChanged(callbacks.get(i), config);
3644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003645 }
3646 }
3647
3648 final void handleActivityConfigurationChanged(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003649 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003650 if (r == null || r.activity == null) {
3651 return;
3652 }
Bob Leee5408332009-09-04 18:31:17 -07003653
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003654 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003655 + r.activityInfo.name);
3656
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003657 performConfigurationChanged(r.activity, mCompatConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658 }
3659
Romain Guy7eabe552011-07-21 14:56:34 -07003660 final void handleProfilerControl(boolean start, ProfilerControlData pcd, int profileType) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003661 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003662 try {
Romain Guy7eabe552011-07-21 14:56:34 -07003663 switch (profileType) {
3664 case 1:
3665 ViewDebug.startLooperProfiling(pcd.path, pcd.fd.getFileDescriptor());
3666 break;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003667 default:
3668 mProfiler.setProfiler(pcd.path, pcd.fd);
3669 mProfiler.autoStopProfiler = false;
3670 mProfiler.startProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07003671 break;
3672 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003673 } catch (RuntimeException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003674 Slog.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003675 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003676 } finally {
3677 try {
3678 pcd.fd.close();
3679 } catch (IOException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003680 Slog.w(TAG, "Failure closing profile fd", e);
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003681 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003682 }
3683 } else {
Romain Guy7eabe552011-07-21 14:56:34 -07003684 switch (profileType) {
3685 case 1:
3686 ViewDebug.stopLooperProfiling();
3687 break;
3688 default:
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003689 mProfiler.stopProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07003690 break;
Romain Guy7eabe552011-07-21 14:56:34 -07003691 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003692 }
3693 }
Bob Leee5408332009-09-04 18:31:17 -07003694
Andy McFadden824c5102010-07-09 16:26:57 -07003695 final void handleDumpHeap(boolean managed, DumpHeapData dhd) {
3696 if (managed) {
3697 try {
3698 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor());
3699 } catch (IOException e) {
3700 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
3701 + " -- can the process access this path?");
3702 } finally {
3703 try {
3704 dhd.fd.close();
3705 } catch (IOException e) {
3706 Slog.w(TAG, "Failure closing profile fd", e);
3707 }
3708 }
3709 } else {
Andy McFadden06a6b552010-07-13 16:28:09 -07003710 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07003711 }
3712 }
3713
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003714 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
3715 boolean hasPkgInfo = false;
3716 if (packages != null) {
3717 for (int i=packages.length-1; i>=0; i--) {
3718 //Slog.i(TAG, "Cleaning old package: " + packages[i]);
3719 if (!hasPkgInfo) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003720 WeakReference<LoadedApk> ref;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003721 ref = mPackages.get(packages[i]);
3722 if (ref != null && ref.get() != null) {
3723 hasPkgInfo = true;
3724 } else {
3725 ref = mResourcePackages.get(packages[i]);
3726 if (ref != null && ref.get() != null) {
3727 hasPkgInfo = true;
3728 }
3729 }
3730 }
3731 mPackages.remove(packages[i]);
3732 mResourcePackages.remove(packages[i]);
3733 }
3734 }
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003735 ApplicationPackageManager.handlePackageBroadcast(cmd, packages,
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003736 hasPkgInfo);
3737 }
3738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003739 final void handleLowMemory() {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003740 ArrayList<ComponentCallbacks2> callbacks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003741
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003742 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003743 callbacks = collectComponentCallbacksLocked(true, null);
3744 }
Bob Leee5408332009-09-04 18:31:17 -07003745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 final int N = callbacks.size();
3747 for (int i=0; i<N; i++) {
3748 callbacks.get(i).onLowMemory();
3749 }
3750
Chris Tatece229052009-03-25 16:44:52 -07003751 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3752 if (Process.myUid() != Process.SYSTEM_UID) {
3753 int sqliteReleased = SQLiteDatabase.releaseMemory();
3754 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3755 }
Bob Leee5408332009-09-04 18:31:17 -07003756
Mike Reedcaf0df12009-04-27 14:32:05 -04003757 // Ask graphics to free up as much as possible (font/image caches)
3758 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003759
3760 BinderInternal.forceGc("mem");
3761 }
3762
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003763 final void handleTrimMemory(int level) {
Teng-Hui Zhud9624132012-03-01 15:18:05 -08003764 WindowManagerImpl.getDefault().trimMemory(level);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003765 ArrayList<ComponentCallbacks2> callbacks;
3766
3767 synchronized (mPackages) {
3768 callbacks = collectComponentCallbacksLocked(true, null);
3769 }
3770
3771 final int N = callbacks.size();
3772 for (int i=0; i<N; i++) {
3773 callbacks.get(i).onTrimMemory(level);
3774 }
Teng-Hui Zhud9624132012-03-01 15:18:05 -08003775 WindowManagerImpl.getDefault().terminateEgl();
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003776 }
3777
Romain Guya9582652011-11-10 14:20:10 -08003778 private void setupGraphicsSupport(LoadedApk info) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003779 if (Process.isIsolated()) {
3780 // Isolated processes aren't going to do UI.
3781 return;
3782 }
Romain Guya9582652011-11-10 14:20:10 -08003783 try {
3784 int uid = Process.myUid();
3785 String[] packages = getPackageManager().getPackagesForUid(uid);
3786
3787 // If there are several packages in this application we won't
3788 // initialize the graphics disk caches
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003789 if (packages != null && packages.length == 1) {
Romain Guya9582652011-11-10 14:20:10 -08003790 ContextImpl appContext = new ContextImpl();
3791 appContext.init(info, null, this);
3792
3793 HardwareRenderer.setupDiskCache(appContext.getCacheDir());
Jason Samsa6f338c2012-02-24 16:22:16 -08003794 RenderScript.setupDiskCache(appContext.getCacheDir());
Romain Guya9582652011-11-10 14:20:10 -08003795 }
3796 } catch (RemoteException e) {
3797 // Ignore
3798 }
3799 }
3800
Romain Guy65b345f2011-07-27 18:51:50 -07003801 private void handleBindApplication(AppBindData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003802 mBoundApplication = data;
3803 mConfiguration = new Configuration(data.config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003804 mCompatConfiguration = new Configuration(data.config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003806 mProfiler = new Profiler();
3807 mProfiler.profileFile = data.initProfileFile;
3808 mProfiler.profileFd = data.initProfileFd;
3809 mProfiler.autoStopProfiler = data.initAutoStopProfiler;
3810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003811 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003812 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813 android.ddm.DdmHandleAppName.setAppName(data.processName);
3814
Dianne Hackborn5d927c22011-09-02 12:22:18 -07003815 if (data.persistent) {
3816 // Persistent processes on low-memory devices do not get to
3817 // use hardware accelerated drawing, since this can add too much
3818 // overhead to the process.
3819 Display display = WindowManagerImpl.getDefault().getDefaultDisplay();
3820 if (!ActivityManager.isHighEndGfx(display)) {
3821 HardwareRenderer.disable(false);
3822 }
3823 }
Romain Guya9582652011-11-10 14:20:10 -08003824
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003825 if (mProfiler.profileFd != null) {
3826 mProfiler.startProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003827 }
3828
Joe Onoratod630f102011-03-17 18:42:26 -07003829 // If the app is Honeycomb MR1 or earlier, switch its AsyncTask
3830 // implementation to use the pool executor. Normally, we use the
3831 // serialized executor as the default. This has to happen in the
3832 // main thread so the main looper is set right.
Dianne Hackborn81e92762011-10-09 16:00:21 -07003833 if (data.appInfo.targetSdkVersion <= android.os.Build.VERSION_CODES.HONEYCOMB_MR1) {
Joe Onoratod630f102011-03-17 18:42:26 -07003834 AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
3835 }
3836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003837 /*
3838 * Before spawning a new process, reset the time zone to be the system time zone.
3839 * This needs to be done because the system time zone could have changed after the
3840 * the spawning of this process. Without doing this this process would have the incorrect
3841 * system time zone.
3842 */
3843 TimeZone.setDefault(null);
3844
3845 /*
3846 * Initialize the default locale in this process for the reasons we set the time zone.
3847 */
3848 Locale.setDefault(data.config.locale);
3849
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003850 /*
3851 * Update the system configuration since its preloaded and might not
3852 * reflect configuration changes. The configuration object passed
3853 * in AppBindData can be safely assumed to be up to date
3854 */
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07003855 applyConfigurationToResourcesLocked(data.config, data.compatInfo);
Dianne Hackborn836e2622011-10-04 18:32:39 -07003856 applyCompatConfiguration();
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003857
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003858 data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859
Romain Guya9582652011-11-10 14:20:10 -08003860 setupGraphicsSupport(data.info);
3861
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003862 /**
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003863 * For system applications on userdebug/eng builds, log stack
3864 * traces of disk and network access to dropbox for analysis.
3865 */
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07003866 if ((data.appInfo.flags &
3867 (ApplicationInfo.FLAG_SYSTEM |
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07003868 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0) {
3869 StrictMode.conditionallyEnableDebugLogging();
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003870 }
3871
3872 /**
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07003873 * For apps targetting SDK Honeycomb or later, we don't allow
3874 * network usage on the main event loop / UI thread.
3875 *
3876 * Note to those grepping: this is what ultimately throws
3877 * NetworkOnMainThreadException ...
3878 */
3879 if (data.appInfo.targetSdkVersion > 9) {
3880 StrictMode.enableDeathOnNetwork();
3881 }
3882
3883 /**
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003884 * Switch this process to density compatibility mode if needed.
3885 */
3886 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3887 == 0) {
3888 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3889 }
Bob Leee5408332009-09-04 18:31:17 -07003890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003891 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3892 // XXX should have option to change the port.
3893 Debug.changeDebugPort(8100);
3894 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003895 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896 + " is waiting for the debugger on port 8100...");
3897
3898 IActivityManager mgr = ActivityManagerNative.getDefault();
3899 try {
3900 mgr.showWaitingForDebugger(mAppThread, true);
3901 } catch (RemoteException ex) {
3902 }
3903
3904 Debug.waitForDebugger();
3905
3906 try {
3907 mgr.showWaitingForDebugger(mAppThread, false);
3908 } catch (RemoteException ex) {
3909 }
3910
3911 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003912 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003913 + " can be debugged on port 8100...");
3914 }
3915 }
3916
Siva Velusamy92a8b222012-03-09 16:24:04 -08003917 // Enable OpenGL tracing if required
3918 if (data.enableOpenGlTrace) {
3919 GLUtils.enableTracing();
3920 }
3921
Robert Greenwalt434203a2010-10-11 16:00:27 -07003922 /**
3923 * Initialize the default http proxy in this process for the reasons we set the time zone.
3924 */
3925 IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08003926 if (b != null) {
3927 // In pre-boot mode (doing initial launch to collect password), not
3928 // all system is up. This includes the connectivity service, so don't
3929 // crash if we can't get it.
3930 IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
3931 try {
3932 ProxyProperties proxyProperties = service.getProxy();
3933 Proxy.setHttpProxySystemProperty(proxyProperties);
3934 } catch (RemoteException e) {}
3935 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003937 if (data.instrumentationName != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08003938 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003939 appContext.init(data.info, null, this);
3940 InstrumentationInfo ii = null;
3941 try {
3942 ii = appContext.getPackageManager().
3943 getInstrumentationInfo(data.instrumentationName, 0);
3944 } catch (PackageManager.NameNotFoundException e) {
3945 }
3946 if (ii == null) {
3947 throw new RuntimeException(
3948 "Unable to find instrumentation info for: "
3949 + data.instrumentationName);
3950 }
3951
3952 mInstrumentationAppDir = ii.sourceDir;
3953 mInstrumentationAppPackage = ii.packageName;
3954 mInstrumentedAppDir = data.info.getAppDir();
3955
3956 ApplicationInfo instrApp = new ApplicationInfo();
3957 instrApp.packageName = ii.packageName;
3958 instrApp.sourceDir = ii.sourceDir;
3959 instrApp.publicSourceDir = ii.publicSourceDir;
3960 instrApp.dataDir = ii.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003961 instrApp.nativeLibraryDir = ii.nativeLibraryDir;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003962 LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003963 appContext.getClassLoader(), false, true);
Dianne Hackborn21556372010-02-04 16:34:40 -08003964 ContextImpl instrContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003965 instrContext.init(pi, null, this);
3966
3967 try {
3968 java.lang.ClassLoader cl = instrContext.getClassLoader();
3969 mInstrumentation = (Instrumentation)
3970 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3971 } catch (Exception e) {
3972 throw new RuntimeException(
3973 "Unable to instantiate instrumentation "
3974 + data.instrumentationName + ": " + e.toString(), e);
3975 }
3976
3977 mInstrumentation.init(this, instrContext, appContext,
3978 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3979
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003980 if (mProfiler.profileFile != null && !ii.handleProfiling
3981 && mProfiler.profileFd == null) {
3982 mProfiler.handlingProfiling = true;
3983 File file = new File(mProfiler.profileFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003984 file.getParentFile().mkdirs();
3985 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3986 }
3987
3988 try {
3989 mInstrumentation.onCreate(data.instrumentationArgs);
3990 }
3991 catch (Exception e) {
3992 throw new RuntimeException(
3993 "Exception thrown in onCreate() of "
3994 + data.instrumentationName + ": " + e.toString(), e);
3995 }
3996
3997 } else {
3998 mInstrumentation = new Instrumentation();
3999 }
4000
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08004001 if ((data.appInfo.flags&ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
Dianne Hackbornde398512011-01-18 18:45:21 -08004002 dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08004003 }
4004
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08004005 // Allow disk access during application and provider setup. This could
Jeff Sharkey7c501672012-02-28 12:08:37 -08004006 // block processing ordered broadcasts, but later processing would
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08004007 // probably end up doing the same disk access.
Jeff Sharkey7c501672012-02-28 12:08:37 -08004008 final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 try {
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08004010 // If the app is being launched for full backup or restore, bring it up in
4011 // a restricted environment with the base application class.
4012 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
4013 mInitialApplication = app;
Jeff Sharkey7c501672012-02-28 12:08:37 -08004014
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08004015 // don't bring up providers in restricted mode; they may depend on the
4016 // app's custom Application class
4017 if (!data.restrictedBackupMode) {
4018 List<ProviderInfo> providers = data.providers;
4019 if (providers != null) {
4020 installContentProviders(app, providers);
4021 // For process that contains content providers, we want to
4022 // ensure that the JIT is enabled "at some point".
4023 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
4024 }
4025 }
4026
4027 try {
4028 mInstrumentation.callApplicationOnCreate(app);
4029 } catch (Exception e) {
4030 if (!mInstrumentation.onException(app, e)) {
4031 throw new RuntimeException(
4032 "Unable to create application " + app.getClass().getName()
4033 + ": " + e.toString(), e);
4034 }
4035 }
4036 } finally {
4037 StrictMode.setThreadPolicy(savedPolicy);
4038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004039 }
4040
4041 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
4042 IActivityManager am = ActivityManagerNative.getDefault();
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07004043 if (mProfiler.profileFile != null && mProfiler.handlingProfiling
4044 && mProfiler.profileFd == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004045 Debug.stopMethodTracing();
4046 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004047 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004048 // + ", app thr: " + mAppThread);
4049 try {
4050 am.finishInstrumentation(mAppThread, resultCode, results);
4051 } catch (RemoteException ex) {
4052 }
4053 }
4054
Romain Guy65b345f2011-07-27 18:51:50 -07004055 private void installContentProviders(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004056 Context context, List<ProviderInfo> providers) {
4057 final ArrayList<IActivityManager.ContentProviderHolder> results =
4058 new ArrayList<IActivityManager.ContentProviderHolder>();
4059
4060 Iterator<ProviderInfo> i = providers.iterator();
4061 while (i.hasNext()) {
4062 ProviderInfo cpi = i.next();
4063 StringBuilder buf = new StringBuilder(128);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07004064 buf.append("Pub ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004065 buf.append(cpi.authority);
4066 buf.append(": ");
4067 buf.append(cpi.name);
4068 Log.i(TAG, buf.toString());
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004069 IContentProvider cp = installProvider(context, null, cpi,
4070 false /*noisy*/, true /*noReleaseNeeded*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004071 if (cp != null) {
4072 IActivityManager.ContentProviderHolder cph =
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004073 new IActivityManager.ContentProviderHolder(cpi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004074 cph.provider = cp;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004075 cph.noReleaseNeeded = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004076 results.add(cph);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004077 }
4078 }
4079
4080 try {
4081 ActivityManagerNative.getDefault().publishContentProviders(
4082 getApplicationThread(), results);
4083 } catch (RemoteException ex) {
4084 }
4085 }
4086
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004087 public final IContentProvider acquireProvider(Context c, String name) {
4088 IContentProvider provider = acquireExistingProvider(c, name);
4089 if (provider != null) {
4090 return provider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004091 }
4092
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004093 // There is a possible race here. Another thread may try to acquire
4094 // the same provider at the same time. When this happens, we want to ensure
4095 // that the first one wins.
4096 // Note that we cannot hold the lock while acquiring and installing the
4097 // provider since it might take a long time to run and it could also potentially
4098 // be re-entrant in the case where the provider is in the same process.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004099 IActivityManager.ContentProviderHolder holder = null;
4100 try {
4101 holder = ActivityManagerNative.getDefault().getContentProvider(
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004102 getApplicationThread(), name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004103 } catch (RemoteException ex) {
4104 }
4105 if (holder == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004106 Slog.e(TAG, "Failed to find provider info for " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004107 return null;
4108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004109
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004110 // Install provider will increment the reference count for us, and break
4111 // any ties in the race.
4112 provider = installProvider(c, holder.provider, holder.info,
4113 true /*noisy*/, holder.noReleaseNeeded);
4114 if (holder.provider != null && provider != holder.provider) {
4115 if (localLOGV) {
4116 Slog.v(TAG, "acquireProvider: lost the race, releasing extraneous "
4117 + "reference to the content provider");
4118 }
4119 try {
4120 ActivityManagerNative.getDefault().removeContentProvider(
4121 getApplicationThread(), name);
4122 } catch (RemoteException ex) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004123 }
4124 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004125 return provider;
4126 }
4127
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07004128 public final IContentProvider acquireExistingProvider(Context c, String name) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004129 synchronized (mProviderMap) {
4130 ProviderClientRecord pr = mProviderMap.get(name);
4131 if (pr == null) {
4132 return null;
4133 }
4134
4135 IContentProvider provider = pr.mProvider;
4136 IBinder jBinder = provider.asBinder();
4137
4138 // Only increment the ref count if we have one. If we don't then the
4139 // provider is not reference counted and never needs to be released.
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07004140 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004141 if (prc != null) {
4142 prc.count += 1;
4143 if (prc.count == 1) {
4144 if (localLOGV) {
4145 Slog.v(TAG, "acquireExistingProvider: "
4146 + "snatched provider from the jaws of death");
4147 }
4148 // Because the provider previously had a reference count of zero,
4149 // it was scheduled to be removed. Cancel that.
4150 mH.removeMessages(H.REMOVE_PROVIDER, provider);
4151 }
4152 }
4153 return provider;
4154 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07004155 }
4156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004157 public final boolean releaseProvider(IContentProvider provider) {
4158 if(provider == null) {
4159 return false;
4160 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004161
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004162 IBinder jBinder = provider.asBinder();
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004163 synchronized (mProviderMap) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004165 if (prc == null) {
4166 // The provider has no ref count, no release is needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004167 return false;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004168 }
4169
4170 if (prc.count == 0) {
4171 if (localLOGV) Slog.v(TAG, "releaseProvider: ref count already 0, how?");
4172 return false;
4173 }
4174
4175 prc.count -= 1;
4176 if (prc.count == 0) {
4177 // Schedule the actual remove asynchronously, since we don't know the context
4178 // this will be called in.
4179 // TODO: it would be nice to post a delayed message, so
4180 // if we come back and need the same provider quickly
4181 // we will still have it available.
4182 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
4183 mH.sendMessage(msg);
4184 }
4185 return true;
4186 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004187 }
4188
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004189 final void completeRemoveProvider(IContentProvider provider) {
4190 IBinder jBinder = provider.asBinder();
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004191 String remoteProviderName = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004192 synchronized(mProviderMap) {
4193 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004194 if (prc == null) {
4195 // Either no release is needed (so we shouldn't be here) or the
4196 // provider was already released.
4197 if (localLOGV) Slog.v(TAG, "completeRemoveProvider: release not needed");
4198 return;
4199 }
4200
4201 if (prc.count != 0) {
4202 // There was a race! Some other client managed to acquire
4203 // the provider before the removal was completed.
4204 // Abort the removal. We will do it later.
4205 if (localLOGV) Slog.v(TAG, "completeRemoveProvider: lost the race, "
4206 + "provider still in use");
4207 return;
4208 }
4209
4210 mProviderRefCountMap.remove(jBinder);
4211
4212 Iterator<ProviderClientRecord> iter = mProviderMap.values().iterator();
4213 while (iter.hasNext()) {
4214 ProviderClientRecord pr = iter.next();
4215 IBinder myBinder = pr.mProvider.asBinder();
4216 if (myBinder == jBinder) {
4217 iter.remove();
4218 if (pr.mLocalProvider == null) {
4219 myBinder.unlinkToDeath(pr, 0);
4220 if (remoteProviderName == null) {
4221 remoteProviderName = pr.mName;
4222 }
4223 }
4224 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004225 }
4226 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004227
4228 if (remoteProviderName != null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004229 try {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004230 if (localLOGV) {
4231 Slog.v(TAG, "removeProvider: Invoking ActivityManagerNative."
4232 + "removeContentProvider(" + remoteProviderName + ")");
4233 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004234 ActivityManagerNative.getDefault().removeContentProvider(
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004235 getApplicationThread(), remoteProviderName);
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004236 } catch (RemoteException e) {
4237 //do nothing content provider object is dead any way
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004238 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004239 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004240 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004241
4242 final void removeDeadProvider(String name, IContentProvider provider) {
4243 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004244 ProviderClientRecord pr = mProviderMap.get(name);
Jeff Brown2a4c5ac2011-08-23 11:58:26 -07004245 if (pr != null && pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004246 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004247 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07004248 if (removed != null) {
4249 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
4250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004251 }
4252 }
4253 }
4254
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004255 /**
4256 * Installs the provider.
4257 *
4258 * Providers that are local to the process or that come from the system server
4259 * may be installed permanently which is indicated by setting noReleaseNeeded to true.
4260 * Other remote providers are reference counted. The initial reference count
4261 * for all reference counted providers is one. Providers that are not reference
4262 * counted do not have a reference count (at all).
4263 *
4264 * This method detects when a provider has already been installed. When this happens,
4265 * it increments the reference count of the existing provider (if appropriate)
4266 * and returns the existing provider. This can happen due to concurrent
4267 * attempts to acquire the same provider.
4268 */
Romain Guy65b345f2011-07-27 18:51:50 -07004269 private IContentProvider installProvider(Context context,
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004270 IContentProvider provider, ProviderInfo info,
4271 boolean noisy, boolean noReleaseNeeded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004272 ContentProvider localProvider = null;
4273 if (provider == null) {
4274 if (noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004275 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004276 + info.name);
4277 }
4278 Context c = null;
4279 ApplicationInfo ai = info.applicationInfo;
4280 if (context.getPackageName().equals(ai.packageName)) {
4281 c = context;
4282 } else if (mInitialApplication != null &&
4283 mInitialApplication.getPackageName().equals(ai.packageName)) {
4284 c = mInitialApplication;
4285 } else {
4286 try {
4287 c = context.createPackageContext(ai.packageName,
4288 Context.CONTEXT_INCLUDE_CODE);
4289 } catch (PackageManager.NameNotFoundException e) {
Romain Guy65b345f2011-07-27 18:51:50 -07004290 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291 }
4292 }
4293 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004294 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004295 ai.packageName +
4296 " while loading content provider " +
4297 info.name);
4298 return null;
4299 }
4300 try {
4301 final java.lang.ClassLoader cl = c.getClassLoader();
4302 localProvider = (ContentProvider)cl.
4303 loadClass(info.name).newInstance();
4304 provider = localProvider.getIContentProvider();
4305 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004306 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004307 info.name + " from sourceDir " +
4308 info.applicationInfo.sourceDir);
4309 return null;
4310 }
Joe Onorato43a17652011-04-06 19:22:23 -07004311 if (false) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004312 TAG, "Instantiating local provider " + info.name);
4313 // XXX Need to create the correct context for this provider.
4314 localProvider.attachInfo(c, info);
4315 } catch (java.lang.Exception e) {
4316 if (!mInstrumentation.onException(null, e)) {
4317 throw new RuntimeException(
4318 "Unable to get provider " + info.name
4319 + ": " + e.toString(), e);
4320 }
4321 return null;
4322 }
4323 } else if (localLOGV) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004324 Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004325 + info.name);
4326 }
4327
4328 synchronized (mProviderMap) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004329 // There is a possibility that this thread raced with another thread to
4330 // add the provider. If we find another thread got there first then we
4331 // just get out of the way and return the original provider.
4332 IBinder jBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004333 String names[] = PATTERN_SEMICOLON.split(info.authority);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004334 for (int i = 0; i < names.length; i++) {
4335 ProviderClientRecord pr = mProviderMap.get(names[i]);
4336 if (pr != null) {
4337 if (localLOGV) {
4338 Slog.v(TAG, "installProvider: lost the race, "
4339 + "using existing named provider");
4340 }
4341 provider = pr.mProvider;
4342 } else {
4343 pr = new ProviderClientRecord(names[i], provider, localProvider);
4344 if (localProvider == null) {
4345 try {
4346 jBinder.linkToDeath(pr, 0);
4347 } catch (RemoteException e) {
4348 // Provider already dead. Bail out of here without making
4349 // any changes to the provider map or other data structures.
4350 return null;
4351 }
4352 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004353 mProviderMap.put(names[i], pr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004354 }
4355 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004357 if (localProvider != null) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004358 ProviderClientRecord pr = mLocalProviders.get(jBinder);
4359 if (pr != null) {
4360 if (localLOGV) {
4361 Slog.v(TAG, "installProvider: lost the race, "
4362 + "using existing local provider");
4363 }
4364 provider = pr.mProvider;
4365 } else {
4366 pr = new ProviderClientRecord(null, provider, localProvider);
4367 mLocalProviders.put(jBinder, pr);
4368 }
4369 }
4370
4371 if (!noReleaseNeeded) {
4372 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
4373 if (prc != null) {
4374 if (localLOGV) {
4375 Slog.v(TAG, "installProvider: lost the race, incrementing ref count");
4376 }
4377 prc.count += 1;
4378 if (prc.count == 1) {
4379 if (localLOGV) {
4380 Slog.v(TAG, "installProvider: "
4381 + "snatched provider from the jaws of death");
4382 }
4383 // Because the provider previously had a reference count of zero,
4384 // it was scheduled to be removed. Cancel that.
4385 mH.removeMessages(H.REMOVE_PROVIDER, provider);
4386 }
4387 } else {
4388 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
4389 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004390 }
4391 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004392 return provider;
4393 }
4394
Romain Guy65b345f2011-07-27 18:51:50 -07004395 private void attach(boolean system) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004396 sThreadLocal.set(this);
4397 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004398 if (!system) {
Dianne Hackborn6dd005b2011-07-18 13:22:50 -07004399 ViewRootImpl.addFirstDrawHandler(new Runnable() {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08004400 public void run() {
4401 ensureJitEnabled();
4402 }
4403 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004404 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
4405 RuntimeInit.setApplicationObject(mAppThread.asBinder());
4406 IActivityManager mgr = ActivityManagerNative.getDefault();
4407 try {
4408 mgr.attachApplication(mAppThread);
4409 } catch (RemoteException ex) {
Romain Guy65b345f2011-07-27 18:51:50 -07004410 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004411 }
4412 } else {
4413 // Don't set application object here -- if the system crashes,
4414 // we can't display an alert, we just want to die die die.
4415 android.ddm.DdmHandleAppName.setAppName("system_process");
4416 try {
4417 mInstrumentation = new Instrumentation();
Dianne Hackborn21556372010-02-04 16:34:40 -08004418 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004419 context.init(getSystemContext().mPackageInfo, null, this);
4420 Application app = Instrumentation.newApplication(Application.class, context);
4421 mAllApplications.add(app);
4422 mInitialApplication = app;
4423 app.onCreate();
4424 } catch (Exception e) {
4425 throw new RuntimeException(
4426 "Unable to instantiate Application():" + e.toString(), e);
4427 }
4428 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004429
Dianne Hackbornc68c9132011-07-29 01:25:18 -07004430 ViewRootImpl.addConfigCallback(new ComponentCallbacks2() {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004431 public void onConfigurationChanged(Configuration newConfig) {
4432 synchronized (mPackages) {
Dianne Hackbornae078162010-03-18 11:29:37 -07004433 // We need to apply this change to the resources
4434 // immediately, because upon returning the view
4435 // hierarchy will be informed about it.
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004436 if (applyConfigurationToResourcesLocked(newConfig, null)) {
Dianne Hackbornae078162010-03-18 11:29:37 -07004437 // This actually changed the resources! Tell
4438 // everyone about it.
4439 if (mPendingConfiguration == null ||
4440 mPendingConfiguration.isOtherSeqNewer(newConfig)) {
4441 mPendingConfiguration = newConfig;
4442
4443 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
4444 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004445 }
4446 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004447 }
4448 public void onLowMemory() {
4449 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -07004450 public void onTrimMemory(int level) {
4451 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004452 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004453 }
4454
Romain Guy5e9120d2012-01-30 12:17:22 -08004455 public static ActivityThread systemMain() {
Dianne Hackborn5d927c22011-09-02 12:22:18 -07004456 HardwareRenderer.disable(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004457 ActivityThread thread = new ActivityThread();
4458 thread.attach(true);
4459 return thread;
4460 }
4461
Jeff Brown10e89712011-07-08 18:52:57 -07004462 public final void installSystemProviders(List<ProviderInfo> providers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004463 if (providers != null) {
Jeff Brown10e89712011-07-08 18:52:57 -07004464 installContentProviders(mInitialApplication, providers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004465 }
4466 }
4467
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004468 public int getIntCoreSetting(String key, int defaultValue) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08004469 synchronized (mPackages) {
4470 if (mCoreSettings != null) {
4471 return mCoreSettings.getInt(key, defaultValue);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004472 } else {
4473 return defaultValue;
4474 }
4475 }
4476 }
4477
Romain Guy65b345f2011-07-27 18:51:50 -07004478 public static void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07004479 SamplingProfilerIntegration.start();
4480
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -08004481 // CloseGuard defaults to true and can be quite spammy. We
4482 // disable it here, but selectively enable it later (via
4483 // StrictMode) on debug builds, but using DropBox, not logs.
4484 CloseGuard.setEnabled(false);
4485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004486 Process.setArgV0("<pre-initialized>");
4487
4488 Looper.prepareMainLooper();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07004489 if (sMainThreadHandler == null) {
4490 sMainThreadHandler = new Handler();
4491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004492
4493 ActivityThread thread = new ActivityThread();
4494 thread.attach(false);
4495
Romain Guy5e9120d2012-01-30 12:17:22 -08004496 AsyncTask.init();
4497
Dianne Hackborn287952c2010-09-22 22:34:31 -07004498 if (false) {
4499 Looper.myLooper().setMessageLogging(new
4500 LogPrinter(Log.DEBUG, "ActivityThread"));
4501 }
4502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004503 Looper.loop();
4504
Jeff Brown10e89712011-07-08 18:52:57 -07004505 throw new RuntimeException("Main thread loop unexpectedly exited");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004506 }
4507}