blob: e2e791b1abba3fd1f0e4c3a5d3dc8aa96d7ce8d6 [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;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700141 private static final boolean DEBUG_MEMORY_TRIM = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
143 private static final Pattern PATTERN_SEMICOLON = Pattern.compile(";");
144 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
145 private static final int LOG_ON_PAUSE_CALLED = 30021;
146 private static final int LOG_ON_RESUME_CALLED = 30022;
147
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700148 static ContextImpl mSystemContext = null;
Bob Leee5408332009-09-04 18:31:17 -0700149
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700150 static IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700152 final ApplicationThread mAppThread = new ApplicationThread();
153 final Looper mLooper = Looper.myLooper();
154 final H mH = new H();
155 final HashMap<IBinder, ActivityClientRecord> mActivities
156 = new HashMap<IBinder, ActivityClientRecord>();
157 // List of new activities (via ActivityRecord.nextIdle) that should
158 // be reported when next we idle.
159 ActivityClientRecord mNewActivities = null;
160 // Number of activities that are currently visible on-screen.
161 int mNumVisibleActivities = 0;
162 final HashMap<IBinder, Service> mServices
163 = new HashMap<IBinder, Service>();
164 AppBindData mBoundApplication;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700165 Profiler mProfiler;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700166 Configuration mConfiguration;
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700167 Configuration mCompatConfiguration;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700168 Configuration mResConfiguration;
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700169 CompatibilityInfo mResCompatibilityInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700170 Application mInitialApplication;
171 final ArrayList<Application> mAllApplications
172 = new ArrayList<Application>();
173 // set of instantiated backup agents, keyed by package name
174 final HashMap<String, BackupAgent> mBackupAgents = new HashMap<String, BackupAgent>();
Romain Guy65b345f2011-07-27 18:51:50 -0700175 static final ThreadLocal<ActivityThread> sThreadLocal = new ThreadLocal<ActivityThread>();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700176 Instrumentation mInstrumentation;
177 String mInstrumentationAppDir = null;
Brian Carlstromd893a892012-04-01 21:30:26 -0700178 String mInstrumentationAppLibraryDir = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700179 String mInstrumentationAppPackage = null;
180 String mInstrumentedAppDir = null;
Brian Carlstromd893a892012-04-01 21:30:26 -0700181 String mInstrumentedAppLibraryDir = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700182 boolean mSystemThread = false;
183 boolean mJitEnabled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700185 // These can be accessed by multiple threads; mPackages is the lock.
186 // XXX For now we keep around information about all packages we have
187 // seen, not removing entries from this map.
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800188 // NOTE: The activity and window managers need to call in to
Dianne Hackborn2f0b1752011-05-31 17:59:49 -0700189 // ActivityThread to do things like update resource configurations,
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800190 // which means this lock gets held while the activity and window managers
191 // holds their own lock. Thus you MUST NEVER call back into the activity manager
192 // or window manager or anything that depends on them while holding this lock.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700193 final HashMap<String, WeakReference<LoadedApk>> mPackages
194 = new HashMap<String, WeakReference<LoadedApk>>();
195 final HashMap<String, WeakReference<LoadedApk>> mResourcePackages
196 = new HashMap<String, WeakReference<LoadedApk>>();
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700197 final HashMap<CompatibilityInfo, DisplayMetrics> mDisplayMetrics
198 = new HashMap<CompatibilityInfo, DisplayMetrics>();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700199 final HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources
200 = new HashMap<ResourcesKey, WeakReference<Resources> >();
201 final ArrayList<ActivityClientRecord> mRelaunchingActivities
202 = new ArrayList<ActivityClientRecord>();
203 Configuration mPendingConfiguration = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700205 // The lock of mProviderMap protects the following variables.
206 final HashMap<String, ProviderClientRecord> mProviderMap
207 = new HashMap<String, ProviderClientRecord>();
208 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap
209 = new HashMap<IBinder, ProviderRefCount>();
210 final HashMap<IBinder, ProviderClientRecord> mLocalProviders
211 = new HashMap<IBinder, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212
Jeff Hamilton52d32032011-01-08 15:31:26 -0600213 final HashMap<Activity, ArrayList<OnActivityPausedListener>> mOnPauseListeners
214 = new HashMap<Activity, ArrayList<OnActivityPausedListener>>();
215
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700216 final GcIdler mGcIdler = new GcIdler();
217 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700219 static Handler sMainThreadHandler; // set once in main()
220
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800221 Bundle mCoreSettings = null;
222
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400223 static final class ActivityClientRecord {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700225 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 Intent intent;
227 Bundle state;
228 Activity activity;
229 Window window;
230 Activity parent;
231 String embeddedID;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700232 Activity.NonConfigurationInstances lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 boolean paused;
234 boolean stopped;
235 boolean hideForNow;
236 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700237 Configuration createdConfig;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700238 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700240 String profileFile;
241 ParcelFileDescriptor profileFd;
242 boolean autoStopProfiler;
243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 ActivityInfo activityInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400245 CompatibilityInfo compatInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700246 LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247
248 List<ResultInfo> pendingResults;
249 List<Intent> pendingIntents;
250
251 boolean startsNotResumed;
252 boolean isForward;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800253 int pendingConfigChanges;
254 boolean onlyLocalRequest;
255
256 View mPendingRemoveWindow;
257 WindowManager mPendingRemoveWindowManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700259 ActivityClientRecord() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 parent = null;
261 embeddedID = null;
262 paused = false;
263 stopped = false;
264 hideForNow = false;
265 nextIdle = null;
266 }
267
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800268 public boolean isPreHoneycomb() {
269 if (activity != null) {
270 return activity.getApplicationInfo().targetSdkVersion
271 < android.os.Build.VERSION_CODES.HONEYCOMB;
272 }
273 return false;
274 }
275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276 public String toString() {
277 ComponentName componentName = intent.getComponent();
278 return "ActivityRecord{"
279 + Integer.toHexString(System.identityHashCode(this))
280 + " token=" + token + " " + (componentName == null
281 ? "no component name" : componentName.toShortString())
282 + "}";
283 }
284 }
285
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400286 final class ProviderClientRecord implements IBinder.DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 final String mName;
288 final IContentProvider mProvider;
289 final ContentProvider mLocalProvider;
290
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700291 ProviderClientRecord(String name, IContentProvider provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800292 ContentProvider localProvider) {
293 mName = name;
294 mProvider = provider;
295 mLocalProvider = localProvider;
296 }
297
298 public void binderDied() {
299 removeDeadProvider(mName, mProvider);
300 }
301 }
302
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400303 static final class NewIntentData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 List<Intent> intents;
305 IBinder token;
306 public String toString() {
307 return "NewIntentData{intents=" + intents + " token=" + token + "}";
308 }
309 }
310
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400311 static final class ReceiverData extends BroadcastReceiver.PendingResult {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700312 public ReceiverData(Intent intent, int resultCode, String resultData, Bundle resultExtras,
313 boolean ordered, boolean sticky, IBinder token) {
314 super(resultCode, resultData, resultExtras, TYPE_COMPONENT, ordered, sticky, token);
315 this.intent = intent;
316 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 Intent intent;
319 ActivityInfo info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400320 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321 public String toString() {
322 return "ReceiverData{intent=" + intent + " packageName=" +
Dianne Hackborne829fef2010-10-26 17:44:01 -0700323 info.packageName + " resultCode=" + getResultCode()
324 + " resultData=" + getResultData() + " resultExtras="
325 + getResultExtras(false) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326 }
327 }
328
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400329 static final class CreateBackupAgentData {
Christopher Tate181fafa2009-05-14 11:12:14 -0700330 ApplicationInfo appInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400331 CompatibilityInfo compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700332 int backupMode;
333 public String toString() {
334 return "CreateBackupAgentData{appInfo=" + appInfo
335 + " backupAgent=" + appInfo.backupAgentName
336 + " mode=" + backupMode + "}";
337 }
338 }
Bob Leee5408332009-09-04 18:31:17 -0700339
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400340 static final class CreateServiceData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800341 IBinder token;
342 ServiceInfo info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400343 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344 Intent intent;
345 public String toString() {
346 return "CreateServiceData{token=" + token + " className="
347 + info.name + " packageName=" + info.packageName
348 + " intent=" + intent + "}";
349 }
350 }
351
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400352 static final class BindServiceData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 IBinder token;
354 Intent intent;
355 boolean rebind;
356 public String toString() {
357 return "BindServiceData{token=" + token + " intent=" + intent + "}";
358 }
359 }
360
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400361 static final class ServiceArgsData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362 IBinder token;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700363 boolean taskRemoved;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700365 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366 Intent args;
367 public String toString() {
368 return "ServiceArgsData{token=" + token + " startId=" + startId
369 + " args=" + args + "}";
370 }
371 }
372
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400373 static final class AppBindData {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700374 LoadedApk info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 String processName;
376 ApplicationInfo appInfo;
377 List<ProviderInfo> providers;
378 ComponentName instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 Bundle instrumentationArgs;
380 IInstrumentationWatcher instrumentationWatcher;
381 int debugMode;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800382 boolean enableOpenGlTrace;
Christopher Tate181fafa2009-05-14 11:12:14 -0700383 boolean restrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700384 boolean persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 Configuration config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400386 CompatibilityInfo compatInfo;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700387
388 /** Initial values for {@link Profiler}. */
389 String initProfileFile;
390 ParcelFileDescriptor initProfileFd;
391 boolean initAutoStopProfiler;
392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800393 public String toString() {
394 return "AppBindData{appInfo=" + appInfo + "}";
395 }
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700396 }
397
398 static final class Profiler {
399 String profileFile;
400 ParcelFileDescriptor profileFd;
401 boolean autoStopProfiler;
402 boolean profiling;
403 boolean handlingProfiling;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700404 public void setProfiler(String file, ParcelFileDescriptor fd) {
405 if (profiling) {
406 if (fd != null) {
407 try {
408 fd.close();
409 } catch (IOException e) {
Romain Guya998dff2012-03-23 18:58:36 -0700410 // Ignore
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700411 }
412 }
413 return;
414 }
415 if (profileFd != null) {
416 try {
417 profileFd.close();
418 } catch (IOException e) {
Romain Guya998dff2012-03-23 18:58:36 -0700419 // Ignore
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700420 }
421 }
422 profileFile = file;
423 profileFd = fd;
424 }
425 public void startProfiling() {
426 if (profileFd == null || profiling) {
427 return;
428 }
429 try {
430 Debug.startMethodTracing(profileFile, profileFd.getFileDescriptor(),
431 8 * 1024 * 1024, 0);
432 profiling = true;
433 } catch (RuntimeException e) {
434 Slog.w(TAG, "Profiling failed on path " + profileFile);
435 try {
436 profileFd.close();
437 profileFd = null;
438 } catch (IOException e2) {
439 Slog.w(TAG, "Failure closing profile fd", e2);
440 }
441 }
442 }
443 public void stopProfiling() {
444 if (profiling) {
445 profiling = false;
446 Debug.stopMethodTracing();
447 if (profileFd != null) {
448 try {
449 profileFd.close();
450 } catch (IOException e) {
451 }
452 }
453 profileFd = null;
454 profileFile = null;
455 }
456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800457 }
458
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400459 static final class DumpComponentInfo {
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700460 ParcelFileDescriptor fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700461 IBinder token;
Dianne Hackborn30d71892010-12-11 10:37:55 -0800462 String prefix;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463 String[] args;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800464 }
465
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400466 static final class ResultData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467 IBinder token;
468 List<ResultInfo> results;
469 public String toString() {
470 return "ResultData{token=" + token + " results" + results + "}";
471 }
472 }
473
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400474 static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800475 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 String what;
477 String who;
478 }
479
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400480 static final class ProfilerControlData {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700481 String path;
482 ParcelFileDescriptor fd;
483 }
484
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400485 static final class DumpHeapData {
Andy McFadden824c5102010-07-09 16:26:57 -0700486 String path;
487 ParcelFileDescriptor fd;
488 }
489
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400490 static final class UpdateCompatibilityData {
491 String pkg;
492 CompatibilityInfo info;
493 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -0700494
Romain Guy65b345f2011-07-27 18:51:50 -0700495 private native void dumpGraphicsInfo(FileDescriptor fd);
Chet Haase9c1e23b2011-03-24 10:51:31 -0700496
Romain Guy65b345f2011-07-27 18:51:50 -0700497 private class ApplicationThread extends ApplicationThreadNative {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700498 private static final String HEAP_COLUMN = "%13s %8s %8s %8s %8s %8s %8s";
499 private static final String ONE_COUNT_COLUMN = "%21s %8d";
500 private static final String TWO_COUNT_COLUMNS = "%21s %8d %21s %8d";
Vasu Nori3c7131f2010-09-21 14:36:57 -0700501 private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
Bob Leee5408332009-09-04 18:31:17 -0700502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 // Formatting for checkin service - update version if row format changes
504 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;
Bob Leee5408332009-09-04 18:31:17 -0700505
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700506 private void updatePendingConfiguration(Configuration config) {
507 synchronized (mPackages) {
508 if (mPendingConfiguration == null ||
509 mPendingConfiguration.isOtherSeqNewer(config)) {
510 mPendingConfiguration = config;
511 }
512 }
513 }
514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800515 public final void schedulePauseActivity(IBinder token, boolean finished,
516 boolean userLeaving, int configChanges) {
517 queueOrSendMessage(
518 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
519 token,
520 (userLeaving ? 1 : 0),
521 configChanges);
522 }
523
524 public final void scheduleStopActivity(IBinder token, boolean showWindow,
525 int configChanges) {
526 queueOrSendMessage(
527 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
528 token, 0, configChanges);
529 }
530
531 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
532 queueOrSendMessage(
533 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
534 token);
535 }
536
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800537 public final void scheduleSleeping(IBinder token, boolean sleeping) {
538 queueOrSendMessage(H.SLEEPING, token, sleeping ? 1 : 0);
539 }
540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800541 public final void scheduleResumeActivity(IBinder token, boolean isForward) {
542 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
543 }
544
545 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
546 ResultData res = new ResultData();
547 res.token = token;
548 res.results = results;
549 queueOrSendMessage(H.SEND_RESULT, res);
550 }
551
552 // we use token to identify this activity without having to send the
553 // activity itself back to the activity manager. (matters more with ipc)
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700554 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700555 ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
556 Bundle state, List<ResultInfo> pendingResults,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700557 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward,
558 String profileName, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700559 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560
561 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700562 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563 r.intent = intent;
564 r.activityInfo = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400565 r.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566 r.state = state;
567
568 r.pendingResults = pendingResults;
569 r.pendingIntents = pendingNewIntents;
570
571 r.startsNotResumed = notResumed;
572 r.isForward = isForward;
573
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700574 r.profileFile = profileName;
575 r.profileFd = profileFd;
576 r.autoStopProfiler = autoStopProfiler;
577
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700578 updatePendingConfiguration(curConfig);
579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
581 }
582
583 public final void scheduleRelaunchActivity(IBinder token,
584 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800585 int configChanges, boolean notResumed, Configuration config) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800586 requestRelaunchActivity(token, pendingResults, pendingNewIntents,
587 configChanges, notResumed, config, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588 }
589
590 public final void scheduleNewIntent(List<Intent> intents, IBinder token) {
591 NewIntentData data = new NewIntentData();
592 data.intents = intents;
593 data.token = token;
594
595 queueOrSendMessage(H.NEW_INTENT, data);
596 }
597
598 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
599 int configChanges) {
600 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
601 configChanges);
602 }
603
604 public final void scheduleReceiver(Intent intent, ActivityInfo info,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400605 CompatibilityInfo compatInfo, int resultCode, String data, Bundle extras,
606 boolean sync) {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700607 ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
608 sync, false, mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609 r.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400610 r.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 queueOrSendMessage(H.RECEIVER, r);
612 }
613
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400614 public final void scheduleCreateBackupAgent(ApplicationInfo app,
615 CompatibilityInfo compatInfo, int backupMode) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700616 CreateBackupAgentData d = new CreateBackupAgentData();
617 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400618 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700619 d.backupMode = backupMode;
620
621 queueOrSendMessage(H.CREATE_BACKUP_AGENT, d);
622 }
623
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400624 public final void scheduleDestroyBackupAgent(ApplicationInfo app,
625 CompatibilityInfo compatInfo) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700626 CreateBackupAgentData d = new CreateBackupAgentData();
627 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400628 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700629
630 queueOrSendMessage(H.DESTROY_BACKUP_AGENT, d);
631 }
632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 public final void scheduleCreateService(IBinder token,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400634 ServiceInfo info, CompatibilityInfo compatInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 CreateServiceData s = new CreateServiceData();
636 s.token = token;
637 s.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400638 s.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639
640 queueOrSendMessage(H.CREATE_SERVICE, s);
641 }
642
643 public final void scheduleBindService(IBinder token, Intent intent,
644 boolean rebind) {
645 BindServiceData s = new BindServiceData();
646 s.token = token;
647 s.intent = intent;
648 s.rebind = rebind;
649
Amith Yamasani742a6712011-05-04 14:49:28 -0700650 if (DEBUG_SERVICE)
651 Slog.v(TAG, "scheduleBindService token=" + token + " intent=" + intent + " uid="
652 + Binder.getCallingUid() + " pid=" + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 queueOrSendMessage(H.BIND_SERVICE, s);
654 }
655
656 public final void scheduleUnbindService(IBinder token, Intent intent) {
657 BindServiceData s = new BindServiceData();
658 s.token = token;
659 s.intent = intent;
660
661 queueOrSendMessage(H.UNBIND_SERVICE, s);
662 }
663
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700664 public final void scheduleServiceArgs(IBinder token, boolean taskRemoved, int startId,
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700665 int flags ,Intent args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 ServiceArgsData s = new ServiceArgsData();
667 s.token = token;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700668 s.taskRemoved = taskRemoved;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 s.startId = startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700670 s.flags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 s.args = args;
672
673 queueOrSendMessage(H.SERVICE_ARGS, s);
674 }
675
676 public final void scheduleStopService(IBinder token) {
677 queueOrSendMessage(H.STOP_SERVICE, token);
678 }
679
680 public final void bindApplication(String processName,
681 ApplicationInfo appInfo, List<ProviderInfo> providers,
682 ComponentName instrumentationName, String profileFile,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700683 ParcelFileDescriptor profileFd, boolean autoStopProfiler,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
Siva Velusamy92a8b222012-03-09 16:24:04 -0800685 int debugMode, boolean enableOpenGlTrace, boolean isRestrictedBackupMode,
686 boolean persistent, Configuration config, CompatibilityInfo compatInfo,
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700687 Map<String, IBinder> services, Bundle coreSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688
689 if (services != null) {
690 // Setup the service cache in the ServiceManager
691 ServiceManager.initServiceCache(services);
692 }
693
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800694 setCoreSettings(coreSettings);
695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 AppBindData data = new AppBindData();
697 data.processName = processName;
698 data.appInfo = appInfo;
699 data.providers = providers;
700 data.instrumentationName = instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 data.instrumentationArgs = instrumentationArgs;
702 data.instrumentationWatcher = instrumentationWatcher;
703 data.debugMode = debugMode;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800704 data.enableOpenGlTrace = enableOpenGlTrace;
Christopher Tate181fafa2009-05-14 11:12:14 -0700705 data.restrictedBackupMode = isRestrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700706 data.persistent = persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 data.config = config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400708 data.compatInfo = compatInfo;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700709 data.initProfileFile = profileFile;
710 data.initProfileFd = profileFd;
711 data.initAutoStopProfiler = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 queueOrSendMessage(H.BIND_APPLICATION, data);
713 }
714
715 public final void scheduleExit() {
716 queueOrSendMessage(H.EXIT_APPLICATION, null);
717 }
718
Christopher Tate5e1ab332009-09-01 20:32:49 -0700719 public final void scheduleSuicide() {
720 queueOrSendMessage(H.SUICIDE, null);
721 }
722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 public void requestThumbnail(IBinder token) {
724 queueOrSendMessage(H.REQUEST_THUMBNAIL, token);
725 }
726
727 public void scheduleConfigurationChanged(Configuration config) {
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700728 updatePendingConfiguration(config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 queueOrSendMessage(H.CONFIGURATION_CHANGED, config);
730 }
731
732 public void updateTimeZone() {
733 TimeZone.setDefault(null);
734 }
735
Robert Greenwalt03595d02010-11-02 14:08:23 -0700736 public void clearDnsCache() {
737 // a non-standard API to get this to libcore
738 InetAddress.clearDnsCache();
739 }
740
Robert Greenwalt434203a2010-10-11 16:00:27 -0700741 public void setHttpProxy(String host, String port, String exclList) {
742 Proxy.setHttpProxySystemProperty(host, port, exclList);
743 }
744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 public void processInBackground() {
746 mH.removeMessages(H.GC_WHEN_IDLE);
747 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
748 }
749
750 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700751 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700752 try {
753 data.fd = ParcelFileDescriptor.dup(fd);
754 data.token = servicetoken;
755 data.args = args;
756 queueOrSendMessage(H.DUMP_SERVICE, data);
757 } catch (IOException e) {
758 Slog.w(TAG, "dumpService failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 }
760 }
761
762 // This function exists to make sure all receiver dispatching is
763 // correctly ordered, since these are one-way calls and the binder driver
764 // applies transaction ordering per object for such calls.
765 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700766 int resultCode, String dataStr, Bundle extras, boolean ordered,
767 boolean sticky) throws RemoteException {
768 receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 }
Bob Leee5408332009-09-04 18:31:17 -0700770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 public void scheduleLowMemory() {
772 queueOrSendMessage(H.LOW_MEMORY, null);
773 }
774
775 public void scheduleActivityConfigurationChanged(IBinder token) {
776 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token);
777 }
778
Romain Guy7eabe552011-07-21 14:56:34 -0700779 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd,
780 int profileType) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700781 ProfilerControlData pcd = new ProfilerControlData();
782 pcd.path = path;
783 pcd.fd = fd;
Romain Guy7eabe552011-07-21 14:56:34 -0700784 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0, profileType);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800785 }
786
Andy McFadden824c5102010-07-09 16:26:57 -0700787 public void dumpHeap(boolean managed, String path, ParcelFileDescriptor fd) {
788 DumpHeapData dhd = new DumpHeapData();
789 dhd.path = path;
790 dhd.fd = fd;
791 queueOrSendMessage(H.DUMP_HEAP, dhd, managed ? 1 : 0);
792 }
793
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700794 public void setSchedulingGroup(int group) {
795 // Note: do this immediately, since going into the foreground
796 // should happen regardless of what pending work we have to do
797 // and the activity manager will wait for us to report back that
798 // we are done before sending us to the background.
799 try {
800 Process.setProcessGroup(Process.myPid(), group);
801 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800802 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700803 }
804 }
Bob Leee5408332009-09-04 18:31:17 -0700805
Dianne Hackborn3025ef32009-08-31 21:31:47 -0700806 public void getMemoryInfo(Debug.MemoryInfo outInfo) {
807 Debug.getMemoryInfo(outInfo);
808 }
Bob Leee5408332009-09-04 18:31:17 -0700809
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700810 public void dispatchPackageBroadcast(int cmd, String[] packages) {
811 queueOrSendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
812 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700813
814 public void scheduleCrash(String msg) {
815 queueOrSendMessage(H.SCHEDULE_CRASH, msg);
816 }
Dianne Hackborn625ac272010-09-17 18:29:22 -0700817
Dianne Hackborn30d71892010-12-11 10:37:55 -0800818 public void dumpActivity(FileDescriptor fd, IBinder activitytoken,
819 String prefix, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700820 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700821 try {
822 data.fd = ParcelFileDescriptor.dup(fd);
823 data.token = activitytoken;
824 data.prefix = prefix;
825 data.args = args;
826 queueOrSendMessage(H.DUMP_ACTIVITY, data);
827 } catch (IOException e) {
828 Slog.w(TAG, "dumpActivity failed", e);
Dianne Hackborn625ac272010-09-17 18:29:22 -0700829 }
830 }
Chet Haase9c1e23b2011-03-24 10:51:31 -0700831
Marco Nelissen18cb2872011-11-15 11:19:53 -0800832 public void dumpProvider(FileDescriptor fd, IBinder providertoken,
833 String[] args) {
834 DumpComponentInfo data = new DumpComponentInfo();
835 try {
836 data.fd = ParcelFileDescriptor.dup(fd);
837 data.token = providertoken;
838 data.args = args;
839 queueOrSendMessage(H.DUMP_PROVIDER, data);
840 } catch (IOException e) {
841 Slog.w(TAG, "dumpProvider failed", e);
842 }
843 }
844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 @Override
Dianne Hackbornb437e092011-08-05 17:50:29 -0700846 public Debug.MemoryInfo dumpMemInfo(FileDescriptor fd, boolean checkin,
847 boolean all, String[] args) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700848 FileOutputStream fout = new FileOutputStream(fd);
849 PrintWriter pw = new PrintWriter(fout);
850 try {
Romain Guya998dff2012-03-23 18:58:36 -0700851 return dumpMemInfo(pw, checkin, all);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700852 } finally {
Chet Haase9c1e23b2011-03-24 10:51:31 -0700853 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -0700854 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700855 }
856
Romain Guya998dff2012-03-23 18:58:36 -0700857 private Debug.MemoryInfo dumpMemInfo(PrintWriter pw, boolean checkin, boolean all) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 long nativeMax = Debug.getNativeHeapSize() / 1024;
859 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
860 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
861
862 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
863 Debug.getMemoryInfo(memInfo);
864
Dianne Hackbornb437e092011-08-05 17:50:29 -0700865 if (!all) {
866 return memInfo;
867 }
868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 Runtime runtime = Runtime.getRuntime();
870
871 long dalvikMax = runtime.totalMemory() / 1024;
872 long dalvikFree = runtime.freeMemory() / 1024;
873 long dalvikAllocated = dalvikMax - dalvikFree;
874 long viewInstanceCount = ViewDebug.getViewInstanceCount();
Romain Guy65b345f2011-07-27 18:51:50 -0700875 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
Brian Carlstromc21550a2010-10-05 21:34:06 -0700876 long appContextInstanceCount = Debug.countInstancesOfClass(ContextImpl.class);
877 long activityInstanceCount = Debug.countInstancesOfClass(Activity.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 int globalAssetCount = AssetManager.getGlobalAssetCount();
879 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
880 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
881 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
882 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
Brian Carlstromc9d5b312010-10-05 22:23:41 -0700883 long openSslSocketCount = Debug.countInstancesOfClass(OpenSSLSocketImpl.class);
Vasu Noric3849202010-03-09 10:47:25 -0800884 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -0700885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 // For checkin, we print one long comma-separated list of values
Dianne Hackbornb437e092011-08-05 17:50:29 -0700887 if (checkin) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 // NOTE: if you change anything significant below, also consider changing
889 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -0700890 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -0700892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 // Header
894 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
895 pw.print(Process.myPid()); pw.print(',');
896 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 // Heap info - max
899 pw.print(nativeMax); pw.print(',');
900 pw.print(dalvikMax); pw.print(',');
901 pw.print("N/A,");
902 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 // Heap info - allocated
905 pw.print(nativeAllocated); pw.print(',');
906 pw.print(dalvikAllocated); pw.print(',');
907 pw.print("N/A,");
908 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 // Heap info - free
911 pw.print(nativeFree); pw.print(',');
912 pw.print(dalvikFree); pw.print(',');
913 pw.print("N/A,");
914 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 // Heap info - proportional set size
917 pw.print(memInfo.nativePss); pw.print(',');
918 pw.print(memInfo.dalvikPss); pw.print(',');
919 pw.print(memInfo.otherPss); pw.print(',');
920 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700921
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 // Heap info - shared
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700923 pw.print(memInfo.nativeSharedDirty); pw.print(',');
924 pw.print(memInfo.dalvikSharedDirty); pw.print(',');
925 pw.print(memInfo.otherSharedDirty); pw.print(',');
926 pw.print(memInfo.nativeSharedDirty + memInfo.dalvikSharedDirty
927 + memInfo.otherSharedDirty); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 // Heap info - private
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700930 pw.print(memInfo.nativePrivateDirty); pw.print(',');
931 pw.print(memInfo.dalvikPrivateDirty); pw.print(',');
932 pw.print(memInfo.otherPrivateDirty); pw.print(',');
933 pw.print(memInfo.nativePrivateDirty + memInfo.dalvikPrivateDirty
934 + memInfo.otherPrivateDirty); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 // Object counts
937 pw.print(viewInstanceCount); pw.print(',');
938 pw.print(viewRootInstanceCount); pw.print(',');
939 pw.print(appContextInstanceCount); pw.print(',');
940 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 pw.print(globalAssetCount); pw.print(',');
943 pw.print(globalAssetManagerCount); pw.print(',');
944 pw.print(binderLocalObjectCount); pw.print(',');
945 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 pw.print(binderDeathObjectCount); pw.print(',');
948 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 // SQL
Vasu Noric3849202010-03-09 10:47:25 -0800951 pw.print(stats.memoryUsed / 1024); pw.print(',');
Jeff Brown2a293b62012-01-19 14:02:22 -0800952 pw.print(stats.memoryUsed / 1024); pw.print(',');
953 pw.print(stats.pageCacheOverflow / 1024); pw.print(',');
Dianne Hackbornb437e092011-08-05 17:50:29 -0700954 pw.print(stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -0800955 for (int i = 0; i < stats.dbStats.size(); i++) {
956 DbStats dbStats = stats.dbStats.get(i);
Dianne Hackbornb437e092011-08-05 17:50:29 -0700957 pw.print(','); pw.print(dbStats.dbName);
958 pw.print(','); pw.print(dbStats.pageSize);
959 pw.print(','); pw.print(dbStats.dbSize);
960 pw.print(','); pw.print(dbStats.lookaside);
961 pw.print(','); pw.print(dbStats.cache);
962 pw.print(','); pw.print(dbStats.cache);
Vasu Noric3849202010-03-09 10:47:25 -0800963 }
Dianne Hackbornb437e092011-08-05 17:50:29 -0700964 pw.println();
Bob Leee5408332009-09-04 18:31:17 -0700965
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700966 return memInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 }
Bob Leee5408332009-09-04 18:31:17 -0700968
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 // otherwise, show human-readable format
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700970 printRow(pw, HEAP_COLUMN, "", "", "Shared", "Private", "Heap", "Heap", "Heap");
971 printRow(pw, HEAP_COLUMN, "", "Pss", "Dirty", "Dirty", "Size", "Alloc", "Free");
972 printRow(pw, HEAP_COLUMN, "", "------", "------", "------", "------", "------",
973 "------");
974 printRow(pw, HEAP_COLUMN, "Native", memInfo.nativePss, memInfo.nativeSharedDirty,
975 memInfo.nativePrivateDirty, nativeMax, nativeAllocated, nativeFree);
976 printRow(pw, HEAP_COLUMN, "Dalvik", memInfo.dalvikPss, memInfo.dalvikSharedDirty,
977 memInfo.dalvikPrivateDirty, dalvikMax, dalvikAllocated, dalvikFree);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700979 int otherPss = memInfo.otherPss;
980 int otherSharedDirty = memInfo.otherSharedDirty;
981 int otherPrivateDirty = memInfo.otherPrivateDirty;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700983 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
Romain Guy65b345f2011-07-27 18:51:50 -0700984 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700985 memInfo.getOtherPss(i), memInfo.getOtherSharedDirty(i),
986 memInfo.getOtherPrivateDirty(i), "", "", "");
987 otherPss -= memInfo.getOtherPss(i);
988 otherSharedDirty -= memInfo.getOtherSharedDirty(i);
989 otherPrivateDirty -= memInfo.getOtherPrivateDirty(i);
990 }
991
992 printRow(pw, HEAP_COLUMN, "Unknown", otherPss, otherSharedDirty,
993 otherPrivateDirty, "", "", "");
994 printRow(pw, HEAP_COLUMN, "TOTAL", memInfo.getTotalPss(),
995 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
996 nativeMax+dalvikMax, nativeAllocated+dalvikAllocated,
997 nativeFree+dalvikFree);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998
999 pw.println(" ");
1000 pw.println(" Objects");
Romain Guy65b345f2011-07-27 18:51:50 -07001001 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRootImpl:",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 viewRootInstanceCount);
1003
1004 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
1005 "Activities:", activityInstanceCount);
1006
1007 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
1008 "AssetManagers:", globalAssetManagerCount);
1009
1010 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
1011 "Proxy Binders:", binderProxyObjectCount);
1012 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
1013
1014 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -07001015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 // SQLite mem info
1017 pw.println(" ");
1018 pw.println(" SQL");
Jeff Brown2a293b62012-01-19 14:02:22 -08001019 printRow(pw, ONE_COUNT_COLUMN, "MEMORY_USED:", stats.memoryUsed / 1024);
1020 printRow(pw, TWO_COUNT_COLUMNS, "PAGECACHE_OVERFLOW:",
1021 stats.pageCacheOverflow / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -08001022 pw.println(" ");
1023 int N = stats.dbStats.size();
1024 if (N > 0) {
1025 pw.println(" DATABASES");
Vasu Nori3c7131f2010-09-21 14:36:57 -07001026 printRow(pw, " %8s %8s %14s %14s %s", "pgsz", "dbsz", "Lookaside(b)", "cache",
1027 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -08001028 for (int i = 0; i < N; i++) {
1029 DbStats dbStats = stats.dbStats.get(i);
Vasu Nori3c7131f2010-09-21 14:36:57 -07001030 printRow(pw, DB_INFO_FORMAT,
1031 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
1032 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
1033 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
1034 dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -08001035 }
1036 }
Bob Leee5408332009-09-04 18:31:17 -07001037
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07001038 // Asset details.
1039 String assetAlloc = AssetManager.getAssetAllocations();
1040 if (assetAlloc != null) {
1041 pw.println(" ");
1042 pw.println(" Asset Allocations");
1043 pw.print(assetAlloc);
1044 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001045
1046 return memInfo;
1047 }
1048
1049 @Override
1050 public void dumpGfxInfo(FileDescriptor fd, String[] args) {
1051 dumpGraphicsInfo(fd);
Romain Guy65b345f2011-07-27 18:51:50 -07001052 WindowManagerImpl.getDefault().dumpGfxInfo(fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 }
1054
Jeff Brown6754ba22011-12-14 20:20:01 -08001055 @Override
1056 public void dumpDbInfo(FileDescriptor fd, String[] args) {
1057 PrintWriter pw = new PrintWriter(new FileOutputStream(fd));
1058 PrintWriterPrinter printer = new PrintWriterPrinter(pw);
1059 SQLiteDebug.dump(printer, args);
1060 pw.flush();
1061 }
1062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 private void printRow(PrintWriter pw, String format, Object...objs) {
1064 pw.println(String.format(format, objs));
1065 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001066
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08001067 public void setCoreSettings(Bundle coreSettings) {
1068 queueOrSendMessage(H.SET_CORE_SETTINGS, coreSettings);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001069 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001070
1071 public void updatePackageCompatibilityInfo(String pkg, CompatibilityInfo info) {
1072 UpdateCompatibilityData ucd = new UpdateCompatibilityData();
1073 ucd.pkg = pkg;
1074 ucd.info = info;
1075 queueOrSendMessage(H.UPDATE_PACKAGE_COMPATIBILITY_INFO, ucd);
1076 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001077
1078 public void scheduleTrimMemory(int level) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001079 queueOrSendMessage(H.TRIM_MEMORY, null, level);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001080 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 }
1083
Romain Guy65b345f2011-07-27 18:51:50 -07001084 private class H extends Handler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 public static final int LAUNCH_ACTIVITY = 100;
1086 public static final int PAUSE_ACTIVITY = 101;
1087 public static final int PAUSE_ACTIVITY_FINISHING= 102;
1088 public static final int STOP_ACTIVITY_SHOW = 103;
1089 public static final int STOP_ACTIVITY_HIDE = 104;
1090 public static final int SHOW_WINDOW = 105;
1091 public static final int HIDE_WINDOW = 106;
1092 public static final int RESUME_ACTIVITY = 107;
1093 public static final int SEND_RESULT = 108;
Brian Carlstromed7e0072011-03-24 13:27:57 -07001094 public static final int DESTROY_ACTIVITY = 109;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 public static final int BIND_APPLICATION = 110;
1096 public static final int EXIT_APPLICATION = 111;
1097 public static final int NEW_INTENT = 112;
1098 public static final int RECEIVER = 113;
1099 public static final int CREATE_SERVICE = 114;
1100 public static final int SERVICE_ARGS = 115;
1101 public static final int STOP_SERVICE = 116;
1102 public static final int REQUEST_THUMBNAIL = 117;
1103 public static final int CONFIGURATION_CHANGED = 118;
1104 public static final int CLEAN_UP_CONTEXT = 119;
1105 public static final int GC_WHEN_IDLE = 120;
1106 public static final int BIND_SERVICE = 121;
1107 public static final int UNBIND_SERVICE = 122;
1108 public static final int DUMP_SERVICE = 123;
1109 public static final int LOW_MEMORY = 124;
1110 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
1111 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001112 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -07001113 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001114 public static final int DESTROY_BACKUP_AGENT = 129;
1115 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001116 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001117 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001118 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001119 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -07001120 public static final int DUMP_HEAP = 135;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001121 public static final int DUMP_ACTIVITY = 136;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001122 public static final int SLEEPING = 137;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001123 public static final int SET_CORE_SETTINGS = 138;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001124 public static final int UPDATE_PACKAGE_COMPATIBILITY_INFO = 139;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001125 public static final int TRIM_MEMORY = 140;
Marco Nelissen18cb2872011-11-15 11:19:53 -08001126 public static final int DUMP_PROVIDER = 141;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127 String codeToString(int code) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001128 if (DEBUG_MESSAGES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 switch (code) {
1130 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
1131 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
1132 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
1133 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
1134 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
1135 case SHOW_WINDOW: return "SHOW_WINDOW";
1136 case HIDE_WINDOW: return "HIDE_WINDOW";
1137 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
1138 case SEND_RESULT: return "SEND_RESULT";
1139 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
1140 case BIND_APPLICATION: return "BIND_APPLICATION";
1141 case EXIT_APPLICATION: return "EXIT_APPLICATION";
1142 case NEW_INTENT: return "NEW_INTENT";
1143 case RECEIVER: return "RECEIVER";
1144 case CREATE_SERVICE: return "CREATE_SERVICE";
1145 case SERVICE_ARGS: return "SERVICE_ARGS";
1146 case STOP_SERVICE: return "STOP_SERVICE";
1147 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
1148 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
1149 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
1150 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
1151 case BIND_SERVICE: return "BIND_SERVICE";
1152 case UNBIND_SERVICE: return "UNBIND_SERVICE";
1153 case DUMP_SERVICE: return "DUMP_SERVICE";
1154 case LOW_MEMORY: return "LOW_MEMORY";
1155 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
1156 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001157 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -07001158 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
1159 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -07001160 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001161 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001162 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001163 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001164 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -07001165 case DUMP_HEAP: return "DUMP_HEAP";
Dianne Hackborn625ac272010-09-17 18:29:22 -07001166 case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001167 case SLEEPING: return "SLEEPING";
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001168 case SET_CORE_SETTINGS: return "SET_CORE_SETTINGS";
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001169 case UPDATE_PACKAGE_COMPATIBILITY_INFO: return "UPDATE_PACKAGE_COMPATIBILITY_INFO";
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001170 case TRIM_MEMORY: return "TRIM_MEMORY";
Marco Nelissen18cb2872011-11-15 11:19:53 -08001171 case DUMP_PROVIDER: return "DUMP_PROVIDER";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172 }
1173 }
1174 return "(unknown)";
1175 }
1176 public void handleMessage(Message msg) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001177 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 switch (msg.what) {
1179 case LAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001180 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181
1182 r.packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001183 r.activityInfo.applicationInfo, r.compatInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001184 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 } break;
1186 case RELAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001187 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08001188 handleRelaunchActivity(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 } break;
1190 case PAUSE_ACTIVITY:
1191 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -07001192 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 break;
1194 case PAUSE_ACTIVITY_FINISHING:
1195 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
1196 break;
1197 case STOP_ACTIVITY_SHOW:
1198 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
1199 break;
1200 case STOP_ACTIVITY_HIDE:
1201 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
1202 break;
1203 case SHOW_WINDOW:
1204 handleWindowVisibility((IBinder)msg.obj, true);
1205 break;
1206 case HIDE_WINDOW:
1207 handleWindowVisibility((IBinder)msg.obj, false);
1208 break;
1209 case RESUME_ACTIVITY:
1210 handleResumeActivity((IBinder)msg.obj, true,
1211 msg.arg1 != 0);
1212 break;
1213 case SEND_RESULT:
1214 handleSendResult((ResultData)msg.obj);
1215 break;
1216 case DESTROY_ACTIVITY:
1217 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
1218 msg.arg2, false);
1219 break;
1220 case BIND_APPLICATION:
1221 AppBindData data = (AppBindData)msg.obj;
1222 handleBindApplication(data);
1223 break;
1224 case EXIT_APPLICATION:
1225 if (mInitialApplication != null) {
1226 mInitialApplication.onTerminate();
1227 }
1228 Looper.myLooper().quit();
1229 break;
1230 case NEW_INTENT:
1231 handleNewIntent((NewIntentData)msg.obj);
1232 break;
1233 case RECEIVER:
1234 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001235 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001236 break;
1237 case CREATE_SERVICE:
1238 handleCreateService((CreateServiceData)msg.obj);
1239 break;
1240 case BIND_SERVICE:
1241 handleBindService((BindServiceData)msg.obj);
1242 break;
1243 case UNBIND_SERVICE:
1244 handleUnbindService((BindServiceData)msg.obj);
1245 break;
1246 case SERVICE_ARGS:
1247 handleServiceArgs((ServiceArgsData)msg.obj);
1248 break;
1249 case STOP_SERVICE:
1250 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001251 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 break;
1253 case REQUEST_THUMBNAIL:
1254 handleRequestThumbnail((IBinder)msg.obj);
1255 break;
1256 case CONFIGURATION_CHANGED:
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001257 handleConfigurationChanged((Configuration)msg.obj, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258 break;
1259 case CLEAN_UP_CONTEXT:
1260 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1261 cci.context.performFinalCleanup(cci.who, cci.what);
1262 break;
1263 case GC_WHEN_IDLE:
1264 scheduleGcIdler();
1265 break;
1266 case DUMP_SERVICE:
Dianne Hackborn625ac272010-09-17 18:29:22 -07001267 handleDumpService((DumpComponentInfo)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 break;
1269 case LOW_MEMORY:
1270 handleLowMemory();
1271 break;
1272 case ACTIVITY_CONFIGURATION_CHANGED:
1273 handleActivityConfigurationChanged((IBinder)msg.obj);
1274 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001275 case PROFILER_CONTROL:
Romain Guy7eabe552011-07-21 14:56:34 -07001276 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj, msg.arg2);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001277 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001278 case CREATE_BACKUP_AGENT:
1279 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1280 break;
1281 case DESTROY_BACKUP_AGENT:
1282 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1283 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001284 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001285 Process.killProcess(Process.myPid());
1286 break;
1287 case REMOVE_PROVIDER:
1288 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001289 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001290 case ENABLE_JIT:
1291 ensureJitEnabled();
1292 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001293 case DISPATCH_PACKAGE_BROADCAST:
1294 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
1295 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001296 case SCHEDULE_CRASH:
1297 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001298 case DUMP_HEAP:
1299 handleDumpHeap(msg.arg1 != 0, (DumpHeapData)msg.obj);
1300 break;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001301 case DUMP_ACTIVITY:
1302 handleDumpActivity((DumpComponentInfo)msg.obj);
1303 break;
Marco Nelissen18cb2872011-11-15 11:19:53 -08001304 case DUMP_PROVIDER:
1305 handleDumpProvider((DumpComponentInfo)msg.obj);
1306 break;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001307 case SLEEPING:
1308 handleSleeping((IBinder)msg.obj, msg.arg1 != 0);
1309 break;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001310 case SET_CORE_SETTINGS:
1311 handleSetCoreSettings((Bundle) msg.obj);
1312 break;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001313 case UPDATE_PACKAGE_COMPATIBILITY_INFO:
1314 handleUpdatePackageCompatibilityInfo((UpdateCompatibilityData)msg.obj);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001315 break;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001316 case TRIM_MEMORY:
1317 handleTrimMemory(msg.arg1);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001318 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07001320 if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 }
Bob Leee5408332009-09-04 18:31:17 -07001322
Brian Carlstromed7e0072011-03-24 13:27:57 -07001323 private void maybeSnapshot() {
1324 if (mBoundApplication != null && SamplingProfilerIntegration.isEnabled()) {
Sen Hubde75702010-05-28 01:54:03 -07001325 // convert the *private* ActivityThread.PackageInfo to *public* known
1326 // android.content.pm.PackageInfo
1327 String packageName = mBoundApplication.info.mPackageName;
1328 android.content.pm.PackageInfo packageInfo = null;
1329 try {
1330 Context context = getSystemContext();
1331 if(context == null) {
1332 Log.e(TAG, "cannot get a valid context");
1333 return;
1334 }
1335 PackageManager pm = context.getPackageManager();
1336 if(pm == null) {
1337 Log.e(TAG, "cannot get a valid PackageManager");
1338 return;
1339 }
1340 packageInfo = pm.getPackageInfo(
1341 packageName, PackageManager.GET_ACTIVITIES);
1342 } catch (NameNotFoundException e) {
1343 Log.e(TAG, "cannot get package info for " + packageName, e);
1344 }
1345 SamplingProfilerIntegration.writeSnapshot(mBoundApplication.processName, packageInfo);
Bob Leee5408332009-09-04 18:31:17 -07001346 }
1347 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 }
1349
Romain Guy65b345f2011-07-27 18:51:50 -07001350 private class Idler implements MessageQueue.IdleHandler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001352 ActivityClientRecord a = mNewActivities;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001353 boolean stopProfiling = false;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001354 if (mBoundApplication != null && mProfiler.profileFd != null
1355 && mProfiler.autoStopProfiler) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001356 stopProfiling = true;
1357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 if (a != null) {
1359 mNewActivities = null;
1360 IActivityManager am = ActivityManagerNative.getDefault();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001361 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001363 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 TAG, "Reporting idle of " + a +
1365 " finished=" +
Romain Guy65b345f2011-07-27 18:51:50 -07001366 (a.activity != null && a.activity.mFinished));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 if (a.activity != null && !a.activity.mFinished) {
1368 try {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001369 am.activityIdle(a.token, a.createdConfig, stopProfiling);
Dianne Hackborne88846e2009-09-30 21:34:25 -07001370 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371 } catch (RemoteException ex) {
Romain Guy65b345f2011-07-27 18:51:50 -07001372 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 }
1374 }
1375 prev = a;
1376 a = a.nextIdle;
1377 prev.nextIdle = null;
1378 } while (a != null);
1379 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001380 if (stopProfiling) {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001381 mProfiler.stopProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001382 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001383 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 return false;
1385 }
1386 }
1387
1388 final class GcIdler implements MessageQueue.IdleHandler {
1389 public final boolean queueIdle() {
1390 doGcIfNeeded();
1391 return false;
1392 }
1393 }
1394
Romain Guy65b345f2011-07-27 18:51:50 -07001395 private static class ResourcesKey {
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001396 final private String mResDir;
1397 final private float mScale;
1398 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07001399
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001400 ResourcesKey(String resDir, float scale) {
1401 mResDir = resDir;
1402 mScale = scale;
1403 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
1404 }
Bob Leee5408332009-09-04 18:31:17 -07001405
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001406 @Override
1407 public int hashCode() {
1408 return mHash;
1409 }
1410
1411 @Override
1412 public boolean equals(Object obj) {
1413 if (!(obj instanceof ResourcesKey)) {
1414 return false;
1415 }
1416 ResourcesKey peer = (ResourcesKey) obj;
1417 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
1418 }
1419 }
1420
Romain Guy65b345f2011-07-27 18:51:50 -07001421 public static ActivityThread currentActivityThread() {
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07001422 return sThreadLocal.get();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424
Romain Guy65b345f2011-07-27 18:51:50 -07001425 public static String currentPackageName() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001426 ActivityThread am = currentActivityThread();
1427 return (am != null && am.mBoundApplication != null)
1428 ? am.mBoundApplication.processName : null;
1429 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430
Romain Guy65b345f2011-07-27 18:51:50 -07001431 public static Application currentApplication() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001432 ActivityThread am = currentActivityThread();
1433 return am != null ? am.mInitialApplication : null;
1434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001436 public static IPackageManager getPackageManager() {
1437 if (sPackageManager != null) {
1438 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1439 return sPackageManager;
1440 }
1441 IBinder b = ServiceManager.getService("package");
1442 //Slog.v("PackageManager", "default service binder = " + b);
1443 sPackageManager = IPackageManager.Stub.asInterface(b);
1444 //Slog.v("PackageManager", "default service = " + sPackageManager);
1445 return sPackageManager;
1446 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001448 DisplayMetrics getDisplayMetricsLocked(CompatibilityInfo ci, boolean forceUpdate) {
1449 DisplayMetrics dm = mDisplayMetrics.get(ci);
1450 if (dm != null && !forceUpdate) {
1451 return dm;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001452 }
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001453 if (dm == null) {
1454 dm = new DisplayMetrics();
1455 mDisplayMetrics.put(ci, dm);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001456 }
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001457 Display d = WindowManagerImpl.getDefault(ci).getDefaultDisplay();
1458 d.getMetrics(dm);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001459 //Slog.i("foo", "New metrics: w=" + metrics.widthPixels + " h="
1460 // + metrics.heightPixels + " den=" + metrics.density
1461 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001462 return dm;
1463 }
1464
Romain Guy65b345f2011-07-27 18:51:50 -07001465 private Configuration mMainThreadConfig = new Configuration();
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001466 Configuration applyConfigCompatMainThread(Configuration config, CompatibilityInfo compat) {
1467 if (config == null) {
1468 return null;
1469 }
1470 if (compat != null && !compat.supportsScreen()) {
1471 mMainThreadConfig.setTo(config);
1472 config = mMainThreadConfig;
1473 compat.applyToConfiguration(config);
1474 }
1475 return config;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001476 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001478 /**
1479 * Creates the top level Resources for applications with the given compatibility info.
1480 *
1481 * @param resDir the resource directory.
1482 * @param compInfo the compability info. It will use the default compatibility info when it's
1483 * null.
1484 */
1485 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
1486 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
1487 Resources r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001489 // Resources is app scale dependent.
1490 if (false) {
1491 Slog.w(TAG, "getTopLevelResources: " + resDir + " / "
1492 + compInfo.applicationScale);
1493 }
1494 WeakReference<Resources> wr = mActiveResources.get(key);
1495 r = wr != null ? wr.get() : null;
1496 //if (r != null) Slog.i(TAG, "isUpToDate " + resDir + ": " + r.getAssets().isUpToDate());
1497 if (r != null && r.getAssets().isUpToDate()) {
1498 if (false) {
1499 Slog.w(TAG, "Returning cached resources " + r + " " + resDir
1500 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
1501 }
1502 return r;
1503 }
1504 }
1505
1506 //if (r != null) {
1507 // Slog.w(TAG, "Throwing away out-of-date resources!!!! "
1508 // + r + " " + resDir);
1509 //}
1510
1511 AssetManager assets = new AssetManager();
1512 if (assets.addAssetPath(resDir) == 0) {
1513 return null;
1514 }
1515
1516 //Slog.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
Dianne Hackborn836e2622011-10-04 18:32:39 -07001517 DisplayMetrics metrics = getDisplayMetricsLocked(null, false);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001518 r = new Resources(assets, metrics, getConfiguration(), compInfo);
1519 if (false) {
1520 Slog.i(TAG, "Created app resources " + resDir + " " + r + ": "
1521 + r.getConfiguration() + " appScale="
1522 + r.getCompatibilityInfo().applicationScale);
1523 }
1524
1525 synchronized (mPackages) {
1526 WeakReference<Resources> wr = mActiveResources.get(key);
1527 Resources existing = wr != null ? wr.get() : null;
1528 if (existing != null && existing.getAssets().isUpToDate()) {
1529 // Someone else already created the resources while we were
1530 // unlocked; go ahead and use theirs.
1531 r.getAssets().close();
1532 return existing;
1533 }
1534
1535 // XXX need to remove entries when weak references go away
1536 mActiveResources.put(key, new WeakReference<Resources>(r));
1537 return r;
1538 }
1539 }
1540
1541 /**
1542 * Creates the top level resources for the given package.
1543 */
1544 Resources getTopLevelResources(String resDir, LoadedApk pkgInfo) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001545 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo.get());
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001546 }
1547
1548 final Handler getHandler() {
1549 return mH;
1550 }
1551
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001552 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
1553 int flags) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001554 synchronized (mPackages) {
1555 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
1557 ref = mPackages.get(packageName);
1558 } else {
1559 ref = mResourcePackages.get(packageName);
1560 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001561 LoadedApk packageInfo = ref != null ? ref.get() : null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001562 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001563 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
1564 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 if (packageInfo != null && (packageInfo.mResources == null
1566 || packageInfo.mResources.getAssets().isUpToDate())) {
1567 if (packageInfo.isSecurityViolation()
1568 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
1569 throw new SecurityException(
1570 "Requesting code from " + packageName
1571 + " to be run in process "
1572 + mBoundApplication.processName
1573 + "/" + mBoundApplication.appInfo.uid);
1574 }
1575 return packageInfo;
1576 }
1577 }
1578
1579 ApplicationInfo ai = null;
1580 try {
1581 ai = getPackageManager().getApplicationInfo(packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07001582 PackageManager.GET_SHARED_LIBRARY_FILES, UserId.myUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 } catch (RemoteException e) {
Romain Guy65b345f2011-07-27 18:51:50 -07001584 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 }
1586
1587 if (ai != null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001588 return getPackageInfo(ai, compatInfo, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 }
1590
1591 return null;
1592 }
1593
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001594 public final LoadedApk getPackageInfo(ApplicationInfo ai, CompatibilityInfo compatInfo,
1595 int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
1597 boolean securityViolation = includeCode && ai.uid != 0
1598 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
Amith Yamasani742a6712011-05-04 14:49:28 -07001599 ? !UserId.isSameApp(ai.uid, mBoundApplication.appInfo.uid)
1600 : true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 if ((flags&(Context.CONTEXT_INCLUDE_CODE
1602 |Context.CONTEXT_IGNORE_SECURITY))
1603 == Context.CONTEXT_INCLUDE_CODE) {
1604 if (securityViolation) {
1605 String msg = "Requesting code from " + ai.packageName
1606 + " (with uid " + ai.uid + ")";
1607 if (mBoundApplication != null) {
1608 msg = msg + " to be run in process "
1609 + mBoundApplication.processName + " (with uid "
1610 + mBoundApplication.appInfo.uid + ")";
1611 }
1612 throw new SecurityException(msg);
1613 }
1614 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001615 return getPackageInfo(ai, compatInfo, null, securityViolation, includeCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616 }
1617
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001618 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai,
1619 CompatibilityInfo compatInfo) {
1620 return getPackageInfo(ai, compatInfo, null, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 }
1622
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001623 public final LoadedApk peekPackageInfo(String packageName, boolean includeCode) {
1624 synchronized (mPackages) {
1625 WeakReference<LoadedApk> ref;
1626 if (includeCode) {
1627 ref = mPackages.get(packageName);
1628 } else {
1629 ref = mResourcePackages.get(packageName);
1630 }
1631 return ref != null ? ref.get() : null;
1632 }
1633 }
1634
Romain Guy65b345f2011-07-27 18:51:50 -07001635 private LoadedApk getPackageInfo(ApplicationInfo aInfo, CompatibilityInfo compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
1637 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001638 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 if (includeCode) {
1640 ref = mPackages.get(aInfo.packageName);
1641 } else {
1642 ref = mResourcePackages.get(aInfo.packageName);
1643 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001644 LoadedApk packageInfo = ref != null ? ref.get() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 if (packageInfo == null || (packageInfo.mResources != null
1646 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001647 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 : "Loading resource-only package ") + aInfo.packageName
1649 + " (in " + (mBoundApplication != null
1650 ? mBoundApplication.processName : null)
1651 + ")");
1652 packageInfo =
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001653 new LoadedApk(this, aInfo, compatInfo, this, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 securityViolation, includeCode &&
1655 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
1656 if (includeCode) {
1657 mPackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001658 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 } else {
1660 mResourcePackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001661 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 }
1663 }
1664 return packageInfo;
1665 }
1666 }
1667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 ActivityThread() {
1669 }
1670
1671 public ApplicationThread getApplicationThread()
1672 {
1673 return mAppThread;
1674 }
1675
1676 public Instrumentation getInstrumentation()
1677 {
1678 return mInstrumentation;
1679 }
1680
1681 public Configuration getConfiguration() {
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001682 return mResConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 }
1684
1685 public boolean isProfiling() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001686 return mProfiler != null && mProfiler.profileFile != null
1687 && mProfiler.profileFd == null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 }
1689
1690 public String getProfileFilePath() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001691 return mProfiler.profileFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 }
1693
1694 public Looper getLooper() {
1695 return mLooper;
1696 }
1697
1698 public Application getApplication() {
1699 return mInitialApplication;
1700 }
Bob Leee5408332009-09-04 18:31:17 -07001701
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07001702 public String getProcessName() {
1703 return mBoundApplication.processName;
1704 }
Bob Leee5408332009-09-04 18:31:17 -07001705
Dianne Hackborn21556372010-02-04 16:34:40 -08001706 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 synchronized (this) {
1708 if (mSystemContext == null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001709 ContextImpl context =
1710 ContextImpl.createSystemContext(this);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001711 LoadedApk info = new LoadedApk(this, "android", context, null,
1712 CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 context.init(info, null, this);
1714 context.getResources().updateConfiguration(
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001715 getConfiguration(), getDisplayMetricsLocked(
1716 CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO, false));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 mSystemContext = context;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001718 //Slog.i(TAG, "Created system resources " + context.getResources()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 // + ": " + context.getResources().getConfiguration());
1720 }
1721 }
1722 return mSystemContext;
1723 }
1724
Mike Cleron432b7132009-09-24 15:28:29 -07001725 public void installSystemApplicationInfo(ApplicationInfo info) {
1726 synchronized (this) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001727 ContextImpl context = getSystemContext();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001728 context.init(new LoadedApk(this, "android", context, info,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001729 CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO), null, this);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001730
1731 // give ourselves a default profiler
1732 mProfiler = new Profiler();
Mike Cleron432b7132009-09-24 15:28:29 -07001733 }
1734 }
1735
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001736 void ensureJitEnabled() {
1737 if (!mJitEnabled) {
1738 mJitEnabled = true;
1739 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
1740 }
1741 }
1742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 void scheduleGcIdler() {
1744 if (!mGcIdlerScheduled) {
1745 mGcIdlerScheduled = true;
1746 Looper.myQueue().addIdleHandler(mGcIdler);
1747 }
1748 mH.removeMessages(H.GC_WHEN_IDLE);
1749 }
1750
1751 void unscheduleGcIdler() {
1752 if (mGcIdlerScheduled) {
1753 mGcIdlerScheduled = false;
1754 Looper.myQueue().removeIdleHandler(mGcIdler);
1755 }
1756 mH.removeMessages(H.GC_WHEN_IDLE);
1757 }
1758
1759 void doGcIfNeeded() {
1760 mGcIdlerScheduled = false;
1761 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001762 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763 // + "m now=" + now);
1764 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001765 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 BinderInternal.forceGc("bg");
1767 }
1768 }
1769
Jeff Hamilton52d32032011-01-08 15:31:26 -06001770 public void registerOnActivityPausedListener(Activity activity,
1771 OnActivityPausedListener listener) {
1772 synchronized (mOnPauseListeners) {
1773 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
1774 if (list == null) {
1775 list = new ArrayList<OnActivityPausedListener>();
1776 mOnPauseListeners.put(activity, list);
1777 }
1778 list.add(listener);
1779 }
1780 }
1781
Jeff Hamiltonce3224c2011-01-17 11:05:03 -08001782 public void unregisterOnActivityPausedListener(Activity activity,
1783 OnActivityPausedListener listener) {
1784 synchronized (mOnPauseListeners) {
1785 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
1786 if (list != null) {
1787 list.remove(listener);
1788 }
1789 }
1790 }
1791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 public final ActivityInfo resolveActivityInfo(Intent intent) {
1793 ActivityInfo aInfo = intent.resolveActivityInfo(
1794 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
1795 if (aInfo == null) {
1796 // Throw an exception.
1797 Instrumentation.checkStartActivityResult(
Dianne Hackborna4972e92012-03-14 10:38:05 -07001798 ActivityManager.START_CLASS_NOT_FOUND, intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001799 }
1800 return aInfo;
1801 }
Bob Leee5408332009-09-04 18:31:17 -07001802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001805 Activity.NonConfigurationInstances lastNonConfigurationInstances) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001806 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001808 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 r.intent = intent;
1810 r.state = state;
1811 r.parent = parent;
1812 r.embeddedID = id;
1813 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001814 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 if (localLOGV) {
1816 ComponentName compname = intent.getComponent();
1817 String name;
1818 if (compname != null) {
1819 name = compname.toShortString();
1820 } else {
1821 name = "(Intent " + intent + ").getComponent() returned null";
1822 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001823 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 + ", comp=" + name
1825 + ", token=" + token);
1826 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07001827 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 }
1829
1830 public final Activity getActivity(IBinder token) {
1831 return mActivities.get(token).activity;
1832 }
1833
1834 public final void sendActivityResult(
1835 IBinder token, String id, int requestCode,
1836 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001837 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07001838 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
1840 list.add(new ResultInfo(id, requestCode, resultCode, data));
1841 mAppThread.scheduleSendResult(token, list);
1842 }
1843
1844 // if the thread hasn't started yet, we don't have the handler, so just
1845 // save the messages until we're ready.
Romain Guy65b345f2011-07-27 18:51:50 -07001846 private void queueOrSendMessage(int what, Object obj) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001847 queueOrSendMessage(what, obj, 0, 0);
1848 }
1849
Romain Guy65b345f2011-07-27 18:51:50 -07001850 private void queueOrSendMessage(int what, Object obj, int arg1) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001851 queueOrSendMessage(what, obj, arg1, 0);
1852 }
1853
Romain Guy65b345f2011-07-27 18:51:50 -07001854 private void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 synchronized (this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001856 if (DEBUG_MESSAGES) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
1858 + ": " + arg1 + " / " + obj);
1859 Message msg = Message.obtain();
1860 msg.what = what;
1861 msg.obj = obj;
1862 msg.arg1 = arg1;
1863 msg.arg2 = arg2;
1864 mH.sendMessage(msg);
1865 }
1866 }
1867
Dianne Hackborn21556372010-02-04 16:34:40 -08001868 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 String what) {
1870 ContextCleanupInfo cci = new ContextCleanupInfo();
1871 cci.context = context;
1872 cci.who = who;
1873 cci.what = what;
1874 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
1875 }
1876
Romain Guy65b345f2011-07-27 18:51:50 -07001877 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
1879
1880 ActivityInfo aInfo = r.activityInfo;
1881 if (r.packageInfo == null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001882 r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 Context.CONTEXT_INCLUDE_CODE);
1884 }
Bob Leee5408332009-09-04 18:31:17 -07001885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 ComponentName component = r.intent.getComponent();
1887 if (component == null) {
1888 component = r.intent.resolveActivity(
1889 mInitialApplication.getPackageManager());
1890 r.intent.setComponent(component);
1891 }
1892
1893 if (r.activityInfo.targetActivity != null) {
1894 component = new ComponentName(r.activityInfo.packageName,
1895 r.activityInfo.targetActivity);
1896 }
1897
1898 Activity activity = null;
1899 try {
1900 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
1901 activity = mInstrumentation.newActivity(
1902 cl, component.getClassName(), r.intent);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08001903 StrictMode.incrementExpectedActivityCount(activity.getClass());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 r.intent.setExtrasClassLoader(cl);
1905 if (r.state != null) {
1906 r.state.setClassLoader(cl);
1907 }
1908 } catch (Exception e) {
1909 if (!mInstrumentation.onException(activity, e)) {
1910 throw new RuntimeException(
1911 "Unable to instantiate activity " + component
1912 + ": " + e.toString(), e);
1913 }
1914 }
1915
1916 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001917 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001918
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001919 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
1920 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 TAG, r + ": app=" + app
1922 + ", appName=" + app.getPackageName()
1923 + ", pkg=" + r.packageInfo.getPackageName()
1924 + ", comp=" + r.intent.getComponent().toShortString()
1925 + ", dir=" + r.packageInfo.getAppDir());
1926
1927 if (activity != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001928 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 appContext.init(r.packageInfo, r.token, this);
1930 appContext.setOuterContext(activity);
1931 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001932 Configuration config = new Configuration(mCompatConfiguration);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001933 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07001934 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001935 activity.attach(appContext, this, getInstrumentation(), r.token,
1936 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001937 r.embeddedID, r.lastNonConfigurationInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07001938
Christopher Tateb70f3df2009-04-07 16:07:59 -07001939 if (customIntent != null) {
1940 activity.mIntent = customIntent;
1941 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001942 r.lastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 activity.mStartedActivity = false;
1944 int theme = r.activityInfo.getThemeResource();
1945 if (theme != 0) {
1946 activity.setTheme(theme);
1947 }
1948
1949 activity.mCalled = false;
1950 mInstrumentation.callActivityOnCreate(activity, r.state);
1951 if (!activity.mCalled) {
1952 throw new SuperNotCalledException(
1953 "Activity " + r.intent.getComponent().toShortString() +
1954 " did not call through to super.onCreate()");
1955 }
1956 r.activity = activity;
1957 r.stopped = true;
1958 if (!r.activity.mFinished) {
1959 activity.performStart();
1960 r.stopped = false;
1961 }
1962 if (!r.activity.mFinished) {
1963 if (r.state != null) {
1964 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
1965 }
1966 }
1967 if (!r.activity.mFinished) {
1968 activity.mCalled = false;
1969 mInstrumentation.callActivityOnPostCreate(activity, r.state);
1970 if (!activity.mCalled) {
1971 throw new SuperNotCalledException(
1972 "Activity " + r.intent.getComponent().toShortString() +
1973 " did not call through to super.onPostCreate()");
1974 }
1975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 }
1977 r.paused = true;
1978
1979 mActivities.put(r.token, r);
1980
1981 } catch (SuperNotCalledException e) {
1982 throw e;
1983
1984 } catch (Exception e) {
1985 if (!mInstrumentation.onException(activity, e)) {
1986 throw new RuntimeException(
1987 "Unable to start activity " + component
1988 + ": " + e.toString(), e);
1989 }
1990 }
1991
1992 return activity;
1993 }
1994
Romain Guy65b345f2011-07-27 18:51:50 -07001995 private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 // If we are getting ready to gc after going to the background, well
1997 // we are back active so skip it.
1998 unscheduleGcIdler();
1999
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002000 if (r.profileFd != null) {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002001 mProfiler.setProfiler(r.profileFile, r.profileFd);
2002 mProfiler.startProfiling();
2003 mProfiler.autoStopProfiler = r.autoStopProfiler;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002004 }
2005
Dianne Hackborn58f42a52011-10-10 13:46:34 -07002006 // Make sure we are running with the most recent config.
2007 handleConfigurationChanged(null, null);
2008
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002009 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07002011 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012
2013 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002014 r.createdConfig = new Configuration(mConfiguration);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08002015 Bundle oldState = r.state;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 handleResumeActivity(r.token, false, r.isForward);
2017
2018 if (!r.activity.mFinished && r.startsNotResumed) {
2019 // The activity manager actually wants this one to start out
2020 // paused, because it needs to be visible but isn't in the
2021 // foreground. We accomplish this by going through the
2022 // normal startup (because activities expect to go through
2023 // onResume() the first time they run, before their window
2024 // is displayed), and then pausing it. However, in this case
2025 // we do -not- need to do the full pause cycle (of freezing
2026 // and such) because the activity manager assumes it can just
2027 // retain the current state it has.
2028 try {
2029 r.activity.mCalled = false;
2030 mInstrumentation.callActivityOnPause(r.activity);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08002031 // We need to keep around the original state, in case
2032 // we need to be created again.
2033 r.state = oldState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 if (!r.activity.mCalled) {
2035 throw new SuperNotCalledException(
2036 "Activity " + r.intent.getComponent().toShortString() +
2037 " did not call through to super.onPause()");
2038 }
2039
2040 } catch (SuperNotCalledException e) {
2041 throw e;
2042
2043 } catch (Exception e) {
2044 if (!mInstrumentation.onException(r.activity, e)) {
2045 throw new RuntimeException(
2046 "Unable to pause activity "
2047 + r.intent.getComponent().toShortString()
2048 + ": " + e.toString(), e);
2049 }
2050 }
2051 r.paused = true;
2052 }
2053 } else {
2054 // If there was an error, for any reason, tell the activity
2055 // manager to stop us.
2056 try {
2057 ActivityManagerNative.getDefault()
2058 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
2059 } catch (RemoteException ex) {
Romain Guy65b345f2011-07-27 18:51:50 -07002060 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061 }
2062 }
2063 }
2064
Romain Guy65b345f2011-07-27 18:51:50 -07002065 private void deliverNewIntents(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 List<Intent> intents) {
2067 final int N = intents.size();
2068 for (int i=0; i<N; i++) {
2069 Intent intent = intents.get(i);
2070 intent.setExtrasClassLoader(r.activity.getClassLoader());
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002071 r.activity.mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
2073 }
2074 }
2075
2076 public final void performNewIntents(IBinder token,
2077 List<Intent> intents) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002078 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 if (r != null) {
2080 final boolean resumed = !r.paused;
2081 if (resumed) {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002082 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 mInstrumentation.callActivityOnPause(r.activity);
2084 }
2085 deliverNewIntents(r, intents);
2086 if (resumed) {
Dianne Hackbornb46ed762011-06-02 18:33:15 -07002087 r.activity.performResume();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002088 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 }
2090 }
2091 }
Bob Leee5408332009-09-04 18:31:17 -07002092
Romain Guy65b345f2011-07-27 18:51:50 -07002093 private void handleNewIntent(NewIntentData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002094 performNewIntents(data.token, data.intents);
2095 }
2096
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002097 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
2098
2099 /**
2100 * Return the Intent that's currently being handled by a
2101 * BroadcastReceiver on this thread, or null if none.
2102 * @hide
2103 */
2104 public static Intent getIntentBeingBroadcast() {
2105 return sCurrentBroadcastIntent.get();
2106 }
2107
Romain Guy65b345f2011-07-27 18:51:50 -07002108 private void handleReceiver(ReceiverData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109 // If we are getting ready to gc after going to the background, well
2110 // we are back active so skip it.
2111 unscheduleGcIdler();
2112
2113 String component = data.intent.getComponent().getClassName();
2114
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002115 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002116 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117
2118 IActivityManager mgr = ActivityManagerNative.getDefault();
2119
Romain Guy65b345f2011-07-27 18:51:50 -07002120 BroadcastReceiver receiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121 try {
2122 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2123 data.intent.setExtrasClassLoader(cl);
Dianne Hackborne829fef2010-10-26 17:44:01 -07002124 data.setExtrasClassLoader(cl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002125 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
2126 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07002127 if (DEBUG_BROADCAST) Slog.i(TAG,
2128 "Finishing failed broadcast to " + data.intent.getComponent());
2129 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 throw new RuntimeException(
2131 "Unable to instantiate receiver " + component
2132 + ": " + e.toString(), e);
2133 }
2134
2135 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08002136 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07002137
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002138 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139 TAG, "Performing receive of " + data.intent
2140 + ": app=" + app
2141 + ", appName=" + app.getPackageName()
2142 + ", pkg=" + packageInfo.getPackageName()
2143 + ", comp=" + data.intent.getComponent().toShortString()
2144 + ", dir=" + packageInfo.getAppDir());
2145
Dianne Hackborn21556372010-02-04 16:34:40 -08002146 ContextImpl context = (ContextImpl)app.getBaseContext();
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002147 sCurrentBroadcastIntent.set(data.intent);
Dianne Hackborne829fef2010-10-26 17:44:01 -07002148 receiver.setPendingResult(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149 receiver.onReceive(context.getReceiverRestrictedContext(),
2150 data.intent);
2151 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07002152 if (DEBUG_BROADCAST) Slog.i(TAG,
2153 "Finishing failed broadcast to " + data.intent.getComponent());
2154 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002155 if (!mInstrumentation.onException(receiver, e)) {
2156 throw new RuntimeException(
2157 "Unable to start receiver " + component
2158 + ": " + e.toString(), e);
2159 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002160 } finally {
2161 sCurrentBroadcastIntent.set(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002162 }
2163
Dianne Hackborne829fef2010-10-26 17:44:01 -07002164 if (receiver.getPendingResult() != null) {
2165 data.finish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002166 }
2167 }
2168
Christopher Tate181fafa2009-05-14 11:12:14 -07002169 // Instantiate a BackupAgent and tell it that it's alive
Romain Guy65b345f2011-07-27 18:51:50 -07002170 private void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002171 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07002172
2173 // no longer idle; we have backup work to do
2174 unscheduleGcIdler();
2175
2176 // instantiate the BackupAgent class named in the manifest
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002177 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07002178 String packageName = packageInfo.mPackageName;
2179 if (mBackupAgents.get(packageName) != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002180 Slog.d(TAG, "BackupAgent " + " for " + packageName
Christopher Tate181fafa2009-05-14 11:12:14 -07002181 + " already exists");
2182 return;
2183 }
Bob Leee5408332009-09-04 18:31:17 -07002184
Christopher Tate181fafa2009-05-14 11:12:14 -07002185 BackupAgent agent = null;
2186 String classname = data.appInfo.backupAgentName;
Christopher Tate4a627c72011-04-01 14:43:32 -07002187
Christopher Tate79ec80d2011-06-24 14:58:49 -07002188 // full backup operation but no app-supplied agent? use the default implementation
2189 if (classname == null && (data.backupMode == IApplicationThread.BACKUP_MODE_FULL
2190 || data.backupMode == IApplicationThread.BACKUP_MODE_RESTORE_FULL)) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002191 classname = "android.app.backup.FullBackupAgent";
Christopher Tate181fafa2009-05-14 11:12:14 -07002192 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002193
Christopher Tate181fafa2009-05-14 11:12:14 -07002194 try {
Christopher Tated1475e02009-07-09 15:36:17 -07002195 IBinder binder = null;
2196 try {
Christopher Tate4a627c72011-04-01 14:43:32 -07002197 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing agent class " + classname);
2198
Christopher Tated1475e02009-07-09 15:36:17 -07002199 java.lang.ClassLoader cl = packageInfo.getClassLoader();
Christopher Tate4a627c72011-04-01 14:43:32 -07002200 agent = (BackupAgent) cl.loadClass(classname).newInstance();
Christopher Tated1475e02009-07-09 15:36:17 -07002201
2202 // set up the agent's context
Dianne Hackborn21556372010-02-04 16:34:40 -08002203 ContextImpl context = new ContextImpl();
Christopher Tated1475e02009-07-09 15:36:17 -07002204 context.init(packageInfo, null, this);
2205 context.setOuterContext(agent);
2206 agent.attach(context);
2207
2208 agent.onCreate();
2209 binder = agent.onBind();
2210 mBackupAgents.put(packageName, agent);
2211 } catch (Exception e) {
2212 // If this is during restore, fail silently; otherwise go
2213 // ahead and let the user see the crash.
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002214 Slog.e(TAG, "Agent threw during creation: " + e);
Christopher Tate75a99702011-05-18 16:28:19 -07002215 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE
2216 && data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE_FULL) {
Christopher Tated1475e02009-07-09 15:36:17 -07002217 throw e;
2218 }
2219 // falling through with 'binder' still null
2220 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002221
2222 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07002223 try {
2224 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
2225 } catch (RemoteException e) {
2226 // nothing to do.
2227 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002228 } catch (Exception e) {
2229 throw new RuntimeException("Unable to create BackupAgent "
Christopher Tate4a627c72011-04-01 14:43:32 -07002230 + classname + ": " + e.toString(), e);
Christopher Tate181fafa2009-05-14 11:12:14 -07002231 }
2232 }
2233
2234 // Tear down a BackupAgent
Romain Guy65b345f2011-07-27 18:51:50 -07002235 private void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002236 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07002237
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002238 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07002239 String packageName = packageInfo.mPackageName;
2240 BackupAgent agent = mBackupAgents.get(packageName);
2241 if (agent != null) {
2242 try {
2243 agent.onDestroy();
2244 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002245 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07002246 e.printStackTrace();
2247 }
2248 mBackupAgents.remove(packageName);
2249 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002250 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07002251 }
2252 }
2253
Romain Guy65b345f2011-07-27 18:51:50 -07002254 private void handleCreateService(CreateServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002255 // If we are getting ready to gc after going to the background, well
2256 // we are back active so skip it.
2257 unscheduleGcIdler();
2258
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002259 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002260 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 Service service = null;
2262 try {
2263 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2264 service = (Service) cl.loadClass(data.info.name).newInstance();
2265 } catch (Exception e) {
2266 if (!mInstrumentation.onException(service, e)) {
2267 throw new RuntimeException(
2268 "Unable to instantiate service " + data.info.name
2269 + ": " + e.toString(), e);
2270 }
2271 }
2272
2273 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002274 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002275
Dianne Hackborn21556372010-02-04 16:34:40 -08002276 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002277 context.init(packageInfo, null, this);
2278
Dianne Hackborn0be1f782009-11-09 12:30:12 -08002279 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002280 context.setOuterContext(service);
2281 service.attach(context, this, data.info.name, data.token, app,
2282 ActivityManagerNative.getDefault());
2283 service.onCreate();
2284 mServices.put(data.token, service);
2285 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002286 ActivityManagerNative.getDefault().serviceDoneExecuting(
2287 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002288 } catch (RemoteException e) {
2289 // nothing to do.
2290 }
2291 } catch (Exception e) {
2292 if (!mInstrumentation.onException(service, e)) {
2293 throw new RuntimeException(
2294 "Unable to create service " + data.info.name
2295 + ": " + e.toString(), e);
2296 }
2297 }
2298 }
2299
Romain Guy65b345f2011-07-27 18:51:50 -07002300 private void handleBindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002301 Service s = mServices.get(data.token);
Amith Yamasani742a6712011-05-04 14:49:28 -07002302 if (DEBUG_SERVICE)
2303 Slog.v(TAG, "handleBindService s=" + s + " rebind=" + data.rebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002304 if (s != null) {
2305 try {
2306 data.intent.setExtrasClassLoader(s.getClassLoader());
2307 try {
2308 if (!data.rebind) {
2309 IBinder binder = s.onBind(data.intent);
2310 ActivityManagerNative.getDefault().publishService(
2311 data.token, data.intent, binder);
2312 } else {
2313 s.onRebind(data.intent);
2314 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002315 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002316 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002317 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 } catch (RemoteException ex) {
2319 }
2320 } catch (Exception e) {
2321 if (!mInstrumentation.onException(s, e)) {
2322 throw new RuntimeException(
2323 "Unable to bind to service " + s
2324 + " with " + data.intent + ": " + e.toString(), e);
2325 }
2326 }
2327 }
2328 }
2329
Romain Guy65b345f2011-07-27 18:51:50 -07002330 private void handleUnbindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002331 Service s = mServices.get(data.token);
2332 if (s != null) {
2333 try {
2334 data.intent.setExtrasClassLoader(s.getClassLoader());
2335 boolean doRebind = s.onUnbind(data.intent);
2336 try {
2337 if (doRebind) {
2338 ActivityManagerNative.getDefault().unbindFinished(
2339 data.token, data.intent, doRebind);
2340 } else {
2341 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002342 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002343 }
2344 } catch (RemoteException ex) {
2345 }
2346 } catch (Exception e) {
2347 if (!mInstrumentation.onException(s, e)) {
2348 throw new RuntimeException(
2349 "Unable to unbind to service " + s
2350 + " with " + data.intent + ": " + e.toString(), e);
2351 }
2352 }
2353 }
2354 }
2355
Dianne Hackborn625ac272010-09-17 18:29:22 -07002356 private void handleDumpService(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08002357 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
2358 try {
2359 Service s = mServices.get(info.token);
2360 if (s != null) {
2361 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
2362 s.dump(info.fd.getFileDescriptor(), pw, info.args);
2363 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08002365 } finally {
2366 IoUtils.closeQuietly(info.fd);
2367 StrictMode.setThreadPolicy(oldPolicy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 }
2369 }
2370
Dianne Hackborn625ac272010-09-17 18:29:22 -07002371 private void handleDumpActivity(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08002372 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
2373 try {
2374 ActivityClientRecord r = mActivities.get(info.token);
2375 if (r != null && r.activity != null) {
2376 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
2377 r.activity.dump(info.prefix, info.fd.getFileDescriptor(), pw, info.args);
2378 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07002379 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08002380 } finally {
2381 IoUtils.closeQuietly(info.fd);
2382 StrictMode.setThreadPolicy(oldPolicy);
Dianne Hackborn625ac272010-09-17 18:29:22 -07002383 }
2384 }
2385
Marco Nelissen18cb2872011-11-15 11:19:53 -08002386 private void handleDumpProvider(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08002387 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
2388 try {
2389 ProviderClientRecord r = mLocalProviders.get(info.token);
2390 if (r != null && r.mLocalProvider != null) {
2391 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
2392 r.mLocalProvider.dump(info.fd.getFileDescriptor(), pw, info.args);
2393 pw.flush();
Marco Nelissen18cb2872011-11-15 11:19:53 -08002394 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08002395 } finally {
2396 IoUtils.closeQuietly(info.fd);
2397 StrictMode.setThreadPolicy(oldPolicy);
Marco Nelissen18cb2872011-11-15 11:19:53 -08002398 }
2399 }
2400
Romain Guy65b345f2011-07-27 18:51:50 -07002401 private void handleServiceArgs(ServiceArgsData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002402 Service s = mServices.get(data.token);
2403 if (s != null) {
2404 try {
2405 if (data.args != null) {
2406 data.args.setExtrasClassLoader(s.getClassLoader());
2407 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002408 int res;
2409 if (!data.taskRemoved) {
2410 res = s.onStartCommand(data.args, data.flags, data.startId);
2411 } else {
2412 s.onTaskRemoved(data.args);
2413 res = Service.START_TASK_REMOVED_COMPLETE;
2414 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002415
2416 QueuedWork.waitToFinish();
2417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002419 ActivityManagerNative.getDefault().serviceDoneExecuting(
2420 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002421 } catch (RemoteException e) {
2422 // nothing to do.
2423 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002424 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002425 } catch (Exception e) {
2426 if (!mInstrumentation.onException(s, e)) {
2427 throw new RuntimeException(
2428 "Unable to start service " + s
2429 + " with " + data.args + ": " + e.toString(), e);
2430 }
2431 }
2432 }
2433 }
2434
Romain Guy65b345f2011-07-27 18:51:50 -07002435 private void handleStopService(IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002436 Service s = mServices.remove(token);
2437 if (s != null) {
2438 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002439 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002440 s.onDestroy();
2441 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002442 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08002444 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002445 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002446
2447 QueuedWork.waitToFinish();
2448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002449 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002450 ActivityManagerNative.getDefault().serviceDoneExecuting(
2451 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002452 } catch (RemoteException e) {
2453 // nothing to do.
2454 }
2455 } catch (Exception e) {
2456 if (!mInstrumentation.onException(s, e)) {
2457 throw new RuntimeException(
2458 "Unable to stop service " + s
2459 + ": " + e.toString(), e);
2460 }
2461 }
2462 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002463 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002464 }
2465
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002466 public final ActivityClientRecord performResumeActivity(IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002467 boolean clearHide) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002468 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002469 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002470 + " finished=" + r.activity.mFinished);
2471 if (r != null && !r.activity.mFinished) {
2472 if (clearHide) {
2473 r.hideForNow = false;
2474 r.activity.mStartedActivity = false;
2475 }
2476 try {
2477 if (r.pendingIntents != null) {
2478 deliverNewIntents(r, r.pendingIntents);
2479 r.pendingIntents = null;
2480 }
2481 if (r.pendingResults != null) {
2482 deliverResults(r, r.pendingResults);
2483 r.pendingResults = null;
2484 }
2485 r.activity.performResume();
2486
Bob Leee5408332009-09-04 18:31:17 -07002487 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490 r.paused = false;
2491 r.stopped = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 r.state = null;
2493 } catch (Exception e) {
2494 if (!mInstrumentation.onException(r.activity, e)) {
2495 throw new RuntimeException(
2496 "Unable to resume activity "
2497 + r.intent.getComponent().toShortString()
2498 + ": " + e.toString(), e);
2499 }
2500 }
2501 }
2502 return r;
2503 }
2504
Romain Guya998dff2012-03-23 18:58:36 -07002505 static final void cleanUpPendingRemoveWindows(ActivityClientRecord r) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002506 if (r.mPendingRemoveWindow != null) {
2507 r.mPendingRemoveWindowManager.removeViewImmediate(r.mPendingRemoveWindow);
2508 IBinder wtoken = r.mPendingRemoveWindow.getWindowToken();
2509 if (wtoken != null) {
2510 WindowManagerImpl.getDefault().closeAll(wtoken,
2511 r.activity.getClass().getName(), "Activity");
2512 }
2513 }
2514 r.mPendingRemoveWindow = null;
2515 r.mPendingRemoveWindowManager = null;
2516 }
2517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2519 // If we are getting ready to gc after going to the background, well
2520 // we are back active so skip it.
2521 unscheduleGcIdler();
2522
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002523 ActivityClientRecord r = performResumeActivity(token, clearHide);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524
2525 if (r != null) {
2526 final Activity a = r.activity;
2527
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002528 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 TAG, "Resume " + r + " started activity: " +
2530 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2531 + ", finished: " + a.mFinished);
2532
2533 final int forwardBit = isForward ?
2534 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 // If the window hasn't yet been added to the window manager,
2537 // and this guy didn't finish itself or start another activity,
2538 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002539 boolean willBeVisible = !a.mStartedActivity;
2540 if (!willBeVisible) {
2541 try {
2542 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
2543 a.getActivityToken());
2544 } catch (RemoteException e) {
2545 }
2546 }
2547 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002548 r.window = r.activity.getWindow();
2549 View decor = r.window.getDecorView();
2550 decor.setVisibility(View.INVISIBLE);
2551 ViewManager wm = a.getWindowManager();
2552 WindowManager.LayoutParams l = r.window.getAttributes();
2553 a.mDecor = decor;
2554 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2555 l.softInputMode |= forwardBit;
2556 if (a.mVisibleFromClient) {
2557 a.mWindowAdded = true;
2558 wm.addView(decor, l);
2559 }
2560
2561 // If the window has already been added, but during resume
2562 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002563 // window visible.
2564 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002565 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 TAG, "Launch " + r + " mStartedActivity set");
2567 r.hideForNow = true;
2568 }
2569
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002570 // Get rid of anything left hanging around.
2571 cleanUpPendingRemoveWindows(r);
2572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 // The window is now visible if it has been added, we are not
2574 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002575 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002576 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002578 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002579 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 performConfigurationChanged(r.activity, r.newConfig);
2581 r.newConfig = null;
2582 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002583 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 + isForward);
2585 WindowManager.LayoutParams l = r.window.getAttributes();
2586 if ((l.softInputMode
2587 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2588 != forwardBit) {
2589 l.softInputMode = (l.softInputMode
2590 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2591 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002592 if (r.activity.mVisibleFromClient) {
2593 ViewManager wm = a.getWindowManager();
2594 View decor = r.window.getDecorView();
2595 wm.updateViewLayout(decor, l);
2596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002597 }
2598 r.activity.mVisibleFromServer = true;
2599 mNumVisibleActivities++;
2600 if (r.activity.mVisibleFromClient) {
2601 r.activity.makeVisible();
2602 }
2603 }
2604
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002605 if (!r.onlyLocalRequest) {
2606 r.nextIdle = mNewActivities;
2607 mNewActivities = r;
2608 if (localLOGV) Slog.v(
2609 TAG, "Scheduling idle handler for " + r);
2610 Looper.myQueue().addIdleHandler(new Idler());
2611 }
2612 r.onlyLocalRequest = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002613
2614 } else {
2615 // If an exception was thrown when trying to resume, then
2616 // just end this activity.
2617 try {
2618 ActivityManagerNative.getDefault()
2619 .finishActivity(token, Activity.RESULT_CANCELED, null);
2620 } catch (RemoteException ex) {
2621 }
2622 }
2623 }
2624
2625 private int mThumbnailWidth = -1;
2626 private int mThumbnailHeight = -1;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002627 private Bitmap mAvailThumbnailBitmap = null;
2628 private Canvas mThumbnailCanvas = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629
Romain Guy65b345f2011-07-27 18:51:50 -07002630 private Bitmap createThumbnailBitmap(ActivityClientRecord r) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002631 Bitmap thumbnail = mAvailThumbnailBitmap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002632 try {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002633 if (thumbnail == null) {
2634 int w = mThumbnailWidth;
2635 int h;
2636 if (w < 0) {
2637 Resources res = r.activity.getResources();
2638 mThumbnailHeight = h =
2639 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002641 mThumbnailWidth = w =
2642 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
2643 } else {
2644 h = mThumbnailHeight;
2645 }
2646
2647 // On platforms where we don't want thumbnails, set dims to (0,0)
2648 if ((w > 0) && (h > 0)) {
2649 thumbnail = Bitmap.createBitmap(w, h, THUMBNAIL_FORMAT);
2650 thumbnail.eraseColor(0);
2651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002652 }
2653
Dianne Hackbornfb3806d2010-12-09 13:14:12 -08002654 if (thumbnail != null) {
2655 Canvas cv = mThumbnailCanvas;
2656 if (cv == null) {
2657 mThumbnailCanvas = cv = new Canvas();
2658 }
2659
2660 cv.setBitmap(thumbnail);
2661 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
2662 mAvailThumbnailBitmap = thumbnail;
2663 thumbnail = null;
2664 }
Dianne Hackborn6311d0a2011-08-02 16:37:58 -07002665 cv.setBitmap(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 }
Jim Miller0b2a6d02010-07-13 18:01:29 -07002667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002668 } catch (Exception e) {
2669 if (!mInstrumentation.onException(r.activity, e)) {
2670 throw new RuntimeException(
2671 "Unable to create thumbnail of "
2672 + r.intent.getComponent().toShortString()
2673 + ": " + e.toString(), e);
2674 }
2675 thumbnail = null;
2676 }
2677
2678 return thumbnail;
2679 }
2680
Romain Guy65b345f2011-07-27 18:51:50 -07002681 private void handlePauseActivity(IBinder token, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 boolean userLeaving, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002683 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002685 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 if (userLeaving) {
2687 performUserLeavingActivity(r);
2688 }
Bob Leee5408332009-09-04 18:31:17 -07002689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 r.activity.mConfigChangeFlags |= configChanges;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002691 performPauseActivity(token, finished, r.isPreHoneycomb());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07002693 // Make sure any pending writes are now committed.
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002694 if (r.isPreHoneycomb()) {
2695 QueuedWork.waitToFinish();
2696 }
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07002697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 // Tell the activity manager we have paused.
2699 try {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002700 ActivityManagerNative.getDefault().activityPaused(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002701 } catch (RemoteException ex) {
2702 }
2703 }
2704 }
2705
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002706 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002707 mInstrumentation.callActivityOnUserLeaving(r.activity);
2708 }
2709
2710 final Bundle performPauseActivity(IBinder token, boolean finished,
2711 boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002712 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002713 return r != null ? performPauseActivity(r, finished, saveState) : null;
2714 }
2715
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002716 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002717 boolean saveState) {
2718 if (r.paused) {
2719 if (r.activity.mFinished) {
2720 // If we are finishing, we won't call onResume() in certain cases.
2721 // So here we likewise don't want to call onPause() if the activity
2722 // isn't resumed.
2723 return null;
2724 }
2725 RuntimeException e = new RuntimeException(
2726 "Performing pause of activity that is not resumed: "
2727 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002728 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 }
2730 Bundle state = null;
2731 if (finished) {
2732 r.activity.mFinished = true;
2733 }
2734 try {
2735 // Next have the activity save its current state and managed dialogs...
2736 if (!r.activity.mFinished && saveState) {
2737 state = new Bundle();
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04002738 state.setAllowFds(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002739 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2740 r.state = state;
2741 }
2742 // Now we are idle.
2743 r.activity.mCalled = false;
2744 mInstrumentation.callActivityOnPause(r.activity);
2745 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
2746 if (!r.activity.mCalled) {
2747 throw new SuperNotCalledException(
2748 "Activity " + r.intent.getComponent().toShortString() +
2749 " did not call through to super.onPause()");
2750 }
2751
2752 } catch (SuperNotCalledException e) {
2753 throw e;
2754
2755 } catch (Exception e) {
2756 if (!mInstrumentation.onException(r.activity, e)) {
2757 throw new RuntimeException(
2758 "Unable to pause activity "
2759 + r.intent.getComponent().toShortString()
2760 + ": " + e.toString(), e);
2761 }
2762 }
2763 r.paused = true;
Jeff Hamilton52d32032011-01-08 15:31:26 -06002764
2765 // Notify any outstanding on paused listeners
2766 ArrayList<OnActivityPausedListener> listeners;
2767 synchronized (mOnPauseListeners) {
2768 listeners = mOnPauseListeners.remove(r.activity);
2769 }
2770 int size = (listeners != null ? listeners.size() : 0);
2771 for (int i = 0; i < size; i++) {
2772 listeners.get(i).onPaused(r.activity);
2773 }
2774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775 return state;
2776 }
2777
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002778 final void performStopActivity(IBinder token, boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002779 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002780 performStopActivityInner(r, null, false, saveState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781 }
2782
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07002783 private static class StopInfo implements Runnable {
2784 ActivityClientRecord activity;
2785 Bundle state;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 Bitmap thumbnail;
2787 CharSequence description;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07002788
2789 @Override public void run() {
2790 // Tell activity manager we have been stopped.
2791 try {
2792 if (DEBUG_MEMORY_TRIM) Slog.v(TAG, "Reporting activity stopped: " + activity);
2793 ActivityManagerNative.getDefault().activityStopped(
2794 activity.token, state, thumbnail, description);
2795 } catch (RemoteException ex) {
2796 }
2797 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002798 }
2799
Jeff Brownddaa9ac2011-11-11 20:16:14 -08002800 private static final class ProviderRefCount {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002801 public int count;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08002802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803 ProviderRefCount(int pCount) {
2804 count = pCount;
2805 }
2806 }
2807
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002808 /**
2809 * Core implementation of stopping an activity. Note this is a little
2810 * tricky because the server's meaning of stop is slightly different
2811 * than our client -- for the server, stop means to save state and give
2812 * it the result when it is done, but the window may still be visible.
2813 * For the client, we want to call onStop()/onStart() to indicate when
2814 * the activity's UI visibillity changes.
2815 */
Romain Guy65b345f2011-07-27 18:51:50 -07002816 private void performStopActivityInner(ActivityClientRecord r,
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002817 StopInfo info, boolean keepShown, boolean saveState) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002818 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002819 Bundle state = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820 if (r != null) {
2821 if (!keepShown && r.stopped) {
2822 if (r.activity.mFinished) {
2823 // If we are finishing, we won't call onResume() in certain
2824 // cases. So here we likewise don't want to call onStop()
2825 // if the activity isn't resumed.
2826 return;
2827 }
2828 RuntimeException e = new RuntimeException(
2829 "Performing stop of activity that is not resumed: "
2830 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002831 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 }
2833
2834 if (info != null) {
2835 try {
2836 // First create a thumbnail for the activity...
Dianne Hackborn0500b3c2011-11-01 15:28:43 -07002837 // For now, don't create the thumbnail here; we are
2838 // doing that by doing a screen snapshot.
2839 info.thumbnail = null; //createThumbnailBitmap(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840 info.description = r.activity.onCreateDescription();
2841 } catch (Exception e) {
2842 if (!mInstrumentation.onException(r.activity, e)) {
2843 throw new RuntimeException(
2844 "Unable to save state of activity "
2845 + r.intent.getComponent().toShortString()
2846 + ": " + e.toString(), e);
2847 }
2848 }
2849 }
2850
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002851 // Next have the activity save its current state and managed dialogs...
2852 if (!r.activity.mFinished && saveState) {
2853 if (r.state == null) {
2854 state = new Bundle();
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04002855 state.setAllowFds(false);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002856 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2857 r.state = state;
2858 } else {
2859 state = r.state;
2860 }
2861 }
2862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 if (!keepShown) {
2864 try {
2865 // Now we are idle.
2866 r.activity.performStop();
2867 } catch (Exception e) {
2868 if (!mInstrumentation.onException(r.activity, e)) {
2869 throw new RuntimeException(
2870 "Unable to stop activity "
2871 + r.intent.getComponent().toShortString()
2872 + ": " + e.toString(), e);
2873 }
2874 }
2875 r.stopped = true;
2876 }
2877
2878 r.paused = true;
2879 }
2880 }
2881
Romain Guy65b345f2011-07-27 18:51:50 -07002882 private void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883 View v = r.activity.mDecor;
2884 if (v != null) {
2885 if (show) {
2886 if (!r.activity.mVisibleFromServer) {
2887 r.activity.mVisibleFromServer = true;
2888 mNumVisibleActivities++;
2889 if (r.activity.mVisibleFromClient) {
2890 r.activity.makeVisible();
2891 }
2892 }
2893 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002894 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002895 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002896 performConfigurationChanged(r.activity, r.newConfig);
2897 r.newConfig = null;
2898 }
2899 } else {
2900 if (r.activity.mVisibleFromServer) {
2901 r.activity.mVisibleFromServer = false;
2902 mNumVisibleActivities--;
2903 v.setVisibility(View.INVISIBLE);
2904 }
2905 }
2906 }
2907 }
2908
Romain Guy65b345f2011-07-27 18:51:50 -07002909 private void handleStopActivity(IBinder token, boolean show, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002910 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002911 r.activity.mConfigChangeFlags |= configChanges;
2912
2913 StopInfo info = new StopInfo();
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002914 performStopActivityInner(r, info, show, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002916 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917 TAG, "Finishing stop of " + r + ": show=" + show
2918 + " win=" + r.window);
2919
2920 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07002921
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002922 // Make sure any pending writes are now committed.
2923 if (!r.isPreHoneycomb()) {
2924 QueuedWork.waitToFinish();
2925 }
2926
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07002927 // Schedule the call to tell the activity manager we have
2928 // stopped. We don't do this immediately, because we want to
2929 // have a chance for any other pending work (in particular memory
2930 // trim requests) to complete before you tell the activity
2931 // manager to proceed and allow us to go fully into the background.
2932 info.activity = r;
2933 info.state = r.state;
2934 mH.post(info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002935 }
2936
2937 final void performRestartActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002938 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002939 if (r.stopped) {
2940 r.activity.performRestart();
2941 r.stopped = false;
2942 }
2943 }
2944
Romain Guy65b345f2011-07-27 18:51:50 -07002945 private void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002946 ActivityClientRecord r = mActivities.get(token);
Dianne Hackbornbfddc0f2010-12-14 11:28:01 -08002947
2948 if (r == null) {
2949 Log.w(TAG, "handleWindowVisibility: no activity for token " + token);
2950 return;
2951 }
2952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002953 if (!show && !r.stopped) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002954 performStopActivityInner(r, null, show, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002955 } else if (show && r.stopped) {
2956 // If we are getting ready to gc after going to the background, well
2957 // we are back active so skip it.
2958 unscheduleGcIdler();
2959
2960 r.activity.performRestart();
2961 r.stopped = false;
2962 }
2963 if (r.activity.mDecor != null) {
Joe Onorato43a17652011-04-06 19:22:23 -07002964 if (false) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002965 TAG, "Handle window " + r + " visibility: " + show);
2966 updateVisibility(r, show);
2967 }
2968 }
2969
Romain Guy65b345f2011-07-27 18:51:50 -07002970 private void handleSleeping(IBinder token, boolean sleeping) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002971 ActivityClientRecord r = mActivities.get(token);
2972
2973 if (r == null) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08002974 Log.w(TAG, "handleSleeping: no activity for token " + token);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002975 return;
2976 }
2977
2978 if (sleeping) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08002979 if (!r.stopped && !r.isPreHoneycomb()) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002980 try {
2981 // Now we are idle.
2982 r.activity.performStop();
2983 } catch (Exception e) {
2984 if (!mInstrumentation.onException(r.activity, e)) {
2985 throw new RuntimeException(
2986 "Unable to stop activity "
2987 + r.intent.getComponent().toShortString()
2988 + ": " + e.toString(), e);
2989 }
2990 }
2991 r.stopped = true;
2992 }
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002993
2994 // Make sure any pending writes are now committed.
2995 if (!r.isPreHoneycomb()) {
2996 QueuedWork.waitToFinish();
2997 }
2998
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002999 // Tell activity manager we slept.
3000 try {
3001 ActivityManagerNative.getDefault().activitySlept(r.token);
3002 } catch (RemoteException ex) {
3003 }
3004 } else {
3005 if (r.stopped && r.activity.mVisibleFromServer) {
3006 r.activity.performRestart();
3007 r.stopped = false;
3008 }
3009 }
3010 }
3011
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003012 private void handleSetCoreSettings(Bundle coreSettings) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08003013 synchronized (mPackages) {
3014 mCoreSettings = coreSettings;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003015 }
3016 }
3017
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003018 private void handleUpdatePackageCompatibilityInfo(UpdateCompatibilityData data) {
3019 LoadedApk apk = peekPackageInfo(data.pkg, false);
3020 if (apk != null) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003021 apk.mCompatibilityInfo.set(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003022 }
3023 apk = peekPackageInfo(data.pkg, true);
3024 if (apk != null) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003025 apk.mCompatibilityInfo.set(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003026 }
3027 handleConfigurationChanged(mConfiguration, data.info);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003028 WindowManagerImpl.getDefault().reportNewConfiguration(mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003029 }
3030
Romain Guy65b345f2011-07-27 18:51:50 -07003031 private void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003032 final int N = results.size();
3033 for (int i=0; i<N; i++) {
3034 ResultInfo ri = results.get(i);
3035 try {
3036 if (ri.mData != null) {
3037 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
3038 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003039 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07003040 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003041 r.activity.dispatchActivityResult(ri.mResultWho,
3042 ri.mRequestCode, ri.mResultCode, ri.mData);
3043 } catch (Exception e) {
3044 if (!mInstrumentation.onException(r.activity, e)) {
3045 throw new RuntimeException(
3046 "Failure delivering result " + ri + " to activity "
3047 + r.intent.getComponent().toShortString()
3048 + ": " + e.toString(), e);
3049 }
3050 }
3051 }
3052 }
3053
Romain Guy65b345f2011-07-27 18:51:50 -07003054 private void handleSendResult(ResultData res) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003055 ActivityClientRecord r = mActivities.get(res.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003056 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 if (r != null) {
3058 final boolean resumed = !r.paused;
3059 if (!r.activity.mFinished && r.activity.mDecor != null
3060 && r.hideForNow && resumed) {
3061 // We had hidden the activity because it started another
3062 // one... we have gotten a result back and we are not
3063 // paused, so make sure our window is visible.
3064 updateVisibility(r, true);
3065 }
3066 if (resumed) {
3067 try {
3068 // Now we are idle.
3069 r.activity.mCalled = false;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07003070 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003071 mInstrumentation.callActivityOnPause(r.activity);
3072 if (!r.activity.mCalled) {
3073 throw new SuperNotCalledException(
3074 "Activity " + r.intent.getComponent().toShortString()
3075 + " did not call through to super.onPause()");
3076 }
3077 } catch (SuperNotCalledException e) {
3078 throw e;
3079 } catch (Exception e) {
3080 if (!mInstrumentation.onException(r.activity, e)) {
3081 throw new RuntimeException(
3082 "Unable to pause activity "
3083 + r.intent.getComponent().toShortString()
3084 + ": " + e.toString(), e);
3085 }
3086 }
3087 }
3088 deliverResults(r, res.results);
3089 if (resumed) {
Dianne Hackbornb46ed762011-06-02 18:33:15 -07003090 r.activity.performResume();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07003091 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003092 }
3093 }
3094 }
3095
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003096 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003097 return performDestroyActivity(token, finishing, 0, false);
3098 }
3099
Romain Guy65b345f2011-07-27 18:51:50 -07003100 private ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003101 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003102 ActivityClientRecord r = mActivities.get(token);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003103 Class activityClass = null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003104 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003105 if (r != null) {
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003106 activityClass = r.activity.getClass();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003107 r.activity.mConfigChangeFlags |= configChanges;
3108 if (finishing) {
3109 r.activity.mFinished = true;
3110 }
3111 if (!r.paused) {
3112 try {
3113 r.activity.mCalled = false;
3114 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07003115 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003116 r.activity.getComponentName().getClassName());
3117 if (!r.activity.mCalled) {
3118 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003119 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003120 + " did not call through to super.onPause()");
3121 }
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 pause 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.paused = true;
3133 }
3134 if (!r.stopped) {
3135 try {
3136 r.activity.performStop();
3137 } catch (SuperNotCalledException e) {
3138 throw e;
3139 } catch (Exception e) {
3140 if (!mInstrumentation.onException(r.activity, e)) {
3141 throw new RuntimeException(
3142 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003143 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003144 + ": " + e.toString(), e);
3145 }
3146 }
3147 r.stopped = true;
3148 }
3149 if (getNonConfigInstance) {
3150 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003151 r.lastNonConfigurationInstances
3152 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003153 } catch (Exception e) {
3154 if (!mInstrumentation.onException(r.activity, e)) {
3155 throw new RuntimeException(
3156 "Unable to retain activity "
3157 + r.intent.getComponent().toShortString()
3158 + ": " + e.toString(), e);
3159 }
3160 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003161 }
3162 try {
3163 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07003164 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003165 if (!r.activity.mCalled) {
3166 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003167 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003168 " did not call through to super.onDestroy()");
3169 }
3170 if (r.window != null) {
3171 r.window.closeAllPanels();
3172 }
3173 } catch (SuperNotCalledException e) {
3174 throw e;
3175 } catch (Exception e) {
3176 if (!mInstrumentation.onException(r.activity, e)) {
3177 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003178 "Unable to destroy activity " + safeToComponentShortString(r.intent)
3179 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003180 }
3181 }
3182 }
3183 mActivities.remove(token);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003184 StrictMode.decrementExpectedActivityCount(activityClass);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003185 return r;
3186 }
3187
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003188 private static String safeToComponentShortString(Intent intent) {
3189 ComponentName component = intent.getComponent();
3190 return component == null ? "[Unknown]" : component.toShortString();
3191 }
3192
Romain Guy65b345f2011-07-27 18:51:50 -07003193 private void handleDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003194 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003195 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003196 configChanges, getNonConfigInstance);
3197 if (r != null) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003198 cleanUpPendingRemoveWindows(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 WindowManager wm = r.activity.getWindowManager();
3200 View v = r.activity.mDecor;
3201 if (v != null) {
3202 if (r.activity.mVisibleFromServer) {
3203 mNumVisibleActivities--;
3204 }
3205 IBinder wtoken = v.getWindowToken();
3206 if (r.activity.mWindowAdded) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003207 if (r.onlyLocalRequest) {
3208 // Hold off on removing this until the new activity's
3209 // window is being added.
3210 r.mPendingRemoveWindow = v;
3211 r.mPendingRemoveWindowManager = wm;
3212 } else {
3213 wm.removeViewImmediate(v);
3214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003215 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003216 if (wtoken != null && r.mPendingRemoveWindow == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003217 WindowManagerImpl.getDefault().closeAll(wtoken,
3218 r.activity.getClass().getName(), "Activity");
3219 }
3220 r.activity.mDecor = null;
3221 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003222 if (r.mPendingRemoveWindow == null) {
3223 // If we are delaying the removal of the activity window, then
3224 // we can't clean up all windows here. Note that we can't do
3225 // so later either, which means any windows that aren't closed
3226 // by the app will leak. Well we try to warning them a lot
3227 // about leaking windows, because that is a bug, so if they are
3228 // using this recreate facility then they get to live with leaks.
3229 WindowManagerImpl.getDefault().closeAll(token,
3230 r.activity.getClass().getName(), "Activity");
3231 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003232
3233 // Mocked out contexts won't be participating in the normal
3234 // process lifecycle, but if we're running with a proper
3235 // ApplicationContext we need to have it tear down things
3236 // cleanly.
3237 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08003238 if (c instanceof ContextImpl) {
3239 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003240 r.activity.getClass().getName(), "Activity");
3241 }
3242 }
3243 if (finishing) {
3244 try {
3245 ActivityManagerNative.getDefault().activityDestroyed(token);
3246 } catch (RemoteException ex) {
3247 // If the system process has died, it's game over for everyone.
3248 }
3249 }
3250 }
3251
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003252 public final void requestRelaunchActivity(IBinder token,
3253 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
3254 int configChanges, boolean notResumed, Configuration config,
3255 boolean fromServer) {
3256 ActivityClientRecord target = null;
3257
3258 synchronized (mPackages) {
3259 for (int i=0; i<mRelaunchingActivities.size(); i++) {
3260 ActivityClientRecord r = mRelaunchingActivities.get(i);
3261 if (r.token == token) {
3262 target = r;
3263 if (pendingResults != null) {
3264 if (r.pendingResults != null) {
3265 r.pendingResults.addAll(pendingResults);
3266 } else {
3267 r.pendingResults = pendingResults;
3268 }
3269 }
3270 if (pendingNewIntents != null) {
3271 if (r.pendingIntents != null) {
3272 r.pendingIntents.addAll(pendingNewIntents);
3273 } else {
3274 r.pendingIntents = pendingNewIntents;
3275 }
3276 }
3277 break;
3278 }
3279 }
3280
3281 if (target == null) {
3282 target = new ActivityClientRecord();
3283 target.token = token;
3284 target.pendingResults = pendingResults;
3285 target.pendingIntents = pendingNewIntents;
3286 if (!fromServer) {
3287 ActivityClientRecord existing = mActivities.get(token);
3288 if (existing != null) {
3289 target.startsNotResumed = existing.paused;
3290 }
3291 target.onlyLocalRequest = true;
3292 }
3293 mRelaunchingActivities.add(target);
3294 queueOrSendMessage(H.RELAUNCH_ACTIVITY, target);
3295 }
3296
3297 if (fromServer) {
3298 target.startsNotResumed = notResumed;
3299 target.onlyLocalRequest = false;
3300 }
3301 if (config != null) {
3302 target.createdConfig = config;
3303 }
3304 target.pendingConfigChanges |= configChanges;
3305 }
3306 }
3307
Romain Guy65b345f2011-07-27 18:51:50 -07003308 private void handleRelaunchActivity(ActivityClientRecord tmp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 // If we are getting ready to gc after going to the background, well
3310 // we are back active so skip it.
3311 unscheduleGcIdler();
3312
3313 Configuration changedConfig = null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003314 int configChanges = 0;
Bob Leee5408332009-09-04 18:31:17 -07003315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316 // First: make sure we have the most recent configuration and most
3317 // recent version of the activity, or skip it if some previous call
3318 // had taken a more recent version.
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003319 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320 int N = mRelaunchingActivities.size();
3321 IBinder token = tmp.token;
3322 tmp = null;
3323 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003324 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 if (r.token == token) {
3326 tmp = r;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003327 configChanges |= tmp.pendingConfigChanges;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003328 mRelaunchingActivities.remove(i);
3329 i--;
3330 N--;
3331 }
3332 }
Bob Leee5408332009-09-04 18:31:17 -07003333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003334 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003335 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003336 return;
3337 }
Bob Leee5408332009-09-04 18:31:17 -07003338
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003339 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
3340 + tmp.token + " with configChanges=0x"
3341 + Integer.toHexString(configChanges));
3342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003343 if (mPendingConfiguration != null) {
3344 changedConfig = mPendingConfiguration;
3345 mPendingConfiguration = null;
3346 }
3347 }
Bob Leee5408332009-09-04 18:31:17 -07003348
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003349 if (tmp.createdConfig != null) {
3350 // If the activity manager is passing us its current config,
3351 // assume that is really what we want regardless of what we
3352 // may have pending.
3353 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003354 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
3355 && mConfiguration.diff(tmp.createdConfig) != 0)) {
3356 if (changedConfig == null
3357 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
3358 changedConfig = tmp.createdConfig;
3359 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003360 }
3361 }
3362
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003363 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003364 + tmp.token + ": changedConfig=" + changedConfig);
3365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366 // If there was a pending configuration change, execute it first.
3367 if (changedConfig != null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003368 handleConfigurationChanged(changedConfig, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 }
Bob Leee5408332009-09-04 18:31:17 -07003370
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003371 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003372 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003373 if (r == null) {
3374 return;
3375 }
Bob Leee5408332009-09-04 18:31:17 -07003376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003377 r.activity.mConfigChangeFlags |= configChanges;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003378 r.onlyLocalRequest = tmp.onlyLocalRequest;
Christopher Tateb70f3df2009-04-07 16:07:59 -07003379 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07003380
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003381 r.activity.mChangingConfigurations = true;
3382
Dianne Hackborne2b04802010-12-09 09:24:55 -08003383 // Need to ensure state is saved.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003384 if (!r.paused) {
Dianne Hackborne2b04802010-12-09 09:24:55 -08003385 performPauseActivity(r.token, false, r.isPreHoneycomb());
3386 }
3387 if (r.state == null && !r.stopped && !r.isPreHoneycomb()) {
3388 r.state = new Bundle();
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04003389 r.state.setAllowFds(false);
Dianne Hackborne2b04802010-12-09 09:24:55 -08003390 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003391 }
Bob Leee5408332009-09-04 18:31:17 -07003392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07003394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003395 r.activity = null;
3396 r.window = null;
3397 r.hideForNow = false;
3398 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07003399 // Merge any pending results and pending intents; don't just replace them
3400 if (tmp.pendingResults != null) {
3401 if (r.pendingResults == null) {
3402 r.pendingResults = tmp.pendingResults;
3403 } else {
3404 r.pendingResults.addAll(tmp.pendingResults);
3405 }
3406 }
3407 if (tmp.pendingIntents != null) {
3408 if (r.pendingIntents == null) {
3409 r.pendingIntents = tmp.pendingIntents;
3410 } else {
3411 r.pendingIntents.addAll(tmp.pendingIntents);
3412 }
3413 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003414 r.startsNotResumed = tmp.startsNotResumed;
Bob Leee5408332009-09-04 18:31:17 -07003415
Christopher Tateb70f3df2009-04-07 16:07:59 -07003416 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003417 }
3418
Romain Guy65b345f2011-07-27 18:51:50 -07003419 private void handleRequestThumbnail(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003420 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003421 Bitmap thumbnail = createThumbnailBitmap(r);
3422 CharSequence description = null;
3423 try {
3424 description = r.activity.onCreateDescription();
3425 } catch (Exception e) {
3426 if (!mInstrumentation.onException(r.activity, e)) {
3427 throw new RuntimeException(
3428 "Unable to create description of activity "
3429 + r.intent.getComponent().toShortString()
3430 + ": " + e.toString(), e);
3431 }
3432 }
3433 //System.out.println("Reporting top thumbnail " + thumbnail);
3434 try {
3435 ActivityManagerNative.getDefault().reportThumbnail(
3436 token, thumbnail, description);
3437 } catch (RemoteException ex) {
3438 }
3439 }
3440
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003441 ArrayList<ComponentCallbacks2> collectComponentCallbacksLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003442 boolean allActivities, Configuration newConfig) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003443 ArrayList<ComponentCallbacks2> callbacks
3444 = new ArrayList<ComponentCallbacks2>();
Bob Leee5408332009-09-04 18:31:17 -07003445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003446 if (mActivities.size() > 0) {
Romain Guya998dff2012-03-23 18:58:36 -07003447 for (ActivityClientRecord ar : mActivities.values()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003448 Activity a = ar.activity;
3449 if (a != null) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003450 Configuration thisConfig = applyConfigCompatMainThread(newConfig,
3451 ar.packageInfo.mCompatibilityInfo.getIfNeeded());
Romain Guya998dff2012-03-23 18:58:36 -07003452 if (!ar.activity.mFinished && (allActivities || !ar.paused)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003453 // If the activity is currently resumed, its configuration
3454 // needs to change right now.
3455 callbacks.add(a);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003456 } else if (thisConfig != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003457 // Otherwise, we will tell it about the change
3458 // the next time it is resumed or shown. Note that
3459 // the activity manager may, before then, decide the
3460 // activity needs to be destroyed to handle its new
3461 // configuration.
Romain Guya998dff2012-03-23 18:58:36 -07003462 if (DEBUG_CONFIGURATION) {
3463 Slog.v(TAG, "Setting activity "
3464 + ar.activityInfo.name + " newConfig=" + thisConfig);
3465 }
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003466 ar.newConfig = thisConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003467 }
3468 }
3469 }
3470 }
3471 if (mServices.size() > 0) {
Romain Guya998dff2012-03-23 18:58:36 -07003472 for (Service service : mServices.values()) {
3473 callbacks.add(service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003474 }
3475 }
3476 synchronized (mProviderMap) {
3477 if (mLocalProviders.size() > 0) {
Romain Guya998dff2012-03-23 18:58:36 -07003478 for (ProviderClientRecord providerClientRecord : mLocalProviders.values()) {
3479 callbacks.add(providerClientRecord.mLocalProvider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003480 }
3481 }
3482 }
3483 final int N = mAllApplications.size();
3484 for (int i=0; i<N; i++) {
3485 callbacks.add(mAllApplications.get(i));
3486 }
Bob Leee5408332009-09-04 18:31:17 -07003487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003488 return callbacks;
3489 }
Bob Leee5408332009-09-04 18:31:17 -07003490
Romain Guya998dff2012-03-23 18:58:36 -07003491 private static void performConfigurationChanged(ComponentCallbacks2 cb, Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003492 // Only for Activity objects, check that they actually call up to their
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003493 // superclass implementation. ComponentCallbacks2 is an interface, so
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494 // we check the runtime type and act accordingly.
3495 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
3496 if (activity != null) {
3497 activity.mCalled = false;
3498 }
Bob Leee5408332009-09-04 18:31:17 -07003499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003500 boolean shouldChangeConfig = false;
3501 if ((activity == null) || (activity.mCurrentConfig == null)) {
3502 shouldChangeConfig = true;
3503 } else {
Bob Leee5408332009-09-04 18:31:17 -07003504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003505 // If the new config is the same as the config this Activity
3506 // is already running with then don't bother calling
3507 // onConfigurationChanged
3508 int diff = activity.mCurrentConfig.diff(config);
3509 if (diff != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003510 // If this activity doesn't handle any of the config changes
3511 // then don't bother calling onConfigurationChanged as we're
3512 // going to destroy it.
Dianne Hackborne6676352011-06-01 16:51:20 -07003513 if ((~activity.mActivityInfo.getRealConfigChanged() & diff) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003514 shouldChangeConfig = true;
3515 }
3516 }
3517 }
Bob Leee5408332009-09-04 18:31:17 -07003518
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003519 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003520 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003521 if (shouldChangeConfig) {
3522 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07003523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003524 if (activity != null) {
3525 if (!activity.mCalled) {
3526 throw new SuperNotCalledException(
3527 "Activity " + activity.getLocalClassName() +
3528 " did not call through to super.onConfigurationChanged()");
3529 }
3530 activity.mConfigChangeFlags = 0;
3531 activity.mCurrentConfig = new Configuration(config);
3532 }
3533 }
3534 }
3535
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07003536 public final void applyConfigurationToResources(Configuration config) {
3537 synchronized (mPackages) {
3538 applyConfigurationToResourcesLocked(config, null);
3539 }
3540 }
3541
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003542 final boolean applyConfigurationToResourcesLocked(Configuration config,
3543 CompatibilityInfo compat) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003544 if (mResConfiguration == null) {
3545 mResConfiguration = new Configuration();
3546 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003547 if (!mResConfiguration.isOtherSeqNewer(config) && compat == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003548 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq="
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003549 + mResConfiguration.seq + ", newSeq=" + config.seq);
Dianne Hackbornae078162010-03-18 11:29:37 -07003550 return false;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003551 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003552 int changes = mResConfiguration.updateFrom(config);
Dianne Hackborn836e2622011-10-04 18:32:39 -07003553 DisplayMetrics dm = getDisplayMetricsLocked(null, true);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003554
3555 if (compat != null && (mResCompatibilityInfo == null ||
3556 !mResCompatibilityInfo.equals(compat))) {
3557 mResCompatibilityInfo = compat;
3558 changes |= ActivityInfo.CONFIG_SCREEN_LAYOUT
3559 | ActivityInfo.CONFIG_SCREEN_SIZE
3560 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3561 }
Bob Leee5408332009-09-04 18:31:17 -07003562
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003563 // set it for java, this also affects newly created Resources
3564 if (config.locale != null) {
3565 Locale.setDefault(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003566 }
Bob Leee5408332009-09-04 18:31:17 -07003567
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003568 Resources.updateSystemConfiguration(config, dm, compat);
Bob Leee5408332009-09-04 18:31:17 -07003569
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003570 ApplicationPackageManager.configurationChanged();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003571 //Slog.i(TAG, "Configuration changed in " + currentPackageName());
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003572
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003573 Iterator<WeakReference<Resources>> it =
3574 mActiveResources.values().iterator();
3575 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
3576 // mActiveResources.entrySet().iterator();
3577 while (it.hasNext()) {
3578 WeakReference<Resources> v = it.next();
3579 Resources r = v.get();
3580 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003581 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources "
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003582 + r + " config to: " + config);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003583 r.updateConfiguration(config, dm, compat);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003584 //Slog.i(TAG, "Updated app resources " + v.getKey()
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003585 // + " " + r + ": " + r.getConfiguration());
3586 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003587 //Slog.i(TAG, "Removing old resources " + v.getKey());
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003588 it.remove();
3589 }
3590 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003591
3592 return changes != 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003593 }
Dianne Hackborn836e2622011-10-04 18:32:39 -07003594
3595 final Configuration applyCompatConfiguration() {
3596 Configuration config = mConfiguration;
3597 if (mCompatConfiguration == null) {
3598 mCompatConfiguration = new Configuration();
3599 }
3600 mCompatConfiguration.setTo(mConfiguration);
3601 if (mResCompatibilityInfo != null && !mResCompatibilityInfo.supportsScreen()) {
3602 mResCompatibilityInfo.applyToConfiguration(mCompatConfiguration);
3603 config = mCompatConfiguration;
3604 }
3605 return config;
3606 }
3607
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003608 final void handleConfigurationChanged(Configuration config, CompatibilityInfo compat) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003609
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003610 ArrayList<ComponentCallbacks2> callbacks = null;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003611
3612 synchronized (mPackages) {
3613 if (mPendingConfiguration != null) {
3614 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
3615 config = mPendingConfiguration;
3616 }
3617 mPendingConfiguration = null;
3618 }
3619
3620 if (config == null) {
3621 return;
3622 }
3623
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003624 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003625 + config);
3626
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003627 applyConfigurationToResourcesLocked(config, compat);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003629 if (mConfiguration == null) {
3630 mConfiguration = new Configuration();
3631 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003632 if (!mConfiguration.isOtherSeqNewer(config) && compat == null) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003633 return;
3634 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 mConfiguration.updateFrom(config);
Dianne Hackborn836e2622011-10-04 18:32:39 -07003636 config = applyCompatConfiguration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003637 callbacks = collectComponentCallbacksLocked(false, config);
3638 }
Romain Guy65b345f2011-07-27 18:51:50 -07003639
3640 // Cleanup hardware accelerated stuff
3641 WindowManagerImpl.getDefault().trimLocalMemory();
Bob Leee5408332009-09-04 18:31:17 -07003642
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003643 if (callbacks != null) {
3644 final int N = callbacks.size();
3645 for (int i=0; i<N; i++) {
3646 performConfigurationChanged(callbacks.get(i), config);
3647 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003648 }
3649 }
3650
3651 final void handleActivityConfigurationChanged(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003652 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003653 if (r == null || r.activity == null) {
3654 return;
3655 }
Bob Leee5408332009-09-04 18:31:17 -07003656
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003657 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003658 + r.activityInfo.name);
3659
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003660 performConfigurationChanged(r.activity, mCompatConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661 }
3662
Romain Guy7eabe552011-07-21 14:56:34 -07003663 final void handleProfilerControl(boolean start, ProfilerControlData pcd, int profileType) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003664 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003665 try {
Romain Guy7eabe552011-07-21 14:56:34 -07003666 switch (profileType) {
3667 case 1:
3668 ViewDebug.startLooperProfiling(pcd.path, pcd.fd.getFileDescriptor());
3669 break;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003670 default:
3671 mProfiler.setProfiler(pcd.path, pcd.fd);
3672 mProfiler.autoStopProfiler = false;
3673 mProfiler.startProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07003674 break;
3675 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003676 } catch (RuntimeException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003677 Slog.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003678 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003679 } finally {
3680 try {
3681 pcd.fd.close();
3682 } catch (IOException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003683 Slog.w(TAG, "Failure closing profile fd", e);
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003684 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003685 }
3686 } else {
Romain Guy7eabe552011-07-21 14:56:34 -07003687 switch (profileType) {
3688 case 1:
3689 ViewDebug.stopLooperProfiling();
3690 break;
3691 default:
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003692 mProfiler.stopProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07003693 break;
Romain Guy7eabe552011-07-21 14:56:34 -07003694 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003695 }
3696 }
Bob Leee5408332009-09-04 18:31:17 -07003697
Romain Guya998dff2012-03-23 18:58:36 -07003698 static final void handleDumpHeap(boolean managed, DumpHeapData dhd) {
Andy McFadden824c5102010-07-09 16:26:57 -07003699 if (managed) {
3700 try {
3701 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor());
3702 } catch (IOException e) {
3703 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
3704 + " -- can the process access this path?");
3705 } finally {
3706 try {
3707 dhd.fd.close();
3708 } catch (IOException e) {
3709 Slog.w(TAG, "Failure closing profile fd", e);
3710 }
3711 }
3712 } else {
Andy McFadden06a6b552010-07-13 16:28:09 -07003713 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07003714 }
3715 }
3716
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003717 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
3718 boolean hasPkgInfo = false;
3719 if (packages != null) {
3720 for (int i=packages.length-1; i>=0; i--) {
3721 //Slog.i(TAG, "Cleaning old package: " + packages[i]);
3722 if (!hasPkgInfo) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003723 WeakReference<LoadedApk> ref;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003724 ref = mPackages.get(packages[i]);
3725 if (ref != null && ref.get() != null) {
3726 hasPkgInfo = true;
3727 } else {
3728 ref = mResourcePackages.get(packages[i]);
3729 if (ref != null && ref.get() != null) {
3730 hasPkgInfo = true;
3731 }
3732 }
3733 }
3734 mPackages.remove(packages[i]);
3735 mResourcePackages.remove(packages[i]);
3736 }
3737 }
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003738 ApplicationPackageManager.handlePackageBroadcast(cmd, packages,
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003739 hasPkgInfo);
3740 }
3741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003742 final void handleLowMemory() {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003743 ArrayList<ComponentCallbacks2> callbacks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003744
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003745 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 callbacks = collectComponentCallbacksLocked(true, null);
3747 }
Bob Leee5408332009-09-04 18:31:17 -07003748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003749 final int N = callbacks.size();
3750 for (int i=0; i<N; i++) {
3751 callbacks.get(i).onLowMemory();
3752 }
3753
Chris Tatece229052009-03-25 16:44:52 -07003754 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3755 if (Process.myUid() != Process.SYSTEM_UID) {
3756 int sqliteReleased = SQLiteDatabase.releaseMemory();
3757 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3758 }
Bob Leee5408332009-09-04 18:31:17 -07003759
Mike Reedcaf0df12009-04-27 14:32:05 -04003760 // Ask graphics to free up as much as possible (font/image caches)
3761 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003762
3763 BinderInternal.forceGc("mem");
3764 }
3765
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003766 final void handleTrimMemory(int level) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003767 if (DEBUG_MEMORY_TRIM) Slog.v(TAG, "Trimming memory to level: " + level);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003768
Romain Guy19f86e82012-04-23 15:19:07 -07003769 final WindowManagerImpl windowManager = WindowManagerImpl.getDefault();
3770 windowManager.startTrimMemory(level);
3771
3772 ArrayList<ComponentCallbacks2> callbacks;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003773 synchronized (mPackages) {
3774 callbacks = collectComponentCallbacksLocked(true, null);
3775 }
3776
3777 final int N = callbacks.size();
Romain Guya998dff2012-03-23 18:58:36 -07003778 for (int i = 0; i < N; i++) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003779 callbacks.get(i).onTrimMemory(level);
3780 }
Romain Guy19f86e82012-04-23 15:19:07 -07003781
3782 windowManager.endTrimMemory();
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003783 }
3784
Romain Guya9582652011-11-10 14:20:10 -08003785 private void setupGraphicsSupport(LoadedApk info) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003786 if (Process.isIsolated()) {
3787 // Isolated processes aren't going to do UI.
3788 return;
3789 }
Romain Guya9582652011-11-10 14:20:10 -08003790 try {
3791 int uid = Process.myUid();
3792 String[] packages = getPackageManager().getPackagesForUid(uid);
3793
3794 // If there are several packages in this application we won't
3795 // initialize the graphics disk caches
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003796 if (packages != null && packages.length == 1) {
Romain Guya9582652011-11-10 14:20:10 -08003797 ContextImpl appContext = new ContextImpl();
3798 appContext.init(info, null, this);
3799
3800 HardwareRenderer.setupDiskCache(appContext.getCacheDir());
Jason Samsa6f338c2012-02-24 16:22:16 -08003801 RenderScript.setupDiskCache(appContext.getCacheDir());
Romain Guya9582652011-11-10 14:20:10 -08003802 }
3803 } catch (RemoteException e) {
3804 // Ignore
3805 }
3806 }
3807
Romain Guy65b345f2011-07-27 18:51:50 -07003808 private void handleBindApplication(AppBindData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003809 mBoundApplication = data;
3810 mConfiguration = new Configuration(data.config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003811 mCompatConfiguration = new Configuration(data.config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003812
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003813 mProfiler = new Profiler();
3814 mProfiler.profileFile = data.initProfileFile;
3815 mProfiler.profileFd = data.initProfileFd;
3816 mProfiler.autoStopProfiler = data.initAutoStopProfiler;
3817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003818 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003819 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003820 android.ddm.DdmHandleAppName.setAppName(data.processName);
3821
Dianne Hackborn5d927c22011-09-02 12:22:18 -07003822 if (data.persistent) {
3823 // Persistent processes on low-memory devices do not get to
3824 // use hardware accelerated drawing, since this can add too much
3825 // overhead to the process.
3826 Display display = WindowManagerImpl.getDefault().getDefaultDisplay();
3827 if (!ActivityManager.isHighEndGfx(display)) {
3828 HardwareRenderer.disable(false);
3829 }
3830 }
Romain Guya9582652011-11-10 14:20:10 -08003831
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003832 if (mProfiler.profileFd != null) {
3833 mProfiler.startProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003834 }
3835
Joe Onoratod630f102011-03-17 18:42:26 -07003836 // If the app is Honeycomb MR1 or earlier, switch its AsyncTask
3837 // implementation to use the pool executor. Normally, we use the
3838 // serialized executor as the default. This has to happen in the
3839 // main thread so the main looper is set right.
Dianne Hackborn81e92762011-10-09 16:00:21 -07003840 if (data.appInfo.targetSdkVersion <= android.os.Build.VERSION_CODES.HONEYCOMB_MR1) {
Joe Onoratod630f102011-03-17 18:42:26 -07003841 AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
3842 }
3843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003844 /*
3845 * Before spawning a new process, reset the time zone to be the system time zone.
3846 * This needs to be done because the system time zone could have changed after the
3847 * the spawning of this process. Without doing this this process would have the incorrect
3848 * system time zone.
3849 */
3850 TimeZone.setDefault(null);
3851
3852 /*
3853 * Initialize the default locale in this process for the reasons we set the time zone.
3854 */
3855 Locale.setDefault(data.config.locale);
3856
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003857 /*
3858 * Update the system configuration since its preloaded and might not
3859 * reflect configuration changes. The configuration object passed
3860 * in AppBindData can be safely assumed to be up to date
3861 */
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07003862 applyConfigurationToResourcesLocked(data.config, data.compatInfo);
Dianne Hackborn836e2622011-10-04 18:32:39 -07003863 applyCompatConfiguration();
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003864
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003865 data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866
Romain Guya9582652011-11-10 14:20:10 -08003867 setupGraphicsSupport(data.info);
3868
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003869 /**
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003870 * For system applications on userdebug/eng builds, log stack
3871 * traces of disk and network access to dropbox for analysis.
3872 */
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07003873 if ((data.appInfo.flags &
3874 (ApplicationInfo.FLAG_SYSTEM |
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07003875 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0) {
3876 StrictMode.conditionallyEnableDebugLogging();
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003877 }
3878
3879 /**
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07003880 * For apps targetting SDK Honeycomb or later, we don't allow
3881 * network usage on the main event loop / UI thread.
3882 *
3883 * Note to those grepping: this is what ultimately throws
3884 * NetworkOnMainThreadException ...
3885 */
3886 if (data.appInfo.targetSdkVersion > 9) {
3887 StrictMode.enableDeathOnNetwork();
3888 }
3889
3890 /**
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003891 * Switch this process to density compatibility mode if needed.
3892 */
3893 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3894 == 0) {
3895 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3896 }
Bob Leee5408332009-09-04 18:31:17 -07003897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003898 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3899 // XXX should have option to change the port.
3900 Debug.changeDebugPort(8100);
3901 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003902 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 + " is waiting for the debugger on port 8100...");
3904
3905 IActivityManager mgr = ActivityManagerNative.getDefault();
3906 try {
3907 mgr.showWaitingForDebugger(mAppThread, true);
3908 } catch (RemoteException ex) {
3909 }
3910
3911 Debug.waitForDebugger();
3912
3913 try {
3914 mgr.showWaitingForDebugger(mAppThread, false);
3915 } catch (RemoteException ex) {
3916 }
3917
3918 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003919 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 + " can be debugged on port 8100...");
3921 }
3922 }
3923
Siva Velusamy92a8b222012-03-09 16:24:04 -08003924 // Enable OpenGL tracing if required
3925 if (data.enableOpenGlTrace) {
3926 GLUtils.enableTracing();
3927 }
3928
Robert Greenwalt434203a2010-10-11 16:00:27 -07003929 /**
3930 * Initialize the default http proxy in this process for the reasons we set the time zone.
3931 */
3932 IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08003933 if (b != null) {
3934 // In pre-boot mode (doing initial launch to collect password), not
3935 // all system is up. This includes the connectivity service, so don't
3936 // crash if we can't get it.
3937 IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
3938 try {
3939 ProxyProperties proxyProperties = service.getProxy();
3940 Proxy.setHttpProxySystemProperty(proxyProperties);
3941 } catch (RemoteException e) {}
3942 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003944 if (data.instrumentationName != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08003945 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003946 appContext.init(data.info, null, this);
3947 InstrumentationInfo ii = null;
3948 try {
3949 ii = appContext.getPackageManager().
3950 getInstrumentationInfo(data.instrumentationName, 0);
3951 } catch (PackageManager.NameNotFoundException e) {
3952 }
3953 if (ii == null) {
3954 throw new RuntimeException(
3955 "Unable to find instrumentation info for: "
3956 + data.instrumentationName);
3957 }
3958
3959 mInstrumentationAppDir = ii.sourceDir;
Brian Carlstromd893a892012-04-01 21:30:26 -07003960 mInstrumentationAppLibraryDir = ii.nativeLibraryDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003961 mInstrumentationAppPackage = ii.packageName;
3962 mInstrumentedAppDir = data.info.getAppDir();
Brian Carlstromd893a892012-04-01 21:30:26 -07003963 mInstrumentedAppLibraryDir = data.info.getLibDir();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003964
3965 ApplicationInfo instrApp = new ApplicationInfo();
3966 instrApp.packageName = ii.packageName;
3967 instrApp.sourceDir = ii.sourceDir;
3968 instrApp.publicSourceDir = ii.publicSourceDir;
3969 instrApp.dataDir = ii.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003970 instrApp.nativeLibraryDir = ii.nativeLibraryDir;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003971 LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003972 appContext.getClassLoader(), false, true);
Dianne Hackborn21556372010-02-04 16:34:40 -08003973 ContextImpl instrContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003974 instrContext.init(pi, null, this);
3975
3976 try {
3977 java.lang.ClassLoader cl = instrContext.getClassLoader();
3978 mInstrumentation = (Instrumentation)
3979 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3980 } catch (Exception e) {
3981 throw new RuntimeException(
3982 "Unable to instantiate instrumentation "
3983 + data.instrumentationName + ": " + e.toString(), e);
3984 }
3985
3986 mInstrumentation.init(this, instrContext, appContext,
3987 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3988
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003989 if (mProfiler.profileFile != null && !ii.handleProfiling
3990 && mProfiler.profileFd == null) {
3991 mProfiler.handlingProfiling = true;
3992 File file = new File(mProfiler.profileFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003993 file.getParentFile().mkdirs();
3994 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3995 }
3996
3997 try {
3998 mInstrumentation.onCreate(data.instrumentationArgs);
3999 }
4000 catch (Exception e) {
4001 throw new RuntimeException(
4002 "Exception thrown in onCreate() of "
4003 + data.instrumentationName + ": " + e.toString(), e);
4004 }
4005
4006 } else {
4007 mInstrumentation = new Instrumentation();
4008 }
4009
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08004010 if ((data.appInfo.flags&ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
Dianne Hackbornde398512011-01-18 18:45:21 -08004011 dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08004012 }
4013
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08004014 // Allow disk access during application and provider setup. This could
Jeff Sharkey7c501672012-02-28 12:08:37 -08004015 // block processing ordered broadcasts, but later processing would
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08004016 // probably end up doing the same disk access.
Jeff Sharkey7c501672012-02-28 12:08:37 -08004017 final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004018 try {
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08004019 // If the app is being launched for full backup or restore, bring it up in
4020 // a restricted environment with the base application class.
4021 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
4022 mInitialApplication = app;
Jeff Sharkey7c501672012-02-28 12:08:37 -08004023
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08004024 // don't bring up providers in restricted mode; they may depend on the
4025 // app's custom Application class
4026 if (!data.restrictedBackupMode) {
4027 List<ProviderInfo> providers = data.providers;
4028 if (providers != null) {
4029 installContentProviders(app, providers);
4030 // For process that contains content providers, we want to
4031 // ensure that the JIT is enabled "at some point".
4032 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
4033 }
4034 }
4035
4036 try {
4037 mInstrumentation.callApplicationOnCreate(app);
4038 } catch (Exception e) {
4039 if (!mInstrumentation.onException(app, e)) {
4040 throw new RuntimeException(
4041 "Unable to create application " + app.getClass().getName()
4042 + ": " + e.toString(), e);
4043 }
4044 }
4045 } finally {
4046 StrictMode.setThreadPolicy(savedPolicy);
4047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004048 }
4049
4050 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
4051 IActivityManager am = ActivityManagerNative.getDefault();
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07004052 if (mProfiler.profileFile != null && mProfiler.handlingProfiling
4053 && mProfiler.profileFd == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004054 Debug.stopMethodTracing();
4055 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004056 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004057 // + ", app thr: " + mAppThread);
4058 try {
4059 am.finishInstrumentation(mAppThread, resultCode, results);
4060 } catch (RemoteException ex) {
4061 }
4062 }
4063
Romain Guy65b345f2011-07-27 18:51:50 -07004064 private void installContentProviders(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004065 Context context, List<ProviderInfo> providers) {
4066 final ArrayList<IActivityManager.ContentProviderHolder> results =
4067 new ArrayList<IActivityManager.ContentProviderHolder>();
4068
Romain Guya998dff2012-03-23 18:58:36 -07004069 for (ProviderInfo cpi : providers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004070 StringBuilder buf = new StringBuilder(128);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07004071 buf.append("Pub ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004072 buf.append(cpi.authority);
4073 buf.append(": ");
4074 buf.append(cpi.name);
4075 Log.i(TAG, buf.toString());
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004076 IContentProvider cp = installProvider(context, null, cpi,
4077 false /*noisy*/, true /*noReleaseNeeded*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004078 if (cp != null) {
4079 IActivityManager.ContentProviderHolder cph =
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004080 new IActivityManager.ContentProviderHolder(cpi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004081 cph.provider = cp;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004082 cph.noReleaseNeeded = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004083 results.add(cph);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004084 }
4085 }
4086
4087 try {
4088 ActivityManagerNative.getDefault().publishContentProviders(
4089 getApplicationThread(), results);
4090 } catch (RemoteException ex) {
4091 }
4092 }
4093
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004094 public final IContentProvider acquireProvider(Context c, String name) {
4095 IContentProvider provider = acquireExistingProvider(c, name);
4096 if (provider != null) {
4097 return provider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004098 }
4099
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004100 // There is a possible race here. Another thread may try to acquire
4101 // the same provider at the same time. When this happens, we want to ensure
4102 // that the first one wins.
4103 // Note that we cannot hold the lock while acquiring and installing the
4104 // provider since it might take a long time to run and it could also potentially
4105 // be re-entrant in the case where the provider is in the same process.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004106 IActivityManager.ContentProviderHolder holder = null;
4107 try {
4108 holder = ActivityManagerNative.getDefault().getContentProvider(
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004109 getApplicationThread(), name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004110 } catch (RemoteException ex) {
4111 }
4112 if (holder == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004113 Slog.e(TAG, "Failed to find provider info for " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004114 return null;
4115 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004116
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004117 // Install provider will increment the reference count for us, and break
4118 // any ties in the race.
4119 provider = installProvider(c, holder.provider, holder.info,
4120 true /*noisy*/, holder.noReleaseNeeded);
4121 if (holder.provider != null && provider != holder.provider) {
4122 if (localLOGV) {
4123 Slog.v(TAG, "acquireProvider: lost the race, releasing extraneous "
4124 + "reference to the content provider");
4125 }
4126 try {
4127 ActivityManagerNative.getDefault().removeContentProvider(
4128 getApplicationThread(), name);
4129 } catch (RemoteException ex) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004130 }
4131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004132 return provider;
4133 }
4134
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07004135 public final IContentProvider acquireExistingProvider(Context c, String name) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004136 synchronized (mProviderMap) {
4137 ProviderClientRecord pr = mProviderMap.get(name);
4138 if (pr == null) {
4139 return null;
4140 }
4141
4142 IContentProvider provider = pr.mProvider;
4143 IBinder jBinder = provider.asBinder();
4144
4145 // Only increment the ref count if we have one. If we don't then the
4146 // provider is not reference counted and never needs to be released.
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07004147 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004148 if (prc != null) {
4149 prc.count += 1;
4150 if (prc.count == 1) {
4151 if (localLOGV) {
4152 Slog.v(TAG, "acquireExistingProvider: "
4153 + "snatched provider from the jaws of death");
4154 }
4155 // Because the provider previously had a reference count of zero,
4156 // it was scheduled to be removed. Cancel that.
4157 mH.removeMessages(H.REMOVE_PROVIDER, provider);
4158 }
4159 }
4160 return provider;
4161 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07004162 }
4163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164 public final boolean releaseProvider(IContentProvider provider) {
4165 if(provider == null) {
4166 return false;
4167 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169 IBinder jBinder = provider.asBinder();
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004170 synchronized (mProviderMap) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004171 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004172 if (prc == null) {
4173 // The provider has no ref count, no release is needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 return false;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004175 }
4176
4177 if (prc.count == 0) {
4178 if (localLOGV) Slog.v(TAG, "releaseProvider: ref count already 0, how?");
4179 return false;
4180 }
4181
4182 prc.count -= 1;
4183 if (prc.count == 0) {
4184 // Schedule the actual remove asynchronously, since we don't know the context
4185 // this will be called in.
4186 // TODO: it would be nice to post a delayed message, so
4187 // if we come back and need the same provider quickly
4188 // we will still have it available.
4189 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
4190 mH.sendMessage(msg);
4191 }
4192 return true;
4193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004194 }
4195
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004196 final void completeRemoveProvider(IContentProvider provider) {
4197 IBinder jBinder = provider.asBinder();
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004198 String remoteProviderName = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004199 synchronized(mProviderMap) {
4200 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004201 if (prc == null) {
4202 // Either no release is needed (so we shouldn't be here) or the
4203 // provider was already released.
4204 if (localLOGV) Slog.v(TAG, "completeRemoveProvider: release not needed");
4205 return;
4206 }
4207
4208 if (prc.count != 0) {
4209 // There was a race! Some other client managed to acquire
4210 // the provider before the removal was completed.
4211 // Abort the removal. We will do it later.
4212 if (localLOGV) Slog.v(TAG, "completeRemoveProvider: lost the race, "
4213 + "provider still in use");
4214 return;
4215 }
4216
4217 mProviderRefCountMap.remove(jBinder);
4218
4219 Iterator<ProviderClientRecord> iter = mProviderMap.values().iterator();
4220 while (iter.hasNext()) {
4221 ProviderClientRecord pr = iter.next();
4222 IBinder myBinder = pr.mProvider.asBinder();
4223 if (myBinder == jBinder) {
4224 iter.remove();
4225 if (pr.mLocalProvider == null) {
4226 myBinder.unlinkToDeath(pr, 0);
4227 if (remoteProviderName == null) {
4228 remoteProviderName = pr.mName;
4229 }
4230 }
4231 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004232 }
4233 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004234
4235 if (remoteProviderName != null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004236 try {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004237 if (localLOGV) {
4238 Slog.v(TAG, "removeProvider: Invoking ActivityManagerNative."
4239 + "removeContentProvider(" + remoteProviderName + ")");
4240 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004241 ActivityManagerNative.getDefault().removeContentProvider(
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004242 getApplicationThread(), remoteProviderName);
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004243 } catch (RemoteException e) {
4244 //do nothing content provider object is dead any way
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004245 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004246 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004247 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004248
4249 final void removeDeadProvider(String name, IContentProvider provider) {
4250 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004251 ProviderClientRecord pr = mProviderMap.get(name);
Jeff Brown2a4c5ac2011-08-23 11:58:26 -07004252 if (pr != null && pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004253 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004254 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07004255 if (removed != null) {
4256 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
4257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004258 }
4259 }
4260 }
4261
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004262 /**
4263 * Installs the provider.
4264 *
4265 * Providers that are local to the process or that come from the system server
4266 * may be installed permanently which is indicated by setting noReleaseNeeded to true.
4267 * Other remote providers are reference counted. The initial reference count
4268 * for all reference counted providers is one. Providers that are not reference
4269 * counted do not have a reference count (at all).
4270 *
4271 * This method detects when a provider has already been installed. When this happens,
4272 * it increments the reference count of the existing provider (if appropriate)
4273 * and returns the existing provider. This can happen due to concurrent
4274 * attempts to acquire the same provider.
4275 */
Romain Guy65b345f2011-07-27 18:51:50 -07004276 private IContentProvider installProvider(Context context,
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004277 IContentProvider provider, ProviderInfo info,
4278 boolean noisy, boolean noReleaseNeeded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004279 ContentProvider localProvider = null;
4280 if (provider == null) {
4281 if (noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004282 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004283 + info.name);
4284 }
4285 Context c = null;
4286 ApplicationInfo ai = info.applicationInfo;
4287 if (context.getPackageName().equals(ai.packageName)) {
4288 c = context;
4289 } else if (mInitialApplication != null &&
4290 mInitialApplication.getPackageName().equals(ai.packageName)) {
4291 c = mInitialApplication;
4292 } else {
4293 try {
4294 c = context.createPackageContext(ai.packageName,
4295 Context.CONTEXT_INCLUDE_CODE);
4296 } catch (PackageManager.NameNotFoundException e) {
Romain Guy65b345f2011-07-27 18:51:50 -07004297 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004298 }
4299 }
4300 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004301 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004302 ai.packageName +
4303 " while loading content provider " +
4304 info.name);
4305 return null;
4306 }
4307 try {
4308 final java.lang.ClassLoader cl = c.getClassLoader();
4309 localProvider = (ContentProvider)cl.
4310 loadClass(info.name).newInstance();
4311 provider = localProvider.getIContentProvider();
4312 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004313 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004314 info.name + " from sourceDir " +
4315 info.applicationInfo.sourceDir);
4316 return null;
4317 }
Joe Onorato43a17652011-04-06 19:22:23 -07004318 if (false) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004319 TAG, "Instantiating local provider " + info.name);
4320 // XXX Need to create the correct context for this provider.
4321 localProvider.attachInfo(c, info);
4322 } catch (java.lang.Exception e) {
4323 if (!mInstrumentation.onException(null, e)) {
4324 throw new RuntimeException(
4325 "Unable to get provider " + info.name
4326 + ": " + e.toString(), e);
4327 }
4328 return null;
4329 }
4330 } else if (localLOGV) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004331 Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004332 + info.name);
4333 }
4334
4335 synchronized (mProviderMap) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004336 // There is a possibility that this thread raced with another thread to
4337 // add the provider. If we find another thread got there first then we
4338 // just get out of the way and return the original provider.
4339 IBinder jBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004340 String names[] = PATTERN_SEMICOLON.split(info.authority);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004341 for (int i = 0; i < names.length; i++) {
4342 ProviderClientRecord pr = mProviderMap.get(names[i]);
4343 if (pr != null) {
4344 if (localLOGV) {
4345 Slog.v(TAG, "installProvider: lost the race, "
4346 + "using existing named provider");
4347 }
4348 provider = pr.mProvider;
4349 } else {
4350 pr = new ProviderClientRecord(names[i], provider, localProvider);
4351 if (localProvider == null) {
4352 try {
4353 jBinder.linkToDeath(pr, 0);
4354 } catch (RemoteException e) {
4355 // Provider already dead. Bail out of here without making
4356 // any changes to the provider map or other data structures.
4357 return null;
4358 }
4359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004360 mProviderMap.put(names[i], pr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004361 }
4362 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004363
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004364 if (localProvider != null) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004365 ProviderClientRecord pr = mLocalProviders.get(jBinder);
4366 if (pr != null) {
4367 if (localLOGV) {
4368 Slog.v(TAG, "installProvider: lost the race, "
4369 + "using existing local provider");
4370 }
4371 provider = pr.mProvider;
4372 } else {
4373 pr = new ProviderClientRecord(null, provider, localProvider);
4374 mLocalProviders.put(jBinder, pr);
4375 }
4376 }
4377
4378 if (!noReleaseNeeded) {
4379 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
4380 if (prc != null) {
4381 if (localLOGV) {
4382 Slog.v(TAG, "installProvider: lost the race, incrementing ref count");
4383 }
4384 prc.count += 1;
4385 if (prc.count == 1) {
4386 if (localLOGV) {
4387 Slog.v(TAG, "installProvider: "
4388 + "snatched provider from the jaws of death");
4389 }
4390 // Because the provider previously had a reference count of zero,
4391 // it was scheduled to be removed. Cancel that.
4392 mH.removeMessages(H.REMOVE_PROVIDER, provider);
4393 }
4394 } else {
4395 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
4396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004397 }
4398 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004399 return provider;
4400 }
4401
Romain Guy65b345f2011-07-27 18:51:50 -07004402 private void attach(boolean system) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004403 sThreadLocal.set(this);
4404 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004405 if (!system) {
Dianne Hackborn6dd005b2011-07-18 13:22:50 -07004406 ViewRootImpl.addFirstDrawHandler(new Runnable() {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08004407 public void run() {
4408 ensureJitEnabled();
4409 }
4410 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004411 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
4412 RuntimeInit.setApplicationObject(mAppThread.asBinder());
4413 IActivityManager mgr = ActivityManagerNative.getDefault();
4414 try {
4415 mgr.attachApplication(mAppThread);
4416 } catch (RemoteException ex) {
Romain Guy65b345f2011-07-27 18:51:50 -07004417 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004418 }
4419 } else {
4420 // Don't set application object here -- if the system crashes,
4421 // we can't display an alert, we just want to die die die.
4422 android.ddm.DdmHandleAppName.setAppName("system_process");
4423 try {
4424 mInstrumentation = new Instrumentation();
Dianne Hackborn21556372010-02-04 16:34:40 -08004425 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004426 context.init(getSystemContext().mPackageInfo, null, this);
4427 Application app = Instrumentation.newApplication(Application.class, context);
4428 mAllApplications.add(app);
4429 mInitialApplication = app;
4430 app.onCreate();
4431 } catch (Exception e) {
4432 throw new RuntimeException(
4433 "Unable to instantiate Application():" + e.toString(), e);
4434 }
4435 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004436
Dianne Hackbornc68c9132011-07-29 01:25:18 -07004437 ViewRootImpl.addConfigCallback(new ComponentCallbacks2() {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004438 public void onConfigurationChanged(Configuration newConfig) {
4439 synchronized (mPackages) {
Dianne Hackbornae078162010-03-18 11:29:37 -07004440 // We need to apply this change to the resources
4441 // immediately, because upon returning the view
4442 // hierarchy will be informed about it.
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004443 if (applyConfigurationToResourcesLocked(newConfig, null)) {
Dianne Hackbornae078162010-03-18 11:29:37 -07004444 // This actually changed the resources! Tell
4445 // everyone about it.
4446 if (mPendingConfiguration == null ||
4447 mPendingConfiguration.isOtherSeqNewer(newConfig)) {
4448 mPendingConfiguration = newConfig;
4449
4450 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
4451 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004452 }
4453 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004454 }
4455 public void onLowMemory() {
4456 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -07004457 public void onTrimMemory(int level) {
4458 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004459 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004460 }
4461
Romain Guy5e9120d2012-01-30 12:17:22 -08004462 public static ActivityThread systemMain() {
Dianne Hackborn5d927c22011-09-02 12:22:18 -07004463 HardwareRenderer.disable(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004464 ActivityThread thread = new ActivityThread();
4465 thread.attach(true);
4466 return thread;
4467 }
4468
Jeff Brown10e89712011-07-08 18:52:57 -07004469 public final void installSystemProviders(List<ProviderInfo> providers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004470 if (providers != null) {
Jeff Brown10e89712011-07-08 18:52:57 -07004471 installContentProviders(mInitialApplication, providers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004472 }
4473 }
4474
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004475 public int getIntCoreSetting(String key, int defaultValue) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08004476 synchronized (mPackages) {
4477 if (mCoreSettings != null) {
4478 return mCoreSettings.getInt(key, defaultValue);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004479 } else {
4480 return defaultValue;
4481 }
4482 }
4483 }
4484
Romain Guy65b345f2011-07-27 18:51:50 -07004485 public static void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07004486 SamplingProfilerIntegration.start();
4487
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -08004488 // CloseGuard defaults to true and can be quite spammy. We
4489 // disable it here, but selectively enable it later (via
4490 // StrictMode) on debug builds, but using DropBox, not logs.
4491 CloseGuard.setEnabled(false);
4492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004493 Process.setArgV0("<pre-initialized>");
4494
4495 Looper.prepareMainLooper();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07004496 if (sMainThreadHandler == null) {
4497 sMainThreadHandler = new Handler();
4498 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004499
4500 ActivityThread thread = new ActivityThread();
4501 thread.attach(false);
4502
Romain Guy5e9120d2012-01-30 12:17:22 -08004503 AsyncTask.init();
4504
Dianne Hackborn287952c2010-09-22 22:34:31 -07004505 if (false) {
4506 Looper.myLooper().setMessageLogging(new
4507 LogPrinter(Log.DEBUG, "ActivityThread"));
4508 }
4509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004510 Looper.loop();
4511
Jeff Brown10e89712011-07-08 18:52:57 -07004512 throw new RuntimeException("Main thread loop unexpectedly exited");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004513 }
4514}