blob: 98c4e10a2886bfe7e173943f1e44e42ae86322dc [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;
Brian Carlstromd893a892012-04-01 21:30:26 -0700177 String mInstrumentationAppLibraryDir = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700178 String mInstrumentationAppPackage = null;
179 String mInstrumentedAppDir = null;
Brian Carlstromd893a892012-04-01 21:30:26 -0700180 String mInstrumentedAppLibraryDir = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700181 boolean mSystemThread = false;
182 boolean mJitEnabled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700184 // These can be accessed by multiple threads; mPackages is the lock.
185 // XXX For now we keep around information about all packages we have
186 // seen, not removing entries from this map.
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800187 // NOTE: The activity and window managers need to call in to
Dianne Hackborn2f0b1752011-05-31 17:59:49 -0700188 // ActivityThread to do things like update resource configurations,
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800189 // which means this lock gets held while the activity and window managers
190 // holds their own lock. Thus you MUST NEVER call back into the activity manager
191 // or window manager or anything that depends on them while holding this lock.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700192 final HashMap<String, WeakReference<LoadedApk>> mPackages
193 = new HashMap<String, WeakReference<LoadedApk>>();
194 final HashMap<String, WeakReference<LoadedApk>> mResourcePackages
195 = new HashMap<String, WeakReference<LoadedApk>>();
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700196 final HashMap<CompatibilityInfo, DisplayMetrics> mDisplayMetrics
197 = new HashMap<CompatibilityInfo, DisplayMetrics>();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700198 final HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources
199 = new HashMap<ResourcesKey, WeakReference<Resources> >();
200 final ArrayList<ActivityClientRecord> mRelaunchingActivities
201 = new ArrayList<ActivityClientRecord>();
202 Configuration mPendingConfiguration = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700204 // The lock of mProviderMap protects the following variables.
205 final HashMap<String, ProviderClientRecord> mProviderMap
206 = new HashMap<String, ProviderClientRecord>();
207 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap
208 = new HashMap<IBinder, ProviderRefCount>();
209 final HashMap<IBinder, ProviderClientRecord> mLocalProviders
210 = new HashMap<IBinder, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211
Jeff Hamilton52d32032011-01-08 15:31:26 -0600212 final HashMap<Activity, ArrayList<OnActivityPausedListener>> mOnPauseListeners
213 = new HashMap<Activity, ArrayList<OnActivityPausedListener>>();
214
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700215 final GcIdler mGcIdler = new GcIdler();
216 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700218 static Handler sMainThreadHandler; // set once in main()
219
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800220 Bundle mCoreSettings = null;
221
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400222 static final class ActivityClientRecord {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700224 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 Intent intent;
226 Bundle state;
227 Activity activity;
228 Window window;
229 Activity parent;
230 String embeddedID;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700231 Activity.NonConfigurationInstances lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 boolean paused;
233 boolean stopped;
234 boolean hideForNow;
235 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700236 Configuration createdConfig;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700237 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700239 String profileFile;
240 ParcelFileDescriptor profileFd;
241 boolean autoStopProfiler;
242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 ActivityInfo activityInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400244 CompatibilityInfo compatInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700245 LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246
247 List<ResultInfo> pendingResults;
248 List<Intent> pendingIntents;
249
250 boolean startsNotResumed;
251 boolean isForward;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800252 int pendingConfigChanges;
253 boolean onlyLocalRequest;
254
255 View mPendingRemoveWindow;
256 WindowManager mPendingRemoveWindowManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700258 ActivityClientRecord() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 parent = null;
260 embeddedID = null;
261 paused = false;
262 stopped = false;
263 hideForNow = false;
264 nextIdle = null;
265 }
266
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800267 public boolean isPreHoneycomb() {
268 if (activity != null) {
269 return activity.getApplicationInfo().targetSdkVersion
270 < android.os.Build.VERSION_CODES.HONEYCOMB;
271 }
272 return false;
273 }
274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 public String toString() {
276 ComponentName componentName = intent.getComponent();
277 return "ActivityRecord{"
278 + Integer.toHexString(System.identityHashCode(this))
279 + " token=" + token + " " + (componentName == null
280 ? "no component name" : componentName.toShortString())
281 + "}";
282 }
283 }
284
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400285 final class ProviderClientRecord implements IBinder.DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 final String mName;
287 final IContentProvider mProvider;
288 final ContentProvider mLocalProvider;
289
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700290 ProviderClientRecord(String name, IContentProvider provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291 ContentProvider localProvider) {
292 mName = name;
293 mProvider = provider;
294 mLocalProvider = localProvider;
295 }
296
297 public void binderDied() {
298 removeDeadProvider(mName, mProvider);
299 }
300 }
301
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400302 static final class NewIntentData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303 List<Intent> intents;
304 IBinder token;
305 public String toString() {
306 return "NewIntentData{intents=" + intents + " token=" + token + "}";
307 }
308 }
309
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400310 static final class ReceiverData extends BroadcastReceiver.PendingResult {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700311 public ReceiverData(Intent intent, int resultCode, String resultData, Bundle resultExtras,
312 boolean ordered, boolean sticky, IBinder token) {
313 super(resultCode, resultData, resultExtras, TYPE_COMPONENT, ordered, sticky, token);
314 this.intent = intent;
315 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317 Intent intent;
318 ActivityInfo info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400319 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320 public String toString() {
321 return "ReceiverData{intent=" + intent + " packageName=" +
Dianne Hackborne829fef2010-10-26 17:44:01 -0700322 info.packageName + " resultCode=" + getResultCode()
323 + " resultData=" + getResultData() + " resultExtras="
324 + getResultExtras(false) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 }
326 }
327
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400328 static final class CreateBackupAgentData {
Christopher Tate181fafa2009-05-14 11:12:14 -0700329 ApplicationInfo appInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400330 CompatibilityInfo compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700331 int backupMode;
332 public String toString() {
333 return "CreateBackupAgentData{appInfo=" + appInfo
334 + " backupAgent=" + appInfo.backupAgentName
335 + " mode=" + backupMode + "}";
336 }
337 }
Bob Leee5408332009-09-04 18:31:17 -0700338
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400339 static final class CreateServiceData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800340 IBinder token;
341 ServiceInfo info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400342 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 Intent intent;
344 public String toString() {
345 return "CreateServiceData{token=" + token + " className="
346 + info.name + " packageName=" + info.packageName
347 + " intent=" + intent + "}";
348 }
349 }
350
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400351 static final class BindServiceData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800352 IBinder token;
353 Intent intent;
354 boolean rebind;
355 public String toString() {
356 return "BindServiceData{token=" + token + " intent=" + intent + "}";
357 }
358 }
359
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400360 static final class ServiceArgsData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 IBinder token;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700362 boolean taskRemoved;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700364 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365 Intent args;
366 public String toString() {
367 return "ServiceArgsData{token=" + token + " startId=" + startId
368 + " args=" + args + "}";
369 }
370 }
371
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400372 static final class AppBindData {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700373 LoadedApk info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374 String processName;
375 ApplicationInfo appInfo;
376 List<ProviderInfo> providers;
377 ComponentName instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800378 Bundle instrumentationArgs;
379 IInstrumentationWatcher instrumentationWatcher;
380 int debugMode;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800381 boolean enableOpenGlTrace;
Christopher Tate181fafa2009-05-14 11:12:14 -0700382 boolean restrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700383 boolean persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 Configuration config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400385 CompatibilityInfo compatInfo;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700386
387 /** Initial values for {@link Profiler}. */
388 String initProfileFile;
389 ParcelFileDescriptor initProfileFd;
390 boolean initAutoStopProfiler;
391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392 public String toString() {
393 return "AppBindData{appInfo=" + appInfo + "}";
394 }
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700395 }
396
397 static final class Profiler {
398 String profileFile;
399 ParcelFileDescriptor profileFd;
400 boolean autoStopProfiler;
401 boolean profiling;
402 boolean handlingProfiling;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700403 public void setProfiler(String file, ParcelFileDescriptor fd) {
404 if (profiling) {
405 if (fd != null) {
406 try {
407 fd.close();
408 } catch (IOException e) {
Romain Guya998dff2012-03-23 18:58:36 -0700409 // Ignore
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700410 }
411 }
412 return;
413 }
414 if (profileFd != null) {
415 try {
416 profileFd.close();
417 } catch (IOException e) {
Romain Guya998dff2012-03-23 18:58:36 -0700418 // Ignore
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700419 }
420 }
421 profileFile = file;
422 profileFd = fd;
423 }
424 public void startProfiling() {
425 if (profileFd == null || profiling) {
426 return;
427 }
428 try {
429 Debug.startMethodTracing(profileFile, profileFd.getFileDescriptor(),
430 8 * 1024 * 1024, 0);
431 profiling = true;
432 } catch (RuntimeException e) {
433 Slog.w(TAG, "Profiling failed on path " + profileFile);
434 try {
435 profileFd.close();
436 profileFd = null;
437 } catch (IOException e2) {
438 Slog.w(TAG, "Failure closing profile fd", e2);
439 }
440 }
441 }
442 public void stopProfiling() {
443 if (profiling) {
444 profiling = false;
445 Debug.stopMethodTracing();
446 if (profileFd != null) {
447 try {
448 profileFd.close();
449 } catch (IOException e) {
450 }
451 }
452 profileFd = null;
453 profileFile = null;
454 }
455 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 }
457
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400458 static final class DumpComponentInfo {
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700459 ParcelFileDescriptor fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700460 IBinder token;
Dianne Hackborn30d71892010-12-11 10:37:55 -0800461 String prefix;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 String[] args;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463 }
464
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400465 static final class ResultData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466 IBinder token;
467 List<ResultInfo> results;
468 public String toString() {
469 return "ResultData{token=" + token + " results" + results + "}";
470 }
471 }
472
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400473 static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800474 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475 String what;
476 String who;
477 }
478
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400479 static final class ProfilerControlData {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700480 String path;
481 ParcelFileDescriptor fd;
482 }
483
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400484 static final class DumpHeapData {
Andy McFadden824c5102010-07-09 16:26:57 -0700485 String path;
486 ParcelFileDescriptor fd;
487 }
488
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400489 static final class UpdateCompatibilityData {
490 String pkg;
491 CompatibilityInfo info;
492 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -0700493
Romain Guy65b345f2011-07-27 18:51:50 -0700494 private native void dumpGraphicsInfo(FileDescriptor fd);
Chet Haase9c1e23b2011-03-24 10:51:31 -0700495
Romain Guy65b345f2011-07-27 18:51:50 -0700496 private class ApplicationThread extends ApplicationThreadNative {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700497 private static final String HEAP_COLUMN = "%13s %8s %8s %8s %8s %8s %8s";
498 private static final String ONE_COUNT_COLUMN = "%21s %8d";
499 private static final String TWO_COUNT_COLUMNS = "%21s %8d %21s %8d";
Vasu Nori3c7131f2010-09-21 14:36:57 -0700500 private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
Bob Leee5408332009-09-04 18:31:17 -0700501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800502 // Formatting for checkin service - update version if row format changes
503 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;
Bob Leee5408332009-09-04 18:31:17 -0700504
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700505 private void updatePendingConfiguration(Configuration config) {
506 synchronized (mPackages) {
507 if (mPendingConfiguration == null ||
508 mPendingConfiguration.isOtherSeqNewer(config)) {
509 mPendingConfiguration = config;
510 }
511 }
512 }
513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514 public final void schedulePauseActivity(IBinder token, boolean finished,
515 boolean userLeaving, int configChanges) {
516 queueOrSendMessage(
517 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
518 token,
519 (userLeaving ? 1 : 0),
520 configChanges);
521 }
522
523 public final void scheduleStopActivity(IBinder token, boolean showWindow,
524 int configChanges) {
525 queueOrSendMessage(
526 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
527 token, 0, configChanges);
528 }
529
530 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
531 queueOrSendMessage(
532 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
533 token);
534 }
535
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800536 public final void scheduleSleeping(IBinder token, boolean sleeping) {
537 queueOrSendMessage(H.SLEEPING, token, sleeping ? 1 : 0);
538 }
539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 public final void scheduleResumeActivity(IBinder token, boolean isForward) {
541 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
542 }
543
544 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
545 ResultData res = new ResultData();
546 res.token = token;
547 res.results = results;
548 queueOrSendMessage(H.SEND_RESULT, res);
549 }
550
551 // we use token to identify this activity without having to send the
552 // activity itself back to the activity manager. (matters more with ipc)
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700553 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700554 ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
555 Bundle state, List<ResultInfo> pendingResults,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700556 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward,
557 String profileName, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700558 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559
560 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700561 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 r.intent = intent;
563 r.activityInfo = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400564 r.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565 r.state = state;
566
567 r.pendingResults = pendingResults;
568 r.pendingIntents = pendingNewIntents;
569
570 r.startsNotResumed = notResumed;
571 r.isForward = isForward;
572
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700573 r.profileFile = profileName;
574 r.profileFd = profileFd;
575 r.autoStopProfiler = autoStopProfiler;
576
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700577 updatePendingConfiguration(curConfig);
578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
580 }
581
582 public final void scheduleRelaunchActivity(IBinder token,
583 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800584 int configChanges, boolean notResumed, Configuration config) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800585 requestRelaunchActivity(token, pendingResults, pendingNewIntents,
586 configChanges, notResumed, config, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587 }
588
589 public final void scheduleNewIntent(List<Intent> intents, IBinder token) {
590 NewIntentData data = new NewIntentData();
591 data.intents = intents;
592 data.token = token;
593
594 queueOrSendMessage(H.NEW_INTENT, data);
595 }
596
597 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
598 int configChanges) {
599 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
600 configChanges);
601 }
602
603 public final void scheduleReceiver(Intent intent, ActivityInfo info,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400604 CompatibilityInfo compatInfo, int resultCode, String data, Bundle extras,
605 boolean sync) {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700606 ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
607 sync, false, mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 r.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400609 r.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 queueOrSendMessage(H.RECEIVER, r);
611 }
612
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400613 public final void scheduleCreateBackupAgent(ApplicationInfo app,
614 CompatibilityInfo compatInfo, int backupMode) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700615 CreateBackupAgentData d = new CreateBackupAgentData();
616 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400617 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700618 d.backupMode = backupMode;
619
620 queueOrSendMessage(H.CREATE_BACKUP_AGENT, d);
621 }
622
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400623 public final void scheduleDestroyBackupAgent(ApplicationInfo app,
624 CompatibilityInfo compatInfo) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700625 CreateBackupAgentData d = new CreateBackupAgentData();
626 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400627 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700628
629 queueOrSendMessage(H.DESTROY_BACKUP_AGENT, d);
630 }
631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 public final void scheduleCreateService(IBinder token,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400633 ServiceInfo info, CompatibilityInfo compatInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634 CreateServiceData s = new CreateServiceData();
635 s.token = token;
636 s.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400637 s.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638
639 queueOrSendMessage(H.CREATE_SERVICE, s);
640 }
641
642 public final void scheduleBindService(IBinder token, Intent intent,
643 boolean rebind) {
644 BindServiceData s = new BindServiceData();
645 s.token = token;
646 s.intent = intent;
647 s.rebind = rebind;
648
Amith Yamasani742a6712011-05-04 14:49:28 -0700649 if (DEBUG_SERVICE)
650 Slog.v(TAG, "scheduleBindService token=" + token + " intent=" + intent + " uid="
651 + Binder.getCallingUid() + " pid=" + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 queueOrSendMessage(H.BIND_SERVICE, s);
653 }
654
655 public final void scheduleUnbindService(IBinder token, Intent intent) {
656 BindServiceData s = new BindServiceData();
657 s.token = token;
658 s.intent = intent;
659
660 queueOrSendMessage(H.UNBIND_SERVICE, s);
661 }
662
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700663 public final void scheduleServiceArgs(IBinder token, boolean taskRemoved, int startId,
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700664 int flags ,Intent args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 ServiceArgsData s = new ServiceArgsData();
666 s.token = token;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700667 s.taskRemoved = taskRemoved;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668 s.startId = startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700669 s.flags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670 s.args = args;
671
672 queueOrSendMessage(H.SERVICE_ARGS, s);
673 }
674
675 public final void scheduleStopService(IBinder token) {
676 queueOrSendMessage(H.STOP_SERVICE, token);
677 }
678
679 public final void bindApplication(String processName,
680 ApplicationInfo appInfo, List<ProviderInfo> providers,
681 ComponentName instrumentationName, String profileFile,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700682 ParcelFileDescriptor profileFd, boolean autoStopProfiler,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
Siva Velusamy92a8b222012-03-09 16:24:04 -0800684 int debugMode, boolean enableOpenGlTrace, boolean isRestrictedBackupMode,
685 boolean persistent, Configuration config, CompatibilityInfo compatInfo,
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700686 Map<String, IBinder> services, Bundle coreSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687
688 if (services != null) {
689 // Setup the service cache in the ServiceManager
690 ServiceManager.initServiceCache(services);
691 }
692
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800693 setCoreSettings(coreSettings);
694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695 AppBindData data = new AppBindData();
696 data.processName = processName;
697 data.appInfo = appInfo;
698 data.providers = providers;
699 data.instrumentationName = instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 data.instrumentationArgs = instrumentationArgs;
701 data.instrumentationWatcher = instrumentationWatcher;
702 data.debugMode = debugMode;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800703 data.enableOpenGlTrace = enableOpenGlTrace;
Christopher Tate181fafa2009-05-14 11:12:14 -0700704 data.restrictedBackupMode = isRestrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700705 data.persistent = persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 data.config = config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400707 data.compatInfo = compatInfo;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700708 data.initProfileFile = profileFile;
709 data.initProfileFd = profileFd;
710 data.initAutoStopProfiler = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 queueOrSendMessage(H.BIND_APPLICATION, data);
712 }
713
714 public final void scheduleExit() {
715 queueOrSendMessage(H.EXIT_APPLICATION, null);
716 }
717
Christopher Tate5e1ab332009-09-01 20:32:49 -0700718 public final void scheduleSuicide() {
719 queueOrSendMessage(H.SUICIDE, null);
720 }
721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 public void requestThumbnail(IBinder token) {
723 queueOrSendMessage(H.REQUEST_THUMBNAIL, token);
724 }
725
726 public void scheduleConfigurationChanged(Configuration config) {
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700727 updatePendingConfiguration(config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 queueOrSendMessage(H.CONFIGURATION_CHANGED, config);
729 }
730
731 public void updateTimeZone() {
732 TimeZone.setDefault(null);
733 }
734
Robert Greenwalt03595d02010-11-02 14:08:23 -0700735 public void clearDnsCache() {
736 // a non-standard API to get this to libcore
737 InetAddress.clearDnsCache();
738 }
739
Robert Greenwalt434203a2010-10-11 16:00:27 -0700740 public void setHttpProxy(String host, String port, String exclList) {
741 Proxy.setHttpProxySystemProperty(host, port, exclList);
742 }
743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 public void processInBackground() {
745 mH.removeMessages(H.GC_WHEN_IDLE);
746 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
747 }
748
749 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700750 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700751 try {
752 data.fd = ParcelFileDescriptor.dup(fd);
753 data.token = servicetoken;
754 data.args = args;
755 queueOrSendMessage(H.DUMP_SERVICE, data);
756 } catch (IOException e) {
757 Slog.w(TAG, "dumpService failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 }
759 }
760
761 // This function exists to make sure all receiver dispatching is
762 // correctly ordered, since these are one-way calls and the binder driver
763 // applies transaction ordering per object for such calls.
764 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700765 int resultCode, String dataStr, Bundle extras, boolean ordered,
766 boolean sticky) throws RemoteException {
767 receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 }
Bob Leee5408332009-09-04 18:31:17 -0700769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 public void scheduleLowMemory() {
771 queueOrSendMessage(H.LOW_MEMORY, null);
772 }
773
774 public void scheduleActivityConfigurationChanged(IBinder token) {
775 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token);
776 }
777
Romain Guy7eabe552011-07-21 14:56:34 -0700778 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd,
779 int profileType) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700780 ProfilerControlData pcd = new ProfilerControlData();
781 pcd.path = path;
782 pcd.fd = fd;
Romain Guy7eabe552011-07-21 14:56:34 -0700783 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0, profileType);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800784 }
785
Andy McFadden824c5102010-07-09 16:26:57 -0700786 public void dumpHeap(boolean managed, String path, ParcelFileDescriptor fd) {
787 DumpHeapData dhd = new DumpHeapData();
788 dhd.path = path;
789 dhd.fd = fd;
790 queueOrSendMessage(H.DUMP_HEAP, dhd, managed ? 1 : 0);
791 }
792
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700793 public void setSchedulingGroup(int group) {
794 // Note: do this immediately, since going into the foreground
795 // should happen regardless of what pending work we have to do
796 // and the activity manager will wait for us to report back that
797 // we are done before sending us to the background.
798 try {
799 Process.setProcessGroup(Process.myPid(), group);
800 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800801 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700802 }
803 }
Bob Leee5408332009-09-04 18:31:17 -0700804
Dianne Hackborn3025ef32009-08-31 21:31:47 -0700805 public void getMemoryInfo(Debug.MemoryInfo outInfo) {
806 Debug.getMemoryInfo(outInfo);
807 }
Bob Leee5408332009-09-04 18:31:17 -0700808
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700809 public void dispatchPackageBroadcast(int cmd, String[] packages) {
810 queueOrSendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
811 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700812
813 public void scheduleCrash(String msg) {
814 queueOrSendMessage(H.SCHEDULE_CRASH, msg);
815 }
Dianne Hackborn625ac272010-09-17 18:29:22 -0700816
Dianne Hackborn30d71892010-12-11 10:37:55 -0800817 public void dumpActivity(FileDescriptor fd, IBinder activitytoken,
818 String prefix, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700819 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700820 try {
821 data.fd = ParcelFileDescriptor.dup(fd);
822 data.token = activitytoken;
823 data.prefix = prefix;
824 data.args = args;
825 queueOrSendMessage(H.DUMP_ACTIVITY, data);
826 } catch (IOException e) {
827 Slog.w(TAG, "dumpActivity failed", e);
Dianne Hackborn625ac272010-09-17 18:29:22 -0700828 }
829 }
Chet Haase9c1e23b2011-03-24 10:51:31 -0700830
Marco Nelissen18cb2872011-11-15 11:19:53 -0800831 public void dumpProvider(FileDescriptor fd, IBinder providertoken,
832 String[] args) {
833 DumpComponentInfo data = new DumpComponentInfo();
834 try {
835 data.fd = ParcelFileDescriptor.dup(fd);
836 data.token = providertoken;
837 data.args = args;
838 queueOrSendMessage(H.DUMP_PROVIDER, data);
839 } catch (IOException e) {
840 Slog.w(TAG, "dumpProvider failed", e);
841 }
842 }
843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 @Override
Dianne Hackbornb437e092011-08-05 17:50:29 -0700845 public Debug.MemoryInfo dumpMemInfo(FileDescriptor fd, boolean checkin,
846 boolean all, String[] args) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700847 FileOutputStream fout = new FileOutputStream(fd);
848 PrintWriter pw = new PrintWriter(fout);
849 try {
Romain Guya998dff2012-03-23 18:58:36 -0700850 return dumpMemInfo(pw, checkin, all);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700851 } finally {
Chet Haase9c1e23b2011-03-24 10:51:31 -0700852 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -0700853 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700854 }
855
Romain Guya998dff2012-03-23 18:58:36 -0700856 private Debug.MemoryInfo dumpMemInfo(PrintWriter pw, boolean checkin, boolean all) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 long nativeMax = Debug.getNativeHeapSize() / 1024;
858 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
859 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
860
861 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
862 Debug.getMemoryInfo(memInfo);
863
Dianne Hackbornb437e092011-08-05 17:50:29 -0700864 if (!all) {
865 return memInfo;
866 }
867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 Runtime runtime = Runtime.getRuntime();
869
870 long dalvikMax = runtime.totalMemory() / 1024;
871 long dalvikFree = runtime.freeMemory() / 1024;
872 long dalvikAllocated = dalvikMax - dalvikFree;
873 long viewInstanceCount = ViewDebug.getViewInstanceCount();
Romain Guy65b345f2011-07-27 18:51:50 -0700874 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
Brian Carlstromc21550a2010-10-05 21:34:06 -0700875 long appContextInstanceCount = Debug.countInstancesOfClass(ContextImpl.class);
876 long activityInstanceCount = Debug.countInstancesOfClass(Activity.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 int globalAssetCount = AssetManager.getGlobalAssetCount();
878 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
879 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
880 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
881 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
Brian Carlstromc9d5b312010-10-05 22:23:41 -0700882 long openSslSocketCount = Debug.countInstancesOfClass(OpenSSLSocketImpl.class);
Vasu Noric3849202010-03-09 10:47:25 -0800883 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -0700884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 // For checkin, we print one long comma-separated list of values
Dianne Hackbornb437e092011-08-05 17:50:29 -0700886 if (checkin) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 // NOTE: if you change anything significant below, also consider changing
888 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -0700889 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -0700891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 // Header
893 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
894 pw.print(Process.myPid()); pw.print(',');
895 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 // Heap info - max
898 pw.print(nativeMax); pw.print(',');
899 pw.print(dalvikMax); pw.print(',');
900 pw.print("N/A,");
901 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 // Heap info - allocated
904 pw.print(nativeAllocated); pw.print(',');
905 pw.print(dalvikAllocated); pw.print(',');
906 pw.print("N/A,");
907 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 // Heap info - free
910 pw.print(nativeFree); pw.print(',');
911 pw.print(dalvikFree); pw.print(',');
912 pw.print("N/A,");
913 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700914
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 // Heap info - proportional set size
916 pw.print(memInfo.nativePss); pw.print(',');
917 pw.print(memInfo.dalvikPss); pw.print(',');
918 pw.print(memInfo.otherPss); pw.print(',');
919 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 // Heap info - shared
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700922 pw.print(memInfo.nativeSharedDirty); pw.print(',');
923 pw.print(memInfo.dalvikSharedDirty); pw.print(',');
924 pw.print(memInfo.otherSharedDirty); pw.print(',');
925 pw.print(memInfo.nativeSharedDirty + memInfo.dalvikSharedDirty
926 + memInfo.otherSharedDirty); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 // Heap info - private
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700929 pw.print(memInfo.nativePrivateDirty); pw.print(',');
930 pw.print(memInfo.dalvikPrivateDirty); pw.print(',');
931 pw.print(memInfo.otherPrivateDirty); pw.print(',');
932 pw.print(memInfo.nativePrivateDirty + memInfo.dalvikPrivateDirty
933 + memInfo.otherPrivateDirty); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 // Object counts
936 pw.print(viewInstanceCount); pw.print(',');
937 pw.print(viewRootInstanceCount); pw.print(',');
938 pw.print(appContextInstanceCount); pw.print(',');
939 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 pw.print(globalAssetCount); pw.print(',');
942 pw.print(globalAssetManagerCount); pw.print(',');
943 pw.print(binderLocalObjectCount); pw.print(',');
944 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 pw.print(binderDeathObjectCount); pw.print(',');
947 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 // SQL
Vasu Noric3849202010-03-09 10:47:25 -0800950 pw.print(stats.memoryUsed / 1024); pw.print(',');
Jeff Brown2a293b62012-01-19 14:02:22 -0800951 pw.print(stats.memoryUsed / 1024); pw.print(',');
952 pw.print(stats.pageCacheOverflow / 1024); pw.print(',');
Dianne Hackbornb437e092011-08-05 17:50:29 -0700953 pw.print(stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -0800954 for (int i = 0; i < stats.dbStats.size(); i++) {
955 DbStats dbStats = stats.dbStats.get(i);
Dianne Hackbornb437e092011-08-05 17:50:29 -0700956 pw.print(','); pw.print(dbStats.dbName);
957 pw.print(','); pw.print(dbStats.pageSize);
958 pw.print(','); pw.print(dbStats.dbSize);
959 pw.print(','); pw.print(dbStats.lookaside);
960 pw.print(','); pw.print(dbStats.cache);
961 pw.print(','); pw.print(dbStats.cache);
Vasu Noric3849202010-03-09 10:47:25 -0800962 }
Dianne Hackbornb437e092011-08-05 17:50:29 -0700963 pw.println();
Bob Leee5408332009-09-04 18:31:17 -0700964
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700965 return memInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 }
Bob Leee5408332009-09-04 18:31:17 -0700967
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 // otherwise, show human-readable format
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700969 printRow(pw, HEAP_COLUMN, "", "", "Shared", "Private", "Heap", "Heap", "Heap");
970 printRow(pw, HEAP_COLUMN, "", "Pss", "Dirty", "Dirty", "Size", "Alloc", "Free");
971 printRow(pw, HEAP_COLUMN, "", "------", "------", "------", "------", "------",
972 "------");
973 printRow(pw, HEAP_COLUMN, "Native", memInfo.nativePss, memInfo.nativeSharedDirty,
974 memInfo.nativePrivateDirty, nativeMax, nativeAllocated, nativeFree);
975 printRow(pw, HEAP_COLUMN, "Dalvik", memInfo.dalvikPss, memInfo.dalvikSharedDirty,
976 memInfo.dalvikPrivateDirty, dalvikMax, dalvikAllocated, dalvikFree);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700978 int otherPss = memInfo.otherPss;
979 int otherSharedDirty = memInfo.otherSharedDirty;
980 int otherPrivateDirty = memInfo.otherPrivateDirty;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700982 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
Romain Guy65b345f2011-07-27 18:51:50 -0700983 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700984 memInfo.getOtherPss(i), memInfo.getOtherSharedDirty(i),
985 memInfo.getOtherPrivateDirty(i), "", "", "");
986 otherPss -= memInfo.getOtherPss(i);
987 otherSharedDirty -= memInfo.getOtherSharedDirty(i);
988 otherPrivateDirty -= memInfo.getOtherPrivateDirty(i);
989 }
990
991 printRow(pw, HEAP_COLUMN, "Unknown", otherPss, otherSharedDirty,
992 otherPrivateDirty, "", "", "");
993 printRow(pw, HEAP_COLUMN, "TOTAL", memInfo.getTotalPss(),
994 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
995 nativeMax+dalvikMax, nativeAllocated+dalvikAllocated,
996 nativeFree+dalvikFree);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997
998 pw.println(" ");
999 pw.println(" Objects");
Romain Guy65b345f2011-07-27 18:51:50 -07001000 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRootImpl:",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 viewRootInstanceCount);
1002
1003 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
1004 "Activities:", activityInstanceCount);
1005
1006 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
1007 "AssetManagers:", globalAssetManagerCount);
1008
1009 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
1010 "Proxy Binders:", binderProxyObjectCount);
1011 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
1012
1013 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -07001014
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 // SQLite mem info
1016 pw.println(" ");
1017 pw.println(" SQL");
Jeff Brown2a293b62012-01-19 14:02:22 -08001018 printRow(pw, ONE_COUNT_COLUMN, "MEMORY_USED:", stats.memoryUsed / 1024);
1019 printRow(pw, TWO_COUNT_COLUMNS, "PAGECACHE_OVERFLOW:",
1020 stats.pageCacheOverflow / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -08001021 pw.println(" ");
1022 int N = stats.dbStats.size();
1023 if (N > 0) {
1024 pw.println(" DATABASES");
Vasu Nori3c7131f2010-09-21 14:36:57 -07001025 printRow(pw, " %8s %8s %14s %14s %s", "pgsz", "dbsz", "Lookaside(b)", "cache",
1026 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -08001027 for (int i = 0; i < N; i++) {
1028 DbStats dbStats = stats.dbStats.get(i);
Vasu Nori3c7131f2010-09-21 14:36:57 -07001029 printRow(pw, DB_INFO_FORMAT,
1030 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
1031 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
1032 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
1033 dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -08001034 }
1035 }
Bob Leee5408332009-09-04 18:31:17 -07001036
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07001037 // Asset details.
1038 String assetAlloc = AssetManager.getAssetAllocations();
1039 if (assetAlloc != null) {
1040 pw.println(" ");
1041 pw.println(" Asset Allocations");
1042 pw.print(assetAlloc);
1043 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001044
1045 return memInfo;
1046 }
1047
1048 @Override
1049 public void dumpGfxInfo(FileDescriptor fd, String[] args) {
1050 dumpGraphicsInfo(fd);
Romain Guy65b345f2011-07-27 18:51:50 -07001051 WindowManagerImpl.getDefault().dumpGfxInfo(fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 }
1053
Jeff Brown6754ba22011-12-14 20:20:01 -08001054 @Override
1055 public void dumpDbInfo(FileDescriptor fd, String[] args) {
1056 PrintWriter pw = new PrintWriter(new FileOutputStream(fd));
1057 PrintWriterPrinter printer = new PrintWriterPrinter(pw);
1058 SQLiteDebug.dump(printer, args);
1059 pw.flush();
1060 }
1061
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 private void printRow(PrintWriter pw, String format, Object...objs) {
1063 pw.println(String.format(format, objs));
1064 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001065
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08001066 public void setCoreSettings(Bundle coreSettings) {
1067 queueOrSendMessage(H.SET_CORE_SETTINGS, coreSettings);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001068 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001069
1070 public void updatePackageCompatibilityInfo(String pkg, CompatibilityInfo info) {
1071 UpdateCompatibilityData ucd = new UpdateCompatibilityData();
1072 ucd.pkg = pkg;
1073 ucd.info = info;
1074 queueOrSendMessage(H.UPDATE_PACKAGE_COMPATIBILITY_INFO, ucd);
1075 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001076
1077 public void scheduleTrimMemory(int level) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001078 queueOrSendMessage(H.TRIM_MEMORY, null, level);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001079 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 }
1082
Romain Guy65b345f2011-07-27 18:51:50 -07001083 private class H extends Handler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 public static final int LAUNCH_ACTIVITY = 100;
1085 public static final int PAUSE_ACTIVITY = 101;
1086 public static final int PAUSE_ACTIVITY_FINISHING= 102;
1087 public static final int STOP_ACTIVITY_SHOW = 103;
1088 public static final int STOP_ACTIVITY_HIDE = 104;
1089 public static final int SHOW_WINDOW = 105;
1090 public static final int HIDE_WINDOW = 106;
1091 public static final int RESUME_ACTIVITY = 107;
1092 public static final int SEND_RESULT = 108;
Brian Carlstromed7e0072011-03-24 13:27:57 -07001093 public static final int DESTROY_ACTIVITY = 109;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 public static final int BIND_APPLICATION = 110;
1095 public static final int EXIT_APPLICATION = 111;
1096 public static final int NEW_INTENT = 112;
1097 public static final int RECEIVER = 113;
1098 public static final int CREATE_SERVICE = 114;
1099 public static final int SERVICE_ARGS = 115;
1100 public static final int STOP_SERVICE = 116;
1101 public static final int REQUEST_THUMBNAIL = 117;
1102 public static final int CONFIGURATION_CHANGED = 118;
1103 public static final int CLEAN_UP_CONTEXT = 119;
1104 public static final int GC_WHEN_IDLE = 120;
1105 public static final int BIND_SERVICE = 121;
1106 public static final int UNBIND_SERVICE = 122;
1107 public static final int DUMP_SERVICE = 123;
1108 public static final int LOW_MEMORY = 124;
1109 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
1110 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001111 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -07001112 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001113 public static final int DESTROY_BACKUP_AGENT = 129;
1114 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001115 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001116 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001117 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001118 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -07001119 public static final int DUMP_HEAP = 135;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001120 public static final int DUMP_ACTIVITY = 136;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001121 public static final int SLEEPING = 137;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001122 public static final int SET_CORE_SETTINGS = 138;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001123 public static final int UPDATE_PACKAGE_COMPATIBILITY_INFO = 139;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001124 public static final int TRIM_MEMORY = 140;
Marco Nelissen18cb2872011-11-15 11:19:53 -08001125 public static final int DUMP_PROVIDER = 141;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 String codeToString(int code) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001127 if (DEBUG_MESSAGES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 switch (code) {
1129 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
1130 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
1131 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
1132 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
1133 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
1134 case SHOW_WINDOW: return "SHOW_WINDOW";
1135 case HIDE_WINDOW: return "HIDE_WINDOW";
1136 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
1137 case SEND_RESULT: return "SEND_RESULT";
1138 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
1139 case BIND_APPLICATION: return "BIND_APPLICATION";
1140 case EXIT_APPLICATION: return "EXIT_APPLICATION";
1141 case NEW_INTENT: return "NEW_INTENT";
1142 case RECEIVER: return "RECEIVER";
1143 case CREATE_SERVICE: return "CREATE_SERVICE";
1144 case SERVICE_ARGS: return "SERVICE_ARGS";
1145 case STOP_SERVICE: return "STOP_SERVICE";
1146 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
1147 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
1148 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
1149 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
1150 case BIND_SERVICE: return "BIND_SERVICE";
1151 case UNBIND_SERVICE: return "UNBIND_SERVICE";
1152 case DUMP_SERVICE: return "DUMP_SERVICE";
1153 case LOW_MEMORY: return "LOW_MEMORY";
1154 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
1155 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001156 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -07001157 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
1158 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -07001159 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001160 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001161 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001162 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001163 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -07001164 case DUMP_HEAP: return "DUMP_HEAP";
Dianne Hackborn625ac272010-09-17 18:29:22 -07001165 case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001166 case SLEEPING: return "SLEEPING";
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001167 case SET_CORE_SETTINGS: return "SET_CORE_SETTINGS";
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001168 case UPDATE_PACKAGE_COMPATIBILITY_INFO: return "UPDATE_PACKAGE_COMPATIBILITY_INFO";
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001169 case TRIM_MEMORY: return "TRIM_MEMORY";
Marco Nelissen18cb2872011-11-15 11:19:53 -08001170 case DUMP_PROVIDER: return "DUMP_PROVIDER";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 }
1172 }
1173 return "(unknown)";
1174 }
1175 public void handleMessage(Message msg) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001176 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177 switch (msg.what) {
1178 case LAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001179 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180
1181 r.packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001182 r.activityInfo.applicationInfo, r.compatInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001183 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 } break;
1185 case RELAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001186 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08001187 handleRelaunchActivity(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 } break;
1189 case PAUSE_ACTIVITY:
1190 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -07001191 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 break;
1193 case PAUSE_ACTIVITY_FINISHING:
1194 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
1195 break;
1196 case STOP_ACTIVITY_SHOW:
1197 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
1198 break;
1199 case STOP_ACTIVITY_HIDE:
1200 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
1201 break;
1202 case SHOW_WINDOW:
1203 handleWindowVisibility((IBinder)msg.obj, true);
1204 break;
1205 case HIDE_WINDOW:
1206 handleWindowVisibility((IBinder)msg.obj, false);
1207 break;
1208 case RESUME_ACTIVITY:
1209 handleResumeActivity((IBinder)msg.obj, true,
1210 msg.arg1 != 0);
1211 break;
1212 case SEND_RESULT:
1213 handleSendResult((ResultData)msg.obj);
1214 break;
1215 case DESTROY_ACTIVITY:
1216 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
1217 msg.arg2, false);
1218 break;
1219 case BIND_APPLICATION:
1220 AppBindData data = (AppBindData)msg.obj;
1221 handleBindApplication(data);
1222 break;
1223 case EXIT_APPLICATION:
1224 if (mInitialApplication != null) {
1225 mInitialApplication.onTerminate();
1226 }
1227 Looper.myLooper().quit();
1228 break;
1229 case NEW_INTENT:
1230 handleNewIntent((NewIntentData)msg.obj);
1231 break;
1232 case RECEIVER:
1233 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001234 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 break;
1236 case CREATE_SERVICE:
1237 handleCreateService((CreateServiceData)msg.obj);
1238 break;
1239 case BIND_SERVICE:
1240 handleBindService((BindServiceData)msg.obj);
1241 break;
1242 case UNBIND_SERVICE:
1243 handleUnbindService((BindServiceData)msg.obj);
1244 break;
1245 case SERVICE_ARGS:
1246 handleServiceArgs((ServiceArgsData)msg.obj);
1247 break;
1248 case STOP_SERVICE:
1249 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001250 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251 break;
1252 case REQUEST_THUMBNAIL:
1253 handleRequestThumbnail((IBinder)msg.obj);
1254 break;
1255 case CONFIGURATION_CHANGED:
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001256 handleConfigurationChanged((Configuration)msg.obj, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 break;
1258 case CLEAN_UP_CONTEXT:
1259 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1260 cci.context.performFinalCleanup(cci.who, cci.what);
1261 break;
1262 case GC_WHEN_IDLE:
1263 scheduleGcIdler();
1264 break;
1265 case DUMP_SERVICE:
Dianne Hackborn625ac272010-09-17 18:29:22 -07001266 handleDumpService((DumpComponentInfo)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 break;
1268 case LOW_MEMORY:
1269 handleLowMemory();
1270 break;
1271 case ACTIVITY_CONFIGURATION_CHANGED:
1272 handleActivityConfigurationChanged((IBinder)msg.obj);
1273 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001274 case PROFILER_CONTROL:
Romain Guy7eabe552011-07-21 14:56:34 -07001275 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj, msg.arg2);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001276 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001277 case CREATE_BACKUP_AGENT:
1278 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1279 break;
1280 case DESTROY_BACKUP_AGENT:
1281 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1282 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001283 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001284 Process.killProcess(Process.myPid());
1285 break;
1286 case REMOVE_PROVIDER:
1287 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001288 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001289 case ENABLE_JIT:
1290 ensureJitEnabled();
1291 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001292 case DISPATCH_PACKAGE_BROADCAST:
1293 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
1294 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001295 case SCHEDULE_CRASH:
1296 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001297 case DUMP_HEAP:
1298 handleDumpHeap(msg.arg1 != 0, (DumpHeapData)msg.obj);
1299 break;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001300 case DUMP_ACTIVITY:
1301 handleDumpActivity((DumpComponentInfo)msg.obj);
1302 break;
Marco Nelissen18cb2872011-11-15 11:19:53 -08001303 case DUMP_PROVIDER:
1304 handleDumpProvider((DumpComponentInfo)msg.obj);
1305 break;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001306 case SLEEPING:
1307 handleSleeping((IBinder)msg.obj, msg.arg1 != 0);
1308 break;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001309 case SET_CORE_SETTINGS:
1310 handleSetCoreSettings((Bundle) msg.obj);
1311 break;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001312 case UPDATE_PACKAGE_COMPATIBILITY_INFO:
1313 handleUpdatePackageCompatibilityInfo((UpdateCompatibilityData)msg.obj);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001314 break;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001315 case TRIM_MEMORY:
1316 handleTrimMemory(msg.arg1);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001317 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07001319 if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 }
Bob Leee5408332009-09-04 18:31:17 -07001321
Brian Carlstromed7e0072011-03-24 13:27:57 -07001322 private void maybeSnapshot() {
1323 if (mBoundApplication != null && SamplingProfilerIntegration.isEnabled()) {
Sen Hubde75702010-05-28 01:54:03 -07001324 // convert the *private* ActivityThread.PackageInfo to *public* known
1325 // android.content.pm.PackageInfo
1326 String packageName = mBoundApplication.info.mPackageName;
1327 android.content.pm.PackageInfo packageInfo = null;
1328 try {
1329 Context context = getSystemContext();
1330 if(context == null) {
1331 Log.e(TAG, "cannot get a valid context");
1332 return;
1333 }
1334 PackageManager pm = context.getPackageManager();
1335 if(pm == null) {
1336 Log.e(TAG, "cannot get a valid PackageManager");
1337 return;
1338 }
1339 packageInfo = pm.getPackageInfo(
1340 packageName, PackageManager.GET_ACTIVITIES);
1341 } catch (NameNotFoundException e) {
1342 Log.e(TAG, "cannot get package info for " + packageName, e);
1343 }
1344 SamplingProfilerIntegration.writeSnapshot(mBoundApplication.processName, packageInfo);
Bob Leee5408332009-09-04 18:31:17 -07001345 }
1346 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 }
1348
Romain Guy65b345f2011-07-27 18:51:50 -07001349 private class Idler implements MessageQueue.IdleHandler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001351 ActivityClientRecord a = mNewActivities;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001352 boolean stopProfiling = false;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001353 if (mBoundApplication != null && mProfiler.profileFd != null
1354 && mProfiler.autoStopProfiler) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001355 stopProfiling = true;
1356 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 if (a != null) {
1358 mNewActivities = null;
1359 IActivityManager am = ActivityManagerNative.getDefault();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001360 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001362 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 TAG, "Reporting idle of " + a +
1364 " finished=" +
Romain Guy65b345f2011-07-27 18:51:50 -07001365 (a.activity != null && a.activity.mFinished));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366 if (a.activity != null && !a.activity.mFinished) {
1367 try {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001368 am.activityIdle(a.token, a.createdConfig, stopProfiling);
Dianne Hackborne88846e2009-09-30 21:34:25 -07001369 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 } catch (RemoteException ex) {
Romain Guy65b345f2011-07-27 18:51:50 -07001371 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 }
1373 }
1374 prev = a;
1375 a = a.nextIdle;
1376 prev.nextIdle = null;
1377 } while (a != null);
1378 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001379 if (stopProfiling) {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001380 mProfiler.stopProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001381 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001382 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 return false;
1384 }
1385 }
1386
1387 final class GcIdler implements MessageQueue.IdleHandler {
1388 public final boolean queueIdle() {
1389 doGcIfNeeded();
1390 return false;
1391 }
1392 }
1393
Romain Guy65b345f2011-07-27 18:51:50 -07001394 private static class ResourcesKey {
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001395 final private String mResDir;
1396 final private float mScale;
1397 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07001398
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001399 ResourcesKey(String resDir, float scale) {
1400 mResDir = resDir;
1401 mScale = scale;
1402 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
1403 }
Bob Leee5408332009-09-04 18:31:17 -07001404
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001405 @Override
1406 public int hashCode() {
1407 return mHash;
1408 }
1409
1410 @Override
1411 public boolean equals(Object obj) {
1412 if (!(obj instanceof ResourcesKey)) {
1413 return false;
1414 }
1415 ResourcesKey peer = (ResourcesKey) obj;
1416 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
1417 }
1418 }
1419
Romain Guy65b345f2011-07-27 18:51:50 -07001420 public static ActivityThread currentActivityThread() {
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07001421 return sThreadLocal.get();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423
Romain Guy65b345f2011-07-27 18:51:50 -07001424 public static String currentPackageName() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001425 ActivityThread am = currentActivityThread();
1426 return (am != null && am.mBoundApplication != null)
1427 ? am.mBoundApplication.processName : null;
1428 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429
Romain Guy65b345f2011-07-27 18:51:50 -07001430 public static Application currentApplication() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001431 ActivityThread am = currentActivityThread();
1432 return am != null ? am.mInitialApplication : null;
1433 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001435 public static IPackageManager getPackageManager() {
1436 if (sPackageManager != null) {
1437 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1438 return sPackageManager;
1439 }
1440 IBinder b = ServiceManager.getService("package");
1441 //Slog.v("PackageManager", "default service binder = " + b);
1442 sPackageManager = IPackageManager.Stub.asInterface(b);
1443 //Slog.v("PackageManager", "default service = " + sPackageManager);
1444 return sPackageManager;
1445 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001447 DisplayMetrics getDisplayMetricsLocked(CompatibilityInfo ci, boolean forceUpdate) {
1448 DisplayMetrics dm = mDisplayMetrics.get(ci);
1449 if (dm != null && !forceUpdate) {
1450 return dm;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001451 }
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001452 if (dm == null) {
1453 dm = new DisplayMetrics();
1454 mDisplayMetrics.put(ci, dm);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001455 }
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001456 Display d = WindowManagerImpl.getDefault(ci).getDefaultDisplay();
1457 d.getMetrics(dm);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001458 //Slog.i("foo", "New metrics: w=" + metrics.widthPixels + " h="
1459 // + metrics.heightPixels + " den=" + metrics.density
1460 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001461 return dm;
1462 }
1463
Romain Guy65b345f2011-07-27 18:51:50 -07001464 private Configuration mMainThreadConfig = new Configuration();
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001465 Configuration applyConfigCompatMainThread(Configuration config, CompatibilityInfo compat) {
1466 if (config == null) {
1467 return null;
1468 }
1469 if (compat != null && !compat.supportsScreen()) {
1470 mMainThreadConfig.setTo(config);
1471 config = mMainThreadConfig;
1472 compat.applyToConfiguration(config);
1473 }
1474 return config;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001477 /**
1478 * Creates the top level Resources for applications with the given compatibility info.
1479 *
1480 * @param resDir the resource directory.
1481 * @param compInfo the compability info. It will use the default compatibility info when it's
1482 * null.
1483 */
1484 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
1485 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
1486 Resources r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001488 // Resources is app scale dependent.
1489 if (false) {
1490 Slog.w(TAG, "getTopLevelResources: " + resDir + " / "
1491 + compInfo.applicationScale);
1492 }
1493 WeakReference<Resources> wr = mActiveResources.get(key);
1494 r = wr != null ? wr.get() : null;
1495 //if (r != null) Slog.i(TAG, "isUpToDate " + resDir + ": " + r.getAssets().isUpToDate());
1496 if (r != null && r.getAssets().isUpToDate()) {
1497 if (false) {
1498 Slog.w(TAG, "Returning cached resources " + r + " " + resDir
1499 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
1500 }
1501 return r;
1502 }
1503 }
1504
1505 //if (r != null) {
1506 // Slog.w(TAG, "Throwing away out-of-date resources!!!! "
1507 // + r + " " + resDir);
1508 //}
1509
1510 AssetManager assets = new AssetManager();
1511 if (assets.addAssetPath(resDir) == 0) {
1512 return null;
1513 }
1514
1515 //Slog.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
Dianne Hackborn836e2622011-10-04 18:32:39 -07001516 DisplayMetrics metrics = getDisplayMetricsLocked(null, false);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001517 r = new Resources(assets, metrics, getConfiguration(), compInfo);
1518 if (false) {
1519 Slog.i(TAG, "Created app resources " + resDir + " " + r + ": "
1520 + r.getConfiguration() + " appScale="
1521 + r.getCompatibilityInfo().applicationScale);
1522 }
1523
1524 synchronized (mPackages) {
1525 WeakReference<Resources> wr = mActiveResources.get(key);
1526 Resources existing = wr != null ? wr.get() : null;
1527 if (existing != null && existing.getAssets().isUpToDate()) {
1528 // Someone else already created the resources while we were
1529 // unlocked; go ahead and use theirs.
1530 r.getAssets().close();
1531 return existing;
1532 }
1533
1534 // XXX need to remove entries when weak references go away
1535 mActiveResources.put(key, new WeakReference<Resources>(r));
1536 return r;
1537 }
1538 }
1539
1540 /**
1541 * Creates the top level resources for the given package.
1542 */
1543 Resources getTopLevelResources(String resDir, LoadedApk pkgInfo) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001544 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo.get());
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001545 }
1546
1547 final Handler getHandler() {
1548 return mH;
1549 }
1550
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001551 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
1552 int flags) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001553 synchronized (mPackages) {
1554 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
1556 ref = mPackages.get(packageName);
1557 } else {
1558 ref = mResourcePackages.get(packageName);
1559 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001560 LoadedApk packageInfo = ref != null ? ref.get() : null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001561 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001562 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
1563 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 if (packageInfo != null && (packageInfo.mResources == null
1565 || packageInfo.mResources.getAssets().isUpToDate())) {
1566 if (packageInfo.isSecurityViolation()
1567 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
1568 throw new SecurityException(
1569 "Requesting code from " + packageName
1570 + " to be run in process "
1571 + mBoundApplication.processName
1572 + "/" + mBoundApplication.appInfo.uid);
1573 }
1574 return packageInfo;
1575 }
1576 }
1577
1578 ApplicationInfo ai = null;
1579 try {
1580 ai = getPackageManager().getApplicationInfo(packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07001581 PackageManager.GET_SHARED_LIBRARY_FILES, UserId.myUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 } catch (RemoteException e) {
Romain Guy65b345f2011-07-27 18:51:50 -07001583 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 }
1585
1586 if (ai != null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001587 return getPackageInfo(ai, compatInfo, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 }
1589
1590 return null;
1591 }
1592
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001593 public final LoadedApk getPackageInfo(ApplicationInfo ai, CompatibilityInfo compatInfo,
1594 int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
1596 boolean securityViolation = includeCode && ai.uid != 0
1597 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
Amith Yamasani742a6712011-05-04 14:49:28 -07001598 ? !UserId.isSameApp(ai.uid, mBoundApplication.appInfo.uid)
1599 : true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 if ((flags&(Context.CONTEXT_INCLUDE_CODE
1601 |Context.CONTEXT_IGNORE_SECURITY))
1602 == Context.CONTEXT_INCLUDE_CODE) {
1603 if (securityViolation) {
1604 String msg = "Requesting code from " + ai.packageName
1605 + " (with uid " + ai.uid + ")";
1606 if (mBoundApplication != null) {
1607 msg = msg + " to be run in process "
1608 + mBoundApplication.processName + " (with uid "
1609 + mBoundApplication.appInfo.uid + ")";
1610 }
1611 throw new SecurityException(msg);
1612 }
1613 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001614 return getPackageInfo(ai, compatInfo, null, securityViolation, includeCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 }
1616
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001617 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai,
1618 CompatibilityInfo compatInfo) {
1619 return getPackageInfo(ai, compatInfo, null, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 }
1621
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001622 public final LoadedApk peekPackageInfo(String packageName, boolean includeCode) {
1623 synchronized (mPackages) {
1624 WeakReference<LoadedApk> ref;
1625 if (includeCode) {
1626 ref = mPackages.get(packageName);
1627 } else {
1628 ref = mResourcePackages.get(packageName);
1629 }
1630 return ref != null ? ref.get() : null;
1631 }
1632 }
1633
Romain Guy65b345f2011-07-27 18:51:50 -07001634 private LoadedApk getPackageInfo(ApplicationInfo aInfo, CompatibilityInfo compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
1636 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001637 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 if (includeCode) {
1639 ref = mPackages.get(aInfo.packageName);
1640 } else {
1641 ref = mResourcePackages.get(aInfo.packageName);
1642 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001643 LoadedApk packageInfo = ref != null ? ref.get() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 if (packageInfo == null || (packageInfo.mResources != null
1645 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001646 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 : "Loading resource-only package ") + aInfo.packageName
1648 + " (in " + (mBoundApplication != null
1649 ? mBoundApplication.processName : null)
1650 + ")");
1651 packageInfo =
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001652 new LoadedApk(this, aInfo, compatInfo, this, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 securityViolation, includeCode &&
1654 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
1655 if (includeCode) {
1656 mPackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001657 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 } else {
1659 mResourcePackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001660 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 }
1662 }
1663 return packageInfo;
1664 }
1665 }
1666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 ActivityThread() {
1668 }
1669
1670 public ApplicationThread getApplicationThread()
1671 {
1672 return mAppThread;
1673 }
1674
1675 public Instrumentation getInstrumentation()
1676 {
1677 return mInstrumentation;
1678 }
1679
1680 public Configuration getConfiguration() {
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001681 return mResConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 }
1683
1684 public boolean isProfiling() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001685 return mProfiler != null && mProfiler.profileFile != null
1686 && mProfiler.profileFd == null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 }
1688
1689 public String getProfileFilePath() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001690 return mProfiler.profileFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 }
1692
1693 public Looper getLooper() {
1694 return mLooper;
1695 }
1696
1697 public Application getApplication() {
1698 return mInitialApplication;
1699 }
Bob Leee5408332009-09-04 18:31:17 -07001700
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07001701 public String getProcessName() {
1702 return mBoundApplication.processName;
1703 }
Bob Leee5408332009-09-04 18:31:17 -07001704
Dianne Hackborn21556372010-02-04 16:34:40 -08001705 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 synchronized (this) {
1707 if (mSystemContext == null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001708 ContextImpl context =
1709 ContextImpl.createSystemContext(this);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001710 LoadedApk info = new LoadedApk(this, "android", context, null,
1711 CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 context.init(info, null, this);
1713 context.getResources().updateConfiguration(
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001714 getConfiguration(), getDisplayMetricsLocked(
1715 CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO, false));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 mSystemContext = context;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001717 //Slog.i(TAG, "Created system resources " + context.getResources()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 // + ": " + context.getResources().getConfiguration());
1719 }
1720 }
1721 return mSystemContext;
1722 }
1723
Mike Cleron432b7132009-09-24 15:28:29 -07001724 public void installSystemApplicationInfo(ApplicationInfo info) {
1725 synchronized (this) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001726 ContextImpl context = getSystemContext();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001727 context.init(new LoadedApk(this, "android", context, info,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001728 CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO), null, this);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001729
1730 // give ourselves a default profiler
1731 mProfiler = new Profiler();
Mike Cleron432b7132009-09-24 15:28:29 -07001732 }
1733 }
1734
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001735 void ensureJitEnabled() {
1736 if (!mJitEnabled) {
1737 mJitEnabled = true;
1738 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
1739 }
1740 }
1741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 void scheduleGcIdler() {
1743 if (!mGcIdlerScheduled) {
1744 mGcIdlerScheduled = true;
1745 Looper.myQueue().addIdleHandler(mGcIdler);
1746 }
1747 mH.removeMessages(H.GC_WHEN_IDLE);
1748 }
1749
1750 void unscheduleGcIdler() {
1751 if (mGcIdlerScheduled) {
1752 mGcIdlerScheduled = false;
1753 Looper.myQueue().removeIdleHandler(mGcIdler);
1754 }
1755 mH.removeMessages(H.GC_WHEN_IDLE);
1756 }
1757
1758 void doGcIfNeeded() {
1759 mGcIdlerScheduled = false;
1760 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001761 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 // + "m now=" + now);
1763 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001764 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 BinderInternal.forceGc("bg");
1766 }
1767 }
1768
Jeff Hamilton52d32032011-01-08 15:31:26 -06001769 public void registerOnActivityPausedListener(Activity activity,
1770 OnActivityPausedListener listener) {
1771 synchronized (mOnPauseListeners) {
1772 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
1773 if (list == null) {
1774 list = new ArrayList<OnActivityPausedListener>();
1775 mOnPauseListeners.put(activity, list);
1776 }
1777 list.add(listener);
1778 }
1779 }
1780
Jeff Hamiltonce3224c2011-01-17 11:05:03 -08001781 public void unregisterOnActivityPausedListener(Activity activity,
1782 OnActivityPausedListener listener) {
1783 synchronized (mOnPauseListeners) {
1784 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
1785 if (list != null) {
1786 list.remove(listener);
1787 }
1788 }
1789 }
1790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 public final ActivityInfo resolveActivityInfo(Intent intent) {
1792 ActivityInfo aInfo = intent.resolveActivityInfo(
1793 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
1794 if (aInfo == null) {
1795 // Throw an exception.
1796 Instrumentation.checkStartActivityResult(
Dianne Hackborna4972e92012-03-14 10:38:05 -07001797 ActivityManager.START_CLASS_NOT_FOUND, intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 }
1799 return aInfo;
1800 }
Bob Leee5408332009-09-04 18:31:17 -07001801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001804 Activity.NonConfigurationInstances lastNonConfigurationInstances) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001805 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001807 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 r.intent = intent;
1809 r.state = state;
1810 r.parent = parent;
1811 r.embeddedID = id;
1812 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001813 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 if (localLOGV) {
1815 ComponentName compname = intent.getComponent();
1816 String name;
1817 if (compname != null) {
1818 name = compname.toShortString();
1819 } else {
1820 name = "(Intent " + intent + ").getComponent() returned null";
1821 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001822 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 + ", comp=" + name
1824 + ", token=" + token);
1825 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07001826 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 }
1828
1829 public final Activity getActivity(IBinder token) {
1830 return mActivities.get(token).activity;
1831 }
1832
1833 public final void sendActivityResult(
1834 IBinder token, String id, int requestCode,
1835 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001836 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07001837 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
1839 list.add(new ResultInfo(id, requestCode, resultCode, data));
1840 mAppThread.scheduleSendResult(token, list);
1841 }
1842
1843 // if the thread hasn't started yet, we don't have the handler, so just
1844 // save the messages until we're ready.
Romain Guy65b345f2011-07-27 18:51:50 -07001845 private void queueOrSendMessage(int what, Object obj) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 queueOrSendMessage(what, obj, 0, 0);
1847 }
1848
Romain Guy65b345f2011-07-27 18:51:50 -07001849 private void queueOrSendMessage(int what, Object obj, int arg1) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 queueOrSendMessage(what, obj, arg1, 0);
1851 }
1852
Romain Guy65b345f2011-07-27 18:51:50 -07001853 private void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 synchronized (this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001855 if (DEBUG_MESSAGES) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
1857 + ": " + arg1 + " / " + obj);
1858 Message msg = Message.obtain();
1859 msg.what = what;
1860 msg.obj = obj;
1861 msg.arg1 = arg1;
1862 msg.arg2 = arg2;
1863 mH.sendMessage(msg);
1864 }
1865 }
1866
Dianne Hackborn21556372010-02-04 16:34:40 -08001867 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001868 String what) {
1869 ContextCleanupInfo cci = new ContextCleanupInfo();
1870 cci.context = context;
1871 cci.who = who;
1872 cci.what = what;
1873 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
1874 }
1875
Romain Guy65b345f2011-07-27 18:51:50 -07001876 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
1878
1879 ActivityInfo aInfo = r.activityInfo;
1880 if (r.packageInfo == null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001881 r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882 Context.CONTEXT_INCLUDE_CODE);
1883 }
Bob Leee5408332009-09-04 18:31:17 -07001884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 ComponentName component = r.intent.getComponent();
1886 if (component == null) {
1887 component = r.intent.resolveActivity(
1888 mInitialApplication.getPackageManager());
1889 r.intent.setComponent(component);
1890 }
1891
1892 if (r.activityInfo.targetActivity != null) {
1893 component = new ComponentName(r.activityInfo.packageName,
1894 r.activityInfo.targetActivity);
1895 }
1896
1897 Activity activity = null;
1898 try {
1899 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
1900 activity = mInstrumentation.newActivity(
1901 cl, component.getClassName(), r.intent);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08001902 StrictMode.incrementExpectedActivityCount(activity.getClass());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001903 r.intent.setExtrasClassLoader(cl);
1904 if (r.state != null) {
1905 r.state.setClassLoader(cl);
1906 }
1907 } catch (Exception e) {
1908 if (!mInstrumentation.onException(activity, e)) {
1909 throw new RuntimeException(
1910 "Unable to instantiate activity " + component
1911 + ": " + e.toString(), e);
1912 }
1913 }
1914
1915 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001916 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001917
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001918 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
1919 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 TAG, r + ": app=" + app
1921 + ", appName=" + app.getPackageName()
1922 + ", pkg=" + r.packageInfo.getPackageName()
1923 + ", comp=" + r.intent.getComponent().toShortString()
1924 + ", dir=" + r.packageInfo.getAppDir());
1925
1926 if (activity != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001927 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 appContext.init(r.packageInfo, r.token, this);
1929 appContext.setOuterContext(activity);
1930 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001931 Configuration config = new Configuration(mCompatConfiguration);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001932 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07001933 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001934 activity.attach(appContext, this, getInstrumentation(), r.token,
1935 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001936 r.embeddedID, r.lastNonConfigurationInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07001937
Christopher Tateb70f3df2009-04-07 16:07:59 -07001938 if (customIntent != null) {
1939 activity.mIntent = customIntent;
1940 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001941 r.lastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 activity.mStartedActivity = false;
1943 int theme = r.activityInfo.getThemeResource();
1944 if (theme != 0) {
1945 activity.setTheme(theme);
1946 }
1947
1948 activity.mCalled = false;
1949 mInstrumentation.callActivityOnCreate(activity, r.state);
1950 if (!activity.mCalled) {
1951 throw new SuperNotCalledException(
1952 "Activity " + r.intent.getComponent().toShortString() +
1953 " did not call through to super.onCreate()");
1954 }
1955 r.activity = activity;
1956 r.stopped = true;
1957 if (!r.activity.mFinished) {
1958 activity.performStart();
1959 r.stopped = false;
1960 }
1961 if (!r.activity.mFinished) {
1962 if (r.state != null) {
1963 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
1964 }
1965 }
1966 if (!r.activity.mFinished) {
1967 activity.mCalled = false;
1968 mInstrumentation.callActivityOnPostCreate(activity, r.state);
1969 if (!activity.mCalled) {
1970 throw new SuperNotCalledException(
1971 "Activity " + r.intent.getComponent().toShortString() +
1972 " did not call through to super.onPostCreate()");
1973 }
1974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001975 }
1976 r.paused = true;
1977
1978 mActivities.put(r.token, r);
1979
1980 } catch (SuperNotCalledException e) {
1981 throw e;
1982
1983 } catch (Exception e) {
1984 if (!mInstrumentation.onException(activity, e)) {
1985 throw new RuntimeException(
1986 "Unable to start activity " + component
1987 + ": " + e.toString(), e);
1988 }
1989 }
1990
1991 return activity;
1992 }
1993
Romain Guy65b345f2011-07-27 18:51:50 -07001994 private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001995 // If we are getting ready to gc after going to the background, well
1996 // we are back active so skip it.
1997 unscheduleGcIdler();
1998
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001999 if (r.profileFd != null) {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002000 mProfiler.setProfiler(r.profileFile, r.profileFd);
2001 mProfiler.startProfiling();
2002 mProfiler.autoStopProfiler = r.autoStopProfiler;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002003 }
2004
Dianne Hackborn58f42a52011-10-10 13:46:34 -07002005 // Make sure we are running with the most recent config.
2006 handleConfigurationChanged(null, null);
2007
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002008 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07002010 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011
2012 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002013 r.createdConfig = new Configuration(mConfiguration);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08002014 Bundle oldState = r.state;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002015 handleResumeActivity(r.token, false, r.isForward);
2016
2017 if (!r.activity.mFinished && r.startsNotResumed) {
2018 // The activity manager actually wants this one to start out
2019 // paused, because it needs to be visible but isn't in the
2020 // foreground. We accomplish this by going through the
2021 // normal startup (because activities expect to go through
2022 // onResume() the first time they run, before their window
2023 // is displayed), and then pausing it. However, in this case
2024 // we do -not- need to do the full pause cycle (of freezing
2025 // and such) because the activity manager assumes it can just
2026 // retain the current state it has.
2027 try {
2028 r.activity.mCalled = false;
2029 mInstrumentation.callActivityOnPause(r.activity);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08002030 // We need to keep around the original state, in case
2031 // we need to be created again.
2032 r.state = oldState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 if (!r.activity.mCalled) {
2034 throw new SuperNotCalledException(
2035 "Activity " + r.intent.getComponent().toShortString() +
2036 " did not call through to super.onPause()");
2037 }
2038
2039 } catch (SuperNotCalledException e) {
2040 throw e;
2041
2042 } catch (Exception e) {
2043 if (!mInstrumentation.onException(r.activity, e)) {
2044 throw new RuntimeException(
2045 "Unable to pause activity "
2046 + r.intent.getComponent().toShortString()
2047 + ": " + e.toString(), e);
2048 }
2049 }
2050 r.paused = true;
2051 }
2052 } else {
2053 // If there was an error, for any reason, tell the activity
2054 // manager to stop us.
2055 try {
2056 ActivityManagerNative.getDefault()
2057 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
2058 } catch (RemoteException ex) {
Romain Guy65b345f2011-07-27 18:51:50 -07002059 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 }
2061 }
2062 }
2063
Romain Guy65b345f2011-07-27 18:51:50 -07002064 private void deliverNewIntents(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 List<Intent> intents) {
2066 final int N = intents.size();
2067 for (int i=0; i<N; i++) {
2068 Intent intent = intents.get(i);
2069 intent.setExtrasClassLoader(r.activity.getClassLoader());
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002070 r.activity.mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
2072 }
2073 }
2074
2075 public final void performNewIntents(IBinder token,
2076 List<Intent> intents) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002077 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002078 if (r != null) {
2079 final boolean resumed = !r.paused;
2080 if (resumed) {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002081 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002082 mInstrumentation.callActivityOnPause(r.activity);
2083 }
2084 deliverNewIntents(r, intents);
2085 if (resumed) {
Dianne Hackbornb46ed762011-06-02 18:33:15 -07002086 r.activity.performResume();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002087 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 }
2089 }
2090 }
Bob Leee5408332009-09-04 18:31:17 -07002091
Romain Guy65b345f2011-07-27 18:51:50 -07002092 private void handleNewIntent(NewIntentData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 performNewIntents(data.token, data.intents);
2094 }
2095
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002096 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
2097
2098 /**
2099 * Return the Intent that's currently being handled by a
2100 * BroadcastReceiver on this thread, or null if none.
2101 * @hide
2102 */
2103 public static Intent getIntentBeingBroadcast() {
2104 return sCurrentBroadcastIntent.get();
2105 }
2106
Romain Guy65b345f2011-07-27 18:51:50 -07002107 private void handleReceiver(ReceiverData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002108 // If we are getting ready to gc after going to the background, well
2109 // we are back active so skip it.
2110 unscheduleGcIdler();
2111
2112 String component = data.intent.getComponent().getClassName();
2113
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002114 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002115 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002116
2117 IActivityManager mgr = ActivityManagerNative.getDefault();
2118
Romain Guy65b345f2011-07-27 18:51:50 -07002119 BroadcastReceiver receiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 try {
2121 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2122 data.intent.setExtrasClassLoader(cl);
Dianne Hackborne829fef2010-10-26 17:44:01 -07002123 data.setExtrasClassLoader(cl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
2125 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07002126 if (DEBUG_BROADCAST) Slog.i(TAG,
2127 "Finishing failed broadcast to " + data.intent.getComponent());
2128 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002129 throw new RuntimeException(
2130 "Unable to instantiate receiver " + component
2131 + ": " + e.toString(), e);
2132 }
2133
2134 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08002135 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07002136
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002137 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002138 TAG, "Performing receive of " + data.intent
2139 + ": app=" + app
2140 + ", appName=" + app.getPackageName()
2141 + ", pkg=" + packageInfo.getPackageName()
2142 + ", comp=" + data.intent.getComponent().toShortString()
2143 + ", dir=" + packageInfo.getAppDir());
2144
Dianne Hackborn21556372010-02-04 16:34:40 -08002145 ContextImpl context = (ContextImpl)app.getBaseContext();
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002146 sCurrentBroadcastIntent.set(data.intent);
Dianne Hackborne829fef2010-10-26 17:44:01 -07002147 receiver.setPendingResult(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002148 receiver.onReceive(context.getReceiverRestrictedContext(),
2149 data.intent);
2150 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07002151 if (DEBUG_BROADCAST) Slog.i(TAG,
2152 "Finishing failed broadcast to " + data.intent.getComponent());
2153 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 if (!mInstrumentation.onException(receiver, e)) {
2155 throw new RuntimeException(
2156 "Unable to start receiver " + component
2157 + ": " + e.toString(), e);
2158 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002159 } finally {
2160 sCurrentBroadcastIntent.set(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002161 }
2162
Dianne Hackborne829fef2010-10-26 17:44:01 -07002163 if (receiver.getPendingResult() != null) {
2164 data.finish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002165 }
2166 }
2167
Christopher Tate181fafa2009-05-14 11:12:14 -07002168 // Instantiate a BackupAgent and tell it that it's alive
Romain Guy65b345f2011-07-27 18:51:50 -07002169 private void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002170 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07002171
2172 // no longer idle; we have backup work to do
2173 unscheduleGcIdler();
2174
2175 // instantiate the BackupAgent class named in the manifest
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002176 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07002177 String packageName = packageInfo.mPackageName;
2178 if (mBackupAgents.get(packageName) != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002179 Slog.d(TAG, "BackupAgent " + " for " + packageName
Christopher Tate181fafa2009-05-14 11:12:14 -07002180 + " already exists");
2181 return;
2182 }
Bob Leee5408332009-09-04 18:31:17 -07002183
Christopher Tate181fafa2009-05-14 11:12:14 -07002184 BackupAgent agent = null;
2185 String classname = data.appInfo.backupAgentName;
Christopher Tate4a627c72011-04-01 14:43:32 -07002186
Christopher Tate79ec80d2011-06-24 14:58:49 -07002187 // full backup operation but no app-supplied agent? use the default implementation
2188 if (classname == null && (data.backupMode == IApplicationThread.BACKUP_MODE_FULL
2189 || data.backupMode == IApplicationThread.BACKUP_MODE_RESTORE_FULL)) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002190 classname = "android.app.backup.FullBackupAgent";
Christopher Tate181fafa2009-05-14 11:12:14 -07002191 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002192
Christopher Tate181fafa2009-05-14 11:12:14 -07002193 try {
Christopher Tated1475e02009-07-09 15:36:17 -07002194 IBinder binder = null;
2195 try {
Christopher Tate4a627c72011-04-01 14:43:32 -07002196 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing agent class " + classname);
2197
Christopher Tated1475e02009-07-09 15:36:17 -07002198 java.lang.ClassLoader cl = packageInfo.getClassLoader();
Christopher Tate4a627c72011-04-01 14:43:32 -07002199 agent = (BackupAgent) cl.loadClass(classname).newInstance();
Christopher Tated1475e02009-07-09 15:36:17 -07002200
2201 // set up the agent's context
Dianne Hackborn21556372010-02-04 16:34:40 -08002202 ContextImpl context = new ContextImpl();
Christopher Tated1475e02009-07-09 15:36:17 -07002203 context.init(packageInfo, null, this);
2204 context.setOuterContext(agent);
2205 agent.attach(context);
2206
2207 agent.onCreate();
2208 binder = agent.onBind();
2209 mBackupAgents.put(packageName, agent);
2210 } catch (Exception e) {
2211 // If this is during restore, fail silently; otherwise go
2212 // ahead and let the user see the crash.
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002213 Slog.e(TAG, "Agent threw during creation: " + e);
Christopher Tate75a99702011-05-18 16:28:19 -07002214 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE
2215 && data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE_FULL) {
Christopher Tated1475e02009-07-09 15:36:17 -07002216 throw e;
2217 }
2218 // falling through with 'binder' still null
2219 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002220
2221 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07002222 try {
2223 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
2224 } catch (RemoteException e) {
2225 // nothing to do.
2226 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002227 } catch (Exception e) {
2228 throw new RuntimeException("Unable to create BackupAgent "
Christopher Tate4a627c72011-04-01 14:43:32 -07002229 + classname + ": " + e.toString(), e);
Christopher Tate181fafa2009-05-14 11:12:14 -07002230 }
2231 }
2232
2233 // Tear down a BackupAgent
Romain Guy65b345f2011-07-27 18:51:50 -07002234 private void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002235 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07002236
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002237 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07002238 String packageName = packageInfo.mPackageName;
2239 BackupAgent agent = mBackupAgents.get(packageName);
2240 if (agent != null) {
2241 try {
2242 agent.onDestroy();
2243 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002244 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07002245 e.printStackTrace();
2246 }
2247 mBackupAgents.remove(packageName);
2248 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002249 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07002250 }
2251 }
2252
Romain Guy65b345f2011-07-27 18:51:50 -07002253 private void handleCreateService(CreateServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002254 // If we are getting ready to gc after going to the background, well
2255 // we are back active so skip it.
2256 unscheduleGcIdler();
2257
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002258 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002259 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002260 Service service = null;
2261 try {
2262 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2263 service = (Service) cl.loadClass(data.info.name).newInstance();
2264 } catch (Exception e) {
2265 if (!mInstrumentation.onException(service, e)) {
2266 throw new RuntimeException(
2267 "Unable to instantiate service " + data.info.name
2268 + ": " + e.toString(), e);
2269 }
2270 }
2271
2272 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002273 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002274
Dianne Hackborn21556372010-02-04 16:34:40 -08002275 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002276 context.init(packageInfo, null, this);
2277
Dianne Hackborn0be1f782009-11-09 12:30:12 -08002278 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279 context.setOuterContext(service);
2280 service.attach(context, this, data.info.name, data.token, app,
2281 ActivityManagerNative.getDefault());
2282 service.onCreate();
2283 mServices.put(data.token, service);
2284 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002285 ActivityManagerNative.getDefault().serviceDoneExecuting(
2286 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002287 } catch (RemoteException e) {
2288 // nothing to do.
2289 }
2290 } catch (Exception e) {
2291 if (!mInstrumentation.onException(service, e)) {
2292 throw new RuntimeException(
2293 "Unable to create service " + data.info.name
2294 + ": " + e.toString(), e);
2295 }
2296 }
2297 }
2298
Romain Guy65b345f2011-07-27 18:51:50 -07002299 private void handleBindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002300 Service s = mServices.get(data.token);
Amith Yamasani742a6712011-05-04 14:49:28 -07002301 if (DEBUG_SERVICE)
2302 Slog.v(TAG, "handleBindService s=" + s + " rebind=" + data.rebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002303 if (s != null) {
2304 try {
2305 data.intent.setExtrasClassLoader(s.getClassLoader());
2306 try {
2307 if (!data.rebind) {
2308 IBinder binder = s.onBind(data.intent);
2309 ActivityManagerNative.getDefault().publishService(
2310 data.token, data.intent, binder);
2311 } else {
2312 s.onRebind(data.intent);
2313 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002314 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002315 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002316 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 } catch (RemoteException ex) {
2318 }
2319 } catch (Exception e) {
2320 if (!mInstrumentation.onException(s, e)) {
2321 throw new RuntimeException(
2322 "Unable to bind to service " + s
2323 + " with " + data.intent + ": " + e.toString(), e);
2324 }
2325 }
2326 }
2327 }
2328
Romain Guy65b345f2011-07-27 18:51:50 -07002329 private void handleUnbindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002330 Service s = mServices.get(data.token);
2331 if (s != null) {
2332 try {
2333 data.intent.setExtrasClassLoader(s.getClassLoader());
2334 boolean doRebind = s.onUnbind(data.intent);
2335 try {
2336 if (doRebind) {
2337 ActivityManagerNative.getDefault().unbindFinished(
2338 data.token, data.intent, doRebind);
2339 } else {
2340 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002341 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002342 }
2343 } catch (RemoteException ex) {
2344 }
2345 } catch (Exception e) {
2346 if (!mInstrumentation.onException(s, e)) {
2347 throw new RuntimeException(
2348 "Unable to unbind to service " + s
2349 + " with " + data.intent + ": " + e.toString(), e);
2350 }
2351 }
2352 }
2353 }
2354
Dianne Hackborn625ac272010-09-17 18:29:22 -07002355 private void handleDumpService(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08002356 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
2357 try {
2358 Service s = mServices.get(info.token);
2359 if (s != null) {
2360 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
2361 s.dump(info.fd.getFileDescriptor(), pw, info.args);
2362 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08002364 } finally {
2365 IoUtils.closeQuietly(info.fd);
2366 StrictMode.setThreadPolicy(oldPolicy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367 }
2368 }
2369
Dianne Hackborn625ac272010-09-17 18:29:22 -07002370 private void handleDumpActivity(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08002371 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
2372 try {
2373 ActivityClientRecord r = mActivities.get(info.token);
2374 if (r != null && r.activity != null) {
2375 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
2376 r.activity.dump(info.prefix, info.fd.getFileDescriptor(), pw, info.args);
2377 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07002378 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08002379 } finally {
2380 IoUtils.closeQuietly(info.fd);
2381 StrictMode.setThreadPolicy(oldPolicy);
Dianne Hackborn625ac272010-09-17 18:29:22 -07002382 }
2383 }
2384
Marco Nelissen18cb2872011-11-15 11:19:53 -08002385 private void handleDumpProvider(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08002386 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
2387 try {
2388 ProviderClientRecord r = mLocalProviders.get(info.token);
2389 if (r != null && r.mLocalProvider != null) {
2390 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
2391 r.mLocalProvider.dump(info.fd.getFileDescriptor(), pw, info.args);
2392 pw.flush();
Marco Nelissen18cb2872011-11-15 11:19:53 -08002393 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08002394 } finally {
2395 IoUtils.closeQuietly(info.fd);
2396 StrictMode.setThreadPolicy(oldPolicy);
Marco Nelissen18cb2872011-11-15 11:19:53 -08002397 }
2398 }
2399
Romain Guy65b345f2011-07-27 18:51:50 -07002400 private void handleServiceArgs(ServiceArgsData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401 Service s = mServices.get(data.token);
2402 if (s != null) {
2403 try {
2404 if (data.args != null) {
2405 data.args.setExtrasClassLoader(s.getClassLoader());
2406 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002407 int res;
2408 if (!data.taskRemoved) {
2409 res = s.onStartCommand(data.args, data.flags, data.startId);
2410 } else {
2411 s.onTaskRemoved(data.args);
2412 res = Service.START_TASK_REMOVED_COMPLETE;
2413 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002414
2415 QueuedWork.waitToFinish();
2416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002417 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002418 ActivityManagerNative.getDefault().serviceDoneExecuting(
2419 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002420 } catch (RemoteException e) {
2421 // nothing to do.
2422 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002423 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002424 } catch (Exception e) {
2425 if (!mInstrumentation.onException(s, e)) {
2426 throw new RuntimeException(
2427 "Unable to start service " + s
2428 + " with " + data.args + ": " + e.toString(), e);
2429 }
2430 }
2431 }
2432 }
2433
Romain Guy65b345f2011-07-27 18:51:50 -07002434 private void handleStopService(IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435 Service s = mServices.remove(token);
2436 if (s != null) {
2437 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002438 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 s.onDestroy();
2440 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002441 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002442 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08002443 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002445
2446 QueuedWork.waitToFinish();
2447
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002448 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002449 ActivityManagerNative.getDefault().serviceDoneExecuting(
2450 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451 } catch (RemoteException e) {
2452 // nothing to do.
2453 }
2454 } catch (Exception e) {
2455 if (!mInstrumentation.onException(s, e)) {
2456 throw new RuntimeException(
2457 "Unable to stop service " + s
2458 + ": " + e.toString(), e);
2459 }
2460 }
2461 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002462 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002463 }
2464
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002465 public final ActivityClientRecord performResumeActivity(IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002466 boolean clearHide) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002467 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002468 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002469 + " finished=" + r.activity.mFinished);
2470 if (r != null && !r.activity.mFinished) {
2471 if (clearHide) {
2472 r.hideForNow = false;
2473 r.activity.mStartedActivity = false;
2474 }
2475 try {
2476 if (r.pendingIntents != null) {
2477 deliverNewIntents(r, r.pendingIntents);
2478 r.pendingIntents = null;
2479 }
2480 if (r.pendingResults != null) {
2481 deliverResults(r, r.pendingResults);
2482 r.pendingResults = null;
2483 }
2484 r.activity.performResume();
2485
Bob Leee5408332009-09-04 18:31:17 -07002486 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 r.paused = false;
2490 r.stopped = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491 r.state = null;
2492 } catch (Exception e) {
2493 if (!mInstrumentation.onException(r.activity, e)) {
2494 throw new RuntimeException(
2495 "Unable to resume activity "
2496 + r.intent.getComponent().toShortString()
2497 + ": " + e.toString(), e);
2498 }
2499 }
2500 }
2501 return r;
2502 }
2503
Romain Guya998dff2012-03-23 18:58:36 -07002504 static final void cleanUpPendingRemoveWindows(ActivityClientRecord r) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002505 if (r.mPendingRemoveWindow != null) {
2506 r.mPendingRemoveWindowManager.removeViewImmediate(r.mPendingRemoveWindow);
2507 IBinder wtoken = r.mPendingRemoveWindow.getWindowToken();
2508 if (wtoken != null) {
2509 WindowManagerImpl.getDefault().closeAll(wtoken,
2510 r.activity.getClass().getName(), "Activity");
2511 }
2512 }
2513 r.mPendingRemoveWindow = null;
2514 r.mPendingRemoveWindowManager = null;
2515 }
2516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2518 // If we are getting ready to gc after going to the background, well
2519 // we are back active so skip it.
2520 unscheduleGcIdler();
2521
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002522 ActivityClientRecord r = performResumeActivity(token, clearHide);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523
2524 if (r != null) {
2525 final Activity a = r.activity;
2526
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002527 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002528 TAG, "Resume " + r + " started activity: " +
2529 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2530 + ", finished: " + a.mFinished);
2531
2532 final int forwardBit = isForward ?
2533 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535 // If the window hasn't yet been added to the window manager,
2536 // and this guy didn't finish itself or start another activity,
2537 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002538 boolean willBeVisible = !a.mStartedActivity;
2539 if (!willBeVisible) {
2540 try {
2541 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
2542 a.getActivityToken());
2543 } catch (RemoteException e) {
2544 }
2545 }
2546 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002547 r.window = r.activity.getWindow();
2548 View decor = r.window.getDecorView();
2549 decor.setVisibility(View.INVISIBLE);
2550 ViewManager wm = a.getWindowManager();
2551 WindowManager.LayoutParams l = r.window.getAttributes();
2552 a.mDecor = decor;
2553 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2554 l.softInputMode |= forwardBit;
2555 if (a.mVisibleFromClient) {
2556 a.mWindowAdded = true;
2557 wm.addView(decor, l);
2558 }
2559
2560 // If the window has already been added, but during resume
2561 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002562 // window visible.
2563 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002564 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 TAG, "Launch " + r + " mStartedActivity set");
2566 r.hideForNow = true;
2567 }
2568
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002569 // Get rid of anything left hanging around.
2570 cleanUpPendingRemoveWindows(r);
2571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002572 // The window is now visible if it has been added, we are not
2573 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002574 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002575 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002577 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002578 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 performConfigurationChanged(r.activity, r.newConfig);
2580 r.newConfig = null;
2581 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002582 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583 + isForward);
2584 WindowManager.LayoutParams l = r.window.getAttributes();
2585 if ((l.softInputMode
2586 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2587 != forwardBit) {
2588 l.softInputMode = (l.softInputMode
2589 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2590 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002591 if (r.activity.mVisibleFromClient) {
2592 ViewManager wm = a.getWindowManager();
2593 View decor = r.window.getDecorView();
2594 wm.updateViewLayout(decor, l);
2595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 }
2597 r.activity.mVisibleFromServer = true;
2598 mNumVisibleActivities++;
2599 if (r.activity.mVisibleFromClient) {
2600 r.activity.makeVisible();
2601 }
2602 }
2603
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002604 if (!r.onlyLocalRequest) {
2605 r.nextIdle = mNewActivities;
2606 mNewActivities = r;
2607 if (localLOGV) Slog.v(
2608 TAG, "Scheduling idle handler for " + r);
2609 Looper.myQueue().addIdleHandler(new Idler());
2610 }
2611 r.onlyLocalRequest = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612
2613 } else {
2614 // If an exception was thrown when trying to resume, then
2615 // just end this activity.
2616 try {
2617 ActivityManagerNative.getDefault()
2618 .finishActivity(token, Activity.RESULT_CANCELED, null);
2619 } catch (RemoteException ex) {
2620 }
2621 }
2622 }
2623
2624 private int mThumbnailWidth = -1;
2625 private int mThumbnailHeight = -1;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002626 private Bitmap mAvailThumbnailBitmap = null;
2627 private Canvas mThumbnailCanvas = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628
Romain Guy65b345f2011-07-27 18:51:50 -07002629 private Bitmap createThumbnailBitmap(ActivityClientRecord r) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002630 Bitmap thumbnail = mAvailThumbnailBitmap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002631 try {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002632 if (thumbnail == null) {
2633 int w = mThumbnailWidth;
2634 int h;
2635 if (w < 0) {
2636 Resources res = r.activity.getResources();
2637 mThumbnailHeight = h =
2638 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002639
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002640 mThumbnailWidth = w =
2641 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
2642 } else {
2643 h = mThumbnailHeight;
2644 }
2645
2646 // On platforms where we don't want thumbnails, set dims to (0,0)
2647 if ((w > 0) && (h > 0)) {
2648 thumbnail = Bitmap.createBitmap(w, h, THUMBNAIL_FORMAT);
2649 thumbnail.eraseColor(0);
2650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 }
2652
Dianne Hackbornfb3806d2010-12-09 13:14:12 -08002653 if (thumbnail != null) {
2654 Canvas cv = mThumbnailCanvas;
2655 if (cv == null) {
2656 mThumbnailCanvas = cv = new Canvas();
2657 }
2658
2659 cv.setBitmap(thumbnail);
2660 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
2661 mAvailThumbnailBitmap = thumbnail;
2662 thumbnail = null;
2663 }
Dianne Hackborn6311d0a2011-08-02 16:37:58 -07002664 cv.setBitmap(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002665 }
Jim Miller0b2a6d02010-07-13 18:01:29 -07002666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 } catch (Exception e) {
2668 if (!mInstrumentation.onException(r.activity, e)) {
2669 throw new RuntimeException(
2670 "Unable to create thumbnail of "
2671 + r.intent.getComponent().toShortString()
2672 + ": " + e.toString(), e);
2673 }
2674 thumbnail = null;
2675 }
2676
2677 return thumbnail;
2678 }
2679
Romain Guy65b345f2011-07-27 18:51:50 -07002680 private void handlePauseActivity(IBinder token, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002681 boolean userLeaving, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002682 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002684 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002685 if (userLeaving) {
2686 performUserLeavingActivity(r);
2687 }
Bob Leee5408332009-09-04 18:31:17 -07002688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002689 r.activity.mConfigChangeFlags |= configChanges;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002690 performPauseActivity(token, finished, r.isPreHoneycomb());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002691
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07002692 // Make sure any pending writes are now committed.
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002693 if (r.isPreHoneycomb()) {
2694 QueuedWork.waitToFinish();
2695 }
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07002696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002697 // Tell the activity manager we have paused.
2698 try {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002699 ActivityManagerNative.getDefault().activityPaused(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002700 } catch (RemoteException ex) {
2701 }
2702 }
2703 }
2704
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002705 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706 mInstrumentation.callActivityOnUserLeaving(r.activity);
2707 }
2708
2709 final Bundle performPauseActivity(IBinder token, boolean finished,
2710 boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002711 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002712 return r != null ? performPauseActivity(r, finished, saveState) : null;
2713 }
2714
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002715 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 boolean saveState) {
2717 if (r.paused) {
2718 if (r.activity.mFinished) {
2719 // If we are finishing, we won't call onResume() in certain cases.
2720 // So here we likewise don't want to call onPause() if the activity
2721 // isn't resumed.
2722 return null;
2723 }
2724 RuntimeException e = new RuntimeException(
2725 "Performing pause of activity that is not resumed: "
2726 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002727 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002728 }
2729 Bundle state = null;
2730 if (finished) {
2731 r.activity.mFinished = true;
2732 }
2733 try {
2734 // Next have the activity save its current state and managed dialogs...
2735 if (!r.activity.mFinished && saveState) {
2736 state = new Bundle();
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04002737 state.setAllowFds(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002738 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2739 r.state = state;
2740 }
2741 // Now we are idle.
2742 r.activity.mCalled = false;
2743 mInstrumentation.callActivityOnPause(r.activity);
2744 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
2745 if (!r.activity.mCalled) {
2746 throw new SuperNotCalledException(
2747 "Activity " + r.intent.getComponent().toShortString() +
2748 " did not call through to super.onPause()");
2749 }
2750
2751 } catch (SuperNotCalledException e) {
2752 throw e;
2753
2754 } catch (Exception e) {
2755 if (!mInstrumentation.onException(r.activity, e)) {
2756 throw new RuntimeException(
2757 "Unable to pause activity "
2758 + r.intent.getComponent().toShortString()
2759 + ": " + e.toString(), e);
2760 }
2761 }
2762 r.paused = true;
Jeff Hamilton52d32032011-01-08 15:31:26 -06002763
2764 // Notify any outstanding on paused listeners
2765 ArrayList<OnActivityPausedListener> listeners;
2766 synchronized (mOnPauseListeners) {
2767 listeners = mOnPauseListeners.remove(r.activity);
2768 }
2769 int size = (listeners != null ? listeners.size() : 0);
2770 for (int i = 0; i < size; i++) {
2771 listeners.get(i).onPaused(r.activity);
2772 }
2773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002774 return state;
2775 }
2776
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002777 final void performStopActivity(IBinder token, boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002778 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002779 performStopActivityInner(r, null, false, saveState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002780 }
2781
2782 private static class StopInfo {
2783 Bitmap thumbnail;
2784 CharSequence description;
2785 }
2786
Jeff Brownddaa9ac2011-11-11 20:16:14 -08002787 private static final class ProviderRefCount {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002788 public int count;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08002789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002790 ProviderRefCount(int pCount) {
2791 count = pCount;
2792 }
2793 }
2794
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002795 /**
2796 * Core implementation of stopping an activity. Note this is a little
2797 * tricky because the server's meaning of stop is slightly different
2798 * than our client -- for the server, stop means to save state and give
2799 * it the result when it is done, but the window may still be visible.
2800 * For the client, we want to call onStop()/onStart() to indicate when
2801 * the activity's UI visibillity changes.
2802 */
Romain Guy65b345f2011-07-27 18:51:50 -07002803 private void performStopActivityInner(ActivityClientRecord r,
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002804 StopInfo info, boolean keepShown, boolean saveState) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002805 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002806 Bundle state = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002807 if (r != null) {
2808 if (!keepShown && r.stopped) {
2809 if (r.activity.mFinished) {
2810 // If we are finishing, we won't call onResume() in certain
2811 // cases. So here we likewise don't want to call onStop()
2812 // if the activity isn't resumed.
2813 return;
2814 }
2815 RuntimeException e = new RuntimeException(
2816 "Performing stop of activity that is not resumed: "
2817 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002818 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002819 }
2820
2821 if (info != null) {
2822 try {
2823 // First create a thumbnail for the activity...
Dianne Hackborn0500b3c2011-11-01 15:28:43 -07002824 // For now, don't create the thumbnail here; we are
2825 // doing that by doing a screen snapshot.
2826 info.thumbnail = null; //createThumbnailBitmap(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 info.description = r.activity.onCreateDescription();
2828 } catch (Exception e) {
2829 if (!mInstrumentation.onException(r.activity, e)) {
2830 throw new RuntimeException(
2831 "Unable to save state of activity "
2832 + r.intent.getComponent().toShortString()
2833 + ": " + e.toString(), e);
2834 }
2835 }
2836 }
2837
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002838 // Next have the activity save its current state and managed dialogs...
2839 if (!r.activity.mFinished && saveState) {
2840 if (r.state == null) {
2841 state = new Bundle();
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04002842 state.setAllowFds(false);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002843 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2844 r.state = state;
2845 } else {
2846 state = r.state;
2847 }
2848 }
2849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002850 if (!keepShown) {
2851 try {
2852 // Now we are idle.
2853 r.activity.performStop();
2854 } catch (Exception e) {
2855 if (!mInstrumentation.onException(r.activity, e)) {
2856 throw new RuntimeException(
2857 "Unable to stop activity "
2858 + r.intent.getComponent().toShortString()
2859 + ": " + e.toString(), e);
2860 }
2861 }
2862 r.stopped = true;
2863 }
2864
2865 r.paused = true;
2866 }
2867 }
2868
Romain Guy65b345f2011-07-27 18:51:50 -07002869 private void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 View v = r.activity.mDecor;
2871 if (v != null) {
2872 if (show) {
2873 if (!r.activity.mVisibleFromServer) {
2874 r.activity.mVisibleFromServer = true;
2875 mNumVisibleActivities++;
2876 if (r.activity.mVisibleFromClient) {
2877 r.activity.makeVisible();
2878 }
2879 }
2880 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002881 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002882 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883 performConfigurationChanged(r.activity, r.newConfig);
2884 r.newConfig = null;
2885 }
2886 } else {
2887 if (r.activity.mVisibleFromServer) {
2888 r.activity.mVisibleFromServer = false;
2889 mNumVisibleActivities--;
2890 v.setVisibility(View.INVISIBLE);
2891 }
2892 }
2893 }
2894 }
2895
Romain Guy65b345f2011-07-27 18:51:50 -07002896 private void handleStopActivity(IBinder token, boolean show, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002897 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002898 r.activity.mConfigChangeFlags |= configChanges;
2899
2900 StopInfo info = new StopInfo();
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002901 performStopActivityInner(r, info, show, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002903 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002904 TAG, "Finishing stop of " + r + ": show=" + show
2905 + " win=" + r.window);
2906
2907 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07002908
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002909 // Make sure any pending writes are now committed.
2910 if (!r.isPreHoneycomb()) {
2911 QueuedWork.waitToFinish();
2912 }
2913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002914 // Tell activity manager we have been stopped.
2915 try {
2916 ActivityManagerNative.getDefault().activityStopped(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002917 r.token, r.state, info.thumbnail, info.description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002918 } catch (RemoteException ex) {
2919 }
2920 }
2921
2922 final void performRestartActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002923 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002924 if (r.stopped) {
2925 r.activity.performRestart();
2926 r.stopped = false;
2927 }
2928 }
2929
Romain Guy65b345f2011-07-27 18:51:50 -07002930 private void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002931 ActivityClientRecord r = mActivities.get(token);
Dianne Hackbornbfddc0f2010-12-14 11:28:01 -08002932
2933 if (r == null) {
2934 Log.w(TAG, "handleWindowVisibility: no activity for token " + token);
2935 return;
2936 }
2937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002938 if (!show && !r.stopped) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002939 performStopActivityInner(r, null, show, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 } else if (show && r.stopped) {
2941 // If we are getting ready to gc after going to the background, well
2942 // we are back active so skip it.
2943 unscheduleGcIdler();
2944
2945 r.activity.performRestart();
2946 r.stopped = false;
2947 }
2948 if (r.activity.mDecor != null) {
Joe Onorato43a17652011-04-06 19:22:23 -07002949 if (false) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 TAG, "Handle window " + r + " visibility: " + show);
2951 updateVisibility(r, show);
2952 }
2953 }
2954
Romain Guy65b345f2011-07-27 18:51:50 -07002955 private void handleSleeping(IBinder token, boolean sleeping) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002956 ActivityClientRecord r = mActivities.get(token);
2957
2958 if (r == null) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08002959 Log.w(TAG, "handleSleeping: no activity for token " + token);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002960 return;
2961 }
2962
2963 if (sleeping) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08002964 if (!r.stopped && !r.isPreHoneycomb()) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002965 try {
2966 // Now we are idle.
2967 r.activity.performStop();
2968 } catch (Exception e) {
2969 if (!mInstrumentation.onException(r.activity, e)) {
2970 throw new RuntimeException(
2971 "Unable to stop activity "
2972 + r.intent.getComponent().toShortString()
2973 + ": " + e.toString(), e);
2974 }
2975 }
2976 r.stopped = true;
2977 }
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002978
2979 // Make sure any pending writes are now committed.
2980 if (!r.isPreHoneycomb()) {
2981 QueuedWork.waitToFinish();
2982 }
2983
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002984 // Tell activity manager we slept.
2985 try {
2986 ActivityManagerNative.getDefault().activitySlept(r.token);
2987 } catch (RemoteException ex) {
2988 }
2989 } else {
2990 if (r.stopped && r.activity.mVisibleFromServer) {
2991 r.activity.performRestart();
2992 r.stopped = false;
2993 }
2994 }
2995 }
2996
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08002997 private void handleSetCoreSettings(Bundle coreSettings) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08002998 synchronized (mPackages) {
2999 mCoreSettings = coreSettings;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003000 }
3001 }
3002
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003003 private void handleUpdatePackageCompatibilityInfo(UpdateCompatibilityData data) {
3004 LoadedApk apk = peekPackageInfo(data.pkg, false);
3005 if (apk != null) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003006 apk.mCompatibilityInfo.set(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003007 }
3008 apk = peekPackageInfo(data.pkg, true);
3009 if (apk != null) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003010 apk.mCompatibilityInfo.set(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003011 }
3012 handleConfigurationChanged(mConfiguration, data.info);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003013 WindowManagerImpl.getDefault().reportNewConfiguration(mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003014 }
3015
Romain Guy65b345f2011-07-27 18:51:50 -07003016 private void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017 final int N = results.size();
3018 for (int i=0; i<N; i++) {
3019 ResultInfo ri = results.get(i);
3020 try {
3021 if (ri.mData != null) {
3022 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
3023 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003024 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07003025 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003026 r.activity.dispatchActivityResult(ri.mResultWho,
3027 ri.mRequestCode, ri.mResultCode, ri.mData);
3028 } catch (Exception e) {
3029 if (!mInstrumentation.onException(r.activity, e)) {
3030 throw new RuntimeException(
3031 "Failure delivering result " + ri + " to activity "
3032 + r.intent.getComponent().toShortString()
3033 + ": " + e.toString(), e);
3034 }
3035 }
3036 }
3037 }
3038
Romain Guy65b345f2011-07-27 18:51:50 -07003039 private void handleSendResult(ResultData res) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003040 ActivityClientRecord r = mActivities.get(res.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003041 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003042 if (r != null) {
3043 final boolean resumed = !r.paused;
3044 if (!r.activity.mFinished && r.activity.mDecor != null
3045 && r.hideForNow && resumed) {
3046 // We had hidden the activity because it started another
3047 // one... we have gotten a result back and we are not
3048 // paused, so make sure our window is visible.
3049 updateVisibility(r, true);
3050 }
3051 if (resumed) {
3052 try {
3053 // Now we are idle.
3054 r.activity.mCalled = false;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07003055 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003056 mInstrumentation.callActivityOnPause(r.activity);
3057 if (!r.activity.mCalled) {
3058 throw new SuperNotCalledException(
3059 "Activity " + r.intent.getComponent().toShortString()
3060 + " did not call through to super.onPause()");
3061 }
3062 } catch (SuperNotCalledException e) {
3063 throw e;
3064 } catch (Exception e) {
3065 if (!mInstrumentation.onException(r.activity, e)) {
3066 throw new RuntimeException(
3067 "Unable to pause activity "
3068 + r.intent.getComponent().toShortString()
3069 + ": " + e.toString(), e);
3070 }
3071 }
3072 }
3073 deliverResults(r, res.results);
3074 if (resumed) {
Dianne Hackbornb46ed762011-06-02 18:33:15 -07003075 r.activity.performResume();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07003076 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003077 }
3078 }
3079 }
3080
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003081 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003082 return performDestroyActivity(token, finishing, 0, false);
3083 }
3084
Romain Guy65b345f2011-07-27 18:51:50 -07003085 private ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003086 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003087 ActivityClientRecord r = mActivities.get(token);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003088 Class activityClass = null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003089 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003090 if (r != null) {
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003091 activityClass = r.activity.getClass();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003092 r.activity.mConfigChangeFlags |= configChanges;
3093 if (finishing) {
3094 r.activity.mFinished = true;
3095 }
3096 if (!r.paused) {
3097 try {
3098 r.activity.mCalled = false;
3099 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07003100 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003101 r.activity.getComponentName().getClassName());
3102 if (!r.activity.mCalled) {
3103 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003104 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003105 + " did not call through to super.onPause()");
3106 }
3107 } catch (SuperNotCalledException e) {
3108 throw e;
3109 } catch (Exception e) {
3110 if (!mInstrumentation.onException(r.activity, e)) {
3111 throw new RuntimeException(
3112 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003113 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003114 + ": " + e.toString(), e);
3115 }
3116 }
3117 r.paused = true;
3118 }
3119 if (!r.stopped) {
3120 try {
3121 r.activity.performStop();
3122 } catch (SuperNotCalledException e) {
3123 throw e;
3124 } catch (Exception e) {
3125 if (!mInstrumentation.onException(r.activity, e)) {
3126 throw new RuntimeException(
3127 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003128 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003129 + ": " + e.toString(), e);
3130 }
3131 }
3132 r.stopped = true;
3133 }
3134 if (getNonConfigInstance) {
3135 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003136 r.lastNonConfigurationInstances
3137 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003138 } catch (Exception e) {
3139 if (!mInstrumentation.onException(r.activity, e)) {
3140 throw new RuntimeException(
3141 "Unable to retain activity "
3142 + r.intent.getComponent().toShortString()
3143 + ": " + e.toString(), e);
3144 }
3145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003146 }
3147 try {
3148 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07003149 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003150 if (!r.activity.mCalled) {
3151 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003152 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003153 " did not call through to super.onDestroy()");
3154 }
3155 if (r.window != null) {
3156 r.window.closeAllPanels();
3157 }
3158 } catch (SuperNotCalledException e) {
3159 throw e;
3160 } catch (Exception e) {
3161 if (!mInstrumentation.onException(r.activity, e)) {
3162 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003163 "Unable to destroy activity " + safeToComponentShortString(r.intent)
3164 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003165 }
3166 }
3167 }
3168 mActivities.remove(token);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003169 StrictMode.decrementExpectedActivityCount(activityClass);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003170 return r;
3171 }
3172
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003173 private static String safeToComponentShortString(Intent intent) {
3174 ComponentName component = intent.getComponent();
3175 return component == null ? "[Unknown]" : component.toShortString();
3176 }
3177
Romain Guy65b345f2011-07-27 18:51:50 -07003178 private void handleDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003179 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003180 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003181 configChanges, getNonConfigInstance);
3182 if (r != null) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003183 cleanUpPendingRemoveWindows(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003184 WindowManager wm = r.activity.getWindowManager();
3185 View v = r.activity.mDecor;
3186 if (v != null) {
3187 if (r.activity.mVisibleFromServer) {
3188 mNumVisibleActivities--;
3189 }
3190 IBinder wtoken = v.getWindowToken();
3191 if (r.activity.mWindowAdded) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003192 if (r.onlyLocalRequest) {
3193 // Hold off on removing this until the new activity's
3194 // window is being added.
3195 r.mPendingRemoveWindow = v;
3196 r.mPendingRemoveWindowManager = wm;
3197 } else {
3198 wm.removeViewImmediate(v);
3199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003200 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003201 if (wtoken != null && r.mPendingRemoveWindow == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003202 WindowManagerImpl.getDefault().closeAll(wtoken,
3203 r.activity.getClass().getName(), "Activity");
3204 }
3205 r.activity.mDecor = null;
3206 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003207 if (r.mPendingRemoveWindow == null) {
3208 // If we are delaying the removal of the activity window, then
3209 // we can't clean up all windows here. Note that we can't do
3210 // so later either, which means any windows that aren't closed
3211 // by the app will leak. Well we try to warning them a lot
3212 // about leaking windows, because that is a bug, so if they are
3213 // using this recreate facility then they get to live with leaks.
3214 WindowManagerImpl.getDefault().closeAll(token,
3215 r.activity.getClass().getName(), "Activity");
3216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003217
3218 // Mocked out contexts won't be participating in the normal
3219 // process lifecycle, but if we're running with a proper
3220 // ApplicationContext we need to have it tear down things
3221 // cleanly.
3222 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08003223 if (c instanceof ContextImpl) {
3224 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225 r.activity.getClass().getName(), "Activity");
3226 }
3227 }
3228 if (finishing) {
3229 try {
3230 ActivityManagerNative.getDefault().activityDestroyed(token);
3231 } catch (RemoteException ex) {
3232 // If the system process has died, it's game over for everyone.
3233 }
3234 }
3235 }
3236
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003237 public final void requestRelaunchActivity(IBinder token,
3238 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
3239 int configChanges, boolean notResumed, Configuration config,
3240 boolean fromServer) {
3241 ActivityClientRecord target = null;
3242
3243 synchronized (mPackages) {
3244 for (int i=0; i<mRelaunchingActivities.size(); i++) {
3245 ActivityClientRecord r = mRelaunchingActivities.get(i);
3246 if (r.token == token) {
3247 target = r;
3248 if (pendingResults != null) {
3249 if (r.pendingResults != null) {
3250 r.pendingResults.addAll(pendingResults);
3251 } else {
3252 r.pendingResults = pendingResults;
3253 }
3254 }
3255 if (pendingNewIntents != null) {
3256 if (r.pendingIntents != null) {
3257 r.pendingIntents.addAll(pendingNewIntents);
3258 } else {
3259 r.pendingIntents = pendingNewIntents;
3260 }
3261 }
3262 break;
3263 }
3264 }
3265
3266 if (target == null) {
3267 target = new ActivityClientRecord();
3268 target.token = token;
3269 target.pendingResults = pendingResults;
3270 target.pendingIntents = pendingNewIntents;
3271 if (!fromServer) {
3272 ActivityClientRecord existing = mActivities.get(token);
3273 if (existing != null) {
3274 target.startsNotResumed = existing.paused;
3275 }
3276 target.onlyLocalRequest = true;
3277 }
3278 mRelaunchingActivities.add(target);
3279 queueOrSendMessage(H.RELAUNCH_ACTIVITY, target);
3280 }
3281
3282 if (fromServer) {
3283 target.startsNotResumed = notResumed;
3284 target.onlyLocalRequest = false;
3285 }
3286 if (config != null) {
3287 target.createdConfig = config;
3288 }
3289 target.pendingConfigChanges |= configChanges;
3290 }
3291 }
3292
Romain Guy65b345f2011-07-27 18:51:50 -07003293 private void handleRelaunchActivity(ActivityClientRecord tmp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003294 // If we are getting ready to gc after going to the background, well
3295 // we are back active so skip it.
3296 unscheduleGcIdler();
3297
3298 Configuration changedConfig = null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003299 int configChanges = 0;
Bob Leee5408332009-09-04 18:31:17 -07003300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301 // First: make sure we have the most recent configuration and most
3302 // recent version of the activity, or skip it if some previous call
3303 // had taken a more recent version.
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003304 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003305 int N = mRelaunchingActivities.size();
3306 IBinder token = tmp.token;
3307 tmp = null;
3308 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003309 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003310 if (r.token == token) {
3311 tmp = r;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003312 configChanges |= tmp.pendingConfigChanges;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313 mRelaunchingActivities.remove(i);
3314 i--;
3315 N--;
3316 }
3317 }
Bob Leee5408332009-09-04 18:31:17 -07003318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003320 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 return;
3322 }
Bob Leee5408332009-09-04 18:31:17 -07003323
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003324 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
3325 + tmp.token + " with configChanges=0x"
3326 + Integer.toHexString(configChanges));
3327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003328 if (mPendingConfiguration != null) {
3329 changedConfig = mPendingConfiguration;
3330 mPendingConfiguration = null;
3331 }
3332 }
Bob Leee5408332009-09-04 18:31:17 -07003333
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003334 if (tmp.createdConfig != null) {
3335 // If the activity manager is passing us its current config,
3336 // assume that is really what we want regardless of what we
3337 // may have pending.
3338 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003339 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
3340 && mConfiguration.diff(tmp.createdConfig) != 0)) {
3341 if (changedConfig == null
3342 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
3343 changedConfig = tmp.createdConfig;
3344 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003345 }
3346 }
3347
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003348 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003349 + tmp.token + ": changedConfig=" + changedConfig);
3350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351 // If there was a pending configuration change, execute it first.
3352 if (changedConfig != null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003353 handleConfigurationChanged(changedConfig, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003354 }
Bob Leee5408332009-09-04 18:31:17 -07003355
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003356 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003357 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 if (r == null) {
3359 return;
3360 }
Bob Leee5408332009-09-04 18:31:17 -07003361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003362 r.activity.mConfigChangeFlags |= configChanges;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003363 r.onlyLocalRequest = tmp.onlyLocalRequest;
Christopher Tateb70f3df2009-04-07 16:07:59 -07003364 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07003365
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003366 r.activity.mChangingConfigurations = true;
3367
Dianne Hackborne2b04802010-12-09 09:24:55 -08003368 // Need to ensure state is saved.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 if (!r.paused) {
Dianne Hackborne2b04802010-12-09 09:24:55 -08003370 performPauseActivity(r.token, false, r.isPreHoneycomb());
3371 }
3372 if (r.state == null && !r.stopped && !r.isPreHoneycomb()) {
3373 r.state = new Bundle();
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04003374 r.state.setAllowFds(false);
Dianne Hackborne2b04802010-12-09 09:24:55 -08003375 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003376 }
Bob Leee5408332009-09-04 18:31:17 -07003377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003378 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07003379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 r.activity = null;
3381 r.window = null;
3382 r.hideForNow = false;
3383 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07003384 // Merge any pending results and pending intents; don't just replace them
3385 if (tmp.pendingResults != null) {
3386 if (r.pendingResults == null) {
3387 r.pendingResults = tmp.pendingResults;
3388 } else {
3389 r.pendingResults.addAll(tmp.pendingResults);
3390 }
3391 }
3392 if (tmp.pendingIntents != null) {
3393 if (r.pendingIntents == null) {
3394 r.pendingIntents = tmp.pendingIntents;
3395 } else {
3396 r.pendingIntents.addAll(tmp.pendingIntents);
3397 }
3398 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003399 r.startsNotResumed = tmp.startsNotResumed;
Bob Leee5408332009-09-04 18:31:17 -07003400
Christopher Tateb70f3df2009-04-07 16:07:59 -07003401 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003402 }
3403
Romain Guy65b345f2011-07-27 18:51:50 -07003404 private void handleRequestThumbnail(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003405 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003406 Bitmap thumbnail = createThumbnailBitmap(r);
3407 CharSequence description = null;
3408 try {
3409 description = r.activity.onCreateDescription();
3410 } catch (Exception e) {
3411 if (!mInstrumentation.onException(r.activity, e)) {
3412 throw new RuntimeException(
3413 "Unable to create description of activity "
3414 + r.intent.getComponent().toShortString()
3415 + ": " + e.toString(), e);
3416 }
3417 }
3418 //System.out.println("Reporting top thumbnail " + thumbnail);
3419 try {
3420 ActivityManagerNative.getDefault().reportThumbnail(
3421 token, thumbnail, description);
3422 } catch (RemoteException ex) {
3423 }
3424 }
3425
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003426 ArrayList<ComponentCallbacks2> collectComponentCallbacksLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 boolean allActivities, Configuration newConfig) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003428 ArrayList<ComponentCallbacks2> callbacks
3429 = new ArrayList<ComponentCallbacks2>();
Bob Leee5408332009-09-04 18:31:17 -07003430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431 if (mActivities.size() > 0) {
Romain Guya998dff2012-03-23 18:58:36 -07003432 for (ActivityClientRecord ar : mActivities.values()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003433 Activity a = ar.activity;
3434 if (a != null) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003435 Configuration thisConfig = applyConfigCompatMainThread(newConfig,
3436 ar.packageInfo.mCompatibilityInfo.getIfNeeded());
Romain Guya998dff2012-03-23 18:58:36 -07003437 if (!ar.activity.mFinished && (allActivities || !ar.paused)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003438 // If the activity is currently resumed, its configuration
3439 // needs to change right now.
3440 callbacks.add(a);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003441 } else if (thisConfig != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003442 // Otherwise, we will tell it about the change
3443 // the next time it is resumed or shown. Note that
3444 // the activity manager may, before then, decide the
3445 // activity needs to be destroyed to handle its new
3446 // configuration.
Romain Guya998dff2012-03-23 18:58:36 -07003447 if (DEBUG_CONFIGURATION) {
3448 Slog.v(TAG, "Setting activity "
3449 + ar.activityInfo.name + " newConfig=" + thisConfig);
3450 }
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003451 ar.newConfig = thisConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003452 }
3453 }
3454 }
3455 }
3456 if (mServices.size() > 0) {
Romain Guya998dff2012-03-23 18:58:36 -07003457 for (Service service : mServices.values()) {
3458 callbacks.add(service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003459 }
3460 }
3461 synchronized (mProviderMap) {
3462 if (mLocalProviders.size() > 0) {
Romain Guya998dff2012-03-23 18:58:36 -07003463 for (ProviderClientRecord providerClientRecord : mLocalProviders.values()) {
3464 callbacks.add(providerClientRecord.mLocalProvider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003465 }
3466 }
3467 }
3468 final int N = mAllApplications.size();
3469 for (int i=0; i<N; i++) {
3470 callbacks.add(mAllApplications.get(i));
3471 }
Bob Leee5408332009-09-04 18:31:17 -07003472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 return callbacks;
3474 }
Bob Leee5408332009-09-04 18:31:17 -07003475
Romain Guya998dff2012-03-23 18:58:36 -07003476 private static void performConfigurationChanged(ComponentCallbacks2 cb, Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003477 // Only for Activity objects, check that they actually call up to their
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003478 // superclass implementation. ComponentCallbacks2 is an interface, so
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003479 // we check the runtime type and act accordingly.
3480 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
3481 if (activity != null) {
3482 activity.mCalled = false;
3483 }
Bob Leee5408332009-09-04 18:31:17 -07003484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485 boolean shouldChangeConfig = false;
3486 if ((activity == null) || (activity.mCurrentConfig == null)) {
3487 shouldChangeConfig = true;
3488 } else {
Bob Leee5408332009-09-04 18:31:17 -07003489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003490 // If the new config is the same as the config this Activity
3491 // is already running with then don't bother calling
3492 // onConfigurationChanged
3493 int diff = activity.mCurrentConfig.diff(config);
3494 if (diff != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003495 // If this activity doesn't handle any of the config changes
3496 // then don't bother calling onConfigurationChanged as we're
3497 // going to destroy it.
Dianne Hackborne6676352011-06-01 16:51:20 -07003498 if ((~activity.mActivityInfo.getRealConfigChanged() & diff) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003499 shouldChangeConfig = true;
3500 }
3501 }
3502 }
Bob Leee5408332009-09-04 18:31:17 -07003503
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003504 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003505 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003506 if (shouldChangeConfig) {
3507 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07003508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003509 if (activity != null) {
3510 if (!activity.mCalled) {
3511 throw new SuperNotCalledException(
3512 "Activity " + activity.getLocalClassName() +
3513 " did not call through to super.onConfigurationChanged()");
3514 }
3515 activity.mConfigChangeFlags = 0;
3516 activity.mCurrentConfig = new Configuration(config);
3517 }
3518 }
3519 }
3520
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07003521 public final void applyConfigurationToResources(Configuration config) {
3522 synchronized (mPackages) {
3523 applyConfigurationToResourcesLocked(config, null);
3524 }
3525 }
3526
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003527 final boolean applyConfigurationToResourcesLocked(Configuration config,
3528 CompatibilityInfo compat) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003529 if (mResConfiguration == null) {
3530 mResConfiguration = new Configuration();
3531 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003532 if (!mResConfiguration.isOtherSeqNewer(config) && compat == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003533 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq="
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003534 + mResConfiguration.seq + ", newSeq=" + config.seq);
Dianne Hackbornae078162010-03-18 11:29:37 -07003535 return false;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003536 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003537 int changes = mResConfiguration.updateFrom(config);
Dianne Hackborn836e2622011-10-04 18:32:39 -07003538 DisplayMetrics dm = getDisplayMetricsLocked(null, true);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003539
3540 if (compat != null && (mResCompatibilityInfo == null ||
3541 !mResCompatibilityInfo.equals(compat))) {
3542 mResCompatibilityInfo = compat;
3543 changes |= ActivityInfo.CONFIG_SCREEN_LAYOUT
3544 | ActivityInfo.CONFIG_SCREEN_SIZE
3545 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3546 }
Bob Leee5408332009-09-04 18:31:17 -07003547
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003548 // set it for java, this also affects newly created Resources
3549 if (config.locale != null) {
3550 Locale.setDefault(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003551 }
Bob Leee5408332009-09-04 18:31:17 -07003552
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003553 Resources.updateSystemConfiguration(config, dm, compat);
Bob Leee5408332009-09-04 18:31:17 -07003554
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003555 ApplicationPackageManager.configurationChanged();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003556 //Slog.i(TAG, "Configuration changed in " + currentPackageName());
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003557
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003558 Iterator<WeakReference<Resources>> it =
3559 mActiveResources.values().iterator();
3560 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
3561 // mActiveResources.entrySet().iterator();
3562 while (it.hasNext()) {
3563 WeakReference<Resources> v = it.next();
3564 Resources r = v.get();
3565 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003566 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources "
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003567 + r + " config to: " + config);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003568 r.updateConfiguration(config, dm, compat);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003569 //Slog.i(TAG, "Updated app resources " + v.getKey()
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003570 // + " " + r + ": " + r.getConfiguration());
3571 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003572 //Slog.i(TAG, "Removing old resources " + v.getKey());
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003573 it.remove();
3574 }
3575 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003576
3577 return changes != 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003578 }
Dianne Hackborn836e2622011-10-04 18:32:39 -07003579
3580 final Configuration applyCompatConfiguration() {
3581 Configuration config = mConfiguration;
3582 if (mCompatConfiguration == null) {
3583 mCompatConfiguration = new Configuration();
3584 }
3585 mCompatConfiguration.setTo(mConfiguration);
3586 if (mResCompatibilityInfo != null && !mResCompatibilityInfo.supportsScreen()) {
3587 mResCompatibilityInfo.applyToConfiguration(mCompatConfiguration);
3588 config = mCompatConfiguration;
3589 }
3590 return config;
3591 }
3592
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003593 final void handleConfigurationChanged(Configuration config, CompatibilityInfo compat) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003594
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003595 ArrayList<ComponentCallbacks2> callbacks = null;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003596
3597 synchronized (mPackages) {
3598 if (mPendingConfiguration != null) {
3599 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
3600 config = mPendingConfiguration;
3601 }
3602 mPendingConfiguration = null;
3603 }
3604
3605 if (config == null) {
3606 return;
3607 }
3608
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003609 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003610 + config);
3611
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003612 applyConfigurationToResourcesLocked(config, compat);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003614 if (mConfiguration == null) {
3615 mConfiguration = new Configuration();
3616 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003617 if (!mConfiguration.isOtherSeqNewer(config) && compat == null) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003618 return;
3619 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620 mConfiguration.updateFrom(config);
Dianne Hackborn836e2622011-10-04 18:32:39 -07003621 config = applyCompatConfiguration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003622 callbacks = collectComponentCallbacksLocked(false, config);
3623 }
Romain Guy65b345f2011-07-27 18:51:50 -07003624
3625 // Cleanup hardware accelerated stuff
3626 WindowManagerImpl.getDefault().trimLocalMemory();
Bob Leee5408332009-09-04 18:31:17 -07003627
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003628 if (callbacks != null) {
3629 final int N = callbacks.size();
3630 for (int i=0; i<N; i++) {
3631 performConfigurationChanged(callbacks.get(i), config);
3632 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003633 }
3634 }
3635
3636 final void handleActivityConfigurationChanged(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003637 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003638 if (r == null || r.activity == null) {
3639 return;
3640 }
Bob Leee5408332009-09-04 18:31:17 -07003641
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003642 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003643 + r.activityInfo.name);
3644
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003645 performConfigurationChanged(r.activity, mCompatConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003646 }
3647
Romain Guy7eabe552011-07-21 14:56:34 -07003648 final void handleProfilerControl(boolean start, ProfilerControlData pcd, int profileType) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003649 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003650 try {
Romain Guy7eabe552011-07-21 14:56:34 -07003651 switch (profileType) {
3652 case 1:
3653 ViewDebug.startLooperProfiling(pcd.path, pcd.fd.getFileDescriptor());
3654 break;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003655 default:
3656 mProfiler.setProfiler(pcd.path, pcd.fd);
3657 mProfiler.autoStopProfiler = false;
3658 mProfiler.startProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07003659 break;
3660 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003661 } catch (RuntimeException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003662 Slog.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003663 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003664 } finally {
3665 try {
3666 pcd.fd.close();
3667 } catch (IOException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003668 Slog.w(TAG, "Failure closing profile fd", e);
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003669 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003670 }
3671 } else {
Romain Guy7eabe552011-07-21 14:56:34 -07003672 switch (profileType) {
3673 case 1:
3674 ViewDebug.stopLooperProfiling();
3675 break;
3676 default:
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003677 mProfiler.stopProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07003678 break;
Romain Guy7eabe552011-07-21 14:56:34 -07003679 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003680 }
3681 }
Bob Leee5408332009-09-04 18:31:17 -07003682
Romain Guya998dff2012-03-23 18:58:36 -07003683 static final void handleDumpHeap(boolean managed, DumpHeapData dhd) {
Andy McFadden824c5102010-07-09 16:26:57 -07003684 if (managed) {
3685 try {
3686 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor());
3687 } catch (IOException e) {
3688 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
3689 + " -- can the process access this path?");
3690 } finally {
3691 try {
3692 dhd.fd.close();
3693 } catch (IOException e) {
3694 Slog.w(TAG, "Failure closing profile fd", e);
3695 }
3696 }
3697 } else {
Andy McFadden06a6b552010-07-13 16:28:09 -07003698 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07003699 }
3700 }
3701
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003702 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
3703 boolean hasPkgInfo = false;
3704 if (packages != null) {
3705 for (int i=packages.length-1; i>=0; i--) {
3706 //Slog.i(TAG, "Cleaning old package: " + packages[i]);
3707 if (!hasPkgInfo) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003708 WeakReference<LoadedApk> ref;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003709 ref = mPackages.get(packages[i]);
3710 if (ref != null && ref.get() != null) {
3711 hasPkgInfo = true;
3712 } else {
3713 ref = mResourcePackages.get(packages[i]);
3714 if (ref != null && ref.get() != null) {
3715 hasPkgInfo = true;
3716 }
3717 }
3718 }
3719 mPackages.remove(packages[i]);
3720 mResourcePackages.remove(packages[i]);
3721 }
3722 }
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003723 ApplicationPackageManager.handlePackageBroadcast(cmd, packages,
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003724 hasPkgInfo);
3725 }
3726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003727 final void handleLowMemory() {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003728 ArrayList<ComponentCallbacks2> callbacks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003729
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003730 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003731 callbacks = collectComponentCallbacksLocked(true, null);
3732 }
Bob Leee5408332009-09-04 18:31:17 -07003733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003734 final int N = callbacks.size();
3735 for (int i=0; i<N; i++) {
3736 callbacks.get(i).onLowMemory();
3737 }
3738
Chris Tatece229052009-03-25 16:44:52 -07003739 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3740 if (Process.myUid() != Process.SYSTEM_UID) {
3741 int sqliteReleased = SQLiteDatabase.releaseMemory();
3742 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3743 }
Bob Leee5408332009-09-04 18:31:17 -07003744
Mike Reedcaf0df12009-04-27 14:32:05 -04003745 // Ask graphics to free up as much as possible (font/image caches)
3746 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003747
3748 BinderInternal.forceGc("mem");
3749 }
3750
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003751 final void handleTrimMemory(int level) {
Teng-Hui Zhud9624132012-03-01 15:18:05 -08003752 WindowManagerImpl.getDefault().trimMemory(level);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003753 ArrayList<ComponentCallbacks2> callbacks;
3754
3755 synchronized (mPackages) {
3756 callbacks = collectComponentCallbacksLocked(true, null);
3757 }
3758
3759 final int N = callbacks.size();
Romain Guya998dff2012-03-23 18:58:36 -07003760 for (int i = 0; i < N; i++) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003761 callbacks.get(i).onTrimMemory(level);
3762 }
Teng-Hui Zhud9624132012-03-01 15:18:05 -08003763 WindowManagerImpl.getDefault().terminateEgl();
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003764 }
3765
Romain Guya9582652011-11-10 14:20:10 -08003766 private void setupGraphicsSupport(LoadedApk info) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003767 if (Process.isIsolated()) {
3768 // Isolated processes aren't going to do UI.
3769 return;
3770 }
Romain Guya9582652011-11-10 14:20:10 -08003771 try {
3772 int uid = Process.myUid();
3773 String[] packages = getPackageManager().getPackagesForUid(uid);
3774
3775 // If there are several packages in this application we won't
3776 // initialize the graphics disk caches
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003777 if (packages != null && packages.length == 1) {
Romain Guya9582652011-11-10 14:20:10 -08003778 ContextImpl appContext = new ContextImpl();
3779 appContext.init(info, null, this);
3780
3781 HardwareRenderer.setupDiskCache(appContext.getCacheDir());
Jason Samsa6f338c2012-02-24 16:22:16 -08003782 RenderScript.setupDiskCache(appContext.getCacheDir());
Romain Guya9582652011-11-10 14:20:10 -08003783 }
3784 } catch (RemoteException e) {
3785 // Ignore
3786 }
3787 }
3788
Romain Guy65b345f2011-07-27 18:51:50 -07003789 private void handleBindApplication(AppBindData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003790 mBoundApplication = data;
3791 mConfiguration = new Configuration(data.config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003792 mCompatConfiguration = new Configuration(data.config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003794 mProfiler = new Profiler();
3795 mProfiler.profileFile = data.initProfileFile;
3796 mProfiler.profileFd = data.initProfileFd;
3797 mProfiler.autoStopProfiler = data.initAutoStopProfiler;
3798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003799 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003800 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 android.ddm.DdmHandleAppName.setAppName(data.processName);
3802
Dianne Hackborn5d927c22011-09-02 12:22:18 -07003803 if (data.persistent) {
3804 // Persistent processes on low-memory devices do not get to
3805 // use hardware accelerated drawing, since this can add too much
3806 // overhead to the process.
3807 Display display = WindowManagerImpl.getDefault().getDefaultDisplay();
3808 if (!ActivityManager.isHighEndGfx(display)) {
3809 HardwareRenderer.disable(false);
3810 }
3811 }
Romain Guya9582652011-11-10 14:20:10 -08003812
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003813 if (mProfiler.profileFd != null) {
3814 mProfiler.startProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003815 }
3816
Joe Onoratod630f102011-03-17 18:42:26 -07003817 // If the app is Honeycomb MR1 or earlier, switch its AsyncTask
3818 // implementation to use the pool executor. Normally, we use the
3819 // serialized executor as the default. This has to happen in the
3820 // main thread so the main looper is set right.
Dianne Hackborn81e92762011-10-09 16:00:21 -07003821 if (data.appInfo.targetSdkVersion <= android.os.Build.VERSION_CODES.HONEYCOMB_MR1) {
Joe Onoratod630f102011-03-17 18:42:26 -07003822 AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
3823 }
3824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003825 /*
3826 * Before spawning a new process, reset the time zone to be the system time zone.
3827 * This needs to be done because the system time zone could have changed after the
3828 * the spawning of this process. Without doing this this process would have the incorrect
3829 * system time zone.
3830 */
3831 TimeZone.setDefault(null);
3832
3833 /*
3834 * Initialize the default locale in this process for the reasons we set the time zone.
3835 */
3836 Locale.setDefault(data.config.locale);
3837
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003838 /*
3839 * Update the system configuration since its preloaded and might not
3840 * reflect configuration changes. The configuration object passed
3841 * in AppBindData can be safely assumed to be up to date
3842 */
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07003843 applyConfigurationToResourcesLocked(data.config, data.compatInfo);
Dianne Hackborn836e2622011-10-04 18:32:39 -07003844 applyCompatConfiguration();
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003845
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003846 data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003847
Romain Guya9582652011-11-10 14:20:10 -08003848 setupGraphicsSupport(data.info);
3849
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003850 /**
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003851 * For system applications on userdebug/eng builds, log stack
3852 * traces of disk and network access to dropbox for analysis.
3853 */
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07003854 if ((data.appInfo.flags &
3855 (ApplicationInfo.FLAG_SYSTEM |
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07003856 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0) {
3857 StrictMode.conditionallyEnableDebugLogging();
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003858 }
3859
3860 /**
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07003861 * For apps targetting SDK Honeycomb or later, we don't allow
3862 * network usage on the main event loop / UI thread.
3863 *
3864 * Note to those grepping: this is what ultimately throws
3865 * NetworkOnMainThreadException ...
3866 */
3867 if (data.appInfo.targetSdkVersion > 9) {
3868 StrictMode.enableDeathOnNetwork();
3869 }
3870
3871 /**
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003872 * Switch this process to density compatibility mode if needed.
3873 */
3874 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3875 == 0) {
3876 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3877 }
Bob Leee5408332009-09-04 18:31:17 -07003878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003879 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3880 // XXX should have option to change the port.
3881 Debug.changeDebugPort(8100);
3882 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003883 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003884 + " is waiting for the debugger on port 8100...");
3885
3886 IActivityManager mgr = ActivityManagerNative.getDefault();
3887 try {
3888 mgr.showWaitingForDebugger(mAppThread, true);
3889 } catch (RemoteException ex) {
3890 }
3891
3892 Debug.waitForDebugger();
3893
3894 try {
3895 mgr.showWaitingForDebugger(mAppThread, false);
3896 } catch (RemoteException ex) {
3897 }
3898
3899 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003900 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003901 + " can be debugged on port 8100...");
3902 }
3903 }
3904
Siva Velusamy92a8b222012-03-09 16:24:04 -08003905 // Enable OpenGL tracing if required
3906 if (data.enableOpenGlTrace) {
3907 GLUtils.enableTracing();
3908 }
3909
Robert Greenwalt434203a2010-10-11 16:00:27 -07003910 /**
3911 * Initialize the default http proxy in this process for the reasons we set the time zone.
3912 */
3913 IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08003914 if (b != null) {
3915 // In pre-boot mode (doing initial launch to collect password), not
3916 // all system is up. This includes the connectivity service, so don't
3917 // crash if we can't get it.
3918 IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
3919 try {
3920 ProxyProperties proxyProperties = service.getProxy();
3921 Proxy.setHttpProxySystemProperty(proxyProperties);
3922 } catch (RemoteException e) {}
3923 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003925 if (data.instrumentationName != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08003926 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003927 appContext.init(data.info, null, this);
3928 InstrumentationInfo ii = null;
3929 try {
3930 ii = appContext.getPackageManager().
3931 getInstrumentationInfo(data.instrumentationName, 0);
3932 } catch (PackageManager.NameNotFoundException e) {
3933 }
3934 if (ii == null) {
3935 throw new RuntimeException(
3936 "Unable to find instrumentation info for: "
3937 + data.instrumentationName);
3938 }
3939
3940 mInstrumentationAppDir = ii.sourceDir;
Brian Carlstromd893a892012-04-01 21:30:26 -07003941 mInstrumentationAppLibraryDir = ii.nativeLibraryDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003942 mInstrumentationAppPackage = ii.packageName;
3943 mInstrumentedAppDir = data.info.getAppDir();
Brian Carlstromd893a892012-04-01 21:30:26 -07003944 mInstrumentedAppLibraryDir = data.info.getLibDir();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945
3946 ApplicationInfo instrApp = new ApplicationInfo();
3947 instrApp.packageName = ii.packageName;
3948 instrApp.sourceDir = ii.sourceDir;
3949 instrApp.publicSourceDir = ii.publicSourceDir;
3950 instrApp.dataDir = ii.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003951 instrApp.nativeLibraryDir = ii.nativeLibraryDir;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003952 LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003953 appContext.getClassLoader(), false, true);
Dianne Hackborn21556372010-02-04 16:34:40 -08003954 ContextImpl instrContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955 instrContext.init(pi, null, this);
3956
3957 try {
3958 java.lang.ClassLoader cl = instrContext.getClassLoader();
3959 mInstrumentation = (Instrumentation)
3960 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3961 } catch (Exception e) {
3962 throw new RuntimeException(
3963 "Unable to instantiate instrumentation "
3964 + data.instrumentationName + ": " + e.toString(), e);
3965 }
3966
3967 mInstrumentation.init(this, instrContext, appContext,
3968 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3969
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003970 if (mProfiler.profileFile != null && !ii.handleProfiling
3971 && mProfiler.profileFd == null) {
3972 mProfiler.handlingProfiling = true;
3973 File file = new File(mProfiler.profileFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003974 file.getParentFile().mkdirs();
3975 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3976 }
3977
3978 try {
3979 mInstrumentation.onCreate(data.instrumentationArgs);
3980 }
3981 catch (Exception e) {
3982 throw new RuntimeException(
3983 "Exception thrown in onCreate() of "
3984 + data.instrumentationName + ": " + e.toString(), e);
3985 }
3986
3987 } else {
3988 mInstrumentation = new Instrumentation();
3989 }
3990
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08003991 if ((data.appInfo.flags&ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
Dianne Hackbornde398512011-01-18 18:45:21 -08003992 dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08003993 }
3994
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08003995 // Allow disk access during application and provider setup. This could
Jeff Sharkey7c501672012-02-28 12:08:37 -08003996 // block processing ordered broadcasts, but later processing would
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08003997 // probably end up doing the same disk access.
Jeff Sharkey7c501672012-02-28 12:08:37 -08003998 final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 try {
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08004000 // If the app is being launched for full backup or restore, bring it up in
4001 // a restricted environment with the base application class.
4002 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
4003 mInitialApplication = app;
Jeff Sharkey7c501672012-02-28 12:08:37 -08004004
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08004005 // don't bring up providers in restricted mode; they may depend on the
4006 // app's custom Application class
4007 if (!data.restrictedBackupMode) {
4008 List<ProviderInfo> providers = data.providers;
4009 if (providers != null) {
4010 installContentProviders(app, providers);
4011 // For process that contains content providers, we want to
4012 // ensure that the JIT is enabled "at some point".
4013 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
4014 }
4015 }
4016
4017 try {
4018 mInstrumentation.callApplicationOnCreate(app);
4019 } catch (Exception e) {
4020 if (!mInstrumentation.onException(app, e)) {
4021 throw new RuntimeException(
4022 "Unable to create application " + app.getClass().getName()
4023 + ": " + e.toString(), e);
4024 }
4025 }
4026 } finally {
4027 StrictMode.setThreadPolicy(savedPolicy);
4028 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 }
4030
4031 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
4032 IActivityManager am = ActivityManagerNative.getDefault();
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07004033 if (mProfiler.profileFile != null && mProfiler.handlingProfiling
4034 && mProfiler.profileFd == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035 Debug.stopMethodTracing();
4036 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004037 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004038 // + ", app thr: " + mAppThread);
4039 try {
4040 am.finishInstrumentation(mAppThread, resultCode, results);
4041 } catch (RemoteException ex) {
4042 }
4043 }
4044
Romain Guy65b345f2011-07-27 18:51:50 -07004045 private void installContentProviders(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 Context context, List<ProviderInfo> providers) {
4047 final ArrayList<IActivityManager.ContentProviderHolder> results =
4048 new ArrayList<IActivityManager.ContentProviderHolder>();
4049
Romain Guya998dff2012-03-23 18:58:36 -07004050 for (ProviderInfo cpi : providers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 StringBuilder buf = new StringBuilder(128);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07004052 buf.append("Pub ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004053 buf.append(cpi.authority);
4054 buf.append(": ");
4055 buf.append(cpi.name);
4056 Log.i(TAG, buf.toString());
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004057 IContentProvider cp = installProvider(context, null, cpi,
4058 false /*noisy*/, true /*noReleaseNeeded*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004059 if (cp != null) {
4060 IActivityManager.ContentProviderHolder cph =
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004061 new IActivityManager.ContentProviderHolder(cpi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004062 cph.provider = cp;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004063 cph.noReleaseNeeded = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004064 results.add(cph);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004065 }
4066 }
4067
4068 try {
4069 ActivityManagerNative.getDefault().publishContentProviders(
4070 getApplicationThread(), results);
4071 } catch (RemoteException ex) {
4072 }
4073 }
4074
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004075 public final IContentProvider acquireProvider(Context c, String name) {
4076 IContentProvider provider = acquireExistingProvider(c, name);
4077 if (provider != null) {
4078 return provider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004079 }
4080
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004081 // There is a possible race here. Another thread may try to acquire
4082 // the same provider at the same time. When this happens, we want to ensure
4083 // that the first one wins.
4084 // Note that we cannot hold the lock while acquiring and installing the
4085 // provider since it might take a long time to run and it could also potentially
4086 // be re-entrant in the case where the provider is in the same process.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004087 IActivityManager.ContentProviderHolder holder = null;
4088 try {
4089 holder = ActivityManagerNative.getDefault().getContentProvider(
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004090 getApplicationThread(), name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004091 } catch (RemoteException ex) {
4092 }
4093 if (holder == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004094 Slog.e(TAG, "Failed to find provider info for " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004095 return null;
4096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004097
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004098 // Install provider will increment the reference count for us, and break
4099 // any ties in the race.
4100 provider = installProvider(c, holder.provider, holder.info,
4101 true /*noisy*/, holder.noReleaseNeeded);
4102 if (holder.provider != null && provider != holder.provider) {
4103 if (localLOGV) {
4104 Slog.v(TAG, "acquireProvider: lost the race, releasing extraneous "
4105 + "reference to the content provider");
4106 }
4107 try {
4108 ActivityManagerNative.getDefault().removeContentProvider(
4109 getApplicationThread(), name);
4110 } catch (RemoteException ex) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004111 }
4112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004113 return provider;
4114 }
4115
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07004116 public final IContentProvider acquireExistingProvider(Context c, String name) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004117 synchronized (mProviderMap) {
4118 ProviderClientRecord pr = mProviderMap.get(name);
4119 if (pr == null) {
4120 return null;
4121 }
4122
4123 IContentProvider provider = pr.mProvider;
4124 IBinder jBinder = provider.asBinder();
4125
4126 // Only increment the ref count if we have one. If we don't then the
4127 // provider is not reference counted and never needs to be released.
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07004128 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004129 if (prc != null) {
4130 prc.count += 1;
4131 if (prc.count == 1) {
4132 if (localLOGV) {
4133 Slog.v(TAG, "acquireExistingProvider: "
4134 + "snatched provider from the jaws of death");
4135 }
4136 // Because the provider previously had a reference count of zero,
4137 // it was scheduled to be removed. Cancel that.
4138 mH.removeMessages(H.REMOVE_PROVIDER, provider);
4139 }
4140 }
4141 return provider;
4142 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07004143 }
4144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004145 public final boolean releaseProvider(IContentProvider provider) {
4146 if(provider == null) {
4147 return false;
4148 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004150 IBinder jBinder = provider.asBinder();
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004151 synchronized (mProviderMap) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004152 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004153 if (prc == null) {
4154 // The provider has no ref count, no release is needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004155 return false;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004156 }
4157
4158 if (prc.count == 0) {
4159 if (localLOGV) Slog.v(TAG, "releaseProvider: ref count already 0, how?");
4160 return false;
4161 }
4162
4163 prc.count -= 1;
4164 if (prc.count == 0) {
4165 // Schedule the actual remove asynchronously, since we don't know the context
4166 // this will be called in.
4167 // TODO: it would be nice to post a delayed message, so
4168 // if we come back and need the same provider quickly
4169 // we will still have it available.
4170 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
4171 mH.sendMessage(msg);
4172 }
4173 return true;
4174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004175 }
4176
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004177 final void completeRemoveProvider(IContentProvider provider) {
4178 IBinder jBinder = provider.asBinder();
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004179 String remoteProviderName = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004180 synchronized(mProviderMap) {
4181 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004182 if (prc == null) {
4183 // Either no release is needed (so we shouldn't be here) or the
4184 // provider was already released.
4185 if (localLOGV) Slog.v(TAG, "completeRemoveProvider: release not needed");
4186 return;
4187 }
4188
4189 if (prc.count != 0) {
4190 // There was a race! Some other client managed to acquire
4191 // the provider before the removal was completed.
4192 // Abort the removal. We will do it later.
4193 if (localLOGV) Slog.v(TAG, "completeRemoveProvider: lost the race, "
4194 + "provider still in use");
4195 return;
4196 }
4197
4198 mProviderRefCountMap.remove(jBinder);
4199
4200 Iterator<ProviderClientRecord> iter = mProviderMap.values().iterator();
4201 while (iter.hasNext()) {
4202 ProviderClientRecord pr = iter.next();
4203 IBinder myBinder = pr.mProvider.asBinder();
4204 if (myBinder == jBinder) {
4205 iter.remove();
4206 if (pr.mLocalProvider == null) {
4207 myBinder.unlinkToDeath(pr, 0);
4208 if (remoteProviderName == null) {
4209 remoteProviderName = pr.mName;
4210 }
4211 }
4212 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004213 }
4214 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004215
4216 if (remoteProviderName != null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004217 try {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004218 if (localLOGV) {
4219 Slog.v(TAG, "removeProvider: Invoking ActivityManagerNative."
4220 + "removeContentProvider(" + remoteProviderName + ")");
4221 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004222 ActivityManagerNative.getDefault().removeContentProvider(
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004223 getApplicationThread(), remoteProviderName);
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004224 } catch (RemoteException e) {
4225 //do nothing content provider object is dead any way
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004226 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004227 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004229
4230 final void removeDeadProvider(String name, IContentProvider provider) {
4231 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004232 ProviderClientRecord pr = mProviderMap.get(name);
Jeff Brown2a4c5ac2011-08-23 11:58:26 -07004233 if (pr != null && pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004234 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004235 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07004236 if (removed != null) {
4237 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
4238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004239 }
4240 }
4241 }
4242
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004243 /**
4244 * Installs the provider.
4245 *
4246 * Providers that are local to the process or that come from the system server
4247 * may be installed permanently which is indicated by setting noReleaseNeeded to true.
4248 * Other remote providers are reference counted. The initial reference count
4249 * for all reference counted providers is one. Providers that are not reference
4250 * counted do not have a reference count (at all).
4251 *
4252 * This method detects when a provider has already been installed. When this happens,
4253 * it increments the reference count of the existing provider (if appropriate)
4254 * and returns the existing provider. This can happen due to concurrent
4255 * attempts to acquire the same provider.
4256 */
Romain Guy65b345f2011-07-27 18:51:50 -07004257 private IContentProvider installProvider(Context context,
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004258 IContentProvider provider, ProviderInfo info,
4259 boolean noisy, boolean noReleaseNeeded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004260 ContentProvider localProvider = null;
4261 if (provider == null) {
4262 if (noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004263 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004264 + info.name);
4265 }
4266 Context c = null;
4267 ApplicationInfo ai = info.applicationInfo;
4268 if (context.getPackageName().equals(ai.packageName)) {
4269 c = context;
4270 } else if (mInitialApplication != null &&
4271 mInitialApplication.getPackageName().equals(ai.packageName)) {
4272 c = mInitialApplication;
4273 } else {
4274 try {
4275 c = context.createPackageContext(ai.packageName,
4276 Context.CONTEXT_INCLUDE_CODE);
4277 } catch (PackageManager.NameNotFoundException e) {
Romain Guy65b345f2011-07-27 18:51:50 -07004278 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004279 }
4280 }
4281 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004282 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004283 ai.packageName +
4284 " while loading content provider " +
4285 info.name);
4286 return null;
4287 }
4288 try {
4289 final java.lang.ClassLoader cl = c.getClassLoader();
4290 localProvider = (ContentProvider)cl.
4291 loadClass(info.name).newInstance();
4292 provider = localProvider.getIContentProvider();
4293 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004294 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004295 info.name + " from sourceDir " +
4296 info.applicationInfo.sourceDir);
4297 return null;
4298 }
Joe Onorato43a17652011-04-06 19:22:23 -07004299 if (false) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004300 TAG, "Instantiating local provider " + info.name);
4301 // XXX Need to create the correct context for this provider.
4302 localProvider.attachInfo(c, info);
4303 } catch (java.lang.Exception e) {
4304 if (!mInstrumentation.onException(null, e)) {
4305 throw new RuntimeException(
4306 "Unable to get provider " + info.name
4307 + ": " + e.toString(), e);
4308 }
4309 return null;
4310 }
4311 } else if (localLOGV) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004312 Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004313 + info.name);
4314 }
4315
4316 synchronized (mProviderMap) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004317 // There is a possibility that this thread raced with another thread to
4318 // add the provider. If we find another thread got there first then we
4319 // just get out of the way and return the original provider.
4320 IBinder jBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004321 String names[] = PATTERN_SEMICOLON.split(info.authority);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004322 for (int i = 0; i < names.length; i++) {
4323 ProviderClientRecord pr = mProviderMap.get(names[i]);
4324 if (pr != null) {
4325 if (localLOGV) {
4326 Slog.v(TAG, "installProvider: lost the race, "
4327 + "using existing named provider");
4328 }
4329 provider = pr.mProvider;
4330 } else {
4331 pr = new ProviderClientRecord(names[i], provider, localProvider);
4332 if (localProvider == null) {
4333 try {
4334 jBinder.linkToDeath(pr, 0);
4335 } catch (RemoteException e) {
4336 // Provider already dead. Bail out of here without making
4337 // any changes to the provider map or other data structures.
4338 return null;
4339 }
4340 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004341 mProviderMap.put(names[i], pr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004342 }
4343 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004345 if (localProvider != null) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004346 ProviderClientRecord pr = mLocalProviders.get(jBinder);
4347 if (pr != null) {
4348 if (localLOGV) {
4349 Slog.v(TAG, "installProvider: lost the race, "
4350 + "using existing local provider");
4351 }
4352 provider = pr.mProvider;
4353 } else {
4354 pr = new ProviderClientRecord(null, provider, localProvider);
4355 mLocalProviders.put(jBinder, pr);
4356 }
4357 }
4358
4359 if (!noReleaseNeeded) {
4360 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
4361 if (prc != null) {
4362 if (localLOGV) {
4363 Slog.v(TAG, "installProvider: lost the race, incrementing ref count");
4364 }
4365 prc.count += 1;
4366 if (prc.count == 1) {
4367 if (localLOGV) {
4368 Slog.v(TAG, "installProvider: "
4369 + "snatched provider from the jaws of death");
4370 }
4371 // Because the provider previously had a reference count of zero,
4372 // it was scheduled to be removed. Cancel that.
4373 mH.removeMessages(H.REMOVE_PROVIDER, provider);
4374 }
4375 } else {
4376 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
4377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004378 }
4379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004380 return provider;
4381 }
4382
Romain Guy65b345f2011-07-27 18:51:50 -07004383 private void attach(boolean system) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004384 sThreadLocal.set(this);
4385 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004386 if (!system) {
Dianne Hackborn6dd005b2011-07-18 13:22:50 -07004387 ViewRootImpl.addFirstDrawHandler(new Runnable() {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08004388 public void run() {
4389 ensureJitEnabled();
4390 }
4391 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004392 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
4393 RuntimeInit.setApplicationObject(mAppThread.asBinder());
4394 IActivityManager mgr = ActivityManagerNative.getDefault();
4395 try {
4396 mgr.attachApplication(mAppThread);
4397 } catch (RemoteException ex) {
Romain Guy65b345f2011-07-27 18:51:50 -07004398 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004399 }
4400 } else {
4401 // Don't set application object here -- if the system crashes,
4402 // we can't display an alert, we just want to die die die.
4403 android.ddm.DdmHandleAppName.setAppName("system_process");
4404 try {
4405 mInstrumentation = new Instrumentation();
Dianne Hackborn21556372010-02-04 16:34:40 -08004406 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004407 context.init(getSystemContext().mPackageInfo, null, this);
4408 Application app = Instrumentation.newApplication(Application.class, context);
4409 mAllApplications.add(app);
4410 mInitialApplication = app;
4411 app.onCreate();
4412 } catch (Exception e) {
4413 throw new RuntimeException(
4414 "Unable to instantiate Application():" + e.toString(), e);
4415 }
4416 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004417
Dianne Hackbornc68c9132011-07-29 01:25:18 -07004418 ViewRootImpl.addConfigCallback(new ComponentCallbacks2() {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004419 public void onConfigurationChanged(Configuration newConfig) {
4420 synchronized (mPackages) {
Dianne Hackbornae078162010-03-18 11:29:37 -07004421 // We need to apply this change to the resources
4422 // immediately, because upon returning the view
4423 // hierarchy will be informed about it.
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004424 if (applyConfigurationToResourcesLocked(newConfig, null)) {
Dianne Hackbornae078162010-03-18 11:29:37 -07004425 // This actually changed the resources! Tell
4426 // everyone about it.
4427 if (mPendingConfiguration == null ||
4428 mPendingConfiguration.isOtherSeqNewer(newConfig)) {
4429 mPendingConfiguration = newConfig;
4430
4431 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
4432 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004433 }
4434 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004435 }
4436 public void onLowMemory() {
4437 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -07004438 public void onTrimMemory(int level) {
4439 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004440 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004441 }
4442
Romain Guy5e9120d2012-01-30 12:17:22 -08004443 public static ActivityThread systemMain() {
Dianne Hackborn5d927c22011-09-02 12:22:18 -07004444 HardwareRenderer.disable(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004445 ActivityThread thread = new ActivityThread();
4446 thread.attach(true);
4447 return thread;
4448 }
4449
Jeff Brown10e89712011-07-08 18:52:57 -07004450 public final void installSystemProviders(List<ProviderInfo> providers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004451 if (providers != null) {
Jeff Brown10e89712011-07-08 18:52:57 -07004452 installContentProviders(mInitialApplication, providers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004453 }
4454 }
4455
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004456 public int getIntCoreSetting(String key, int defaultValue) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08004457 synchronized (mPackages) {
4458 if (mCoreSettings != null) {
4459 return mCoreSettings.getInt(key, defaultValue);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004460 } else {
4461 return defaultValue;
4462 }
4463 }
4464 }
4465
Romain Guy65b345f2011-07-27 18:51:50 -07004466 public static void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07004467 SamplingProfilerIntegration.start();
4468
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -08004469 // CloseGuard defaults to true and can be quite spammy. We
4470 // disable it here, but selectively enable it later (via
4471 // StrictMode) on debug builds, but using DropBox, not logs.
4472 CloseGuard.setEnabled(false);
4473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004474 Process.setArgV0("<pre-initialized>");
4475
4476 Looper.prepareMainLooper();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07004477 if (sMainThreadHandler == null) {
4478 sMainThreadHandler = new Handler();
4479 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004480
4481 ActivityThread thread = new ActivityThread();
4482 thread.attach(false);
4483
Romain Guy5e9120d2012-01-30 12:17:22 -08004484 AsyncTask.init();
4485
Dianne Hackborn287952c2010-09-22 22:34:31 -07004486 if (false) {
4487 Looper.myLooper().setMessageLogging(new
4488 LogPrinter(Log.DEBUG, "ActivityThread"));
4489 }
4490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004491 Looper.loop();
4492
Jeff Brown10e89712011-07-08 18:52:57 -07004493 throw new RuntimeException("Main thread loop unexpectedly exited");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004494 }
4495}