blob: e4cfc994870474a88ed0fa89f2d1a188743bdbcf [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;
81
82import com.android.internal.os.BinderInternal;
83import com.android.internal.os.RuntimeInit;
Bob Leee5408332009-09-04 18:31:17 -070084import com.android.internal.os.SamplingProfilerIntegration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085
86import org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl;
87
88import java.io.File;
89import java.io.FileDescriptor;
90import java.io.FileOutputStream;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070091import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import java.io.PrintWriter;
93import java.lang.ref.WeakReference;
Robert Greenwalt03595d02010-11-02 14:08:23 -070094import java.net.InetAddress;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import java.util.ArrayList;
96import java.util.HashMap;
97import java.util.Iterator;
98import java.util.List;
99import java.util.Locale;
100import java.util.Map;
101import java.util.TimeZone;
102import java.util.regex.Pattern;
103
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -0800104import dalvik.system.CloseGuard;
Bob Leee5408332009-09-04 18:31:17 -0700105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106final class SuperNotCalledException extends AndroidRuntimeException {
107 public SuperNotCalledException(String msg) {
108 super(msg);
109 }
110}
111
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700112final class RemoteServiceException extends AndroidRuntimeException {
113 public RemoteServiceException(String msg) {
114 super(msg);
115 }
116}
117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118/**
119 * This manages the execution of the main thread in an
120 * application process, scheduling and executing activities,
121 * broadcasts, and other operations on it as the activity
122 * manager requests.
123 *
124 * {@hide}
125 */
126public final class ActivityThread {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700127 /** @hide */
128 public static final String TAG = "ActivityThread";
Jim Miller0b2a6d02010-07-13 18:01:29 -0700129 private static final android.graphics.Bitmap.Config THUMBNAIL_FORMAT = Bitmap.Config.RGB_565;
Joe Onorato43a17652011-04-06 19:22:23 -0700130 static final boolean localLOGV = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700131 static final boolean DEBUG_MESSAGES = false;
Dianne Hackborne829fef2010-10-26 17:44:01 -0700132 /** @hide */
133 public static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700134 private static final boolean DEBUG_RESULTS = false;
Christopher Tate4a627c72011-04-01 14:43:32 -0700135 private static final boolean DEBUG_BACKUP = true;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700136 private static final boolean DEBUG_CONFIGURATION = false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700137 private static final boolean DEBUG_SERVICE = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
139 private static final Pattern PATTERN_SEMICOLON = Pattern.compile(";");
140 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
141 private static final int LOG_ON_PAUSE_CALLED = 30021;
142 private static final int LOG_ON_RESUME_CALLED = 30022;
143
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700144 static ContextImpl mSystemContext = null;
Bob Leee5408332009-09-04 18:31:17 -0700145
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700146 static IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700148 final ApplicationThread mAppThread = new ApplicationThread();
149 final Looper mLooper = Looper.myLooper();
150 final H mH = new H();
151 final HashMap<IBinder, ActivityClientRecord> mActivities
152 = new HashMap<IBinder, ActivityClientRecord>();
153 // List of new activities (via ActivityRecord.nextIdle) that should
154 // be reported when next we idle.
155 ActivityClientRecord mNewActivities = null;
156 // Number of activities that are currently visible on-screen.
157 int mNumVisibleActivities = 0;
158 final HashMap<IBinder, Service> mServices
159 = new HashMap<IBinder, Service>();
160 AppBindData mBoundApplication;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700161 Profiler mProfiler;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700162 Configuration mConfiguration;
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700163 Configuration mCompatConfiguration;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700164 Configuration mResConfiguration;
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700165 CompatibilityInfo mResCompatibilityInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700166 Application mInitialApplication;
167 final ArrayList<Application> mAllApplications
168 = new ArrayList<Application>();
169 // set of instantiated backup agents, keyed by package name
170 final HashMap<String, BackupAgent> mBackupAgents = new HashMap<String, BackupAgent>();
Romain Guy65b345f2011-07-27 18:51:50 -0700171 static final ThreadLocal<ActivityThread> sThreadLocal = new ThreadLocal<ActivityThread>();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700172 Instrumentation mInstrumentation;
173 String mInstrumentationAppDir = null;
174 String mInstrumentationAppPackage = null;
175 String mInstrumentedAppDir = null;
176 boolean mSystemThread = false;
177 boolean mJitEnabled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700179 // These can be accessed by multiple threads; mPackages is the lock.
180 // XXX For now we keep around information about all packages we have
181 // seen, not removing entries from this map.
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800182 // NOTE: The activity and window managers need to call in to
Dianne Hackborn2f0b1752011-05-31 17:59:49 -0700183 // ActivityThread to do things like update resource configurations,
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800184 // which means this lock gets held while the activity and window managers
185 // holds their own lock. Thus you MUST NEVER call back into the activity manager
186 // or window manager or anything that depends on them while holding this lock.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700187 final HashMap<String, WeakReference<LoadedApk>> mPackages
188 = new HashMap<String, WeakReference<LoadedApk>>();
189 final HashMap<String, WeakReference<LoadedApk>> mResourcePackages
190 = new HashMap<String, WeakReference<LoadedApk>>();
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700191 final HashMap<CompatibilityInfo, DisplayMetrics> mDisplayMetrics
192 = new HashMap<CompatibilityInfo, DisplayMetrics>();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700193 final HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources
194 = new HashMap<ResourcesKey, WeakReference<Resources> >();
195 final ArrayList<ActivityClientRecord> mRelaunchingActivities
196 = new ArrayList<ActivityClientRecord>();
197 Configuration mPendingConfiguration = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700199 // The lock of mProviderMap protects the following variables.
200 final HashMap<String, ProviderClientRecord> mProviderMap
201 = new HashMap<String, ProviderClientRecord>();
202 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap
203 = new HashMap<IBinder, ProviderRefCount>();
204 final HashMap<IBinder, ProviderClientRecord> mLocalProviders
205 = new HashMap<IBinder, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206
Jeff Hamilton52d32032011-01-08 15:31:26 -0600207 final HashMap<Activity, ArrayList<OnActivityPausedListener>> mOnPauseListeners
208 = new HashMap<Activity, ArrayList<OnActivityPausedListener>>();
209
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700210 final GcIdler mGcIdler = new GcIdler();
211 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700213 static Handler sMainThreadHandler; // set once in main()
214
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800215 Bundle mCoreSettings = null;
216
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400217 static final class ActivityClientRecord {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700219 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220 Intent intent;
221 Bundle state;
222 Activity activity;
223 Window window;
224 Activity parent;
225 String embeddedID;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700226 Activity.NonConfigurationInstances lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 boolean paused;
228 boolean stopped;
229 boolean hideForNow;
230 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700231 Configuration createdConfig;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700232 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700234 String profileFile;
235 ParcelFileDescriptor profileFd;
236 boolean autoStopProfiler;
237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 ActivityInfo activityInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400239 CompatibilityInfo compatInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700240 LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241
242 List<ResultInfo> pendingResults;
243 List<Intent> pendingIntents;
244
245 boolean startsNotResumed;
246 boolean isForward;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800247 int pendingConfigChanges;
248 boolean onlyLocalRequest;
249
250 View mPendingRemoveWindow;
251 WindowManager mPendingRemoveWindowManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700253 ActivityClientRecord() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 parent = null;
255 embeddedID = null;
256 paused = false;
257 stopped = false;
258 hideForNow = false;
259 nextIdle = null;
260 }
261
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800262 public boolean isPreHoneycomb() {
263 if (activity != null) {
264 return activity.getApplicationInfo().targetSdkVersion
265 < android.os.Build.VERSION_CODES.HONEYCOMB;
266 }
267 return false;
268 }
269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 public String toString() {
271 ComponentName componentName = intent.getComponent();
272 return "ActivityRecord{"
273 + Integer.toHexString(System.identityHashCode(this))
274 + " token=" + token + " " + (componentName == null
275 ? "no component name" : componentName.toShortString())
276 + "}";
277 }
278 }
279
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400280 final class ProviderClientRecord implements IBinder.DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800281 final String mName;
282 final IContentProvider mProvider;
283 final ContentProvider mLocalProvider;
284
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700285 ProviderClientRecord(String name, IContentProvider provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 ContentProvider localProvider) {
287 mName = name;
288 mProvider = provider;
289 mLocalProvider = localProvider;
290 }
291
292 public void binderDied() {
293 removeDeadProvider(mName, mProvider);
294 }
295 }
296
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400297 static final class NewIntentData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298 List<Intent> intents;
299 IBinder token;
300 public String toString() {
301 return "NewIntentData{intents=" + intents + " token=" + token + "}";
302 }
303 }
304
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400305 static final class ReceiverData extends BroadcastReceiver.PendingResult {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700306 public ReceiverData(Intent intent, int resultCode, String resultData, Bundle resultExtras,
307 boolean ordered, boolean sticky, IBinder token) {
308 super(resultCode, resultData, resultExtras, TYPE_COMPONENT, ordered, sticky, token);
309 this.intent = intent;
310 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312 Intent intent;
313 ActivityInfo info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400314 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 public String toString() {
316 return "ReceiverData{intent=" + intent + " packageName=" +
Dianne Hackborne829fef2010-10-26 17:44:01 -0700317 info.packageName + " resultCode=" + getResultCode()
318 + " resultData=" + getResultData() + " resultExtras="
319 + getResultExtras(false) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320 }
321 }
322
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400323 static final class CreateBackupAgentData {
Christopher Tate181fafa2009-05-14 11:12:14 -0700324 ApplicationInfo appInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400325 CompatibilityInfo compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700326 int backupMode;
327 public String toString() {
328 return "CreateBackupAgentData{appInfo=" + appInfo
329 + " backupAgent=" + appInfo.backupAgentName
330 + " mode=" + backupMode + "}";
331 }
332 }
Bob Leee5408332009-09-04 18:31:17 -0700333
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400334 static final class CreateServiceData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335 IBinder token;
336 ServiceInfo info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400337 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800338 Intent intent;
339 public String toString() {
340 return "CreateServiceData{token=" + token + " className="
341 + info.name + " packageName=" + info.packageName
342 + " intent=" + intent + "}";
343 }
344 }
345
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400346 static final class BindServiceData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347 IBinder token;
348 Intent intent;
349 boolean rebind;
350 public String toString() {
351 return "BindServiceData{token=" + token + " intent=" + intent + "}";
352 }
353 }
354
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400355 static final class ServiceArgsData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356 IBinder token;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700357 boolean taskRemoved;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700359 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360 Intent args;
361 public String toString() {
362 return "ServiceArgsData{token=" + token + " startId=" + startId
363 + " args=" + args + "}";
364 }
365 }
366
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400367 static final class AppBindData {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700368 LoadedApk info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 String processName;
370 ApplicationInfo appInfo;
371 List<ProviderInfo> providers;
372 ComponentName instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800373 Bundle instrumentationArgs;
374 IInstrumentationWatcher instrumentationWatcher;
375 int debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700376 boolean restrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700377 boolean persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800378 Configuration config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400379 CompatibilityInfo compatInfo;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700380
381 /** Initial values for {@link Profiler}. */
382 String initProfileFile;
383 ParcelFileDescriptor initProfileFd;
384 boolean initAutoStopProfiler;
385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386 public String toString() {
387 return "AppBindData{appInfo=" + appInfo + "}";
388 }
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700389 }
390
391 static final class Profiler {
392 String profileFile;
393 ParcelFileDescriptor profileFd;
394 boolean autoStopProfiler;
395 boolean profiling;
396 boolean handlingProfiling;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700397 public void setProfiler(String file, ParcelFileDescriptor fd) {
398 if (profiling) {
399 if (fd != null) {
400 try {
401 fd.close();
402 } catch (IOException e) {
403 }
404 }
405 return;
406 }
407 if (profileFd != null) {
408 try {
409 profileFd.close();
410 } catch (IOException e) {
411 }
412 }
413 profileFile = file;
414 profileFd = fd;
415 }
416 public void startProfiling() {
417 if (profileFd == null || profiling) {
418 return;
419 }
420 try {
421 Debug.startMethodTracing(profileFile, profileFd.getFileDescriptor(),
422 8 * 1024 * 1024, 0);
423 profiling = true;
424 } catch (RuntimeException e) {
425 Slog.w(TAG, "Profiling failed on path " + profileFile);
426 try {
427 profileFd.close();
428 profileFd = null;
429 } catch (IOException e2) {
430 Slog.w(TAG, "Failure closing profile fd", e2);
431 }
432 }
433 }
434 public void stopProfiling() {
435 if (profiling) {
436 profiling = false;
437 Debug.stopMethodTracing();
438 if (profileFd != null) {
439 try {
440 profileFd.close();
441 } catch (IOException e) {
442 }
443 }
444 profileFd = null;
445 profileFile = null;
446 }
447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800448 }
449
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400450 static final class DumpComponentInfo {
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700451 ParcelFileDescriptor fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700452 IBinder token;
Dianne Hackborn30d71892010-12-11 10:37:55 -0800453 String prefix;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800454 String[] args;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 }
456
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400457 static final class ResultData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458 IBinder token;
459 List<ResultInfo> results;
460 public String toString() {
461 return "ResultData{token=" + token + " results" + results + "}";
462 }
463 }
464
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400465 static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800466 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467 String what;
468 String who;
469 }
470
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400471 static final class ProfilerControlData {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700472 String path;
473 ParcelFileDescriptor fd;
474 }
475
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400476 static final class DumpHeapData {
Andy McFadden824c5102010-07-09 16:26:57 -0700477 String path;
478 ParcelFileDescriptor fd;
479 }
480
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400481 static final class UpdateCompatibilityData {
482 String pkg;
483 CompatibilityInfo info;
484 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -0700485
Romain Guy65b345f2011-07-27 18:51:50 -0700486 private native void dumpGraphicsInfo(FileDescriptor fd);
Chet Haase9c1e23b2011-03-24 10:51:31 -0700487
Romain Guy65b345f2011-07-27 18:51:50 -0700488 private class ApplicationThread extends ApplicationThreadNative {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700489 private static final String HEAP_COLUMN = "%13s %8s %8s %8s %8s %8s %8s";
490 private static final String ONE_COUNT_COLUMN = "%21s %8d";
491 private static final String TWO_COUNT_COLUMNS = "%21s %8d %21s %8d";
Vasu Nori3c7131f2010-09-21 14:36:57 -0700492 private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
Bob Leee5408332009-09-04 18:31:17 -0700493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 // Formatting for checkin service - update version if row format changes
495 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;
Bob Leee5408332009-09-04 18:31:17 -0700496
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700497 private void updatePendingConfiguration(Configuration config) {
498 synchronized (mPackages) {
499 if (mPendingConfiguration == null ||
500 mPendingConfiguration.isOtherSeqNewer(config)) {
501 mPendingConfiguration = config;
502 }
503 }
504 }
505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 public final void schedulePauseActivity(IBinder token, boolean finished,
507 boolean userLeaving, int configChanges) {
508 queueOrSendMessage(
509 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
510 token,
511 (userLeaving ? 1 : 0),
512 configChanges);
513 }
514
515 public final void scheduleStopActivity(IBinder token, boolean showWindow,
516 int configChanges) {
517 queueOrSendMessage(
518 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
519 token, 0, configChanges);
520 }
521
522 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
523 queueOrSendMessage(
524 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
525 token);
526 }
527
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800528 public final void scheduleSleeping(IBinder token, boolean sleeping) {
529 queueOrSendMessage(H.SLEEPING, token, sleeping ? 1 : 0);
530 }
531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532 public final void scheduleResumeActivity(IBinder token, boolean isForward) {
533 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
534 }
535
536 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
537 ResultData res = new ResultData();
538 res.token = token;
539 res.results = results;
540 queueOrSendMessage(H.SEND_RESULT, res);
541 }
542
543 // we use token to identify this activity without having to send the
544 // activity itself back to the activity manager. (matters more with ipc)
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700545 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700546 ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
547 Bundle state, List<ResultInfo> pendingResults,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700548 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward,
549 String profileName, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700550 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800551
552 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700553 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800554 r.intent = intent;
555 r.activityInfo = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400556 r.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 r.state = state;
558
559 r.pendingResults = pendingResults;
560 r.pendingIntents = pendingNewIntents;
561
562 r.startsNotResumed = notResumed;
563 r.isForward = isForward;
564
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700565 r.profileFile = profileName;
566 r.profileFd = profileFd;
567 r.autoStopProfiler = autoStopProfiler;
568
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700569 updatePendingConfiguration(curConfig);
570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
572 }
573
574 public final void scheduleRelaunchActivity(IBinder token,
575 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800576 int configChanges, boolean notResumed, Configuration config) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800577 requestRelaunchActivity(token, pendingResults, pendingNewIntents,
578 configChanges, notResumed, config, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 }
580
581 public final void scheduleNewIntent(List<Intent> intents, IBinder token) {
582 NewIntentData data = new NewIntentData();
583 data.intents = intents;
584 data.token = token;
585
586 queueOrSendMessage(H.NEW_INTENT, data);
587 }
588
589 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
590 int configChanges) {
591 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
592 configChanges);
593 }
594
595 public final void scheduleReceiver(Intent intent, ActivityInfo info,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400596 CompatibilityInfo compatInfo, int resultCode, String data, Bundle extras,
597 boolean sync) {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700598 ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
599 sync, false, mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 r.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400601 r.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800602 queueOrSendMessage(H.RECEIVER, r);
603 }
604
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400605 public final void scheduleCreateBackupAgent(ApplicationInfo app,
606 CompatibilityInfo compatInfo, int backupMode) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700607 CreateBackupAgentData d = new CreateBackupAgentData();
608 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400609 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700610 d.backupMode = backupMode;
611
612 queueOrSendMessage(H.CREATE_BACKUP_AGENT, d);
613 }
614
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400615 public final void scheduleDestroyBackupAgent(ApplicationInfo app,
616 CompatibilityInfo compatInfo) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700617 CreateBackupAgentData d = new CreateBackupAgentData();
618 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400619 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700620
621 queueOrSendMessage(H.DESTROY_BACKUP_AGENT, d);
622 }
623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 public final void scheduleCreateService(IBinder token,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400625 ServiceInfo info, CompatibilityInfo compatInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 CreateServiceData s = new CreateServiceData();
627 s.token = token;
628 s.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400629 s.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630
631 queueOrSendMessage(H.CREATE_SERVICE, s);
632 }
633
634 public final void scheduleBindService(IBinder token, Intent intent,
635 boolean rebind) {
636 BindServiceData s = new BindServiceData();
637 s.token = token;
638 s.intent = intent;
639 s.rebind = rebind;
640
Amith Yamasani742a6712011-05-04 14:49:28 -0700641 if (DEBUG_SERVICE)
642 Slog.v(TAG, "scheduleBindService token=" + token + " intent=" + intent + " uid="
643 + Binder.getCallingUid() + " pid=" + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 queueOrSendMessage(H.BIND_SERVICE, s);
645 }
646
647 public final void scheduleUnbindService(IBinder token, Intent intent) {
648 BindServiceData s = new BindServiceData();
649 s.token = token;
650 s.intent = intent;
651
652 queueOrSendMessage(H.UNBIND_SERVICE, s);
653 }
654
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700655 public final void scheduleServiceArgs(IBinder token, boolean taskRemoved, int startId,
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700656 int flags ,Intent args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 ServiceArgsData s = new ServiceArgsData();
658 s.token = token;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700659 s.taskRemoved = taskRemoved;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 s.startId = startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700661 s.flags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 s.args = args;
663
664 queueOrSendMessage(H.SERVICE_ARGS, s);
665 }
666
667 public final void scheduleStopService(IBinder token) {
668 queueOrSendMessage(H.STOP_SERVICE, token);
669 }
670
671 public final void bindApplication(String processName,
672 ApplicationInfo appInfo, List<ProviderInfo> providers,
673 ComponentName instrumentationName, String profileFile,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700674 ParcelFileDescriptor profileFd, boolean autoStopProfiler,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700676 int debugMode, boolean isRestrictedBackupMode, boolean persistent,
677 Configuration config, CompatibilityInfo compatInfo,
678 Map<String, IBinder> services, Bundle coreSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679
680 if (services != null) {
681 // Setup the service cache in the ServiceManager
682 ServiceManager.initServiceCache(services);
683 }
684
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800685 setCoreSettings(coreSettings);
686
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 AppBindData data = new AppBindData();
688 data.processName = processName;
689 data.appInfo = appInfo;
690 data.providers = providers;
691 data.instrumentationName = instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 data.instrumentationArgs = instrumentationArgs;
693 data.instrumentationWatcher = instrumentationWatcher;
694 data.debugMode = debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700695 data.restrictedBackupMode = isRestrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700696 data.persistent = persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 data.config = config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400698 data.compatInfo = compatInfo;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700699 data.initProfileFile = profileFile;
700 data.initProfileFd = profileFd;
701 data.initAutoStopProfiler = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 queueOrSendMessage(H.BIND_APPLICATION, data);
703 }
704
705 public final void scheduleExit() {
706 queueOrSendMessage(H.EXIT_APPLICATION, null);
707 }
708
Christopher Tate5e1ab332009-09-01 20:32:49 -0700709 public final void scheduleSuicide() {
710 queueOrSendMessage(H.SUICIDE, null);
711 }
712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 public void requestThumbnail(IBinder token) {
714 queueOrSendMessage(H.REQUEST_THUMBNAIL, token);
715 }
716
717 public void scheduleConfigurationChanged(Configuration config) {
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700718 updatePendingConfiguration(config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 queueOrSendMessage(H.CONFIGURATION_CHANGED, config);
720 }
721
722 public void updateTimeZone() {
723 TimeZone.setDefault(null);
724 }
725
Robert Greenwalt03595d02010-11-02 14:08:23 -0700726 public void clearDnsCache() {
727 // a non-standard API to get this to libcore
728 InetAddress.clearDnsCache();
729 }
730
Robert Greenwalt434203a2010-10-11 16:00:27 -0700731 public void setHttpProxy(String host, String port, String exclList) {
732 Proxy.setHttpProxySystemProperty(host, port, exclList);
733 }
734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 public void processInBackground() {
736 mH.removeMessages(H.GC_WHEN_IDLE);
737 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
738 }
739
740 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700741 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700742 try {
743 data.fd = ParcelFileDescriptor.dup(fd);
744 data.token = servicetoken;
745 data.args = args;
746 queueOrSendMessage(H.DUMP_SERVICE, data);
747 } catch (IOException e) {
748 Slog.w(TAG, "dumpService failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749 }
750 }
751
752 // This function exists to make sure all receiver dispatching is
753 // correctly ordered, since these are one-way calls and the binder driver
754 // applies transaction ordering per object for such calls.
755 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700756 int resultCode, String dataStr, Bundle extras, boolean ordered,
757 boolean sticky) throws RemoteException {
758 receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 }
Bob Leee5408332009-09-04 18:31:17 -0700760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 public void scheduleLowMemory() {
762 queueOrSendMessage(H.LOW_MEMORY, null);
763 }
764
765 public void scheduleActivityConfigurationChanged(IBinder token) {
766 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token);
767 }
768
Romain Guy7eabe552011-07-21 14:56:34 -0700769 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd,
770 int profileType) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700771 ProfilerControlData pcd = new ProfilerControlData();
772 pcd.path = path;
773 pcd.fd = fd;
Romain Guy7eabe552011-07-21 14:56:34 -0700774 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0, profileType);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800775 }
776
Andy McFadden824c5102010-07-09 16:26:57 -0700777 public void dumpHeap(boolean managed, String path, ParcelFileDescriptor fd) {
778 DumpHeapData dhd = new DumpHeapData();
779 dhd.path = path;
780 dhd.fd = fd;
781 queueOrSendMessage(H.DUMP_HEAP, dhd, managed ? 1 : 0);
782 }
783
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700784 public void setSchedulingGroup(int group) {
785 // Note: do this immediately, since going into the foreground
786 // should happen regardless of what pending work we have to do
787 // and the activity manager will wait for us to report back that
788 // we are done before sending us to the background.
789 try {
790 Process.setProcessGroup(Process.myPid(), group);
791 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800792 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700793 }
794 }
Bob Leee5408332009-09-04 18:31:17 -0700795
Dianne Hackborn3025ef32009-08-31 21:31:47 -0700796 public void getMemoryInfo(Debug.MemoryInfo outInfo) {
797 Debug.getMemoryInfo(outInfo);
798 }
Bob Leee5408332009-09-04 18:31:17 -0700799
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700800 public void dispatchPackageBroadcast(int cmd, String[] packages) {
801 queueOrSendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
802 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700803
804 public void scheduleCrash(String msg) {
805 queueOrSendMessage(H.SCHEDULE_CRASH, msg);
806 }
Dianne Hackborn625ac272010-09-17 18:29:22 -0700807
Dianne Hackborn30d71892010-12-11 10:37:55 -0800808 public void dumpActivity(FileDescriptor fd, IBinder activitytoken,
809 String prefix, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700810 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700811 try {
812 data.fd = ParcelFileDescriptor.dup(fd);
813 data.token = activitytoken;
814 data.prefix = prefix;
815 data.args = args;
816 queueOrSendMessage(H.DUMP_ACTIVITY, data);
817 } catch (IOException e) {
818 Slog.w(TAG, "dumpActivity failed", e);
Dianne Hackborn625ac272010-09-17 18:29:22 -0700819 }
820 }
Chet Haase9c1e23b2011-03-24 10:51:31 -0700821
Marco Nelissen18cb2872011-11-15 11:19:53 -0800822 public void dumpProvider(FileDescriptor fd, IBinder providertoken,
823 String[] args) {
824 DumpComponentInfo data = new DumpComponentInfo();
825 try {
826 data.fd = ParcelFileDescriptor.dup(fd);
827 data.token = providertoken;
828 data.args = args;
829 queueOrSendMessage(H.DUMP_PROVIDER, data);
830 } catch (IOException e) {
831 Slog.w(TAG, "dumpProvider failed", e);
832 }
833 }
834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 @Override
Dianne Hackbornb437e092011-08-05 17:50:29 -0700836 public Debug.MemoryInfo dumpMemInfo(FileDescriptor fd, boolean checkin,
837 boolean all, String[] args) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700838 FileOutputStream fout = new FileOutputStream(fd);
839 PrintWriter pw = new PrintWriter(fout);
840 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -0700841 return dumpMemInfo(pw, checkin, all, args);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700842 } finally {
Chet Haase9c1e23b2011-03-24 10:51:31 -0700843 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -0700844 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700845 }
846
Dianne Hackbornb437e092011-08-05 17:50:29 -0700847 private Debug.MemoryInfo dumpMemInfo(PrintWriter pw, boolean checkin, boolean all,
848 String[] args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 long nativeMax = Debug.getNativeHeapSize() / 1024;
850 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
851 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
852
853 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
854 Debug.getMemoryInfo(memInfo);
855
Dianne Hackbornb437e092011-08-05 17:50:29 -0700856 if (!all) {
857 return memInfo;
858 }
859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 Runtime runtime = Runtime.getRuntime();
861
862 long dalvikMax = runtime.totalMemory() / 1024;
863 long dalvikFree = runtime.freeMemory() / 1024;
864 long dalvikAllocated = dalvikMax - dalvikFree;
865 long viewInstanceCount = ViewDebug.getViewInstanceCount();
Romain Guy65b345f2011-07-27 18:51:50 -0700866 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
Brian Carlstromc21550a2010-10-05 21:34:06 -0700867 long appContextInstanceCount = Debug.countInstancesOfClass(ContextImpl.class);
868 long activityInstanceCount = Debug.countInstancesOfClass(Activity.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 int globalAssetCount = AssetManager.getGlobalAssetCount();
870 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
871 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
872 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
873 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
Brian Carlstromc9d5b312010-10-05 22:23:41 -0700874 long openSslSocketCount = Debug.countInstancesOfClass(OpenSSLSocketImpl.class);
Vasu Noric3849202010-03-09 10:47:25 -0800875 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -0700876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 // For checkin, we print one long comma-separated list of values
Dianne Hackbornb437e092011-08-05 17:50:29 -0700878 if (checkin) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 // NOTE: if you change anything significant below, also consider changing
880 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -0700881 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -0700883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 // Header
885 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
886 pw.print(Process.myPid()); pw.print(',');
887 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 // Heap info - max
890 pw.print(nativeMax); pw.print(',');
891 pw.print(dalvikMax); pw.print(',');
892 pw.print("N/A,");
893 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 // Heap info - allocated
896 pw.print(nativeAllocated); pw.print(',');
897 pw.print(dalvikAllocated); pw.print(',');
898 pw.print("N/A,");
899 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 // Heap info - free
902 pw.print(nativeFree); pw.print(',');
903 pw.print(dalvikFree); pw.print(',');
904 pw.print("N/A,");
905 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 // Heap info - proportional set size
908 pw.print(memInfo.nativePss); pw.print(',');
909 pw.print(memInfo.dalvikPss); pw.print(',');
910 pw.print(memInfo.otherPss); pw.print(',');
911 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 // Heap info - shared
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700914 pw.print(memInfo.nativeSharedDirty); pw.print(',');
915 pw.print(memInfo.dalvikSharedDirty); pw.print(',');
916 pw.print(memInfo.otherSharedDirty); pw.print(',');
917 pw.print(memInfo.nativeSharedDirty + memInfo.dalvikSharedDirty
918 + memInfo.otherSharedDirty); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 // Heap info - private
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700921 pw.print(memInfo.nativePrivateDirty); pw.print(',');
922 pw.print(memInfo.dalvikPrivateDirty); pw.print(',');
923 pw.print(memInfo.otherPrivateDirty); pw.print(',');
924 pw.print(memInfo.nativePrivateDirty + memInfo.dalvikPrivateDirty
925 + memInfo.otherPrivateDirty); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 // Object counts
928 pw.print(viewInstanceCount); pw.print(',');
929 pw.print(viewRootInstanceCount); pw.print(',');
930 pw.print(appContextInstanceCount); pw.print(',');
931 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 pw.print(globalAssetCount); pw.print(',');
934 pw.print(globalAssetManagerCount); pw.print(',');
935 pw.print(binderLocalObjectCount); pw.print(',');
936 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 pw.print(binderDeathObjectCount); pw.print(',');
939 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 // SQL
Vasu Noric3849202010-03-09 10:47:25 -0800942 pw.print(stats.memoryUsed / 1024); pw.print(',');
Jeff Brown2a293b62012-01-19 14:02:22 -0800943 pw.print(stats.memoryUsed / 1024); pw.print(',');
944 pw.print(stats.pageCacheOverflow / 1024); pw.print(',');
Dianne Hackbornb437e092011-08-05 17:50:29 -0700945 pw.print(stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -0800946 for (int i = 0; i < stats.dbStats.size(); i++) {
947 DbStats dbStats = stats.dbStats.get(i);
Dianne Hackbornb437e092011-08-05 17:50:29 -0700948 pw.print(','); pw.print(dbStats.dbName);
949 pw.print(','); pw.print(dbStats.pageSize);
950 pw.print(','); pw.print(dbStats.dbSize);
951 pw.print(','); pw.print(dbStats.lookaside);
952 pw.print(','); pw.print(dbStats.cache);
953 pw.print(','); pw.print(dbStats.cache);
Vasu Noric3849202010-03-09 10:47:25 -0800954 }
Dianne Hackbornb437e092011-08-05 17:50:29 -0700955 pw.println();
Bob Leee5408332009-09-04 18:31:17 -0700956
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700957 return memInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 }
Bob Leee5408332009-09-04 18:31:17 -0700959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 // otherwise, show human-readable format
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700961 printRow(pw, HEAP_COLUMN, "", "", "Shared", "Private", "Heap", "Heap", "Heap");
962 printRow(pw, HEAP_COLUMN, "", "Pss", "Dirty", "Dirty", "Size", "Alloc", "Free");
963 printRow(pw, HEAP_COLUMN, "", "------", "------", "------", "------", "------",
964 "------");
965 printRow(pw, HEAP_COLUMN, "Native", memInfo.nativePss, memInfo.nativeSharedDirty,
966 memInfo.nativePrivateDirty, nativeMax, nativeAllocated, nativeFree);
967 printRow(pw, HEAP_COLUMN, "Dalvik", memInfo.dalvikPss, memInfo.dalvikSharedDirty,
968 memInfo.dalvikPrivateDirty, dalvikMax, dalvikAllocated, dalvikFree);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700970 int otherPss = memInfo.otherPss;
971 int otherSharedDirty = memInfo.otherSharedDirty;
972 int otherPrivateDirty = memInfo.otherPrivateDirty;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700974 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
Romain Guy65b345f2011-07-27 18:51:50 -0700975 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
Dianne Hackborn0e3328f2011-07-17 13:31:17 -0700976 memInfo.getOtherPss(i), memInfo.getOtherSharedDirty(i),
977 memInfo.getOtherPrivateDirty(i), "", "", "");
978 otherPss -= memInfo.getOtherPss(i);
979 otherSharedDirty -= memInfo.getOtherSharedDirty(i);
980 otherPrivateDirty -= memInfo.getOtherPrivateDirty(i);
981 }
982
983 printRow(pw, HEAP_COLUMN, "Unknown", otherPss, otherSharedDirty,
984 otherPrivateDirty, "", "", "");
985 printRow(pw, HEAP_COLUMN, "TOTAL", memInfo.getTotalPss(),
986 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
987 nativeMax+dalvikMax, nativeAllocated+dalvikAllocated,
988 nativeFree+dalvikFree);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989
990 pw.println(" ");
991 pw.println(" Objects");
Romain Guy65b345f2011-07-27 18:51:50 -0700992 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRootImpl:",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 viewRootInstanceCount);
994
995 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
996 "Activities:", activityInstanceCount);
997
998 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
999 "AssetManagers:", globalAssetManagerCount);
1000
1001 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
1002 "Proxy Binders:", binderProxyObjectCount);
1003 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
1004
1005 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -07001006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 // SQLite mem info
1008 pw.println(" ");
1009 pw.println(" SQL");
Jeff Brown2a293b62012-01-19 14:02:22 -08001010 printRow(pw, ONE_COUNT_COLUMN, "MEMORY_USED:", stats.memoryUsed / 1024);
1011 printRow(pw, TWO_COUNT_COLUMNS, "PAGECACHE_OVERFLOW:",
1012 stats.pageCacheOverflow / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -08001013 pw.println(" ");
1014 int N = stats.dbStats.size();
1015 if (N > 0) {
1016 pw.println(" DATABASES");
Vasu Nori3c7131f2010-09-21 14:36:57 -07001017 printRow(pw, " %8s %8s %14s %14s %s", "pgsz", "dbsz", "Lookaside(b)", "cache",
1018 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -08001019 for (int i = 0; i < N; i++) {
1020 DbStats dbStats = stats.dbStats.get(i);
Vasu Nori3c7131f2010-09-21 14:36:57 -07001021 printRow(pw, DB_INFO_FORMAT,
1022 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
1023 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
1024 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
1025 dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -08001026 }
1027 }
Bob Leee5408332009-09-04 18:31:17 -07001028
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07001029 // Asset details.
1030 String assetAlloc = AssetManager.getAssetAllocations();
1031 if (assetAlloc != null) {
1032 pw.println(" ");
1033 pw.println(" Asset Allocations");
1034 pw.print(assetAlloc);
1035 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001036
1037 return memInfo;
1038 }
1039
1040 @Override
1041 public void dumpGfxInfo(FileDescriptor fd, String[] args) {
1042 dumpGraphicsInfo(fd);
Romain Guy65b345f2011-07-27 18:51:50 -07001043 WindowManagerImpl.getDefault().dumpGfxInfo(fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 }
1045
Jeff Brown6754ba22011-12-14 20:20:01 -08001046 @Override
1047 public void dumpDbInfo(FileDescriptor fd, String[] args) {
1048 PrintWriter pw = new PrintWriter(new FileOutputStream(fd));
1049 PrintWriterPrinter printer = new PrintWriterPrinter(pw);
1050 SQLiteDebug.dump(printer, args);
1051 pw.flush();
1052 }
1053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 private void printRow(PrintWriter pw, String format, Object...objs) {
1055 pw.println(String.format(format, objs));
1056 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001057
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08001058 public void setCoreSettings(Bundle coreSettings) {
1059 queueOrSendMessage(H.SET_CORE_SETTINGS, coreSettings);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001060 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001061
1062 public void updatePackageCompatibilityInfo(String pkg, CompatibilityInfo info) {
1063 UpdateCompatibilityData ucd = new UpdateCompatibilityData();
1064 ucd.pkg = pkg;
1065 ucd.info = info;
1066 queueOrSendMessage(H.UPDATE_PACKAGE_COMPATIBILITY_INFO, ucd);
1067 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001068
1069 public void scheduleTrimMemory(int level) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001070 queueOrSendMessage(H.TRIM_MEMORY, null, level);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001071 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001072
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 }
1074
Romain Guy65b345f2011-07-27 18:51:50 -07001075 private class H extends Handler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 public static final int LAUNCH_ACTIVITY = 100;
1077 public static final int PAUSE_ACTIVITY = 101;
1078 public static final int PAUSE_ACTIVITY_FINISHING= 102;
1079 public static final int STOP_ACTIVITY_SHOW = 103;
1080 public static final int STOP_ACTIVITY_HIDE = 104;
1081 public static final int SHOW_WINDOW = 105;
1082 public static final int HIDE_WINDOW = 106;
1083 public static final int RESUME_ACTIVITY = 107;
1084 public static final int SEND_RESULT = 108;
Brian Carlstromed7e0072011-03-24 13:27:57 -07001085 public static final int DESTROY_ACTIVITY = 109;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 public static final int BIND_APPLICATION = 110;
1087 public static final int EXIT_APPLICATION = 111;
1088 public static final int NEW_INTENT = 112;
1089 public static final int RECEIVER = 113;
1090 public static final int CREATE_SERVICE = 114;
1091 public static final int SERVICE_ARGS = 115;
1092 public static final int STOP_SERVICE = 116;
1093 public static final int REQUEST_THUMBNAIL = 117;
1094 public static final int CONFIGURATION_CHANGED = 118;
1095 public static final int CLEAN_UP_CONTEXT = 119;
1096 public static final int GC_WHEN_IDLE = 120;
1097 public static final int BIND_SERVICE = 121;
1098 public static final int UNBIND_SERVICE = 122;
1099 public static final int DUMP_SERVICE = 123;
1100 public static final int LOW_MEMORY = 124;
1101 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
1102 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001103 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -07001104 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001105 public static final int DESTROY_BACKUP_AGENT = 129;
1106 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001107 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001108 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001109 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001110 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -07001111 public static final int DUMP_HEAP = 135;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001112 public static final int DUMP_ACTIVITY = 136;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001113 public static final int SLEEPING = 137;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001114 public static final int SET_CORE_SETTINGS = 138;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001115 public static final int UPDATE_PACKAGE_COMPATIBILITY_INFO = 139;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001116 public static final int TRIM_MEMORY = 140;
Marco Nelissen18cb2872011-11-15 11:19:53 -08001117 public static final int DUMP_PROVIDER = 141;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 String codeToString(int code) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001119 if (DEBUG_MESSAGES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 switch (code) {
1121 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
1122 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
1123 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
1124 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
1125 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
1126 case SHOW_WINDOW: return "SHOW_WINDOW";
1127 case HIDE_WINDOW: return "HIDE_WINDOW";
1128 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
1129 case SEND_RESULT: return "SEND_RESULT";
1130 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
1131 case BIND_APPLICATION: return "BIND_APPLICATION";
1132 case EXIT_APPLICATION: return "EXIT_APPLICATION";
1133 case NEW_INTENT: return "NEW_INTENT";
1134 case RECEIVER: return "RECEIVER";
1135 case CREATE_SERVICE: return "CREATE_SERVICE";
1136 case SERVICE_ARGS: return "SERVICE_ARGS";
1137 case STOP_SERVICE: return "STOP_SERVICE";
1138 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
1139 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
1140 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
1141 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
1142 case BIND_SERVICE: return "BIND_SERVICE";
1143 case UNBIND_SERVICE: return "UNBIND_SERVICE";
1144 case DUMP_SERVICE: return "DUMP_SERVICE";
1145 case LOW_MEMORY: return "LOW_MEMORY";
1146 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
1147 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001148 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -07001149 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
1150 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -07001151 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001152 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001153 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001154 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001155 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -07001156 case DUMP_HEAP: return "DUMP_HEAP";
Dianne Hackborn625ac272010-09-17 18:29:22 -07001157 case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001158 case SLEEPING: return "SLEEPING";
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001159 case SET_CORE_SETTINGS: return "SET_CORE_SETTINGS";
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001160 case UPDATE_PACKAGE_COMPATIBILITY_INFO: return "UPDATE_PACKAGE_COMPATIBILITY_INFO";
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001161 case TRIM_MEMORY: return "TRIM_MEMORY";
Marco Nelissen18cb2872011-11-15 11:19:53 -08001162 case DUMP_PROVIDER: return "DUMP_PROVIDER";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 }
1164 }
1165 return "(unknown)";
1166 }
1167 public void handleMessage(Message msg) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001168 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 switch (msg.what) {
1170 case LAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001171 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172
1173 r.packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001174 r.activityInfo.applicationInfo, r.compatInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001175 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 } break;
1177 case RELAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001178 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08001179 handleRelaunchActivity(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180 } break;
1181 case PAUSE_ACTIVITY:
1182 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -07001183 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 break;
1185 case PAUSE_ACTIVITY_FINISHING:
1186 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
1187 break;
1188 case STOP_ACTIVITY_SHOW:
1189 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
1190 break;
1191 case STOP_ACTIVITY_HIDE:
1192 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
1193 break;
1194 case SHOW_WINDOW:
1195 handleWindowVisibility((IBinder)msg.obj, true);
1196 break;
1197 case HIDE_WINDOW:
1198 handleWindowVisibility((IBinder)msg.obj, false);
1199 break;
1200 case RESUME_ACTIVITY:
1201 handleResumeActivity((IBinder)msg.obj, true,
1202 msg.arg1 != 0);
1203 break;
1204 case SEND_RESULT:
1205 handleSendResult((ResultData)msg.obj);
1206 break;
1207 case DESTROY_ACTIVITY:
1208 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
1209 msg.arg2, false);
1210 break;
1211 case BIND_APPLICATION:
1212 AppBindData data = (AppBindData)msg.obj;
1213 handleBindApplication(data);
1214 break;
1215 case EXIT_APPLICATION:
1216 if (mInitialApplication != null) {
1217 mInitialApplication.onTerminate();
1218 }
1219 Looper.myLooper().quit();
1220 break;
1221 case NEW_INTENT:
1222 handleNewIntent((NewIntentData)msg.obj);
1223 break;
1224 case RECEIVER:
1225 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001226 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 break;
1228 case CREATE_SERVICE:
1229 handleCreateService((CreateServiceData)msg.obj);
1230 break;
1231 case BIND_SERVICE:
1232 handleBindService((BindServiceData)msg.obj);
1233 break;
1234 case UNBIND_SERVICE:
1235 handleUnbindService((BindServiceData)msg.obj);
1236 break;
1237 case SERVICE_ARGS:
1238 handleServiceArgs((ServiceArgsData)msg.obj);
1239 break;
1240 case STOP_SERVICE:
1241 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001242 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 break;
1244 case REQUEST_THUMBNAIL:
1245 handleRequestThumbnail((IBinder)msg.obj);
1246 break;
1247 case CONFIGURATION_CHANGED:
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001248 handleConfigurationChanged((Configuration)msg.obj, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 break;
1250 case CLEAN_UP_CONTEXT:
1251 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1252 cci.context.performFinalCleanup(cci.who, cci.what);
1253 break;
1254 case GC_WHEN_IDLE:
1255 scheduleGcIdler();
1256 break;
1257 case DUMP_SERVICE:
Dianne Hackborn625ac272010-09-17 18:29:22 -07001258 handleDumpService((DumpComponentInfo)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 break;
1260 case LOW_MEMORY:
1261 handleLowMemory();
1262 break;
1263 case ACTIVITY_CONFIGURATION_CHANGED:
1264 handleActivityConfigurationChanged((IBinder)msg.obj);
1265 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001266 case PROFILER_CONTROL:
Romain Guy7eabe552011-07-21 14:56:34 -07001267 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj, msg.arg2);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001268 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001269 case CREATE_BACKUP_AGENT:
1270 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1271 break;
1272 case DESTROY_BACKUP_AGENT:
1273 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1274 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001275 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001276 Process.killProcess(Process.myPid());
1277 break;
1278 case REMOVE_PROVIDER:
1279 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001280 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001281 case ENABLE_JIT:
1282 ensureJitEnabled();
1283 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001284 case DISPATCH_PACKAGE_BROADCAST:
1285 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
1286 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001287 case SCHEDULE_CRASH:
1288 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001289 case DUMP_HEAP:
1290 handleDumpHeap(msg.arg1 != 0, (DumpHeapData)msg.obj);
1291 break;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001292 case DUMP_ACTIVITY:
1293 handleDumpActivity((DumpComponentInfo)msg.obj);
1294 break;
Marco Nelissen18cb2872011-11-15 11:19:53 -08001295 case DUMP_PROVIDER:
1296 handleDumpProvider((DumpComponentInfo)msg.obj);
1297 break;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001298 case SLEEPING:
1299 handleSleeping((IBinder)msg.obj, msg.arg1 != 0);
1300 break;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001301 case SET_CORE_SETTINGS:
1302 handleSetCoreSettings((Bundle) msg.obj);
1303 break;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001304 case UPDATE_PACKAGE_COMPATIBILITY_INFO:
1305 handleUpdatePackageCompatibilityInfo((UpdateCompatibilityData)msg.obj);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001306 break;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001307 case TRIM_MEMORY:
1308 handleTrimMemory(msg.arg1);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001309 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07001311 if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 }
Bob Leee5408332009-09-04 18:31:17 -07001313
Brian Carlstromed7e0072011-03-24 13:27:57 -07001314 private void maybeSnapshot() {
1315 if (mBoundApplication != null && SamplingProfilerIntegration.isEnabled()) {
Sen Hubde75702010-05-28 01:54:03 -07001316 // convert the *private* ActivityThread.PackageInfo to *public* known
1317 // android.content.pm.PackageInfo
1318 String packageName = mBoundApplication.info.mPackageName;
1319 android.content.pm.PackageInfo packageInfo = null;
1320 try {
1321 Context context = getSystemContext();
1322 if(context == null) {
1323 Log.e(TAG, "cannot get a valid context");
1324 return;
1325 }
1326 PackageManager pm = context.getPackageManager();
1327 if(pm == null) {
1328 Log.e(TAG, "cannot get a valid PackageManager");
1329 return;
1330 }
1331 packageInfo = pm.getPackageInfo(
1332 packageName, PackageManager.GET_ACTIVITIES);
1333 } catch (NameNotFoundException e) {
1334 Log.e(TAG, "cannot get package info for " + packageName, e);
1335 }
1336 SamplingProfilerIntegration.writeSnapshot(mBoundApplication.processName, packageInfo);
Bob Leee5408332009-09-04 18:31:17 -07001337 }
1338 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 }
1340
Romain Guy65b345f2011-07-27 18:51:50 -07001341 private class Idler implements MessageQueue.IdleHandler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001343 ActivityClientRecord a = mNewActivities;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001344 boolean stopProfiling = false;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001345 if (mBoundApplication != null && mProfiler.profileFd != null
1346 && mProfiler.autoStopProfiler) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001347 stopProfiling = true;
1348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 if (a != null) {
1350 mNewActivities = null;
1351 IActivityManager am = ActivityManagerNative.getDefault();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001352 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001354 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 TAG, "Reporting idle of " + a +
1356 " finished=" +
Romain Guy65b345f2011-07-27 18:51:50 -07001357 (a.activity != null && a.activity.mFinished));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 if (a.activity != null && !a.activity.mFinished) {
1359 try {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001360 am.activityIdle(a.token, a.createdConfig, stopProfiling);
Dianne Hackborne88846e2009-09-30 21:34:25 -07001361 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 } catch (RemoteException ex) {
Romain Guy65b345f2011-07-27 18:51:50 -07001363 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 }
1365 }
1366 prev = a;
1367 a = a.nextIdle;
1368 prev.nextIdle = null;
1369 } while (a != null);
1370 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001371 if (stopProfiling) {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001372 mProfiler.stopProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001373 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001374 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 return false;
1376 }
1377 }
1378
1379 final class GcIdler implements MessageQueue.IdleHandler {
1380 public final boolean queueIdle() {
1381 doGcIfNeeded();
1382 return false;
1383 }
1384 }
1385
Romain Guy65b345f2011-07-27 18:51:50 -07001386 private static class ResourcesKey {
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001387 final private String mResDir;
1388 final private float mScale;
1389 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07001390
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001391 ResourcesKey(String resDir, float scale) {
1392 mResDir = resDir;
1393 mScale = scale;
1394 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
1395 }
Bob Leee5408332009-09-04 18:31:17 -07001396
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001397 @Override
1398 public int hashCode() {
1399 return mHash;
1400 }
1401
1402 @Override
1403 public boolean equals(Object obj) {
1404 if (!(obj instanceof ResourcesKey)) {
1405 return false;
1406 }
1407 ResourcesKey peer = (ResourcesKey) obj;
1408 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
1409 }
1410 }
1411
Romain Guy65b345f2011-07-27 18:51:50 -07001412 public static ActivityThread currentActivityThread() {
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07001413 return sThreadLocal.get();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001414 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415
Romain Guy65b345f2011-07-27 18:51:50 -07001416 public static String currentPackageName() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001417 ActivityThread am = currentActivityThread();
1418 return (am != null && am.mBoundApplication != null)
1419 ? am.mBoundApplication.processName : null;
1420 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421
Romain Guy65b345f2011-07-27 18:51:50 -07001422 public static Application currentApplication() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001423 ActivityThread am = currentActivityThread();
1424 return am != null ? am.mInitialApplication : null;
1425 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001427 public static IPackageManager getPackageManager() {
1428 if (sPackageManager != null) {
1429 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1430 return sPackageManager;
1431 }
1432 IBinder b = ServiceManager.getService("package");
1433 //Slog.v("PackageManager", "default service binder = " + b);
1434 sPackageManager = IPackageManager.Stub.asInterface(b);
1435 //Slog.v("PackageManager", "default service = " + sPackageManager);
1436 return sPackageManager;
1437 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001439 DisplayMetrics getDisplayMetricsLocked(CompatibilityInfo ci, boolean forceUpdate) {
1440 DisplayMetrics dm = mDisplayMetrics.get(ci);
1441 if (dm != null && !forceUpdate) {
1442 return dm;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001443 }
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001444 if (dm == null) {
1445 dm = new DisplayMetrics();
1446 mDisplayMetrics.put(ci, dm);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001447 }
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001448 Display d = WindowManagerImpl.getDefault(ci).getDefaultDisplay();
1449 d.getMetrics(dm);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001450 //Slog.i("foo", "New metrics: w=" + metrics.widthPixels + " h="
1451 // + metrics.heightPixels + " den=" + metrics.density
1452 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001453 return dm;
1454 }
1455
1456 static Configuration applyConfigCompat(Configuration config, CompatibilityInfo compat) {
1457 if (config == null) {
1458 return null;
1459 }
1460 if (compat != null && !compat.supportsScreen()) {
1461 config = new Configuration(config);
1462 compat.applyToConfiguration(config);
1463 }
1464 return config;
1465 }
1466
Romain Guy65b345f2011-07-27 18:51:50 -07001467 private Configuration mMainThreadConfig = new Configuration();
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001468 Configuration applyConfigCompatMainThread(Configuration config, CompatibilityInfo compat) {
1469 if (config == null) {
1470 return null;
1471 }
1472 if (compat != null && !compat.supportsScreen()) {
1473 mMainThreadConfig.setTo(config);
1474 config = mMainThreadConfig;
1475 compat.applyToConfiguration(config);
1476 }
1477 return config;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001480 /**
1481 * Creates the top level Resources for applications with the given compatibility info.
1482 *
1483 * @param resDir the resource directory.
1484 * @param compInfo the compability info. It will use the default compatibility info when it's
1485 * null.
1486 */
1487 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
1488 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
1489 Resources r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001491 // Resources is app scale dependent.
1492 if (false) {
1493 Slog.w(TAG, "getTopLevelResources: " + resDir + " / "
1494 + compInfo.applicationScale);
1495 }
1496 WeakReference<Resources> wr = mActiveResources.get(key);
1497 r = wr != null ? wr.get() : null;
1498 //if (r != null) Slog.i(TAG, "isUpToDate " + resDir + ": " + r.getAssets().isUpToDate());
1499 if (r != null && r.getAssets().isUpToDate()) {
1500 if (false) {
1501 Slog.w(TAG, "Returning cached resources " + r + " " + resDir
1502 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
1503 }
1504 return r;
1505 }
1506 }
1507
1508 //if (r != null) {
1509 // Slog.w(TAG, "Throwing away out-of-date resources!!!! "
1510 // + r + " " + resDir);
1511 //}
1512
1513 AssetManager assets = new AssetManager();
1514 if (assets.addAssetPath(resDir) == 0) {
1515 return null;
1516 }
1517
1518 //Slog.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
Dianne Hackborn836e2622011-10-04 18:32:39 -07001519 DisplayMetrics metrics = getDisplayMetricsLocked(null, false);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001520 r = new Resources(assets, metrics, getConfiguration(), compInfo);
1521 if (false) {
1522 Slog.i(TAG, "Created app resources " + resDir + " " + r + ": "
1523 + r.getConfiguration() + " appScale="
1524 + r.getCompatibilityInfo().applicationScale);
1525 }
1526
1527 synchronized (mPackages) {
1528 WeakReference<Resources> wr = mActiveResources.get(key);
1529 Resources existing = wr != null ? wr.get() : null;
1530 if (existing != null && existing.getAssets().isUpToDate()) {
1531 // Someone else already created the resources while we were
1532 // unlocked; go ahead and use theirs.
1533 r.getAssets().close();
1534 return existing;
1535 }
1536
1537 // XXX need to remove entries when weak references go away
1538 mActiveResources.put(key, new WeakReference<Resources>(r));
1539 return r;
1540 }
1541 }
1542
1543 /**
1544 * Creates the top level resources for the given package.
1545 */
1546 Resources getTopLevelResources(String resDir, LoadedApk pkgInfo) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001547 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo.get());
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001548 }
1549
1550 final Handler getHandler() {
1551 return mH;
1552 }
1553
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001554 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
1555 int flags) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001556 synchronized (mPackages) {
1557 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
1559 ref = mPackages.get(packageName);
1560 } else {
1561 ref = mResourcePackages.get(packageName);
1562 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001563 LoadedApk packageInfo = ref != null ? ref.get() : null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001564 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001565 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
1566 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 if (packageInfo != null && (packageInfo.mResources == null
1568 || packageInfo.mResources.getAssets().isUpToDate())) {
1569 if (packageInfo.isSecurityViolation()
1570 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
1571 throw new SecurityException(
1572 "Requesting code from " + packageName
1573 + " to be run in process "
1574 + mBoundApplication.processName
1575 + "/" + mBoundApplication.appInfo.uid);
1576 }
1577 return packageInfo;
1578 }
1579 }
1580
1581 ApplicationInfo ai = null;
1582 try {
1583 ai = getPackageManager().getApplicationInfo(packageName,
1584 PackageManager.GET_SHARED_LIBRARY_FILES);
1585 } catch (RemoteException e) {
Romain Guy65b345f2011-07-27 18:51:50 -07001586 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 }
1588
1589 if (ai != null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001590 return getPackageInfo(ai, compatInfo, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 }
1592
1593 return null;
1594 }
1595
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001596 public final LoadedApk getPackageInfo(ApplicationInfo ai, CompatibilityInfo compatInfo,
1597 int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
1599 boolean securityViolation = includeCode && ai.uid != 0
1600 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
Amith Yamasani742a6712011-05-04 14:49:28 -07001601 ? !UserId.isSameApp(ai.uid, mBoundApplication.appInfo.uid)
1602 : true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 if ((flags&(Context.CONTEXT_INCLUDE_CODE
1604 |Context.CONTEXT_IGNORE_SECURITY))
1605 == Context.CONTEXT_INCLUDE_CODE) {
1606 if (securityViolation) {
1607 String msg = "Requesting code from " + ai.packageName
1608 + " (with uid " + ai.uid + ")";
1609 if (mBoundApplication != null) {
1610 msg = msg + " to be run in process "
1611 + mBoundApplication.processName + " (with uid "
1612 + mBoundApplication.appInfo.uid + ")";
1613 }
1614 throw new SecurityException(msg);
1615 }
1616 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001617 return getPackageInfo(ai, compatInfo, null, securityViolation, includeCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 }
1619
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001620 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai,
1621 CompatibilityInfo compatInfo) {
1622 return getPackageInfo(ai, compatInfo, null, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 }
1624
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001625 public final LoadedApk peekPackageInfo(String packageName, boolean includeCode) {
1626 synchronized (mPackages) {
1627 WeakReference<LoadedApk> ref;
1628 if (includeCode) {
1629 ref = mPackages.get(packageName);
1630 } else {
1631 ref = mResourcePackages.get(packageName);
1632 }
1633 return ref != null ? ref.get() : null;
1634 }
1635 }
1636
Romain Guy65b345f2011-07-27 18:51:50 -07001637 private LoadedApk getPackageInfo(ApplicationInfo aInfo, CompatibilityInfo compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
1639 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001640 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 if (includeCode) {
1642 ref = mPackages.get(aInfo.packageName);
1643 } else {
1644 ref = mResourcePackages.get(aInfo.packageName);
1645 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001646 LoadedApk packageInfo = ref != null ? ref.get() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 if (packageInfo == null || (packageInfo.mResources != null
1648 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001649 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 : "Loading resource-only package ") + aInfo.packageName
1651 + " (in " + (mBoundApplication != null
1652 ? mBoundApplication.processName : null)
1653 + ")");
1654 packageInfo =
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001655 new LoadedApk(this, aInfo, compatInfo, this, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 securityViolation, includeCode &&
1657 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
1658 if (includeCode) {
1659 mPackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001660 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 } else {
1662 mResourcePackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001663 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 }
1665 }
1666 return packageInfo;
1667 }
1668 }
1669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 ActivityThread() {
1671 }
1672
1673 public ApplicationThread getApplicationThread()
1674 {
1675 return mAppThread;
1676 }
1677
1678 public Instrumentation getInstrumentation()
1679 {
1680 return mInstrumentation;
1681 }
1682
1683 public Configuration getConfiguration() {
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001684 return mResConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 }
1686
1687 public boolean isProfiling() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001688 return mProfiler != null && mProfiler.profileFile != null
1689 && mProfiler.profileFd == null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690 }
1691
1692 public String getProfileFilePath() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001693 return mProfiler.profileFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 }
1695
1696 public Looper getLooper() {
1697 return mLooper;
1698 }
1699
1700 public Application getApplication() {
1701 return mInitialApplication;
1702 }
Bob Leee5408332009-09-04 18:31:17 -07001703
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07001704 public String getProcessName() {
1705 return mBoundApplication.processName;
1706 }
Bob Leee5408332009-09-04 18:31:17 -07001707
Dianne Hackborn21556372010-02-04 16:34:40 -08001708 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 synchronized (this) {
1710 if (mSystemContext == null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001711 ContextImpl context =
1712 ContextImpl.createSystemContext(this);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001713 LoadedApk info = new LoadedApk(this, "android", context, null,
1714 CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 context.init(info, null, this);
1716 context.getResources().updateConfiguration(
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001717 getConfiguration(), getDisplayMetricsLocked(
1718 CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO, false));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 mSystemContext = context;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001720 //Slog.i(TAG, "Created system resources " + context.getResources()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 // + ": " + context.getResources().getConfiguration());
1722 }
1723 }
1724 return mSystemContext;
1725 }
1726
Mike Cleron432b7132009-09-24 15:28:29 -07001727 public void installSystemApplicationInfo(ApplicationInfo info) {
1728 synchronized (this) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001729 ContextImpl context = getSystemContext();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001730 context.init(new LoadedApk(this, "android", context, info,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001731 CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO), null, this);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001732
1733 // give ourselves a default profiler
1734 mProfiler = new Profiler();
Mike Cleron432b7132009-09-24 15:28:29 -07001735 }
1736 }
1737
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001738 void ensureJitEnabled() {
1739 if (!mJitEnabled) {
1740 mJitEnabled = true;
1741 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
1742 }
1743 }
1744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 void scheduleGcIdler() {
1746 if (!mGcIdlerScheduled) {
1747 mGcIdlerScheduled = true;
1748 Looper.myQueue().addIdleHandler(mGcIdler);
1749 }
1750 mH.removeMessages(H.GC_WHEN_IDLE);
1751 }
1752
1753 void unscheduleGcIdler() {
1754 if (mGcIdlerScheduled) {
1755 mGcIdlerScheduled = false;
1756 Looper.myQueue().removeIdleHandler(mGcIdler);
1757 }
1758 mH.removeMessages(H.GC_WHEN_IDLE);
1759 }
1760
1761 void doGcIfNeeded() {
1762 mGcIdlerScheduled = false;
1763 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001764 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 // + "m now=" + now);
1766 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001767 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 BinderInternal.forceGc("bg");
1769 }
1770 }
1771
Jeff Hamilton52d32032011-01-08 15:31:26 -06001772 public void registerOnActivityPausedListener(Activity activity,
1773 OnActivityPausedListener listener) {
1774 synchronized (mOnPauseListeners) {
1775 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
1776 if (list == null) {
1777 list = new ArrayList<OnActivityPausedListener>();
1778 mOnPauseListeners.put(activity, list);
1779 }
1780 list.add(listener);
1781 }
1782 }
1783
Jeff Hamiltonce3224c2011-01-17 11:05:03 -08001784 public void unregisterOnActivityPausedListener(Activity activity,
1785 OnActivityPausedListener listener) {
1786 synchronized (mOnPauseListeners) {
1787 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
1788 if (list != null) {
1789 list.remove(listener);
1790 }
1791 }
1792 }
1793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 public final ActivityInfo resolveActivityInfo(Intent intent) {
1795 ActivityInfo aInfo = intent.resolveActivityInfo(
1796 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
1797 if (aInfo == null) {
1798 // Throw an exception.
1799 Instrumentation.checkStartActivityResult(
1800 IActivityManager.START_CLASS_NOT_FOUND, intent);
1801 }
1802 return aInfo;
1803 }
Bob Leee5408332009-09-04 18:31:17 -07001804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001807 Activity.NonConfigurationInstances lastNonConfigurationInstances) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001808 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001810 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 r.intent = intent;
1812 r.state = state;
1813 r.parent = parent;
1814 r.embeddedID = id;
1815 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001816 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 if (localLOGV) {
1818 ComponentName compname = intent.getComponent();
1819 String name;
1820 if (compname != null) {
1821 name = compname.toShortString();
1822 } else {
1823 name = "(Intent " + intent + ").getComponent() returned null";
1824 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001825 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 + ", comp=" + name
1827 + ", token=" + token);
1828 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07001829 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 }
1831
1832 public final Activity getActivity(IBinder token) {
1833 return mActivities.get(token).activity;
1834 }
1835
1836 public final void sendActivityResult(
1837 IBinder token, String id, int requestCode,
1838 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001839 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07001840 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
1842 list.add(new ResultInfo(id, requestCode, resultCode, data));
1843 mAppThread.scheduleSendResult(token, list);
1844 }
1845
1846 // if the thread hasn't started yet, we don't have the handler, so just
1847 // save the messages until we're ready.
Romain Guy65b345f2011-07-27 18:51:50 -07001848 private void queueOrSendMessage(int what, Object obj) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 queueOrSendMessage(what, obj, 0, 0);
1850 }
1851
Romain Guy65b345f2011-07-27 18:51:50 -07001852 private void queueOrSendMessage(int what, Object obj, int arg1) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 queueOrSendMessage(what, obj, arg1, 0);
1854 }
1855
Romain Guy65b345f2011-07-27 18:51:50 -07001856 private void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 synchronized (this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001858 if (DEBUG_MESSAGES) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
1860 + ": " + arg1 + " / " + obj);
1861 Message msg = Message.obtain();
1862 msg.what = what;
1863 msg.obj = obj;
1864 msg.arg1 = arg1;
1865 msg.arg2 = arg2;
1866 mH.sendMessage(msg);
1867 }
1868 }
1869
Dianne Hackborn21556372010-02-04 16:34:40 -08001870 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 String what) {
1872 ContextCleanupInfo cci = new ContextCleanupInfo();
1873 cci.context = context;
1874 cci.who = who;
1875 cci.what = what;
1876 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
1877 }
1878
Romain Guy65b345f2011-07-27 18:51:50 -07001879 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
1881
1882 ActivityInfo aInfo = r.activityInfo;
1883 if (r.packageInfo == null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001884 r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 Context.CONTEXT_INCLUDE_CODE);
1886 }
Bob Leee5408332009-09-04 18:31:17 -07001887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 ComponentName component = r.intent.getComponent();
1889 if (component == null) {
1890 component = r.intent.resolveActivity(
1891 mInitialApplication.getPackageManager());
1892 r.intent.setComponent(component);
1893 }
1894
1895 if (r.activityInfo.targetActivity != null) {
1896 component = new ComponentName(r.activityInfo.packageName,
1897 r.activityInfo.targetActivity);
1898 }
1899
1900 Activity activity = null;
1901 try {
1902 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
1903 activity = mInstrumentation.newActivity(
1904 cl, component.getClassName(), r.intent);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08001905 StrictMode.incrementExpectedActivityCount(activity.getClass());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 r.intent.setExtrasClassLoader(cl);
1907 if (r.state != null) {
1908 r.state.setClassLoader(cl);
1909 }
1910 } catch (Exception e) {
1911 if (!mInstrumentation.onException(activity, e)) {
1912 throw new RuntimeException(
1913 "Unable to instantiate activity " + component
1914 + ": " + e.toString(), e);
1915 }
1916 }
1917
1918 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001919 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001920
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001921 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
1922 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 TAG, r + ": app=" + app
1924 + ", appName=" + app.getPackageName()
1925 + ", pkg=" + r.packageInfo.getPackageName()
1926 + ", comp=" + r.intent.getComponent().toShortString()
1927 + ", dir=" + r.packageInfo.getAppDir());
1928
1929 if (activity != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001930 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 appContext.init(r.packageInfo, r.token, this);
1932 appContext.setOuterContext(activity);
1933 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001934 Configuration config = new Configuration(mCompatConfiguration);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001935 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07001936 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001937 activity.attach(appContext, this, getInstrumentation(), r.token,
1938 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001939 r.embeddedID, r.lastNonConfigurationInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07001940
Christopher Tateb70f3df2009-04-07 16:07:59 -07001941 if (customIntent != null) {
1942 activity.mIntent = customIntent;
1943 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001944 r.lastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 activity.mStartedActivity = false;
1946 int theme = r.activityInfo.getThemeResource();
1947 if (theme != 0) {
1948 activity.setTheme(theme);
1949 }
1950
1951 activity.mCalled = false;
1952 mInstrumentation.callActivityOnCreate(activity, r.state);
1953 if (!activity.mCalled) {
1954 throw new SuperNotCalledException(
1955 "Activity " + r.intent.getComponent().toShortString() +
1956 " did not call through to super.onCreate()");
1957 }
1958 r.activity = activity;
1959 r.stopped = true;
1960 if (!r.activity.mFinished) {
1961 activity.performStart();
1962 r.stopped = false;
1963 }
1964 if (!r.activity.mFinished) {
1965 if (r.state != null) {
1966 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
1967 }
1968 }
1969 if (!r.activity.mFinished) {
1970 activity.mCalled = false;
1971 mInstrumentation.callActivityOnPostCreate(activity, r.state);
1972 if (!activity.mCalled) {
1973 throw new SuperNotCalledException(
1974 "Activity " + r.intent.getComponent().toShortString() +
1975 " did not call through to super.onPostCreate()");
1976 }
1977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 }
1979 r.paused = true;
1980
1981 mActivities.put(r.token, r);
1982
1983 } catch (SuperNotCalledException e) {
1984 throw e;
1985
1986 } catch (Exception e) {
1987 if (!mInstrumentation.onException(activity, e)) {
1988 throw new RuntimeException(
1989 "Unable to start activity " + component
1990 + ": " + e.toString(), e);
1991 }
1992 }
1993
1994 return activity;
1995 }
1996
Romain Guy65b345f2011-07-27 18:51:50 -07001997 private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001998 // If we are getting ready to gc after going to the background, well
1999 // we are back active so skip it.
2000 unscheduleGcIdler();
2001
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002002 if (r.profileFd != null) {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002003 mProfiler.setProfiler(r.profileFile, r.profileFd);
2004 mProfiler.startProfiling();
2005 mProfiler.autoStopProfiler = r.autoStopProfiler;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002006 }
2007
Dianne Hackborn58f42a52011-10-10 13:46:34 -07002008 // Make sure we are running with the most recent config.
2009 handleConfigurationChanged(null, null);
2010
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002011 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07002013 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002014
2015 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002016 r.createdConfig = new Configuration(mConfiguration);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08002017 Bundle oldState = r.state;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002018 handleResumeActivity(r.token, false, r.isForward);
2019
2020 if (!r.activity.mFinished && r.startsNotResumed) {
2021 // The activity manager actually wants this one to start out
2022 // paused, because it needs to be visible but isn't in the
2023 // foreground. We accomplish this by going through the
2024 // normal startup (because activities expect to go through
2025 // onResume() the first time they run, before their window
2026 // is displayed), and then pausing it. However, in this case
2027 // we do -not- need to do the full pause cycle (of freezing
2028 // and such) because the activity manager assumes it can just
2029 // retain the current state it has.
2030 try {
2031 r.activity.mCalled = false;
2032 mInstrumentation.callActivityOnPause(r.activity);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08002033 // We need to keep around the original state, in case
2034 // we need to be created again.
2035 r.state = oldState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 if (!r.activity.mCalled) {
2037 throw new SuperNotCalledException(
2038 "Activity " + r.intent.getComponent().toShortString() +
2039 " did not call through to super.onPause()");
2040 }
2041
2042 } catch (SuperNotCalledException e) {
2043 throw e;
2044
2045 } catch (Exception e) {
2046 if (!mInstrumentation.onException(r.activity, e)) {
2047 throw new RuntimeException(
2048 "Unable to pause activity "
2049 + r.intent.getComponent().toShortString()
2050 + ": " + e.toString(), e);
2051 }
2052 }
2053 r.paused = true;
2054 }
2055 } else {
2056 // If there was an error, for any reason, tell the activity
2057 // manager to stop us.
2058 try {
2059 ActivityManagerNative.getDefault()
2060 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
2061 } catch (RemoteException ex) {
Romain Guy65b345f2011-07-27 18:51:50 -07002062 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 }
2064 }
2065 }
2066
Romain Guy65b345f2011-07-27 18:51:50 -07002067 private void deliverNewIntents(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002068 List<Intent> intents) {
2069 final int N = intents.size();
2070 for (int i=0; i<N; i++) {
2071 Intent intent = intents.get(i);
2072 intent.setExtrasClassLoader(r.activity.getClassLoader());
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002073 r.activity.mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
2075 }
2076 }
2077
2078 public final void performNewIntents(IBinder token,
2079 List<Intent> intents) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002080 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 if (r != null) {
2082 final boolean resumed = !r.paused;
2083 if (resumed) {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002084 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 mInstrumentation.callActivityOnPause(r.activity);
2086 }
2087 deliverNewIntents(r, intents);
2088 if (resumed) {
Dianne Hackbornb46ed762011-06-02 18:33:15 -07002089 r.activity.performResume();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002090 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 }
2092 }
2093 }
Bob Leee5408332009-09-04 18:31:17 -07002094
Romain Guy65b345f2011-07-27 18:51:50 -07002095 private void handleNewIntent(NewIntentData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002096 performNewIntents(data.token, data.intents);
2097 }
2098
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002099 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
2100
2101 /**
2102 * Return the Intent that's currently being handled by a
2103 * BroadcastReceiver on this thread, or null if none.
2104 * @hide
2105 */
2106 public static Intent getIntentBeingBroadcast() {
2107 return sCurrentBroadcastIntent.get();
2108 }
2109
Romain Guy65b345f2011-07-27 18:51:50 -07002110 private void handleReceiver(ReceiverData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 // If we are getting ready to gc after going to the background, well
2112 // we are back active so skip it.
2113 unscheduleGcIdler();
2114
2115 String component = data.intent.getComponent().getClassName();
2116
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002117 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002118 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002119
2120 IActivityManager mgr = ActivityManagerNative.getDefault();
2121
Romain Guy65b345f2011-07-27 18:51:50 -07002122 BroadcastReceiver receiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 try {
2124 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2125 data.intent.setExtrasClassLoader(cl);
Dianne Hackborne829fef2010-10-26 17:44:01 -07002126 data.setExtrasClassLoader(cl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
2128 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07002129 if (DEBUG_BROADCAST) Slog.i(TAG,
2130 "Finishing failed broadcast to " + data.intent.getComponent());
2131 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132 throw new RuntimeException(
2133 "Unable to instantiate receiver " + component
2134 + ": " + e.toString(), e);
2135 }
2136
2137 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08002138 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07002139
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002140 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 TAG, "Performing receive of " + data.intent
2142 + ": app=" + app
2143 + ", appName=" + app.getPackageName()
2144 + ", pkg=" + packageInfo.getPackageName()
2145 + ", comp=" + data.intent.getComponent().toShortString()
2146 + ", dir=" + packageInfo.getAppDir());
2147
Dianne Hackborn21556372010-02-04 16:34:40 -08002148 ContextImpl context = (ContextImpl)app.getBaseContext();
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002149 sCurrentBroadcastIntent.set(data.intent);
Dianne Hackborne829fef2010-10-26 17:44:01 -07002150 receiver.setPendingResult(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002151 receiver.onReceive(context.getReceiverRestrictedContext(),
2152 data.intent);
2153 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07002154 if (DEBUG_BROADCAST) Slog.i(TAG,
2155 "Finishing failed broadcast to " + data.intent.getComponent());
2156 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157 if (!mInstrumentation.onException(receiver, e)) {
2158 throw new RuntimeException(
2159 "Unable to start receiver " + component
2160 + ": " + e.toString(), e);
2161 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07002162 } finally {
2163 sCurrentBroadcastIntent.set(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164 }
2165
Dianne Hackborne829fef2010-10-26 17:44:01 -07002166 if (receiver.getPendingResult() != null) {
2167 data.finish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002168 }
2169 }
2170
Christopher Tate181fafa2009-05-14 11:12:14 -07002171 // Instantiate a BackupAgent and tell it that it's alive
Romain Guy65b345f2011-07-27 18:51:50 -07002172 private void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002173 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07002174
2175 // no longer idle; we have backup work to do
2176 unscheduleGcIdler();
2177
2178 // instantiate the BackupAgent class named in the manifest
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002179 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07002180 String packageName = packageInfo.mPackageName;
2181 if (mBackupAgents.get(packageName) != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002182 Slog.d(TAG, "BackupAgent " + " for " + packageName
Christopher Tate181fafa2009-05-14 11:12:14 -07002183 + " already exists");
2184 return;
2185 }
Bob Leee5408332009-09-04 18:31:17 -07002186
Christopher Tate181fafa2009-05-14 11:12:14 -07002187 BackupAgent agent = null;
2188 String classname = data.appInfo.backupAgentName;
Christopher Tate4a627c72011-04-01 14:43:32 -07002189
Christopher Tate79ec80d2011-06-24 14:58:49 -07002190 // full backup operation but no app-supplied agent? use the default implementation
2191 if (classname == null && (data.backupMode == IApplicationThread.BACKUP_MODE_FULL
2192 || data.backupMode == IApplicationThread.BACKUP_MODE_RESTORE_FULL)) {
Christopher Tate4a627c72011-04-01 14:43:32 -07002193 classname = "android.app.backup.FullBackupAgent";
Christopher Tate181fafa2009-05-14 11:12:14 -07002194 }
Christopher Tate4a627c72011-04-01 14:43:32 -07002195
Christopher Tate181fafa2009-05-14 11:12:14 -07002196 try {
Christopher Tated1475e02009-07-09 15:36:17 -07002197 IBinder binder = null;
2198 try {
Christopher Tate4a627c72011-04-01 14:43:32 -07002199 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing agent class " + classname);
2200
Christopher Tated1475e02009-07-09 15:36:17 -07002201 java.lang.ClassLoader cl = packageInfo.getClassLoader();
Christopher Tate4a627c72011-04-01 14:43:32 -07002202 agent = (BackupAgent) cl.loadClass(classname).newInstance();
Christopher Tated1475e02009-07-09 15:36:17 -07002203
2204 // set up the agent's context
Dianne Hackborn21556372010-02-04 16:34:40 -08002205 ContextImpl context = new ContextImpl();
Christopher Tated1475e02009-07-09 15:36:17 -07002206 context.init(packageInfo, null, this);
2207 context.setOuterContext(agent);
2208 agent.attach(context);
2209
2210 agent.onCreate();
2211 binder = agent.onBind();
2212 mBackupAgents.put(packageName, agent);
2213 } catch (Exception e) {
2214 // If this is during restore, fail silently; otherwise go
2215 // ahead and let the user see the crash.
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002216 Slog.e(TAG, "Agent threw during creation: " + e);
Christopher Tate75a99702011-05-18 16:28:19 -07002217 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE
2218 && data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE_FULL) {
Christopher Tated1475e02009-07-09 15:36:17 -07002219 throw e;
2220 }
2221 // falling through with 'binder' still null
2222 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002223
2224 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07002225 try {
2226 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
2227 } catch (RemoteException e) {
2228 // nothing to do.
2229 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002230 } catch (Exception e) {
2231 throw new RuntimeException("Unable to create BackupAgent "
Christopher Tate4a627c72011-04-01 14:43:32 -07002232 + classname + ": " + e.toString(), e);
Christopher Tate181fafa2009-05-14 11:12:14 -07002233 }
2234 }
2235
2236 // Tear down a BackupAgent
Romain Guy65b345f2011-07-27 18:51:50 -07002237 private void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002238 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07002239
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002240 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07002241 String packageName = packageInfo.mPackageName;
2242 BackupAgent agent = mBackupAgents.get(packageName);
2243 if (agent != null) {
2244 try {
2245 agent.onDestroy();
2246 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002247 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07002248 e.printStackTrace();
2249 }
2250 mBackupAgents.remove(packageName);
2251 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002252 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07002253 }
2254 }
2255
Romain Guy65b345f2011-07-27 18:51:50 -07002256 private void handleCreateService(CreateServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002257 // If we are getting ready to gc after going to the background, well
2258 // we are back active so skip it.
2259 unscheduleGcIdler();
2260
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002261 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002262 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 Service service = null;
2264 try {
2265 java.lang.ClassLoader cl = packageInfo.getClassLoader();
2266 service = (Service) cl.loadClass(data.info.name).newInstance();
2267 } catch (Exception e) {
2268 if (!mInstrumentation.onException(service, e)) {
2269 throw new RuntimeException(
2270 "Unable to instantiate service " + data.info.name
2271 + ": " + e.toString(), e);
2272 }
2273 }
2274
2275 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002276 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002277
Dianne Hackborn21556372010-02-04 16:34:40 -08002278 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279 context.init(packageInfo, null, this);
2280
Dianne Hackborn0be1f782009-11-09 12:30:12 -08002281 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002282 context.setOuterContext(service);
2283 service.attach(context, this, data.info.name, data.token, app,
2284 ActivityManagerNative.getDefault());
2285 service.onCreate();
2286 mServices.put(data.token, service);
2287 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002288 ActivityManagerNative.getDefault().serviceDoneExecuting(
2289 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002290 } catch (RemoteException e) {
2291 // nothing to do.
2292 }
2293 } catch (Exception e) {
2294 if (!mInstrumentation.onException(service, e)) {
2295 throw new RuntimeException(
2296 "Unable to create service " + data.info.name
2297 + ": " + e.toString(), e);
2298 }
2299 }
2300 }
2301
Romain Guy65b345f2011-07-27 18:51:50 -07002302 private void handleBindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002303 Service s = mServices.get(data.token);
Amith Yamasani742a6712011-05-04 14:49:28 -07002304 if (DEBUG_SERVICE)
2305 Slog.v(TAG, "handleBindService s=" + s + " rebind=" + data.rebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002306 if (s != null) {
2307 try {
2308 data.intent.setExtrasClassLoader(s.getClassLoader());
2309 try {
2310 if (!data.rebind) {
2311 IBinder binder = s.onBind(data.intent);
2312 ActivityManagerNative.getDefault().publishService(
2313 data.token, data.intent, binder);
2314 } else {
2315 s.onRebind(data.intent);
2316 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002317 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002319 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002320 } catch (RemoteException ex) {
2321 }
2322 } catch (Exception e) {
2323 if (!mInstrumentation.onException(s, e)) {
2324 throw new RuntimeException(
2325 "Unable to bind to service " + s
2326 + " with " + data.intent + ": " + e.toString(), e);
2327 }
2328 }
2329 }
2330 }
2331
Romain Guy65b345f2011-07-27 18:51:50 -07002332 private void handleUnbindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002333 Service s = mServices.get(data.token);
2334 if (s != null) {
2335 try {
2336 data.intent.setExtrasClassLoader(s.getClassLoader());
2337 boolean doRebind = s.onUnbind(data.intent);
2338 try {
2339 if (doRebind) {
2340 ActivityManagerNative.getDefault().unbindFinished(
2341 data.token, data.intent, doRebind);
2342 } else {
2343 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002344 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002345 }
2346 } catch (RemoteException ex) {
2347 }
2348 } catch (Exception e) {
2349 if (!mInstrumentation.onException(s, e)) {
2350 throw new RuntimeException(
2351 "Unable to unbind to service " + s
2352 + " with " + data.intent + ": " + e.toString(), e);
2353 }
2354 }
2355 }
2356 }
2357
Dianne Hackborn625ac272010-09-17 18:29:22 -07002358 private void handleDumpService(DumpComponentInfo info) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07002359 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();
2364 try {
2365 info.fd.close();
2366 } catch (IOException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367 }
2368 }
2369 }
2370
Dianne Hackborn625ac272010-09-17 18:29:22 -07002371 private void handleDumpActivity(DumpComponentInfo info) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07002372 ActivityClientRecord r = mActivities.get(info.token);
2373 if (r != null && r.activity != null) {
2374 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
2375 r.activity.dump(info.prefix, info.fd.getFileDescriptor(), pw, info.args);
2376 pw.flush();
2377 try {
2378 info.fd.close();
2379 } catch (IOException e) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07002380 }
2381 }
2382 }
2383
Marco Nelissen18cb2872011-11-15 11:19:53 -08002384 private void handleDumpProvider(DumpComponentInfo info) {
2385 ProviderClientRecord r = mLocalProviders.get(info.token);
2386 if (r != null && r.mLocalProvider != null) {
2387 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
2388 r.mLocalProvider.dump(info.fd.getFileDescriptor(), pw, info.args);
2389 pw.flush();
2390 try {
2391 info.fd.close();
2392 } catch (IOException e) {
2393 }
2394 }
2395 }
2396
Romain Guy65b345f2011-07-27 18:51:50 -07002397 private void handleServiceArgs(ServiceArgsData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002398 Service s = mServices.get(data.token);
2399 if (s != null) {
2400 try {
2401 if (data.args != null) {
2402 data.args.setExtrasClassLoader(s.getClassLoader());
2403 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002404 int res;
2405 if (!data.taskRemoved) {
2406 res = s.onStartCommand(data.args, data.flags, data.startId);
2407 } else {
2408 s.onTaskRemoved(data.args);
2409 res = Service.START_TASK_REMOVED_COMPLETE;
2410 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002411
2412 QueuedWork.waitToFinish();
2413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002414 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002415 ActivityManagerNative.getDefault().serviceDoneExecuting(
2416 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002417 } catch (RemoteException e) {
2418 // nothing to do.
2419 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002420 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002421 } catch (Exception e) {
2422 if (!mInstrumentation.onException(s, e)) {
2423 throw new RuntimeException(
2424 "Unable to start service " + s
2425 + " with " + data.args + ": " + e.toString(), e);
2426 }
2427 }
2428 }
2429 }
2430
Romain Guy65b345f2011-07-27 18:51:50 -07002431 private void handleStopService(IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 Service s = mServices.remove(token);
2433 if (s != null) {
2434 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002435 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002436 s.onDestroy();
2437 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002438 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08002440 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002442
2443 QueuedWork.waitToFinish();
2444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002445 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002446 ActivityManagerNative.getDefault().serviceDoneExecuting(
2447 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002448 } catch (RemoteException e) {
2449 // nothing to do.
2450 }
2451 } catch (Exception e) {
2452 if (!mInstrumentation.onException(s, e)) {
2453 throw new RuntimeException(
2454 "Unable to stop service " + s
2455 + ": " + e.toString(), e);
2456 }
2457 }
2458 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002459 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002460 }
2461
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002462 public final ActivityClientRecord performResumeActivity(IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002463 boolean clearHide) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002464 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002465 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002466 + " finished=" + r.activity.mFinished);
2467 if (r != null && !r.activity.mFinished) {
2468 if (clearHide) {
2469 r.hideForNow = false;
2470 r.activity.mStartedActivity = false;
2471 }
2472 try {
2473 if (r.pendingIntents != null) {
2474 deliverNewIntents(r, r.pendingIntents);
2475 r.pendingIntents = null;
2476 }
2477 if (r.pendingResults != null) {
2478 deliverResults(r, r.pendingResults);
2479 r.pendingResults = null;
2480 }
2481 r.activity.performResume();
2482
Bob Leee5408332009-09-04 18:31:17 -07002483 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002484 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 r.paused = false;
2487 r.stopped = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 r.state = null;
2489 } catch (Exception e) {
2490 if (!mInstrumentation.onException(r.activity, e)) {
2491 throw new RuntimeException(
2492 "Unable to resume activity "
2493 + r.intent.getComponent().toShortString()
2494 + ": " + e.toString(), e);
2495 }
2496 }
2497 }
2498 return r;
2499 }
2500
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002501 final void cleanUpPendingRemoveWindows(ActivityClientRecord r) {
2502 if (r.mPendingRemoveWindow != null) {
2503 r.mPendingRemoveWindowManager.removeViewImmediate(r.mPendingRemoveWindow);
2504 IBinder wtoken = r.mPendingRemoveWindow.getWindowToken();
2505 if (wtoken != null) {
2506 WindowManagerImpl.getDefault().closeAll(wtoken,
2507 r.activity.getClass().getName(), "Activity");
2508 }
2509 }
2510 r.mPendingRemoveWindow = null;
2511 r.mPendingRemoveWindowManager = null;
2512 }
2513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2515 // If we are getting ready to gc after going to the background, well
2516 // we are back active so skip it.
2517 unscheduleGcIdler();
2518
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002519 ActivityClientRecord r = performResumeActivity(token, clearHide);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520
2521 if (r != null) {
2522 final Activity a = r.activity;
2523
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002524 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 TAG, "Resume " + r + " started activity: " +
2526 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2527 + ", finished: " + a.mFinished);
2528
2529 final int forwardBit = isForward ?
2530 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532 // If the window hasn't yet been added to the window manager,
2533 // and this guy didn't finish itself or start another activity,
2534 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002535 boolean willBeVisible = !a.mStartedActivity;
2536 if (!willBeVisible) {
2537 try {
2538 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
2539 a.getActivityToken());
2540 } catch (RemoteException e) {
2541 }
2542 }
2543 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 r.window = r.activity.getWindow();
2545 View decor = r.window.getDecorView();
2546 decor.setVisibility(View.INVISIBLE);
2547 ViewManager wm = a.getWindowManager();
2548 WindowManager.LayoutParams l = r.window.getAttributes();
2549 a.mDecor = decor;
2550 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2551 l.softInputMode |= forwardBit;
2552 if (a.mVisibleFromClient) {
2553 a.mWindowAdded = true;
2554 wm.addView(decor, l);
2555 }
2556
2557 // If the window has already been added, but during resume
2558 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002559 // window visible.
2560 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002561 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 TAG, "Launch " + r + " mStartedActivity set");
2563 r.hideForNow = true;
2564 }
2565
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002566 // Get rid of anything left hanging around.
2567 cleanUpPendingRemoveWindows(r);
2568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 // The window is now visible if it has been added, we are not
2570 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002571 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002572 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002574 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002575 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 performConfigurationChanged(r.activity, r.newConfig);
2577 r.newConfig = null;
2578 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002579 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 + isForward);
2581 WindowManager.LayoutParams l = r.window.getAttributes();
2582 if ((l.softInputMode
2583 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2584 != forwardBit) {
2585 l.softInputMode = (l.softInputMode
2586 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2587 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002588 if (r.activity.mVisibleFromClient) {
2589 ViewManager wm = a.getWindowManager();
2590 View decor = r.window.getDecorView();
2591 wm.updateViewLayout(decor, l);
2592 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002593 }
2594 r.activity.mVisibleFromServer = true;
2595 mNumVisibleActivities++;
2596 if (r.activity.mVisibleFromClient) {
2597 r.activity.makeVisible();
2598 }
2599 }
2600
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002601 if (!r.onlyLocalRequest) {
2602 r.nextIdle = mNewActivities;
2603 mNewActivities = r;
2604 if (localLOGV) Slog.v(
2605 TAG, "Scheduling idle handler for " + r);
2606 Looper.myQueue().addIdleHandler(new Idler());
2607 }
2608 r.onlyLocalRequest = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609
2610 } else {
2611 // If an exception was thrown when trying to resume, then
2612 // just end this activity.
2613 try {
2614 ActivityManagerNative.getDefault()
2615 .finishActivity(token, Activity.RESULT_CANCELED, null);
2616 } catch (RemoteException ex) {
2617 }
2618 }
2619 }
2620
2621 private int mThumbnailWidth = -1;
2622 private int mThumbnailHeight = -1;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002623 private Bitmap mAvailThumbnailBitmap = null;
2624 private Canvas mThumbnailCanvas = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625
Romain Guy65b345f2011-07-27 18:51:50 -07002626 private Bitmap createThumbnailBitmap(ActivityClientRecord r) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002627 Bitmap thumbnail = mAvailThumbnailBitmap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628 try {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002629 if (thumbnail == null) {
2630 int w = mThumbnailWidth;
2631 int h;
2632 if (w < 0) {
2633 Resources res = r.activity.getResources();
2634 mThumbnailHeight = h =
2635 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002637 mThumbnailWidth = w =
2638 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
2639 } else {
2640 h = mThumbnailHeight;
2641 }
2642
2643 // On platforms where we don't want thumbnails, set dims to (0,0)
2644 if ((w > 0) && (h > 0)) {
2645 thumbnail = Bitmap.createBitmap(w, h, THUMBNAIL_FORMAT);
2646 thumbnail.eraseColor(0);
2647 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002648 }
2649
Dianne Hackbornfb3806d2010-12-09 13:14:12 -08002650 if (thumbnail != null) {
2651 Canvas cv = mThumbnailCanvas;
2652 if (cv == null) {
2653 mThumbnailCanvas = cv = new Canvas();
2654 }
2655
2656 cv.setBitmap(thumbnail);
2657 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
2658 mAvailThumbnailBitmap = thumbnail;
2659 thumbnail = null;
2660 }
Dianne Hackborn6311d0a2011-08-02 16:37:58 -07002661 cv.setBitmap(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662 }
Jim Miller0b2a6d02010-07-13 18:01:29 -07002663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 } catch (Exception e) {
2665 if (!mInstrumentation.onException(r.activity, e)) {
2666 throw new RuntimeException(
2667 "Unable to create thumbnail of "
2668 + r.intent.getComponent().toShortString()
2669 + ": " + e.toString(), e);
2670 }
2671 thumbnail = null;
2672 }
2673
2674 return thumbnail;
2675 }
2676
Romain Guy65b345f2011-07-27 18:51:50 -07002677 private void handlePauseActivity(IBinder token, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678 boolean userLeaving, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002679 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002680 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002681 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 if (userLeaving) {
2683 performUserLeavingActivity(r);
2684 }
Bob Leee5408332009-09-04 18:31:17 -07002685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 r.activity.mConfigChangeFlags |= configChanges;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002687 performPauseActivity(token, finished, r.isPreHoneycomb());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07002689 // Make sure any pending writes are now committed.
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002690 if (r.isPreHoneycomb()) {
2691 QueuedWork.waitToFinish();
2692 }
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07002693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 // Tell the activity manager we have paused.
2695 try {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002696 ActivityManagerNative.getDefault().activityPaused(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002697 } catch (RemoteException ex) {
2698 }
2699 }
2700 }
2701
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002702 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 mInstrumentation.callActivityOnUserLeaving(r.activity);
2704 }
2705
2706 final Bundle performPauseActivity(IBinder token, boolean finished,
2707 boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002708 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002709 return r != null ? performPauseActivity(r, finished, saveState) : null;
2710 }
2711
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002712 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002713 boolean saveState) {
2714 if (r.paused) {
2715 if (r.activity.mFinished) {
2716 // If we are finishing, we won't call onResume() in certain cases.
2717 // So here we likewise don't want to call onPause() if the activity
2718 // isn't resumed.
2719 return null;
2720 }
2721 RuntimeException e = new RuntimeException(
2722 "Performing pause of activity that is not resumed: "
2723 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002724 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002725 }
2726 Bundle state = null;
2727 if (finished) {
2728 r.activity.mFinished = true;
2729 }
2730 try {
2731 // Next have the activity save its current state and managed dialogs...
2732 if (!r.activity.mFinished && saveState) {
2733 state = new Bundle();
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04002734 state.setAllowFds(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002735 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2736 r.state = state;
2737 }
2738 // Now we are idle.
2739 r.activity.mCalled = false;
2740 mInstrumentation.callActivityOnPause(r.activity);
2741 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
2742 if (!r.activity.mCalled) {
2743 throw new SuperNotCalledException(
2744 "Activity " + r.intent.getComponent().toShortString() +
2745 " did not call through to super.onPause()");
2746 }
2747
2748 } catch (SuperNotCalledException e) {
2749 throw e;
2750
2751 } catch (Exception e) {
2752 if (!mInstrumentation.onException(r.activity, e)) {
2753 throw new RuntimeException(
2754 "Unable to pause activity "
2755 + r.intent.getComponent().toShortString()
2756 + ": " + e.toString(), e);
2757 }
2758 }
2759 r.paused = true;
Jeff Hamilton52d32032011-01-08 15:31:26 -06002760
2761 // Notify any outstanding on paused listeners
2762 ArrayList<OnActivityPausedListener> listeners;
2763 synchronized (mOnPauseListeners) {
2764 listeners = mOnPauseListeners.remove(r.activity);
2765 }
2766 int size = (listeners != null ? listeners.size() : 0);
2767 for (int i = 0; i < size; i++) {
2768 listeners.get(i).onPaused(r.activity);
2769 }
2770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002771 return state;
2772 }
2773
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002774 final void performStopActivity(IBinder token, boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002775 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002776 performStopActivityInner(r, null, false, saveState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002777 }
2778
2779 private static class StopInfo {
2780 Bitmap thumbnail;
2781 CharSequence description;
2782 }
2783
Jeff Brownddaa9ac2011-11-11 20:16:14 -08002784 private static final class ProviderRefCount {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002785 public int count;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08002786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002787 ProviderRefCount(int pCount) {
2788 count = pCount;
2789 }
2790 }
2791
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002792 /**
2793 * Core implementation of stopping an activity. Note this is a little
2794 * tricky because the server's meaning of stop is slightly different
2795 * than our client -- for the server, stop means to save state and give
2796 * it the result when it is done, but the window may still be visible.
2797 * For the client, we want to call onStop()/onStart() to indicate when
2798 * the activity's UI visibillity changes.
2799 */
Romain Guy65b345f2011-07-27 18:51:50 -07002800 private void performStopActivityInner(ActivityClientRecord r,
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002801 StopInfo info, boolean keepShown, boolean saveState) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002802 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002803 Bundle state = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002804 if (r != null) {
2805 if (!keepShown && r.stopped) {
2806 if (r.activity.mFinished) {
2807 // If we are finishing, we won't call onResume() in certain
2808 // cases. So here we likewise don't want to call onStop()
2809 // if the activity isn't resumed.
2810 return;
2811 }
2812 RuntimeException e = new RuntimeException(
2813 "Performing stop of activity that is not resumed: "
2814 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002815 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 }
2817
2818 if (info != null) {
2819 try {
2820 // First create a thumbnail for the activity...
Dianne Hackborn0500b3c2011-11-01 15:28:43 -07002821 // For now, don't create the thumbnail here; we are
2822 // doing that by doing a screen snapshot.
2823 info.thumbnail = null; //createThumbnailBitmap(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 info.description = r.activity.onCreateDescription();
2825 } catch (Exception e) {
2826 if (!mInstrumentation.onException(r.activity, e)) {
2827 throw new RuntimeException(
2828 "Unable to save state of activity "
2829 + r.intent.getComponent().toShortString()
2830 + ": " + e.toString(), e);
2831 }
2832 }
2833 }
2834
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002835 // Next have the activity save its current state and managed dialogs...
2836 if (!r.activity.mFinished && saveState) {
2837 if (r.state == null) {
2838 state = new Bundle();
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04002839 state.setAllowFds(false);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002840 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2841 r.state = state;
2842 } else {
2843 state = r.state;
2844 }
2845 }
2846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002847 if (!keepShown) {
2848 try {
2849 // Now we are idle.
2850 r.activity.performStop();
2851 } catch (Exception e) {
2852 if (!mInstrumentation.onException(r.activity, e)) {
2853 throw new RuntimeException(
2854 "Unable to stop activity "
2855 + r.intent.getComponent().toShortString()
2856 + ": " + e.toString(), e);
2857 }
2858 }
2859 r.stopped = true;
2860 }
2861
2862 r.paused = true;
2863 }
2864 }
2865
Romain Guy65b345f2011-07-27 18:51:50 -07002866 private void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002867 View v = r.activity.mDecor;
2868 if (v != null) {
2869 if (show) {
2870 if (!r.activity.mVisibleFromServer) {
2871 r.activity.mVisibleFromServer = true;
2872 mNumVisibleActivities++;
2873 if (r.activity.mVisibleFromClient) {
2874 r.activity.makeVisible();
2875 }
2876 }
2877 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002878 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002879 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002880 performConfigurationChanged(r.activity, r.newConfig);
2881 r.newConfig = null;
2882 }
2883 } else {
2884 if (r.activity.mVisibleFromServer) {
2885 r.activity.mVisibleFromServer = false;
2886 mNumVisibleActivities--;
2887 v.setVisibility(View.INVISIBLE);
2888 }
2889 }
2890 }
2891 }
2892
Romain Guy65b345f2011-07-27 18:51:50 -07002893 private void handleStopActivity(IBinder token, boolean show, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002894 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895 r.activity.mConfigChangeFlags |= configChanges;
2896
2897 StopInfo info = new StopInfo();
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002898 performStopActivityInner(r, info, show, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002899
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002900 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002901 TAG, "Finishing stop of " + r + ": show=" + show
2902 + " win=" + r.window);
2903
2904 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07002905
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002906 // Make sure any pending writes are now committed.
2907 if (!r.isPreHoneycomb()) {
2908 QueuedWork.waitToFinish();
2909 }
2910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002911 // Tell activity manager we have been stopped.
2912 try {
2913 ActivityManagerNative.getDefault().activityStopped(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002914 r.token, r.state, info.thumbnail, info.description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 } catch (RemoteException ex) {
2916 }
2917 }
2918
2919 final void performRestartActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002920 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002921 if (r.stopped) {
2922 r.activity.performRestart();
2923 r.stopped = false;
2924 }
2925 }
2926
Romain Guy65b345f2011-07-27 18:51:50 -07002927 private void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002928 ActivityClientRecord r = mActivities.get(token);
Dianne Hackbornbfddc0f2010-12-14 11:28:01 -08002929
2930 if (r == null) {
2931 Log.w(TAG, "handleWindowVisibility: no activity for token " + token);
2932 return;
2933 }
2934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002935 if (!show && !r.stopped) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002936 performStopActivityInner(r, null, show, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937 } else if (show && r.stopped) {
2938 // If we are getting ready to gc after going to the background, well
2939 // we are back active so skip it.
2940 unscheduleGcIdler();
2941
2942 r.activity.performRestart();
2943 r.stopped = false;
2944 }
2945 if (r.activity.mDecor != null) {
Joe Onorato43a17652011-04-06 19:22:23 -07002946 if (false) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002947 TAG, "Handle window " + r + " visibility: " + show);
2948 updateVisibility(r, show);
2949 }
2950 }
2951
Romain Guy65b345f2011-07-27 18:51:50 -07002952 private void handleSleeping(IBinder token, boolean sleeping) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002953 ActivityClientRecord r = mActivities.get(token);
2954
2955 if (r == null) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08002956 Log.w(TAG, "handleSleeping: no activity for token " + token);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002957 return;
2958 }
2959
2960 if (sleeping) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08002961 if (!r.stopped && !r.isPreHoneycomb()) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002962 try {
2963 // Now we are idle.
2964 r.activity.performStop();
2965 } catch (Exception e) {
2966 if (!mInstrumentation.onException(r.activity, e)) {
2967 throw new RuntimeException(
2968 "Unable to stop activity "
2969 + r.intent.getComponent().toShortString()
2970 + ": " + e.toString(), e);
2971 }
2972 }
2973 r.stopped = true;
2974 }
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002975
2976 // Make sure any pending writes are now committed.
2977 if (!r.isPreHoneycomb()) {
2978 QueuedWork.waitToFinish();
2979 }
2980
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002981 // Tell activity manager we slept.
2982 try {
2983 ActivityManagerNative.getDefault().activitySlept(r.token);
2984 } catch (RemoteException ex) {
2985 }
2986 } else {
2987 if (r.stopped && r.activity.mVisibleFromServer) {
2988 r.activity.performRestart();
2989 r.stopped = false;
2990 }
2991 }
2992 }
2993
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08002994 private void handleSetCoreSettings(Bundle coreSettings) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08002995 synchronized (mPackages) {
2996 mCoreSettings = coreSettings;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08002997 }
2998 }
2999
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003000 private void handleUpdatePackageCompatibilityInfo(UpdateCompatibilityData data) {
3001 LoadedApk apk = peekPackageInfo(data.pkg, false);
3002 if (apk != null) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003003 apk.mCompatibilityInfo.set(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003004 }
3005 apk = peekPackageInfo(data.pkg, true);
3006 if (apk != null) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003007 apk.mCompatibilityInfo.set(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003008 }
3009 handleConfigurationChanged(mConfiguration, data.info);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003010 WindowManagerImpl.getDefault().reportNewConfiguration(mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003011 }
3012
Romain Guy65b345f2011-07-27 18:51:50 -07003013 private void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003014 final int N = results.size();
3015 for (int i=0; i<N; i++) {
3016 ResultInfo ri = results.get(i);
3017 try {
3018 if (ri.mData != null) {
3019 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
3020 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003021 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07003022 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003023 r.activity.dispatchActivityResult(ri.mResultWho,
3024 ri.mRequestCode, ri.mResultCode, ri.mData);
3025 } catch (Exception e) {
3026 if (!mInstrumentation.onException(r.activity, e)) {
3027 throw new RuntimeException(
3028 "Failure delivering result " + ri + " to activity "
3029 + r.intent.getComponent().toShortString()
3030 + ": " + e.toString(), e);
3031 }
3032 }
3033 }
3034 }
3035
Romain Guy65b345f2011-07-27 18:51:50 -07003036 private void handleSendResult(ResultData res) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003037 ActivityClientRecord r = mActivities.get(res.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003038 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003039 if (r != null) {
3040 final boolean resumed = !r.paused;
3041 if (!r.activity.mFinished && r.activity.mDecor != null
3042 && r.hideForNow && resumed) {
3043 // We had hidden the activity because it started another
3044 // one... we have gotten a result back and we are not
3045 // paused, so make sure our window is visible.
3046 updateVisibility(r, true);
3047 }
3048 if (resumed) {
3049 try {
3050 // Now we are idle.
3051 r.activity.mCalled = false;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07003052 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003053 mInstrumentation.callActivityOnPause(r.activity);
3054 if (!r.activity.mCalled) {
3055 throw new SuperNotCalledException(
3056 "Activity " + r.intent.getComponent().toShortString()
3057 + " did not call through to super.onPause()");
3058 }
3059 } catch (SuperNotCalledException e) {
3060 throw e;
3061 } catch (Exception e) {
3062 if (!mInstrumentation.onException(r.activity, e)) {
3063 throw new RuntimeException(
3064 "Unable to pause activity "
3065 + r.intent.getComponent().toShortString()
3066 + ": " + e.toString(), e);
3067 }
3068 }
3069 }
3070 deliverResults(r, res.results);
3071 if (resumed) {
Dianne Hackbornb46ed762011-06-02 18:33:15 -07003072 r.activity.performResume();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07003073 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003074 }
3075 }
3076 }
3077
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003078 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003079 return performDestroyActivity(token, finishing, 0, false);
3080 }
3081
Romain Guy65b345f2011-07-27 18:51:50 -07003082 private ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003083 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003084 ActivityClientRecord r = mActivities.get(token);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003085 Class activityClass = null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003086 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 if (r != null) {
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003088 activityClass = r.activity.getClass();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003089 r.activity.mConfigChangeFlags |= configChanges;
3090 if (finishing) {
3091 r.activity.mFinished = true;
3092 }
3093 if (!r.paused) {
3094 try {
3095 r.activity.mCalled = false;
3096 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07003097 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098 r.activity.getComponentName().getClassName());
3099 if (!r.activity.mCalled) {
3100 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003101 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003102 + " did not call through to super.onPause()");
3103 }
3104 } catch (SuperNotCalledException e) {
3105 throw e;
3106 } catch (Exception e) {
3107 if (!mInstrumentation.onException(r.activity, e)) {
3108 throw new RuntimeException(
3109 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003110 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003111 + ": " + e.toString(), e);
3112 }
3113 }
3114 r.paused = true;
3115 }
3116 if (!r.stopped) {
3117 try {
3118 r.activity.performStop();
3119 } catch (SuperNotCalledException e) {
3120 throw e;
3121 } catch (Exception e) {
3122 if (!mInstrumentation.onException(r.activity, e)) {
3123 throw new RuntimeException(
3124 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003125 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003126 + ": " + e.toString(), e);
3127 }
3128 }
3129 r.stopped = true;
3130 }
3131 if (getNonConfigInstance) {
3132 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003133 r.lastNonConfigurationInstances
3134 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003135 } catch (Exception e) {
3136 if (!mInstrumentation.onException(r.activity, e)) {
3137 throw new RuntimeException(
3138 "Unable to retain activity "
3139 + r.intent.getComponent().toShortString()
3140 + ": " + e.toString(), e);
3141 }
3142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003143 }
3144 try {
3145 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07003146 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003147 if (!r.activity.mCalled) {
3148 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003149 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003150 " did not call through to super.onDestroy()");
3151 }
3152 if (r.window != null) {
3153 r.window.closeAllPanels();
3154 }
3155 } catch (SuperNotCalledException e) {
3156 throw e;
3157 } catch (Exception e) {
3158 if (!mInstrumentation.onException(r.activity, e)) {
3159 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003160 "Unable to destroy activity " + safeToComponentShortString(r.intent)
3161 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003162 }
3163 }
3164 }
3165 mActivities.remove(token);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003166 StrictMode.decrementExpectedActivityCount(activityClass);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003167 return r;
3168 }
3169
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07003170 private static String safeToComponentShortString(Intent intent) {
3171 ComponentName component = intent.getComponent();
3172 return component == null ? "[Unknown]" : component.toShortString();
3173 }
3174
Romain Guy65b345f2011-07-27 18:51:50 -07003175 private void handleDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003176 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003177 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003178 configChanges, getNonConfigInstance);
3179 if (r != null) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003180 cleanUpPendingRemoveWindows(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003181 WindowManager wm = r.activity.getWindowManager();
3182 View v = r.activity.mDecor;
3183 if (v != null) {
3184 if (r.activity.mVisibleFromServer) {
3185 mNumVisibleActivities--;
3186 }
3187 IBinder wtoken = v.getWindowToken();
3188 if (r.activity.mWindowAdded) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003189 if (r.onlyLocalRequest) {
3190 // Hold off on removing this until the new activity's
3191 // window is being added.
3192 r.mPendingRemoveWindow = v;
3193 r.mPendingRemoveWindowManager = wm;
3194 } else {
3195 wm.removeViewImmediate(v);
3196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003197 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003198 if (wtoken != null && r.mPendingRemoveWindow == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 WindowManagerImpl.getDefault().closeAll(wtoken,
3200 r.activity.getClass().getName(), "Activity");
3201 }
3202 r.activity.mDecor = null;
3203 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003204 if (r.mPendingRemoveWindow == null) {
3205 // If we are delaying the removal of the activity window, then
3206 // we can't clean up all windows here. Note that we can't do
3207 // so later either, which means any windows that aren't closed
3208 // by the app will leak. Well we try to warning them a lot
3209 // about leaking windows, because that is a bug, so if they are
3210 // using this recreate facility then they get to live with leaks.
3211 WindowManagerImpl.getDefault().closeAll(token,
3212 r.activity.getClass().getName(), "Activity");
3213 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003214
3215 // Mocked out contexts won't be participating in the normal
3216 // process lifecycle, but if we're running with a proper
3217 // ApplicationContext we need to have it tear down things
3218 // cleanly.
3219 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08003220 if (c instanceof ContextImpl) {
3221 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 r.activity.getClass().getName(), "Activity");
3223 }
3224 }
3225 if (finishing) {
3226 try {
3227 ActivityManagerNative.getDefault().activityDestroyed(token);
3228 } catch (RemoteException ex) {
3229 // If the system process has died, it's game over for everyone.
3230 }
3231 }
3232 }
3233
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003234 public final void requestRelaunchActivity(IBinder token,
3235 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
3236 int configChanges, boolean notResumed, Configuration config,
3237 boolean fromServer) {
3238 ActivityClientRecord target = null;
3239
3240 synchronized (mPackages) {
3241 for (int i=0; i<mRelaunchingActivities.size(); i++) {
3242 ActivityClientRecord r = mRelaunchingActivities.get(i);
3243 if (r.token == token) {
3244 target = r;
3245 if (pendingResults != null) {
3246 if (r.pendingResults != null) {
3247 r.pendingResults.addAll(pendingResults);
3248 } else {
3249 r.pendingResults = pendingResults;
3250 }
3251 }
3252 if (pendingNewIntents != null) {
3253 if (r.pendingIntents != null) {
3254 r.pendingIntents.addAll(pendingNewIntents);
3255 } else {
3256 r.pendingIntents = pendingNewIntents;
3257 }
3258 }
3259 break;
3260 }
3261 }
3262
3263 if (target == null) {
3264 target = new ActivityClientRecord();
3265 target.token = token;
3266 target.pendingResults = pendingResults;
3267 target.pendingIntents = pendingNewIntents;
3268 if (!fromServer) {
3269 ActivityClientRecord existing = mActivities.get(token);
3270 if (existing != null) {
3271 target.startsNotResumed = existing.paused;
3272 }
3273 target.onlyLocalRequest = true;
3274 }
3275 mRelaunchingActivities.add(target);
3276 queueOrSendMessage(H.RELAUNCH_ACTIVITY, target);
3277 }
3278
3279 if (fromServer) {
3280 target.startsNotResumed = notResumed;
3281 target.onlyLocalRequest = false;
3282 }
3283 if (config != null) {
3284 target.createdConfig = config;
3285 }
3286 target.pendingConfigChanges |= configChanges;
3287 }
3288 }
3289
Romain Guy65b345f2011-07-27 18:51:50 -07003290 private void handleRelaunchActivity(ActivityClientRecord tmp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291 // If we are getting ready to gc after going to the background, well
3292 // we are back active so skip it.
3293 unscheduleGcIdler();
3294
3295 Configuration changedConfig = null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003296 int configChanges = 0;
Bob Leee5408332009-09-04 18:31:17 -07003297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003298 // First: make sure we have the most recent configuration and most
3299 // recent version of the activity, or skip it if some previous call
3300 // had taken a more recent version.
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003301 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003302 int N = mRelaunchingActivities.size();
3303 IBinder token = tmp.token;
3304 tmp = null;
3305 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003306 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 if (r.token == token) {
3308 tmp = r;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003309 configChanges |= tmp.pendingConfigChanges;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003310 mRelaunchingActivities.remove(i);
3311 i--;
3312 N--;
3313 }
3314 }
Bob Leee5408332009-09-04 18:31:17 -07003315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003317 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003318 return;
3319 }
Bob Leee5408332009-09-04 18:31:17 -07003320
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003321 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
3322 + tmp.token + " with configChanges=0x"
3323 + Integer.toHexString(configChanges));
3324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 if (mPendingConfiguration != null) {
3326 changedConfig = mPendingConfiguration;
3327 mPendingConfiguration = null;
3328 }
3329 }
Bob Leee5408332009-09-04 18:31:17 -07003330
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003331 if (tmp.createdConfig != null) {
3332 // If the activity manager is passing us its current config,
3333 // assume that is really what we want regardless of what we
3334 // may have pending.
3335 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003336 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
3337 && mConfiguration.diff(tmp.createdConfig) != 0)) {
3338 if (changedConfig == null
3339 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
3340 changedConfig = tmp.createdConfig;
3341 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003342 }
3343 }
3344
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003345 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003346 + tmp.token + ": changedConfig=" + changedConfig);
3347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003348 // If there was a pending configuration change, execute it first.
3349 if (changedConfig != null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003350 handleConfigurationChanged(changedConfig, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351 }
Bob Leee5408332009-09-04 18:31:17 -07003352
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003353 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003354 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003355 if (r == null) {
3356 return;
3357 }
Bob Leee5408332009-09-04 18:31:17 -07003358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003359 r.activity.mConfigChangeFlags |= configChanges;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003360 r.onlyLocalRequest = tmp.onlyLocalRequest;
Christopher Tateb70f3df2009-04-07 16:07:59 -07003361 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07003362
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08003363 r.activity.mChangingConfigurations = true;
3364
Dianne Hackborne2b04802010-12-09 09:24:55 -08003365 // Need to ensure state is saved.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366 if (!r.paused) {
Dianne Hackborne2b04802010-12-09 09:24:55 -08003367 performPauseActivity(r.token, false, r.isPreHoneycomb());
3368 }
3369 if (r.state == null && !r.stopped && !r.isPreHoneycomb()) {
3370 r.state = new Bundle();
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04003371 r.state.setAllowFds(false);
Dianne Hackborne2b04802010-12-09 09:24:55 -08003372 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003373 }
Bob Leee5408332009-09-04 18:31:17 -07003374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003375 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07003376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003377 r.activity = null;
3378 r.window = null;
3379 r.hideForNow = false;
3380 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07003381 // Merge any pending results and pending intents; don't just replace them
3382 if (tmp.pendingResults != null) {
3383 if (r.pendingResults == null) {
3384 r.pendingResults = tmp.pendingResults;
3385 } else {
3386 r.pendingResults.addAll(tmp.pendingResults);
3387 }
3388 }
3389 if (tmp.pendingIntents != null) {
3390 if (r.pendingIntents == null) {
3391 r.pendingIntents = tmp.pendingIntents;
3392 } else {
3393 r.pendingIntents.addAll(tmp.pendingIntents);
3394 }
3395 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003396 r.startsNotResumed = tmp.startsNotResumed;
Bob Leee5408332009-09-04 18:31:17 -07003397
Christopher Tateb70f3df2009-04-07 16:07:59 -07003398 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003399 }
3400
Romain Guy65b345f2011-07-27 18:51:50 -07003401 private void handleRequestThumbnail(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003402 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003403 Bitmap thumbnail = createThumbnailBitmap(r);
3404 CharSequence description = null;
3405 try {
3406 description = r.activity.onCreateDescription();
3407 } catch (Exception e) {
3408 if (!mInstrumentation.onException(r.activity, e)) {
3409 throw new RuntimeException(
3410 "Unable to create description of activity "
3411 + r.intent.getComponent().toShortString()
3412 + ": " + e.toString(), e);
3413 }
3414 }
3415 //System.out.println("Reporting top thumbnail " + thumbnail);
3416 try {
3417 ActivityManagerNative.getDefault().reportThumbnail(
3418 token, thumbnail, description);
3419 } catch (RemoteException ex) {
3420 }
3421 }
3422
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003423 ArrayList<ComponentCallbacks2> collectComponentCallbacksLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003424 boolean allActivities, Configuration newConfig) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003425 ArrayList<ComponentCallbacks2> callbacks
3426 = new ArrayList<ComponentCallbacks2>();
Bob Leee5408332009-09-04 18:31:17 -07003427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428 if (mActivities.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003429 Iterator<ActivityClientRecord> it = mActivities.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003430 while (it.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003431 ActivityClientRecord ar = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003432 Activity a = ar.activity;
3433 if (a != null) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003434 Configuration thisConfig = applyConfigCompatMainThread(newConfig,
3435 ar.packageInfo.mCompatibilityInfo.getIfNeeded());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003436 if (!ar.activity.mFinished && (allActivities ||
3437 (a != null && !ar.paused))) {
3438 // If the activity is currently resumed, its configuration
3439 // needs to change right now.
3440 callbacks.add(a);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003441 } else if (thisConfig != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003442 // Otherwise, we will tell it about the change
3443 // the next time it is resumed or shown. Note that
3444 // the activity manager may, before then, decide the
3445 // activity needs to be destroyed to handle its new
3446 // configuration.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003447 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Setting activity "
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003448 + ar.activityInfo.name + " newConfig=" + thisConfig);
3449 ar.newConfig = thisConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003450 }
3451 }
3452 }
3453 }
3454 if (mServices.size() > 0) {
3455 Iterator<Service> it = mServices.values().iterator();
3456 while (it.hasNext()) {
3457 callbacks.add(it.next());
3458 }
3459 }
3460 synchronized (mProviderMap) {
3461 if (mLocalProviders.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003462 Iterator<ProviderClientRecord> it = mLocalProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003463 while (it.hasNext()) {
3464 callbacks.add(it.next().mLocalProvider);
3465 }
3466 }
3467 }
3468 final int N = mAllApplications.size();
3469 for (int i=0; i<N; i++) {
3470 callbacks.add(mAllApplications.get(i));
3471 }
Bob Leee5408332009-09-04 18:31:17 -07003472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 return callbacks;
3474 }
Bob Leee5408332009-09-04 18:31:17 -07003475
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003476 private final void performConfigurationChanged(
3477 ComponentCallbacks2 cb, Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003478 // Only for Activity objects, check that they actually call up to their
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003479 // superclass implementation. ComponentCallbacks2 is an interface, so
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003480 // we check the runtime type and act accordingly.
3481 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
3482 if (activity != null) {
3483 activity.mCalled = false;
3484 }
Bob Leee5408332009-09-04 18:31:17 -07003485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003486 boolean shouldChangeConfig = false;
3487 if ((activity == null) || (activity.mCurrentConfig == null)) {
3488 shouldChangeConfig = true;
3489 } else {
Bob Leee5408332009-09-04 18:31:17 -07003490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003491 // If the new config is the same as the config this Activity
3492 // is already running with then don't bother calling
3493 // onConfigurationChanged
3494 int diff = activity.mCurrentConfig.diff(config);
3495 if (diff != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003496 // If this activity doesn't handle any of the config changes
3497 // then don't bother calling onConfigurationChanged as we're
3498 // going to destroy it.
Dianne Hackborne6676352011-06-01 16:51:20 -07003499 if ((~activity.mActivityInfo.getRealConfigChanged() & diff) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003500 shouldChangeConfig = true;
3501 }
3502 }
3503 }
Bob Leee5408332009-09-04 18:31:17 -07003504
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003505 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003506 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003507 if (shouldChangeConfig) {
3508 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07003509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003510 if (activity != null) {
3511 if (!activity.mCalled) {
3512 throw new SuperNotCalledException(
3513 "Activity " + activity.getLocalClassName() +
3514 " did not call through to super.onConfigurationChanged()");
3515 }
3516 activity.mConfigChangeFlags = 0;
3517 activity.mCurrentConfig = new Configuration(config);
3518 }
3519 }
3520 }
3521
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07003522 public final void applyConfigurationToResources(Configuration config) {
3523 synchronized (mPackages) {
3524 applyConfigurationToResourcesLocked(config, null);
3525 }
3526 }
3527
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003528 final boolean applyConfigurationToResourcesLocked(Configuration config,
3529 CompatibilityInfo compat) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003530 if (mResConfiguration == null) {
3531 mResConfiguration = new Configuration();
3532 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003533 if (!mResConfiguration.isOtherSeqNewer(config) && compat == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003534 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq="
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003535 + mResConfiguration.seq + ", newSeq=" + config.seq);
Dianne Hackbornae078162010-03-18 11:29:37 -07003536 return false;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003537 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003538 int changes = mResConfiguration.updateFrom(config);
Dianne Hackborn836e2622011-10-04 18:32:39 -07003539 DisplayMetrics dm = getDisplayMetricsLocked(null, true);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003540
3541 if (compat != null && (mResCompatibilityInfo == null ||
3542 !mResCompatibilityInfo.equals(compat))) {
3543 mResCompatibilityInfo = compat;
3544 changes |= ActivityInfo.CONFIG_SCREEN_LAYOUT
3545 | ActivityInfo.CONFIG_SCREEN_SIZE
3546 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3547 }
Bob Leee5408332009-09-04 18:31:17 -07003548
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003549 // set it for java, this also affects newly created Resources
3550 if (config.locale != null) {
3551 Locale.setDefault(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003552 }
Bob Leee5408332009-09-04 18:31:17 -07003553
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003554 Resources.updateSystemConfiguration(config, dm, compat);
Bob Leee5408332009-09-04 18:31:17 -07003555
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003556 ApplicationPackageManager.configurationChanged();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003557 //Slog.i(TAG, "Configuration changed in " + currentPackageName());
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003558
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003559 Iterator<WeakReference<Resources>> it =
3560 mActiveResources.values().iterator();
3561 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
3562 // mActiveResources.entrySet().iterator();
3563 while (it.hasNext()) {
3564 WeakReference<Resources> v = it.next();
3565 Resources r = v.get();
3566 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003567 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources "
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003568 + r + " config to: " + config);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003569 r.updateConfiguration(config, dm, compat);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003570 //Slog.i(TAG, "Updated app resources " + v.getKey()
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003571 // + " " + r + ": " + r.getConfiguration());
3572 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003573 //Slog.i(TAG, "Removing old resources " + v.getKey());
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003574 it.remove();
3575 }
3576 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003577
3578 return changes != 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003579 }
Dianne Hackborn836e2622011-10-04 18:32:39 -07003580
3581 final Configuration applyCompatConfiguration() {
3582 Configuration config = mConfiguration;
3583 if (mCompatConfiguration == null) {
3584 mCompatConfiguration = new Configuration();
3585 }
3586 mCompatConfiguration.setTo(mConfiguration);
3587 if (mResCompatibilityInfo != null && !mResCompatibilityInfo.supportsScreen()) {
3588 mResCompatibilityInfo.applyToConfiguration(mCompatConfiguration);
3589 config = mCompatConfiguration;
3590 }
3591 return config;
3592 }
3593
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003594 final void handleConfigurationChanged(Configuration config, CompatibilityInfo compat) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003595
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003596 ArrayList<ComponentCallbacks2> callbacks = null;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003597
3598 synchronized (mPackages) {
3599 if (mPendingConfiguration != null) {
3600 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
3601 config = mPendingConfiguration;
3602 }
3603 mPendingConfiguration = null;
3604 }
3605
3606 if (config == null) {
3607 return;
3608 }
3609
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003610 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003611 + config);
3612
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003613 applyConfigurationToResourcesLocked(config, compat);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003615 if (mConfiguration == null) {
3616 mConfiguration = new Configuration();
3617 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003618 if (!mConfiguration.isOtherSeqNewer(config) && compat == null) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003619 return;
3620 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003621 mConfiguration.updateFrom(config);
Dianne Hackborn836e2622011-10-04 18:32:39 -07003622 config = applyCompatConfiguration();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003623 callbacks = collectComponentCallbacksLocked(false, config);
3624 }
Romain Guy65b345f2011-07-27 18:51:50 -07003625
3626 // Cleanup hardware accelerated stuff
3627 WindowManagerImpl.getDefault().trimLocalMemory();
Bob Leee5408332009-09-04 18:31:17 -07003628
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003629 if (callbacks != null) {
3630 final int N = callbacks.size();
3631 for (int i=0; i<N; i++) {
3632 performConfigurationChanged(callbacks.get(i), config);
3633 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003634 }
3635 }
3636
3637 final void handleActivityConfigurationChanged(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003638 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003639 if (r == null || r.activity == null) {
3640 return;
3641 }
Bob Leee5408332009-09-04 18:31:17 -07003642
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003643 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003644 + r.activityInfo.name);
3645
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003646 performConfigurationChanged(r.activity, mCompatConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003647 }
3648
Romain Guy7eabe552011-07-21 14:56:34 -07003649 final void handleProfilerControl(boolean start, ProfilerControlData pcd, int profileType) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003650 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003651 try {
Romain Guy7eabe552011-07-21 14:56:34 -07003652 switch (profileType) {
3653 case 1:
3654 ViewDebug.startLooperProfiling(pcd.path, pcd.fd.getFileDescriptor());
3655 break;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003656 default:
3657 mProfiler.setProfiler(pcd.path, pcd.fd);
3658 mProfiler.autoStopProfiler = false;
3659 mProfiler.startProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07003660 break;
3661 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003662 } catch (RuntimeException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003663 Slog.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003664 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003665 } finally {
3666 try {
3667 pcd.fd.close();
3668 } catch (IOException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003669 Slog.w(TAG, "Failure closing profile fd", e);
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003670 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003671 }
3672 } else {
Romain Guy7eabe552011-07-21 14:56:34 -07003673 switch (profileType) {
3674 case 1:
3675 ViewDebug.stopLooperProfiling();
3676 break;
3677 default:
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003678 mProfiler.stopProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07003679 break;
Romain Guy7eabe552011-07-21 14:56:34 -07003680 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003681 }
3682 }
Bob Leee5408332009-09-04 18:31:17 -07003683
Andy McFadden824c5102010-07-09 16:26:57 -07003684 final void handleDumpHeap(boolean managed, DumpHeapData dhd) {
3685 if (managed) {
3686 try {
3687 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor());
3688 } catch (IOException e) {
3689 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
3690 + " -- can the process access this path?");
3691 } finally {
3692 try {
3693 dhd.fd.close();
3694 } catch (IOException e) {
3695 Slog.w(TAG, "Failure closing profile fd", e);
3696 }
3697 }
3698 } else {
Andy McFadden06a6b552010-07-13 16:28:09 -07003699 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07003700 }
3701 }
3702
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003703 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
3704 boolean hasPkgInfo = false;
3705 if (packages != null) {
3706 for (int i=packages.length-1; i>=0; i--) {
3707 //Slog.i(TAG, "Cleaning old package: " + packages[i]);
3708 if (!hasPkgInfo) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003709 WeakReference<LoadedApk> ref;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003710 ref = mPackages.get(packages[i]);
3711 if (ref != null && ref.get() != null) {
3712 hasPkgInfo = true;
3713 } else {
3714 ref = mResourcePackages.get(packages[i]);
3715 if (ref != null && ref.get() != null) {
3716 hasPkgInfo = true;
3717 }
3718 }
3719 }
3720 mPackages.remove(packages[i]);
3721 mResourcePackages.remove(packages[i]);
3722 }
3723 }
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003724 ApplicationPackageManager.handlePackageBroadcast(cmd, packages,
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003725 hasPkgInfo);
3726 }
3727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003728 final void handleLowMemory() {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003729 ArrayList<ComponentCallbacks2> callbacks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003730
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003731 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003732 callbacks = collectComponentCallbacksLocked(true, null);
3733 }
Bob Leee5408332009-09-04 18:31:17 -07003734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003735 final int N = callbacks.size();
3736 for (int i=0; i<N; i++) {
3737 callbacks.get(i).onLowMemory();
3738 }
3739
Chris Tatece229052009-03-25 16:44:52 -07003740 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3741 if (Process.myUid() != Process.SYSTEM_UID) {
3742 int sqliteReleased = SQLiteDatabase.releaseMemory();
3743 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3744 }
Bob Leee5408332009-09-04 18:31:17 -07003745
Mike Reedcaf0df12009-04-27 14:32:05 -04003746 // Ask graphics to free up as much as possible (font/image caches)
3747 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748
3749 BinderInternal.forceGc("mem");
3750 }
3751
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003752 final void handleTrimMemory(int level) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003753 ArrayList<ComponentCallbacks2> callbacks;
3754
3755 synchronized (mPackages) {
3756 callbacks = collectComponentCallbacksLocked(true, null);
3757 }
3758
3759 final int N = callbacks.size();
3760 for (int i=0; i<N; i++) {
3761 callbacks.get(i).onTrimMemory(level);
3762 }
Teng-Hui Zhua34eb912012-01-25 13:46:16 -08003763 WindowManagerImpl.getDefault().trimMemory(level);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003764 }
3765
Romain Guya9582652011-11-10 14:20:10 -08003766 private void setupGraphicsSupport(LoadedApk info) {
3767 try {
3768 int uid = Process.myUid();
3769 String[] packages = getPackageManager().getPackagesForUid(uid);
3770
3771 // If there are several packages in this application we won't
3772 // initialize the graphics disk caches
3773 if (packages.length == 1) {
3774 ContextImpl appContext = new ContextImpl();
3775 appContext.init(info, null, this);
3776
3777 HardwareRenderer.setupDiskCache(appContext.getCacheDir());
3778 }
3779 } catch (RemoteException e) {
3780 // Ignore
3781 }
3782 }
3783
Romain Guy65b345f2011-07-27 18:51:50 -07003784 private void handleBindApplication(AppBindData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003785 mBoundApplication = data;
3786 mConfiguration = new Configuration(data.config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003787 mCompatConfiguration = new Configuration(data.config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003788
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003789 mProfiler = new Profiler();
3790 mProfiler.profileFile = data.initProfileFile;
3791 mProfiler.profileFd = data.initProfileFd;
3792 mProfiler.autoStopProfiler = data.initAutoStopProfiler;
3793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003794 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003795 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003796 android.ddm.DdmHandleAppName.setAppName(data.processName);
3797
Dianne Hackborn5d927c22011-09-02 12:22:18 -07003798 if (data.persistent) {
3799 // Persistent processes on low-memory devices do not get to
3800 // use hardware accelerated drawing, since this can add too much
3801 // overhead to the process.
3802 Display display = WindowManagerImpl.getDefault().getDefaultDisplay();
3803 if (!ActivityManager.isHighEndGfx(display)) {
3804 HardwareRenderer.disable(false);
3805 }
3806 }
Romain Guya9582652011-11-10 14:20:10 -08003807
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003808 if (mProfiler.profileFd != null) {
3809 mProfiler.startProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003810 }
3811
Joe Onoratod630f102011-03-17 18:42:26 -07003812 // If the app is Honeycomb MR1 or earlier, switch its AsyncTask
3813 // implementation to use the pool executor. Normally, we use the
3814 // serialized executor as the default. This has to happen in the
3815 // main thread so the main looper is set right.
Dianne Hackborn81e92762011-10-09 16:00:21 -07003816 if (data.appInfo.targetSdkVersion <= android.os.Build.VERSION_CODES.HONEYCOMB_MR1) {
Joe Onoratod630f102011-03-17 18:42:26 -07003817 AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
3818 }
3819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003820 /*
3821 * Before spawning a new process, reset the time zone to be the system time zone.
3822 * This needs to be done because the system time zone could have changed after the
3823 * the spawning of this process. Without doing this this process would have the incorrect
3824 * system time zone.
3825 */
3826 TimeZone.setDefault(null);
3827
3828 /*
3829 * Initialize the default locale in this process for the reasons we set the time zone.
3830 */
3831 Locale.setDefault(data.config.locale);
3832
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003833 /*
3834 * Update the system configuration since its preloaded and might not
3835 * reflect configuration changes. The configuration object passed
3836 * in AppBindData can be safely assumed to be up to date
3837 */
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07003838 applyConfigurationToResourcesLocked(data.config, data.compatInfo);
Dianne Hackborn836e2622011-10-04 18:32:39 -07003839 applyCompatConfiguration();
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003840
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003841 data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003842
Romain Guya9582652011-11-10 14:20:10 -08003843 setupGraphicsSupport(data.info);
3844
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003845 /**
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003846 * For system applications on userdebug/eng builds, log stack
3847 * traces of disk and network access to dropbox for analysis.
3848 */
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07003849 if ((data.appInfo.flags &
3850 (ApplicationInfo.FLAG_SYSTEM |
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07003851 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0) {
3852 StrictMode.conditionallyEnableDebugLogging();
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003853 }
3854
3855 /**
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07003856 * For apps targetting SDK Honeycomb or later, we don't allow
3857 * network usage on the main event loop / UI thread.
3858 *
3859 * Note to those grepping: this is what ultimately throws
3860 * NetworkOnMainThreadException ...
3861 */
3862 if (data.appInfo.targetSdkVersion > 9) {
3863 StrictMode.enableDeathOnNetwork();
3864 }
3865
3866 /**
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003867 * Switch this process to density compatibility mode if needed.
3868 */
3869 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3870 == 0) {
3871 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3872 }
Bob Leee5408332009-09-04 18:31:17 -07003873
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003874 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3875 // XXX should have option to change the port.
3876 Debug.changeDebugPort(8100);
3877 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003878 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003879 + " is waiting for the debugger on port 8100...");
3880
3881 IActivityManager mgr = ActivityManagerNative.getDefault();
3882 try {
3883 mgr.showWaitingForDebugger(mAppThread, true);
3884 } catch (RemoteException ex) {
3885 }
3886
3887 Debug.waitForDebugger();
3888
3889 try {
3890 mgr.showWaitingForDebugger(mAppThread, false);
3891 } catch (RemoteException ex) {
3892 }
3893
3894 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003895 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896 + " can be debugged on port 8100...");
3897 }
3898 }
3899
Robert Greenwalt434203a2010-10-11 16:00:27 -07003900 /**
3901 * Initialize the default http proxy in this process for the reasons we set the time zone.
3902 */
3903 IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08003904 if (b != null) {
3905 // In pre-boot mode (doing initial launch to collect password), not
3906 // all system is up. This includes the connectivity service, so don't
3907 // crash if we can't get it.
3908 IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
3909 try {
3910 ProxyProperties proxyProperties = service.getProxy();
3911 Proxy.setHttpProxySystemProperty(proxyProperties);
3912 } catch (RemoteException e) {}
3913 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003914
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003915 if (data.instrumentationName != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08003916 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003917 appContext.init(data.info, null, this);
3918 InstrumentationInfo ii = null;
3919 try {
3920 ii = appContext.getPackageManager().
3921 getInstrumentationInfo(data.instrumentationName, 0);
3922 } catch (PackageManager.NameNotFoundException e) {
3923 }
3924 if (ii == null) {
3925 throw new RuntimeException(
3926 "Unable to find instrumentation info for: "
3927 + data.instrumentationName);
3928 }
3929
3930 mInstrumentationAppDir = ii.sourceDir;
3931 mInstrumentationAppPackage = ii.packageName;
3932 mInstrumentedAppDir = data.info.getAppDir();
3933
3934 ApplicationInfo instrApp = new ApplicationInfo();
3935 instrApp.packageName = ii.packageName;
3936 instrApp.sourceDir = ii.sourceDir;
3937 instrApp.publicSourceDir = ii.publicSourceDir;
3938 instrApp.dataDir = ii.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003939 instrApp.nativeLibraryDir = ii.nativeLibraryDir;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003940 LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003941 appContext.getClassLoader(), false, true);
Dianne Hackborn21556372010-02-04 16:34:40 -08003942 ContextImpl instrContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003943 instrContext.init(pi, null, this);
3944
3945 try {
3946 java.lang.ClassLoader cl = instrContext.getClassLoader();
3947 mInstrumentation = (Instrumentation)
3948 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3949 } catch (Exception e) {
3950 throw new RuntimeException(
3951 "Unable to instantiate instrumentation "
3952 + data.instrumentationName + ": " + e.toString(), e);
3953 }
3954
3955 mInstrumentation.init(this, instrContext, appContext,
3956 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3957
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003958 if (mProfiler.profileFile != null && !ii.handleProfiling
3959 && mProfiler.profileFd == null) {
3960 mProfiler.handlingProfiling = true;
3961 File file = new File(mProfiler.profileFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962 file.getParentFile().mkdirs();
3963 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3964 }
3965
3966 try {
3967 mInstrumentation.onCreate(data.instrumentationArgs);
3968 }
3969 catch (Exception e) {
3970 throw new RuntimeException(
3971 "Exception thrown in onCreate() of "
3972 + data.instrumentationName + ": " + e.toString(), e);
3973 }
3974
3975 } else {
3976 mInstrumentation = new Instrumentation();
3977 }
3978
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08003979 if ((data.appInfo.flags&ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
Dianne Hackbornde398512011-01-18 18:45:21 -08003980 dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08003981 }
3982
Christopher Tate181fafa2009-05-14 11:12:14 -07003983 // If the app is being launched for full backup or restore, bring it up in
3984 // a restricted environment with the base application class.
Dianne Hackborn0be1f782009-11-09 12:30:12 -08003985 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003986 mInitialApplication = app;
3987
Christopher Tate75a99702011-05-18 16:28:19 -07003988 // don't bring up providers in restricted mode; they may depend on the
3989 // app's custom Application class
3990 if (!data.restrictedBackupMode){
3991 List<ProviderInfo> providers = data.providers;
3992 if (providers != null) {
3993 installContentProviders(app, providers);
3994 // For process that contains content providers, we want to
3995 // ensure that the JIT is enabled "at some point".
3996 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
3997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003998 }
3999
4000 try {
4001 mInstrumentation.callApplicationOnCreate(app);
4002 } catch (Exception e) {
4003 if (!mInstrumentation.onException(app, e)) {
4004 throw new RuntimeException(
4005 "Unable to create application " + app.getClass().getName()
4006 + ": " + e.toString(), e);
4007 }
4008 }
4009 }
4010
4011 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
4012 IActivityManager am = ActivityManagerNative.getDefault();
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07004013 if (mProfiler.profileFile != null && mProfiler.handlingProfiling
4014 && mProfiler.profileFd == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004015 Debug.stopMethodTracing();
4016 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004017 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004018 // + ", app thr: " + mAppThread);
4019 try {
4020 am.finishInstrumentation(mAppThread, resultCode, results);
4021 } catch (RemoteException ex) {
4022 }
4023 }
4024
Romain Guy65b345f2011-07-27 18:51:50 -07004025 private void installContentProviders(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004026 Context context, List<ProviderInfo> providers) {
4027 final ArrayList<IActivityManager.ContentProviderHolder> results =
4028 new ArrayList<IActivityManager.ContentProviderHolder>();
4029
4030 Iterator<ProviderInfo> i = providers.iterator();
4031 while (i.hasNext()) {
4032 ProviderInfo cpi = i.next();
4033 StringBuilder buf = new StringBuilder(128);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07004034 buf.append("Pub ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035 buf.append(cpi.authority);
4036 buf.append(": ");
4037 buf.append(cpi.name);
4038 Log.i(TAG, buf.toString());
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004039 IContentProvider cp = installProvider(context, null, cpi,
4040 false /*noisy*/, true /*noReleaseNeeded*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004041 if (cp != null) {
4042 IActivityManager.ContentProviderHolder cph =
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004043 new IActivityManager.ContentProviderHolder(cpi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004044 cph.provider = cp;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004045 cph.noReleaseNeeded = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 results.add(cph);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004047 }
4048 }
4049
4050 try {
4051 ActivityManagerNative.getDefault().publishContentProviders(
4052 getApplicationThread(), results);
4053 } catch (RemoteException ex) {
4054 }
4055 }
4056
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004057 public final IContentProvider acquireProvider(Context c, String name) {
4058 IContentProvider provider = acquireExistingProvider(c, name);
4059 if (provider != null) {
4060 return provider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004061 }
4062
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004063 // There is a possible race here. Another thread may try to acquire
4064 // the same provider at the same time. When this happens, we want to ensure
4065 // that the first one wins.
4066 // Note that we cannot hold the lock while acquiring and installing the
4067 // provider since it might take a long time to run and it could also potentially
4068 // be re-entrant in the case where the provider is in the same process.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004069 IActivityManager.ContentProviderHolder holder = null;
4070 try {
4071 holder = ActivityManagerNative.getDefault().getContentProvider(
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004072 getApplicationThread(), name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004073 } catch (RemoteException ex) {
4074 }
4075 if (holder == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004076 Slog.e(TAG, "Failed to find provider info for " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004077 return null;
4078 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004079
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004080 // Install provider will increment the reference count for us, and break
4081 // any ties in the race.
4082 provider = installProvider(c, holder.provider, holder.info,
4083 true /*noisy*/, holder.noReleaseNeeded);
4084 if (holder.provider != null && provider != holder.provider) {
4085 if (localLOGV) {
4086 Slog.v(TAG, "acquireProvider: lost the race, releasing extraneous "
4087 + "reference to the content provider");
4088 }
4089 try {
4090 ActivityManagerNative.getDefault().removeContentProvider(
4091 getApplicationThread(), name);
4092 } catch (RemoteException ex) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004093 }
4094 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004095 return provider;
4096 }
4097
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07004098 public final IContentProvider acquireExistingProvider(Context c, String name) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004099 synchronized (mProviderMap) {
4100 ProviderClientRecord pr = mProviderMap.get(name);
4101 if (pr == null) {
4102 return null;
4103 }
4104
4105 IContentProvider provider = pr.mProvider;
4106 IBinder jBinder = provider.asBinder();
4107
4108 // Only increment the ref count if we have one. If we don't then the
4109 // provider is not reference counted and never needs to be released.
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07004110 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004111 if (prc != null) {
4112 prc.count += 1;
4113 if (prc.count == 1) {
4114 if (localLOGV) {
4115 Slog.v(TAG, "acquireExistingProvider: "
4116 + "snatched provider from the jaws of death");
4117 }
4118 // Because the provider previously had a reference count of zero,
4119 // it was scheduled to be removed. Cancel that.
4120 mH.removeMessages(H.REMOVE_PROVIDER, provider);
4121 }
4122 }
4123 return provider;
4124 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07004125 }
4126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004127 public final boolean releaseProvider(IContentProvider provider) {
4128 if(provider == null) {
4129 return false;
4130 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004132 IBinder jBinder = provider.asBinder();
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004133 synchronized (mProviderMap) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004134 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004135 if (prc == null) {
4136 // The provider has no ref count, no release is needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004137 return false;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004138 }
4139
4140 if (prc.count == 0) {
4141 if (localLOGV) Slog.v(TAG, "releaseProvider: ref count already 0, how?");
4142 return false;
4143 }
4144
4145 prc.count -= 1;
4146 if (prc.count == 0) {
4147 // Schedule the actual remove asynchronously, since we don't know the context
4148 // this will be called in.
4149 // TODO: it would be nice to post a delayed message, so
4150 // if we come back and need the same provider quickly
4151 // we will still have it available.
4152 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
4153 mH.sendMessage(msg);
4154 }
4155 return true;
4156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004157 }
4158
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004159 final void completeRemoveProvider(IContentProvider provider) {
4160 IBinder jBinder = provider.asBinder();
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004161 String remoteProviderName = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004162 synchronized(mProviderMap) {
4163 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004164 if (prc == null) {
4165 // Either no release is needed (so we shouldn't be here) or the
4166 // provider was already released.
4167 if (localLOGV) Slog.v(TAG, "completeRemoveProvider: release not needed");
4168 return;
4169 }
4170
4171 if (prc.count != 0) {
4172 // There was a race! Some other client managed to acquire
4173 // the provider before the removal was completed.
4174 // Abort the removal. We will do it later.
4175 if (localLOGV) Slog.v(TAG, "completeRemoveProvider: lost the race, "
4176 + "provider still in use");
4177 return;
4178 }
4179
4180 mProviderRefCountMap.remove(jBinder);
4181
4182 Iterator<ProviderClientRecord> iter = mProviderMap.values().iterator();
4183 while (iter.hasNext()) {
4184 ProviderClientRecord pr = iter.next();
4185 IBinder myBinder = pr.mProvider.asBinder();
4186 if (myBinder == jBinder) {
4187 iter.remove();
4188 if (pr.mLocalProvider == null) {
4189 myBinder.unlinkToDeath(pr, 0);
4190 if (remoteProviderName == null) {
4191 remoteProviderName = pr.mName;
4192 }
4193 }
4194 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004195 }
4196 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004197
4198 if (remoteProviderName != null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004199 try {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004200 if (localLOGV) {
4201 Slog.v(TAG, "removeProvider: Invoking ActivityManagerNative."
4202 + "removeContentProvider(" + remoteProviderName + ")");
4203 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004204 ActivityManagerNative.getDefault().removeContentProvider(
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004205 getApplicationThread(), remoteProviderName);
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004206 } catch (RemoteException e) {
4207 //do nothing content provider object is dead any way
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004208 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07004209 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07004210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004211
4212 final void removeDeadProvider(String name, IContentProvider provider) {
4213 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004214 ProviderClientRecord pr = mProviderMap.get(name);
Jeff Brown2a4c5ac2011-08-23 11:58:26 -07004215 if (pr != null && pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004216 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004217 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07004218 if (removed != null) {
4219 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
4220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004221 }
4222 }
4223 }
4224
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004225 /**
4226 * Installs the provider.
4227 *
4228 * Providers that are local to the process or that come from the system server
4229 * may be installed permanently which is indicated by setting noReleaseNeeded to true.
4230 * Other remote providers are reference counted. The initial reference count
4231 * for all reference counted providers is one. Providers that are not reference
4232 * counted do not have a reference count (at all).
4233 *
4234 * This method detects when a provider has already been installed. When this happens,
4235 * it increments the reference count of the existing provider (if appropriate)
4236 * and returns the existing provider. This can happen due to concurrent
4237 * attempts to acquire the same provider.
4238 */
Romain Guy65b345f2011-07-27 18:51:50 -07004239 private IContentProvider installProvider(Context context,
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004240 IContentProvider provider, ProviderInfo info,
4241 boolean noisy, boolean noReleaseNeeded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004242 ContentProvider localProvider = null;
4243 if (provider == null) {
4244 if (noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004245 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004246 + info.name);
4247 }
4248 Context c = null;
4249 ApplicationInfo ai = info.applicationInfo;
4250 if (context.getPackageName().equals(ai.packageName)) {
4251 c = context;
4252 } else if (mInitialApplication != null &&
4253 mInitialApplication.getPackageName().equals(ai.packageName)) {
4254 c = mInitialApplication;
4255 } else {
4256 try {
4257 c = context.createPackageContext(ai.packageName,
4258 Context.CONTEXT_INCLUDE_CODE);
4259 } catch (PackageManager.NameNotFoundException e) {
Romain Guy65b345f2011-07-27 18:51:50 -07004260 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004261 }
4262 }
4263 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004264 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004265 ai.packageName +
4266 " while loading content provider " +
4267 info.name);
4268 return null;
4269 }
4270 try {
4271 final java.lang.ClassLoader cl = c.getClassLoader();
4272 localProvider = (ContentProvider)cl.
4273 loadClass(info.name).newInstance();
4274 provider = localProvider.getIContentProvider();
4275 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004276 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004277 info.name + " from sourceDir " +
4278 info.applicationInfo.sourceDir);
4279 return null;
4280 }
Joe Onorato43a17652011-04-06 19:22:23 -07004281 if (false) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004282 TAG, "Instantiating local provider " + info.name);
4283 // XXX Need to create the correct context for this provider.
4284 localProvider.attachInfo(c, info);
4285 } catch (java.lang.Exception e) {
4286 if (!mInstrumentation.onException(null, e)) {
4287 throw new RuntimeException(
4288 "Unable to get provider " + info.name
4289 + ": " + e.toString(), e);
4290 }
4291 return null;
4292 }
4293 } else if (localLOGV) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004294 Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004295 + info.name);
4296 }
4297
4298 synchronized (mProviderMap) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004299 // There is a possibility that this thread raced with another thread to
4300 // add the provider. If we find another thread got there first then we
4301 // just get out of the way and return the original provider.
4302 IBinder jBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004303 String names[] = PATTERN_SEMICOLON.split(info.authority);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004304 for (int i = 0; i < names.length; i++) {
4305 ProviderClientRecord pr = mProviderMap.get(names[i]);
4306 if (pr != null) {
4307 if (localLOGV) {
4308 Slog.v(TAG, "installProvider: lost the race, "
4309 + "using existing named provider");
4310 }
4311 provider = pr.mProvider;
4312 } else {
4313 pr = new ProviderClientRecord(names[i], provider, localProvider);
4314 if (localProvider == null) {
4315 try {
4316 jBinder.linkToDeath(pr, 0);
4317 } catch (RemoteException e) {
4318 // Provider already dead. Bail out of here without making
4319 // any changes to the provider map or other data structures.
4320 return null;
4321 }
4322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004323 mProviderMap.put(names[i], pr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004324 }
4325 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004327 if (localProvider != null) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004328 ProviderClientRecord pr = mLocalProviders.get(jBinder);
4329 if (pr != null) {
4330 if (localLOGV) {
4331 Slog.v(TAG, "installProvider: lost the race, "
4332 + "using existing local provider");
4333 }
4334 provider = pr.mProvider;
4335 } else {
4336 pr = new ProviderClientRecord(null, provider, localProvider);
4337 mLocalProviders.put(jBinder, pr);
4338 }
4339 }
4340
4341 if (!noReleaseNeeded) {
4342 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
4343 if (prc != null) {
4344 if (localLOGV) {
4345 Slog.v(TAG, "installProvider: lost the race, incrementing ref count");
4346 }
4347 prc.count += 1;
4348 if (prc.count == 1) {
4349 if (localLOGV) {
4350 Slog.v(TAG, "installProvider: "
4351 + "snatched provider from the jaws of death");
4352 }
4353 // Because the provider previously had a reference count of zero,
4354 // it was scheduled to be removed. Cancel that.
4355 mH.removeMessages(H.REMOVE_PROVIDER, provider);
4356 }
4357 } else {
4358 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
4359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004360 }
4361 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004362 return provider;
4363 }
4364
Romain Guy65b345f2011-07-27 18:51:50 -07004365 private void attach(boolean system) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004366 sThreadLocal.set(this);
4367 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004368 if (!system) {
Dianne Hackborn6dd005b2011-07-18 13:22:50 -07004369 ViewRootImpl.addFirstDrawHandler(new Runnable() {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08004370 public void run() {
4371 ensureJitEnabled();
4372 }
4373 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004374 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
4375 RuntimeInit.setApplicationObject(mAppThread.asBinder());
4376 IActivityManager mgr = ActivityManagerNative.getDefault();
4377 try {
4378 mgr.attachApplication(mAppThread);
4379 } catch (RemoteException ex) {
Romain Guy65b345f2011-07-27 18:51:50 -07004380 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004381 }
4382 } else {
4383 // Don't set application object here -- if the system crashes,
4384 // we can't display an alert, we just want to die die die.
4385 android.ddm.DdmHandleAppName.setAppName("system_process");
4386 try {
4387 mInstrumentation = new Instrumentation();
Dianne Hackborn21556372010-02-04 16:34:40 -08004388 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004389 context.init(getSystemContext().mPackageInfo, null, this);
4390 Application app = Instrumentation.newApplication(Application.class, context);
4391 mAllApplications.add(app);
4392 mInitialApplication = app;
4393 app.onCreate();
4394 } catch (Exception e) {
4395 throw new RuntimeException(
4396 "Unable to instantiate Application():" + e.toString(), e);
4397 }
4398 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004399
Dianne Hackbornc68c9132011-07-29 01:25:18 -07004400 ViewRootImpl.addConfigCallback(new ComponentCallbacks2() {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004401 public void onConfigurationChanged(Configuration newConfig) {
4402 synchronized (mPackages) {
Dianne Hackbornae078162010-03-18 11:29:37 -07004403 // We need to apply this change to the resources
4404 // immediately, because upon returning the view
4405 // hierarchy will be informed about it.
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004406 if (applyConfigurationToResourcesLocked(newConfig, null)) {
Dianne Hackbornae078162010-03-18 11:29:37 -07004407 // This actually changed the resources! Tell
4408 // everyone about it.
4409 if (mPendingConfiguration == null ||
4410 mPendingConfiguration.isOtherSeqNewer(newConfig)) {
4411 mPendingConfiguration = newConfig;
4412
4413 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
4414 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004415 }
4416 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004417 }
4418 public void onLowMemory() {
4419 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -07004420 public void onTrimMemory(int level) {
4421 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004422 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004423 }
4424
Romain Guy5e9120d2012-01-30 12:17:22 -08004425 public static ActivityThread systemMain() {
Dianne Hackborn5d927c22011-09-02 12:22:18 -07004426 HardwareRenderer.disable(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004427 ActivityThread thread = new ActivityThread();
4428 thread.attach(true);
4429 return thread;
4430 }
4431
Jeff Brown10e89712011-07-08 18:52:57 -07004432 public final void installSystemProviders(List<ProviderInfo> providers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004433 if (providers != null) {
Jeff Brown10e89712011-07-08 18:52:57 -07004434 installContentProviders(mInitialApplication, providers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004435 }
4436 }
4437
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004438 public int getIntCoreSetting(String key, int defaultValue) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08004439 synchronized (mPackages) {
4440 if (mCoreSettings != null) {
4441 return mCoreSettings.getInt(key, defaultValue);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004442 } else {
4443 return defaultValue;
4444 }
4445 }
4446 }
4447
Romain Guy65b345f2011-07-27 18:51:50 -07004448 public static void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07004449 SamplingProfilerIntegration.start();
4450
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -08004451 // CloseGuard defaults to true and can be quite spammy. We
4452 // disable it here, but selectively enable it later (via
4453 // StrictMode) on debug builds, but using DropBox, not logs.
4454 CloseGuard.setEnabled(false);
4455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004456 Process.setArgV0("<pre-initialized>");
4457
4458 Looper.prepareMainLooper();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07004459 if (sMainThreadHandler == null) {
4460 sMainThreadHandler = new Handler();
4461 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004462
4463 ActivityThread thread = new ActivityThread();
4464 thread.attach(false);
4465
Romain Guy5e9120d2012-01-30 12:17:22 -08004466 AsyncTask.init();
4467
Dianne Hackborn287952c2010-09-22 22:34:31 -07004468 if (false) {
4469 Looper.myLooper().setMessageLogging(new
4470 LogPrinter(Log.DEBUG, "ActivityThread"));
4471 }
4472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004473 Looper.loop();
4474
Jeff Brown10e89712011-07-08 18:52:57 -07004475 throw new RuntimeException("Main thread loop unexpectedly exited");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004476 }
4477}