blob: c0714e3bba2541b40933ce81cbe9c444208f05fb [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.app;
18
Christopher Tate45281862010-03-05 15:46:30 -080019import android.app.backup.BackupAgent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.content.BroadcastReceiver;
21import android.content.ComponentCallbacks;
22import android.content.ComponentName;
23import android.content.ContentProvider;
24import android.content.Context;
25import android.content.IContentProvider;
26import android.content.Intent;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070027import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.pm.ActivityInfo;
29import android.content.pm.ApplicationInfo;
30import android.content.pm.IPackageManager;
31import android.content.pm.InstrumentationInfo;
32import android.content.pm.PackageManager;
Sen Hubde75702010-05-28 01:54:03 -070033import android.content.pm.PackageManager.NameNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.content.pm.ProviderInfo;
35import android.content.pm.ServiceInfo;
36import android.content.res.AssetManager;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -070037import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.content.res.Configuration;
39import android.content.res.Resources;
40import android.database.sqlite.SQLiteDatabase;
41import android.database.sqlite.SQLiteDebug;
Vasu Noric3849202010-03-09 10:47:25 -080042import android.database.sqlite.SQLiteDebug.DbStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.graphics.Bitmap;
44import android.graphics.Canvas;
Robert Greenwalt434203a2010-10-11 16:00:27 -070045import android.net.IConnectivityManager;
46import android.net.Proxy;
47import android.net.ProxyProperties;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070048import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.os.Bundle;
50import android.os.Debug;
51import android.os.Handler;
52import android.os.IBinder;
53import android.os.Looper;
54import android.os.Message;
55import android.os.MessageQueue;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070056import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.os.Process;
58import android.os.RemoteException;
59import android.os.ServiceManager;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070060import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.os.SystemClock;
62import android.util.AndroidRuntimeException;
63import android.util.Config;
64import android.util.DisplayMetrics;
65import android.util.EventLog;
66import android.util.Log;
Dianne Hackborn287952c2010-09-22 22:34:31 -070067import android.util.LogPrinter;
Dianne Hackbornc9421ba2010-03-11 22:23:46 -080068import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.view.Display;
Romain Guy52339202010-09-03 16:04:46 -070070import android.view.HardwareRenderer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.view.View;
72import android.view.ViewDebug;
73import android.view.ViewManager;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -080074import android.view.ViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.view.Window;
76import android.view.WindowManager;
77import android.view.WindowManagerImpl;
78
79import com.android.internal.os.BinderInternal;
80import com.android.internal.os.RuntimeInit;
Bob Leee5408332009-09-04 18:31:17 -070081import com.android.internal.os.SamplingProfilerIntegration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082
83import org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl;
84
85import java.io.File;
86import java.io.FileDescriptor;
87import java.io.FileOutputStream;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070088import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import java.io.PrintWriter;
90import java.lang.ref.WeakReference;
Robert Greenwalt03595d02010-11-02 14:08:23 -070091import java.net.InetAddress;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import java.util.ArrayList;
93import java.util.HashMap;
94import java.util.Iterator;
95import java.util.List;
96import java.util.Locale;
97import java.util.Map;
98import java.util.TimeZone;
99import java.util.regex.Pattern;
100
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -0800101import dalvik.system.CloseGuard;
Bob Leee5408332009-09-04 18:31:17 -0700102import dalvik.system.SamplingProfiler;
103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104final class SuperNotCalledException extends AndroidRuntimeException {
105 public SuperNotCalledException(String msg) {
106 super(msg);
107 }
108}
109
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700110final class RemoteServiceException extends AndroidRuntimeException {
111 public RemoteServiceException(String msg) {
112 super(msg);
113 }
114}
115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116/**
117 * This manages the execution of the main thread in an
118 * application process, scheduling and executing activities,
119 * broadcasts, and other operations on it as the activity
120 * manager requests.
121 *
122 * {@hide}
123 */
124public final class ActivityThread {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700125 /** @hide */
126 public static final String TAG = "ActivityThread";
Jim Miller0b2a6d02010-07-13 18:01:29 -0700127 private static final android.graphics.Bitmap.Config THUMBNAIL_FORMAT = Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 private static final boolean DEBUG = false;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700129 static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700130 static final boolean DEBUG_MESSAGES = false;
Dianne Hackborne829fef2010-10-26 17:44:01 -0700131 /** @hide */
132 public static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700133 private static final boolean DEBUG_RESULTS = false;
Christopher Tate436344a2009-09-30 16:17:37 -0700134 private static final boolean DEBUG_BACKUP = false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700135 private static final boolean DEBUG_CONFIGURATION = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
137 private static final Pattern PATTERN_SEMICOLON = Pattern.compile(";");
138 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
139 private static final int LOG_ON_PAUSE_CALLED = 30021;
140 private static final int LOG_ON_RESUME_CALLED = 30022;
141
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700142 static ContextImpl mSystemContext = null;
Bob Leee5408332009-09-04 18:31:17 -0700143
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700144 static IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700146 final ApplicationThread mAppThread = new ApplicationThread();
147 final Looper mLooper = Looper.myLooper();
148 final H mH = new H();
149 final HashMap<IBinder, ActivityClientRecord> mActivities
150 = new HashMap<IBinder, ActivityClientRecord>();
151 // List of new activities (via ActivityRecord.nextIdle) that should
152 // be reported when next we idle.
153 ActivityClientRecord mNewActivities = null;
154 // Number of activities that are currently visible on-screen.
155 int mNumVisibleActivities = 0;
156 final HashMap<IBinder, Service> mServices
157 = new HashMap<IBinder, Service>();
158 AppBindData mBoundApplication;
159 Configuration mConfiguration;
160 Configuration mResConfiguration;
161 Application mInitialApplication;
162 final ArrayList<Application> mAllApplications
163 = new ArrayList<Application>();
164 // set of instantiated backup agents, keyed by package name
165 final HashMap<String, BackupAgent> mBackupAgents = new HashMap<String, BackupAgent>();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700166 static final ThreadLocal<ActivityThread> sThreadLocal = new ThreadLocal();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700167 Instrumentation mInstrumentation;
168 String mInstrumentationAppDir = null;
169 String mInstrumentationAppPackage = null;
170 String mInstrumentedAppDir = null;
171 boolean mSystemThread = false;
172 boolean mJitEnabled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700174 // These can be accessed by multiple threads; mPackages is the lock.
175 // XXX For now we keep around information about all packages we have
176 // seen, not removing entries from this map.
177 final HashMap<String, WeakReference<LoadedApk>> mPackages
178 = new HashMap<String, WeakReference<LoadedApk>>();
179 final HashMap<String, WeakReference<LoadedApk>> mResourcePackages
180 = new HashMap<String, WeakReference<LoadedApk>>();
181 Display mDisplay = null;
182 DisplayMetrics mDisplayMetrics = null;
183 final HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources
184 = new HashMap<ResourcesKey, WeakReference<Resources> >();
185 final ArrayList<ActivityClientRecord> mRelaunchingActivities
186 = new ArrayList<ActivityClientRecord>();
187 Configuration mPendingConfiguration = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700189 // The lock of mProviderMap protects the following variables.
190 final HashMap<String, ProviderClientRecord> mProviderMap
191 = new HashMap<String, ProviderClientRecord>();
192 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap
193 = new HashMap<IBinder, ProviderRefCount>();
194 final HashMap<IBinder, ProviderClientRecord> mLocalProviders
195 = new HashMap<IBinder, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700197 final GcIdler mGcIdler = new GcIdler();
198 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700200 static Handler sMainThreadHandler; // set once in main()
201
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700202 private static final class ActivityClientRecord {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700204 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 Intent intent;
206 Bundle state;
207 Activity activity;
208 Window window;
209 Activity parent;
210 String embeddedID;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700211 Activity.NonConfigurationInstances lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 boolean paused;
213 boolean stopped;
214 boolean hideForNow;
215 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700216 Configuration createdConfig;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700217 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218
219 ActivityInfo activityInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700220 LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221
222 List<ResultInfo> pendingResults;
223 List<Intent> pendingIntents;
224
225 boolean startsNotResumed;
226 boolean isForward;
227
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700228 ActivityClientRecord() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 parent = null;
230 embeddedID = null;
231 paused = false;
232 stopped = false;
233 hideForNow = false;
234 nextIdle = null;
235 }
236
237 public String toString() {
238 ComponentName componentName = intent.getComponent();
239 return "ActivityRecord{"
240 + Integer.toHexString(System.identityHashCode(this))
241 + " token=" + token + " " + (componentName == null
242 ? "no component name" : componentName.toShortString())
243 + "}";
244 }
245 }
246
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700247 private final class ProviderClientRecord implements IBinder.DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 final String mName;
249 final IContentProvider mProvider;
250 final ContentProvider mLocalProvider;
251
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700252 ProviderClientRecord(String name, IContentProvider provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 ContentProvider localProvider) {
254 mName = name;
255 mProvider = provider;
256 mLocalProvider = localProvider;
257 }
258
259 public void binderDied() {
260 removeDeadProvider(mName, mProvider);
261 }
262 }
263
264 private static final class NewIntentData {
265 List<Intent> intents;
266 IBinder token;
267 public String toString() {
268 return "NewIntentData{intents=" + intents + " token=" + token + "}";
269 }
270 }
271
Dianne Hackborne829fef2010-10-26 17:44:01 -0700272 private static final class ReceiverData extends BroadcastReceiver.PendingResult {
273 public ReceiverData(Intent intent, int resultCode, String resultData, Bundle resultExtras,
274 boolean ordered, boolean sticky, IBinder token) {
275 super(resultCode, resultData, resultExtras, TYPE_COMPONENT, ordered, sticky, token);
276 this.intent = intent;
277 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279 Intent intent;
280 ActivityInfo info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800281 public String toString() {
282 return "ReceiverData{intent=" + intent + " packageName=" +
Dianne Hackborne829fef2010-10-26 17:44:01 -0700283 info.packageName + " resultCode=" + getResultCode()
284 + " resultData=" + getResultData() + " resultExtras="
285 + getResultExtras(false) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 }
287 }
288
Christopher Tate181fafa2009-05-14 11:12:14 -0700289 private static final class CreateBackupAgentData {
290 ApplicationInfo appInfo;
291 int backupMode;
292 public String toString() {
293 return "CreateBackupAgentData{appInfo=" + appInfo
294 + " backupAgent=" + appInfo.backupAgentName
295 + " mode=" + backupMode + "}";
296 }
297 }
Bob Leee5408332009-09-04 18:31:17 -0700298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299 private static final class CreateServiceData {
300 IBinder token;
301 ServiceInfo info;
302 Intent intent;
303 public String toString() {
304 return "CreateServiceData{token=" + token + " className="
305 + info.name + " packageName=" + info.packageName
306 + " intent=" + intent + "}";
307 }
308 }
309
310 private static final class BindServiceData {
311 IBinder token;
312 Intent intent;
313 boolean rebind;
314 public String toString() {
315 return "BindServiceData{token=" + token + " intent=" + intent + "}";
316 }
317 }
318
319 private static final class ServiceArgsData {
320 IBinder token;
321 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700322 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 Intent args;
324 public String toString() {
325 return "ServiceArgsData{token=" + token + " startId=" + startId
326 + " args=" + args + "}";
327 }
328 }
329
330 private static final class AppBindData {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700331 LoadedApk info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 String processName;
333 ApplicationInfo appInfo;
334 List<ProviderInfo> providers;
335 ComponentName instrumentationName;
336 String profileFile;
337 Bundle instrumentationArgs;
338 IInstrumentationWatcher instrumentationWatcher;
339 int debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700340 boolean restrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800341 Configuration config;
342 boolean handlingProfiling;
343 public String toString() {
344 return "AppBindData{appInfo=" + appInfo + "}";
345 }
346 }
347
Dianne Hackborn625ac272010-09-17 18:29:22 -0700348 private static final class DumpComponentInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349 FileDescriptor fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700350 IBinder token;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800351 String[] args;
352 boolean dumped;
353 }
354
355 private static final class ResultData {
356 IBinder token;
357 List<ResultInfo> results;
358 public String toString() {
359 return "ResultData{token=" + token + " results" + results + "}";
360 }
361 }
362
363 private static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800364 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365 String what;
366 String who;
367 }
368
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700369 private static final class ProfilerControlData {
370 String path;
371 ParcelFileDescriptor fd;
372 }
373
Andy McFadden824c5102010-07-09 16:26:57 -0700374 private static final class DumpHeapData {
375 String path;
376 ParcelFileDescriptor fd;
377 }
378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 private final class ApplicationThread extends ApplicationThreadNative {
380 private static final String HEAP_COLUMN = "%17s %8s %8s %8s %8s";
381 private static final String ONE_COUNT_COLUMN = "%17s %8d";
382 private static final String TWO_COUNT_COLUMNS = "%17s %8d %17s %8d";
Vasu Nori3c7131f2010-09-21 14:36:57 -0700383 private static final String TWO_COUNT_COLUMNS_DB = "%20s %8d %20s %8d";
384 private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
Bob Leee5408332009-09-04 18:31:17 -0700385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386 // Formatting for checkin service - update version if row format changes
387 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;
Bob Leee5408332009-09-04 18:31:17 -0700388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 public final void schedulePauseActivity(IBinder token, boolean finished,
390 boolean userLeaving, int configChanges) {
391 queueOrSendMessage(
392 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
393 token,
394 (userLeaving ? 1 : 0),
395 configChanges);
396 }
397
398 public final void scheduleStopActivity(IBinder token, boolean showWindow,
399 int configChanges) {
400 queueOrSendMessage(
401 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
402 token, 0, configChanges);
403 }
404
405 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
406 queueOrSendMessage(
407 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
408 token);
409 }
410
411 public final void scheduleResumeActivity(IBinder token, boolean isForward) {
412 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
413 }
414
415 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
416 ResultData res = new ResultData();
417 res.token = token;
418 res.results = results;
419 queueOrSendMessage(H.SEND_RESULT, res);
420 }
421
422 // we use token to identify this activity without having to send the
423 // activity itself back to the activity manager. (matters more with ipc)
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700424 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
426 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700427 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428
429 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700430 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 r.intent = intent;
432 r.activityInfo = info;
433 r.state = state;
434
435 r.pendingResults = pendingResults;
436 r.pendingIntents = pendingNewIntents;
437
438 r.startsNotResumed = notResumed;
439 r.isForward = isForward;
440
441 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
442 }
443
444 public final void scheduleRelaunchActivity(IBinder token,
445 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800446 int configChanges, boolean notResumed, Configuration config) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700447 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800448
449 r.token = token;
450 r.pendingResults = pendingResults;
451 r.pendingIntents = pendingNewIntents;
452 r.startsNotResumed = notResumed;
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800453 r.createdConfig = config;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800454
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800455 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 mRelaunchingActivities.add(r);
457 }
Bob Leee5408332009-09-04 18:31:17 -0700458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800459 queueOrSendMessage(H.RELAUNCH_ACTIVITY, r, configChanges);
460 }
461
462 public final void scheduleNewIntent(List<Intent> intents, IBinder token) {
463 NewIntentData data = new NewIntentData();
464 data.intents = intents;
465 data.token = token;
466
467 queueOrSendMessage(H.NEW_INTENT, data);
468 }
469
470 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
471 int configChanges) {
472 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
473 configChanges);
474 }
475
476 public final void scheduleReceiver(Intent intent, ActivityInfo info,
477 int resultCode, String data, Bundle extras, boolean sync) {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700478 ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
479 sync, false, mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 r.info = info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800481 queueOrSendMessage(H.RECEIVER, r);
482 }
483
Christopher Tate181fafa2009-05-14 11:12:14 -0700484 public final void scheduleCreateBackupAgent(ApplicationInfo app, int backupMode) {
485 CreateBackupAgentData d = new CreateBackupAgentData();
486 d.appInfo = app;
487 d.backupMode = backupMode;
488
489 queueOrSendMessage(H.CREATE_BACKUP_AGENT, d);
490 }
491
492 public final void scheduleDestroyBackupAgent(ApplicationInfo app) {
493 CreateBackupAgentData d = new CreateBackupAgentData();
494 d.appInfo = app;
495
496 queueOrSendMessage(H.DESTROY_BACKUP_AGENT, d);
497 }
498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 public final void scheduleCreateService(IBinder token,
500 ServiceInfo info) {
501 CreateServiceData s = new CreateServiceData();
502 s.token = token;
503 s.info = info;
504
505 queueOrSendMessage(H.CREATE_SERVICE, s);
506 }
507
508 public final void scheduleBindService(IBinder token, Intent intent,
509 boolean rebind) {
510 BindServiceData s = new BindServiceData();
511 s.token = token;
512 s.intent = intent;
513 s.rebind = rebind;
514
515 queueOrSendMessage(H.BIND_SERVICE, s);
516 }
517
518 public final void scheduleUnbindService(IBinder token, Intent intent) {
519 BindServiceData s = new BindServiceData();
520 s.token = token;
521 s.intent = intent;
522
523 queueOrSendMessage(H.UNBIND_SERVICE, s);
524 }
525
526 public final void scheduleServiceArgs(IBinder token, int startId,
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700527 int flags ,Intent args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528 ServiceArgsData s = new ServiceArgsData();
529 s.token = token;
530 s.startId = startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700531 s.flags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532 s.args = args;
533
534 queueOrSendMessage(H.SERVICE_ARGS, s);
535 }
536
537 public final void scheduleStopService(IBinder token) {
538 queueOrSendMessage(H.STOP_SERVICE, token);
539 }
540
541 public final void bindApplication(String processName,
542 ApplicationInfo appInfo, List<ProviderInfo> providers,
543 ComponentName instrumentationName, String profileFile,
544 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
Christopher Tate181fafa2009-05-14 11:12:14 -0700545 int debugMode, boolean isRestrictedBackupMode, Configuration config,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546 Map<String, IBinder> services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547
548 if (services != null) {
549 // Setup the service cache in the ServiceManager
550 ServiceManager.initServiceCache(services);
551 }
552
553 AppBindData data = new AppBindData();
554 data.processName = processName;
555 data.appInfo = appInfo;
556 data.providers = providers;
557 data.instrumentationName = instrumentationName;
558 data.profileFile = profileFile;
559 data.instrumentationArgs = instrumentationArgs;
560 data.instrumentationWatcher = instrumentationWatcher;
561 data.debugMode = debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700562 data.restrictedBackupMode = isRestrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563 data.config = config;
564 queueOrSendMessage(H.BIND_APPLICATION, data);
565 }
566
567 public final void scheduleExit() {
568 queueOrSendMessage(H.EXIT_APPLICATION, null);
569 }
570
Christopher Tate5e1ab332009-09-01 20:32:49 -0700571 public final void scheduleSuicide() {
572 queueOrSendMessage(H.SUICIDE, null);
573 }
574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 public void requestThumbnail(IBinder token) {
576 queueOrSendMessage(H.REQUEST_THUMBNAIL, token);
577 }
578
579 public void scheduleConfigurationChanged(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800580 synchronized (mPackages) {
581 if (mPendingConfiguration == null ||
582 mPendingConfiguration.isOtherSeqNewer(config)) {
583 mPendingConfiguration = config;
584 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585 }
586 queueOrSendMessage(H.CONFIGURATION_CHANGED, config);
587 }
588
589 public void updateTimeZone() {
590 TimeZone.setDefault(null);
591 }
592
Robert Greenwalt03595d02010-11-02 14:08:23 -0700593 public void clearDnsCache() {
594 // a non-standard API to get this to libcore
595 InetAddress.clearDnsCache();
596 }
597
Robert Greenwalt434203a2010-10-11 16:00:27 -0700598 public void setHttpProxy(String host, String port, String exclList) {
599 Proxy.setHttpProxySystemProperty(host, port, exclList);
600 }
601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800602 public void processInBackground() {
603 mH.removeMessages(H.GC_WHEN_IDLE);
604 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
605 }
606
607 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700608 DumpComponentInfo data = new DumpComponentInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609 data.fd = fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700610 data.token = servicetoken;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 data.args = args;
612 data.dumped = false;
613 queueOrSendMessage(H.DUMP_SERVICE, data);
614 synchronized (data) {
615 while (!data.dumped) {
616 try {
617 data.wait();
618 } catch (InterruptedException e) {
619 // no need to do anything here, we will keep waiting until
620 // dumped is set
621 }
622 }
623 }
624 }
625
626 // This function exists to make sure all receiver dispatching is
627 // correctly ordered, since these are one-way calls and the binder driver
628 // applies transaction ordering per object for such calls.
629 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700630 int resultCode, String dataStr, Bundle extras, boolean ordered,
631 boolean sticky) throws RemoteException {
632 receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 }
Bob Leee5408332009-09-04 18:31:17 -0700634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 public void scheduleLowMemory() {
636 queueOrSendMessage(H.LOW_MEMORY, null);
637 }
638
639 public void scheduleActivityConfigurationChanged(IBinder token) {
640 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token);
641 }
642
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700643 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd) {
644 ProfilerControlData pcd = new ProfilerControlData();
645 pcd.path = path;
646 pcd.fd = fd;
647 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800648 }
649
Andy McFadden824c5102010-07-09 16:26:57 -0700650 public void dumpHeap(boolean managed, String path, ParcelFileDescriptor fd) {
651 DumpHeapData dhd = new DumpHeapData();
652 dhd.path = path;
653 dhd.fd = fd;
654 queueOrSendMessage(H.DUMP_HEAP, dhd, managed ? 1 : 0);
655 }
656
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700657 public void setSchedulingGroup(int group) {
658 // Note: do this immediately, since going into the foreground
659 // should happen regardless of what pending work we have to do
660 // and the activity manager will wait for us to report back that
661 // we are done before sending us to the background.
662 try {
663 Process.setProcessGroup(Process.myPid(), group);
664 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800665 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700666 }
667 }
Bob Leee5408332009-09-04 18:31:17 -0700668
Dianne Hackborn3025ef32009-08-31 21:31:47 -0700669 public void getMemoryInfo(Debug.MemoryInfo outInfo) {
670 Debug.getMemoryInfo(outInfo);
671 }
Bob Leee5408332009-09-04 18:31:17 -0700672
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700673 public void dispatchPackageBroadcast(int cmd, String[] packages) {
674 queueOrSendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
675 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700676
677 public void scheduleCrash(String msg) {
678 queueOrSendMessage(H.SCHEDULE_CRASH, msg);
679 }
Dianne Hackborn625ac272010-09-17 18:29:22 -0700680
681 public void dumpActivity(FileDescriptor fd, IBinder activitytoken, String[] args) {
682 DumpComponentInfo data = new DumpComponentInfo();
683 data.fd = fd;
684 data.token = activitytoken;
685 data.args = args;
686 data.dumped = false;
687 queueOrSendMessage(H.DUMP_ACTIVITY, data);
688 synchronized (data) {
689 while (!data.dumped) {
690 try {
691 data.wait();
692 } catch (InterruptedException e) {
693 // no need to do anything here, we will keep waiting until
694 // dumped is set
695 }
696 }
697 }
698 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 @Override
701 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
702 long nativeMax = Debug.getNativeHeapSize() / 1024;
703 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
704 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
705
706 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
707 Debug.getMemoryInfo(memInfo);
708
709 final int nativeShared = memInfo.nativeSharedDirty;
710 final int dalvikShared = memInfo.dalvikSharedDirty;
711 final int otherShared = memInfo.otherSharedDirty;
712
713 final int nativePrivate = memInfo.nativePrivateDirty;
714 final int dalvikPrivate = memInfo.dalvikPrivateDirty;
715 final int otherPrivate = memInfo.otherPrivateDirty;
716
717 Runtime runtime = Runtime.getRuntime();
718
719 long dalvikMax = runtime.totalMemory() / 1024;
720 long dalvikFree = runtime.freeMemory() / 1024;
721 long dalvikAllocated = dalvikMax - dalvikFree;
722 long viewInstanceCount = ViewDebug.getViewInstanceCount();
723 long viewRootInstanceCount = ViewDebug.getViewRootInstanceCount();
Brian Carlstromc21550a2010-10-05 21:34:06 -0700724 long appContextInstanceCount = Debug.countInstancesOfClass(ContextImpl.class);
725 long activityInstanceCount = Debug.countInstancesOfClass(Activity.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 int globalAssetCount = AssetManager.getGlobalAssetCount();
727 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
728 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
729 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
730 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
Brian Carlstromc9d5b312010-10-05 22:23:41 -0700731 long openSslSocketCount = Debug.countInstancesOfClass(OpenSSLSocketImpl.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024;
Vasu Noric3849202010-03-09 10:47:25 -0800733 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -0700734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 // Check to see if we were called by checkin server. If so, print terse format.
736 boolean doCheckinFormat = false;
737 if (args != null) {
738 for (String arg : args) {
739 if ("-c".equals(arg)) doCheckinFormat = true;
740 }
741 }
Bob Leee5408332009-09-04 18:31:17 -0700742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 // For checkin, we print one long comma-separated list of values
744 if (doCheckinFormat) {
745 // NOTE: if you change anything significant below, also consider changing
746 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -0700747 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -0700749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 // Header
751 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
752 pw.print(Process.myPid()); pw.print(',');
753 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 // Heap info - max
756 pw.print(nativeMax); pw.print(',');
757 pw.print(dalvikMax); pw.print(',');
758 pw.print("N/A,");
759 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 // Heap info - allocated
762 pw.print(nativeAllocated); pw.print(',');
763 pw.print(dalvikAllocated); pw.print(',');
764 pw.print("N/A,");
765 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 // Heap info - free
768 pw.print(nativeFree); pw.print(',');
769 pw.print(dalvikFree); pw.print(',');
770 pw.print("N/A,");
771 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 // Heap info - proportional set size
774 pw.print(memInfo.nativePss); pw.print(',');
775 pw.print(memInfo.dalvikPss); pw.print(',');
776 pw.print(memInfo.otherPss); pw.print(',');
777 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 // Heap info - shared
Bob Leee5408332009-09-04 18:31:17 -0700780 pw.print(nativeShared); pw.print(',');
781 pw.print(dalvikShared); pw.print(',');
782 pw.print(otherShared); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800783 pw.print(nativeShared + dalvikShared + otherShared); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 // Heap info - private
Bob Leee5408332009-09-04 18:31:17 -0700786 pw.print(nativePrivate); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 pw.print(dalvikPrivate); pw.print(',');
788 pw.print(otherPrivate); pw.print(',');
789 pw.print(nativePrivate + dalvikPrivate + otherPrivate); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 // Object counts
792 pw.print(viewInstanceCount); pw.print(',');
793 pw.print(viewRootInstanceCount); pw.print(',');
794 pw.print(appContextInstanceCount); pw.print(',');
795 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 pw.print(globalAssetCount); pw.print(',');
798 pw.print(globalAssetManagerCount); pw.print(',');
799 pw.print(binderLocalObjectCount); pw.print(',');
800 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 pw.print(binderDeathObjectCount); pw.print(',');
803 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 // SQL
806 pw.print(sqliteAllocated); pw.print(',');
Vasu Noric3849202010-03-09 10:47:25 -0800807 pw.print(stats.memoryUsed / 1024); pw.print(',');
808 pw.print(stats.pageCacheOverflo / 1024); pw.print(',');
809 pw.print(stats.largestMemAlloc / 1024); pw.print(',');
810 for (int i = 0; i < stats.dbStats.size(); i++) {
811 DbStats dbStats = stats.dbStats.get(i);
812 printRow(pw, DB_INFO_FORMAT, dbStats.pageSize, dbStats.dbSize,
Vasu Nori90a367262010-04-12 12:49:09 -0700813 dbStats.lookaside, dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -0800814 pw.print(',');
815 }
Bob Leee5408332009-09-04 18:31:17 -0700816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 return;
818 }
Bob Leee5408332009-09-04 18:31:17 -0700819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 // otherwise, show human-readable format
821 printRow(pw, HEAP_COLUMN, "", "native", "dalvik", "other", "total");
822 printRow(pw, HEAP_COLUMN, "size:", nativeMax, dalvikMax, "N/A", nativeMax + dalvikMax);
823 printRow(pw, HEAP_COLUMN, "allocated:", nativeAllocated, dalvikAllocated, "N/A",
824 nativeAllocated + dalvikAllocated);
825 printRow(pw, HEAP_COLUMN, "free:", nativeFree, dalvikFree, "N/A",
826 nativeFree + dalvikFree);
827
828 printRow(pw, HEAP_COLUMN, "(Pss):", memInfo.nativePss, memInfo.dalvikPss,
829 memInfo.otherPss, memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss);
830
831 printRow(pw, HEAP_COLUMN, "(shared dirty):", nativeShared, dalvikShared, otherShared,
832 nativeShared + dalvikShared + otherShared);
833 printRow(pw, HEAP_COLUMN, "(priv dirty):", nativePrivate, dalvikPrivate, otherPrivate,
834 nativePrivate + dalvikPrivate + otherPrivate);
835
836 pw.println(" ");
837 pw.println(" Objects");
838 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRoots:",
839 viewRootInstanceCount);
840
841 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
842 "Activities:", activityInstanceCount);
843
844 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
845 "AssetManagers:", globalAssetManagerCount);
846
847 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
848 "Proxy Binders:", binderProxyObjectCount);
849 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
850
851 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -0700852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 // SQLite mem info
854 pw.println(" ");
855 pw.println(" SQL");
Vasu Nori3c7131f2010-09-21 14:36:57 -0700856 printRow(pw, TWO_COUNT_COLUMNS_DB, "heap:", sqliteAllocated, "MEMORY_USED:",
Vasu Noric3849202010-03-09 10:47:25 -0800857 stats.memoryUsed / 1024);
Vasu Nori3c7131f2010-09-21 14:36:57 -0700858 printRow(pw, TWO_COUNT_COLUMNS_DB, "PAGECACHE_OVERFLOW:",
859 stats.pageCacheOverflo / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -0800860 pw.println(" ");
861 int N = stats.dbStats.size();
862 if (N > 0) {
863 pw.println(" DATABASES");
Vasu Nori3c7131f2010-09-21 14:36:57 -0700864 printRow(pw, " %8s %8s %14s %14s %s", "pgsz", "dbsz", "Lookaside(b)", "cache",
865 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -0800866 for (int i = 0; i < N; i++) {
867 DbStats dbStats = stats.dbStats.get(i);
Vasu Nori3c7131f2010-09-21 14:36:57 -0700868 printRow(pw, DB_INFO_FORMAT,
869 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
870 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
871 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
872 dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -0800873 }
874 }
Bob Leee5408332009-09-04 18:31:17 -0700875
Dianne Hackborn82e1ee92009-08-11 18:56:41 -0700876 // Asset details.
877 String assetAlloc = AssetManager.getAssetAllocations();
878 if (assetAlloc != null) {
879 pw.println(" ");
880 pw.println(" Asset Allocations");
881 pw.print(assetAlloc);
882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 }
884
885 private void printRow(PrintWriter pw, String format, Object...objs) {
886 pw.println(String.format(format, objs));
887 }
888 }
889
890 private final class H extends Handler {
891 public static final int LAUNCH_ACTIVITY = 100;
892 public static final int PAUSE_ACTIVITY = 101;
893 public static final int PAUSE_ACTIVITY_FINISHING= 102;
894 public static final int STOP_ACTIVITY_SHOW = 103;
895 public static final int STOP_ACTIVITY_HIDE = 104;
896 public static final int SHOW_WINDOW = 105;
897 public static final int HIDE_WINDOW = 106;
898 public static final int RESUME_ACTIVITY = 107;
899 public static final int SEND_RESULT = 108;
900 public static final int DESTROY_ACTIVITY = 109;
901 public static final int BIND_APPLICATION = 110;
902 public static final int EXIT_APPLICATION = 111;
903 public static final int NEW_INTENT = 112;
904 public static final int RECEIVER = 113;
905 public static final int CREATE_SERVICE = 114;
906 public static final int SERVICE_ARGS = 115;
907 public static final int STOP_SERVICE = 116;
908 public static final int REQUEST_THUMBNAIL = 117;
909 public static final int CONFIGURATION_CHANGED = 118;
910 public static final int CLEAN_UP_CONTEXT = 119;
911 public static final int GC_WHEN_IDLE = 120;
912 public static final int BIND_SERVICE = 121;
913 public static final int UNBIND_SERVICE = 122;
914 public static final int DUMP_SERVICE = 123;
915 public static final int LOW_MEMORY = 124;
916 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
917 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800918 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -0700919 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -0700920 public static final int DESTROY_BACKUP_AGENT = 129;
921 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700922 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800923 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700924 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700925 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -0700926 public static final int DUMP_HEAP = 135;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700927 public static final int DUMP_ACTIVITY = 136;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 String codeToString(int code) {
Dianne Hackborn287952c2010-09-22 22:34:31 -0700929 if (DEBUG_MESSAGES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 switch (code) {
931 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
932 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
933 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
934 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
935 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
936 case SHOW_WINDOW: return "SHOW_WINDOW";
937 case HIDE_WINDOW: return "HIDE_WINDOW";
938 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
939 case SEND_RESULT: return "SEND_RESULT";
940 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
941 case BIND_APPLICATION: return "BIND_APPLICATION";
942 case EXIT_APPLICATION: return "EXIT_APPLICATION";
943 case NEW_INTENT: return "NEW_INTENT";
944 case RECEIVER: return "RECEIVER";
945 case CREATE_SERVICE: return "CREATE_SERVICE";
946 case SERVICE_ARGS: return "SERVICE_ARGS";
947 case STOP_SERVICE: return "STOP_SERVICE";
948 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
949 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
950 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
951 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
952 case BIND_SERVICE: return "BIND_SERVICE";
953 case UNBIND_SERVICE: return "UNBIND_SERVICE";
954 case DUMP_SERVICE: return "DUMP_SERVICE";
955 case LOW_MEMORY: return "LOW_MEMORY";
956 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
957 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800958 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -0700959 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
960 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -0700961 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700962 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800963 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700964 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700965 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -0700966 case DUMP_HEAP: return "DUMP_HEAP";
Dianne Hackborn625ac272010-09-17 18:29:22 -0700967 case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 }
969 }
970 return "(unknown)";
971 }
972 public void handleMessage(Message msg) {
Dianne Hackborn287952c2010-09-22 22:34:31 -0700973 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 switch (msg.what) {
975 case LAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700976 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977
978 r.packageInfo = getPackageInfoNoCheck(
979 r.activityInfo.applicationInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -0700980 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 } break;
982 case RELAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700983 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 handleRelaunchActivity(r, msg.arg1);
985 } break;
986 case PAUSE_ACTIVITY:
987 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -0700988 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 break;
990 case PAUSE_ACTIVITY_FINISHING:
991 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
992 break;
993 case STOP_ACTIVITY_SHOW:
994 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
995 break;
996 case STOP_ACTIVITY_HIDE:
997 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
998 break;
999 case SHOW_WINDOW:
1000 handleWindowVisibility((IBinder)msg.obj, true);
1001 break;
1002 case HIDE_WINDOW:
1003 handleWindowVisibility((IBinder)msg.obj, false);
1004 break;
1005 case RESUME_ACTIVITY:
1006 handleResumeActivity((IBinder)msg.obj, true,
1007 msg.arg1 != 0);
1008 break;
1009 case SEND_RESULT:
1010 handleSendResult((ResultData)msg.obj);
1011 break;
1012 case DESTROY_ACTIVITY:
1013 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
1014 msg.arg2, false);
1015 break;
1016 case BIND_APPLICATION:
1017 AppBindData data = (AppBindData)msg.obj;
1018 handleBindApplication(data);
1019 break;
1020 case EXIT_APPLICATION:
1021 if (mInitialApplication != null) {
1022 mInitialApplication.onTerminate();
1023 }
1024 Looper.myLooper().quit();
1025 break;
1026 case NEW_INTENT:
1027 handleNewIntent((NewIntentData)msg.obj);
1028 break;
1029 case RECEIVER:
1030 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001031 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 break;
1033 case CREATE_SERVICE:
1034 handleCreateService((CreateServiceData)msg.obj);
1035 break;
1036 case BIND_SERVICE:
1037 handleBindService((BindServiceData)msg.obj);
1038 break;
1039 case UNBIND_SERVICE:
1040 handleUnbindService((BindServiceData)msg.obj);
1041 break;
1042 case SERVICE_ARGS:
1043 handleServiceArgs((ServiceArgsData)msg.obj);
1044 break;
1045 case STOP_SERVICE:
1046 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001047 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 break;
1049 case REQUEST_THUMBNAIL:
1050 handleRequestThumbnail((IBinder)msg.obj);
1051 break;
1052 case CONFIGURATION_CHANGED:
1053 handleConfigurationChanged((Configuration)msg.obj);
1054 break;
1055 case CLEAN_UP_CONTEXT:
1056 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1057 cci.context.performFinalCleanup(cci.who, cci.what);
1058 break;
1059 case GC_WHEN_IDLE:
1060 scheduleGcIdler();
1061 break;
1062 case DUMP_SERVICE:
Dianne Hackborn625ac272010-09-17 18:29:22 -07001063 handleDumpService((DumpComponentInfo)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 break;
1065 case LOW_MEMORY:
1066 handleLowMemory();
1067 break;
1068 case ACTIVITY_CONFIGURATION_CHANGED:
1069 handleActivityConfigurationChanged((IBinder)msg.obj);
1070 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001071 case PROFILER_CONTROL:
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001072 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001073 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001074 case CREATE_BACKUP_AGENT:
1075 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1076 break;
1077 case DESTROY_BACKUP_AGENT:
1078 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1079 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001080 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001081 Process.killProcess(Process.myPid());
1082 break;
1083 case REMOVE_PROVIDER:
1084 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001085 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001086 case ENABLE_JIT:
1087 ensureJitEnabled();
1088 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001089 case DISPATCH_PACKAGE_BROADCAST:
1090 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
1091 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001092 case SCHEDULE_CRASH:
1093 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001094 case DUMP_HEAP:
1095 handleDumpHeap(msg.arg1 != 0, (DumpHeapData)msg.obj);
1096 break;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001097 case DUMP_ACTIVITY:
1098 handleDumpActivity((DumpComponentInfo)msg.obj);
1099 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07001101 if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 }
Bob Leee5408332009-09-04 18:31:17 -07001103
1104 void maybeSnapshot() {
1105 if (mBoundApplication != null) {
Sen Hubde75702010-05-28 01:54:03 -07001106 // convert the *private* ActivityThread.PackageInfo to *public* known
1107 // android.content.pm.PackageInfo
1108 String packageName = mBoundApplication.info.mPackageName;
1109 android.content.pm.PackageInfo packageInfo = null;
1110 try {
1111 Context context = getSystemContext();
1112 if(context == null) {
1113 Log.e(TAG, "cannot get a valid context");
1114 return;
1115 }
1116 PackageManager pm = context.getPackageManager();
1117 if(pm == null) {
1118 Log.e(TAG, "cannot get a valid PackageManager");
1119 return;
1120 }
1121 packageInfo = pm.getPackageInfo(
1122 packageName, PackageManager.GET_ACTIVITIES);
1123 } catch (NameNotFoundException e) {
1124 Log.e(TAG, "cannot get package info for " + packageName, e);
1125 }
1126 SamplingProfilerIntegration.writeSnapshot(mBoundApplication.processName, packageInfo);
Bob Leee5408332009-09-04 18:31:17 -07001127 }
1128 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 }
1130
1131 private final class Idler implements MessageQueue.IdleHandler {
1132 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001133 ActivityClientRecord a = mNewActivities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 if (a != null) {
1135 mNewActivities = null;
1136 IActivityManager am = ActivityManagerNative.getDefault();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001137 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001139 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 TAG, "Reporting idle of " + a +
1141 " finished=" +
1142 (a.activity != null ? a.activity.mFinished : false));
1143 if (a.activity != null && !a.activity.mFinished) {
1144 try {
Dianne Hackborne88846e2009-09-30 21:34:25 -07001145 am.activityIdle(a.token, a.createdConfig);
1146 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 } catch (RemoteException ex) {
1148 }
1149 }
1150 prev = a;
1151 a = a.nextIdle;
1152 prev.nextIdle = null;
1153 } while (a != null);
1154 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001155 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 return false;
1157 }
1158 }
1159
1160 final class GcIdler implements MessageQueue.IdleHandler {
1161 public final boolean queueIdle() {
1162 doGcIfNeeded();
1163 return false;
1164 }
1165 }
1166
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001167 private final static class ResourcesKey {
1168 final private String mResDir;
1169 final private float mScale;
1170 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07001171
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001172 ResourcesKey(String resDir, float scale) {
1173 mResDir = resDir;
1174 mScale = scale;
1175 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
1176 }
Bob Leee5408332009-09-04 18:31:17 -07001177
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001178 @Override
1179 public int hashCode() {
1180 return mHash;
1181 }
1182
1183 @Override
1184 public boolean equals(Object obj) {
1185 if (!(obj instanceof ResourcesKey)) {
1186 return false;
1187 }
1188 ResourcesKey peer = (ResourcesKey) obj;
1189 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
1190 }
1191 }
1192
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001193 public static final ActivityThread currentActivityThread() {
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07001194 return sThreadLocal.get();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001197 public static final String currentPackageName() {
1198 ActivityThread am = currentActivityThread();
1199 return (am != null && am.mBoundApplication != null)
1200 ? am.mBoundApplication.processName : null;
1201 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001202
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001203 public static final Application currentApplication() {
1204 ActivityThread am = currentActivityThread();
1205 return am != null ? am.mInitialApplication : null;
1206 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001208 public static IPackageManager getPackageManager() {
1209 if (sPackageManager != null) {
1210 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1211 return sPackageManager;
1212 }
1213 IBinder b = ServiceManager.getService("package");
1214 //Slog.v("PackageManager", "default service binder = " + b);
1215 sPackageManager = IPackageManager.Stub.asInterface(b);
1216 //Slog.v("PackageManager", "default service = " + sPackageManager);
1217 return sPackageManager;
1218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001220 DisplayMetrics getDisplayMetricsLocked(boolean forceUpdate) {
1221 if (mDisplayMetrics != null && !forceUpdate) {
1222 return mDisplayMetrics;
1223 }
1224 if (mDisplay == null) {
1225 WindowManager wm = WindowManagerImpl.getDefault();
1226 mDisplay = wm.getDefaultDisplay();
1227 }
1228 DisplayMetrics metrics = mDisplayMetrics = new DisplayMetrics();
1229 mDisplay.getMetrics(metrics);
1230 //Slog.i("foo", "New metrics: w=" + metrics.widthPixels + " h="
1231 // + metrics.heightPixels + " den=" + metrics.density
1232 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi);
1233 return metrics;
1234 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001236 /**
1237 * Creates the top level Resources for applications with the given compatibility info.
1238 *
1239 * @param resDir the resource directory.
1240 * @param compInfo the compability info. It will use the default compatibility info when it's
1241 * null.
1242 */
1243 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
1244 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
1245 Resources r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001247 // Resources is app scale dependent.
1248 if (false) {
1249 Slog.w(TAG, "getTopLevelResources: " + resDir + " / "
1250 + compInfo.applicationScale);
1251 }
1252 WeakReference<Resources> wr = mActiveResources.get(key);
1253 r = wr != null ? wr.get() : null;
1254 //if (r != null) Slog.i(TAG, "isUpToDate " + resDir + ": " + r.getAssets().isUpToDate());
1255 if (r != null && r.getAssets().isUpToDate()) {
1256 if (false) {
1257 Slog.w(TAG, "Returning cached resources " + r + " " + resDir
1258 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
1259 }
1260 return r;
1261 }
1262 }
1263
1264 //if (r != null) {
1265 // Slog.w(TAG, "Throwing away out-of-date resources!!!! "
1266 // + r + " " + resDir);
1267 //}
1268
1269 AssetManager assets = new AssetManager();
1270 if (assets.addAssetPath(resDir) == 0) {
1271 return null;
1272 }
1273
1274 //Slog.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
1275 DisplayMetrics metrics = getDisplayMetricsLocked(false);
1276 r = new Resources(assets, metrics, getConfiguration(), compInfo);
1277 if (false) {
1278 Slog.i(TAG, "Created app resources " + resDir + " " + r + ": "
1279 + r.getConfiguration() + " appScale="
1280 + r.getCompatibilityInfo().applicationScale);
1281 }
1282
1283 synchronized (mPackages) {
1284 WeakReference<Resources> wr = mActiveResources.get(key);
1285 Resources existing = wr != null ? wr.get() : null;
1286 if (existing != null && existing.getAssets().isUpToDate()) {
1287 // Someone else already created the resources while we were
1288 // unlocked; go ahead and use theirs.
1289 r.getAssets().close();
1290 return existing;
1291 }
1292
1293 // XXX need to remove entries when weak references go away
1294 mActiveResources.put(key, new WeakReference<Resources>(r));
1295 return r;
1296 }
1297 }
1298
1299 /**
1300 * Creates the top level resources for the given package.
1301 */
1302 Resources getTopLevelResources(String resDir, LoadedApk pkgInfo) {
1303 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo);
1304 }
1305
1306 final Handler getHandler() {
1307 return mH;
1308 }
1309
1310 public final LoadedApk getPackageInfo(String packageName, int flags) {
1311 synchronized (mPackages) {
1312 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
1314 ref = mPackages.get(packageName);
1315 } else {
1316 ref = mResourcePackages.get(packageName);
1317 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001318 LoadedApk packageInfo = ref != null ? ref.get() : null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001319 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001320 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
1321 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 if (packageInfo != null && (packageInfo.mResources == null
1323 || packageInfo.mResources.getAssets().isUpToDate())) {
1324 if (packageInfo.isSecurityViolation()
1325 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
1326 throw new SecurityException(
1327 "Requesting code from " + packageName
1328 + " to be run in process "
1329 + mBoundApplication.processName
1330 + "/" + mBoundApplication.appInfo.uid);
1331 }
1332 return packageInfo;
1333 }
1334 }
1335
1336 ApplicationInfo ai = null;
1337 try {
1338 ai = getPackageManager().getApplicationInfo(packageName,
1339 PackageManager.GET_SHARED_LIBRARY_FILES);
1340 } catch (RemoteException e) {
1341 }
1342
1343 if (ai != null) {
1344 return getPackageInfo(ai, flags);
1345 }
1346
1347 return null;
1348 }
1349
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001350 public final LoadedApk getPackageInfo(ApplicationInfo ai, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
1352 boolean securityViolation = includeCode && ai.uid != 0
1353 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
1354 ? ai.uid != mBoundApplication.appInfo.uid : true);
1355 if ((flags&(Context.CONTEXT_INCLUDE_CODE
1356 |Context.CONTEXT_IGNORE_SECURITY))
1357 == Context.CONTEXT_INCLUDE_CODE) {
1358 if (securityViolation) {
1359 String msg = "Requesting code from " + ai.packageName
1360 + " (with uid " + ai.uid + ")";
1361 if (mBoundApplication != null) {
1362 msg = msg + " to be run in process "
1363 + mBoundApplication.processName + " (with uid "
1364 + mBoundApplication.appInfo.uid + ")";
1365 }
1366 throw new SecurityException(msg);
1367 }
1368 }
1369 return getPackageInfo(ai, null, securityViolation, includeCode);
1370 }
1371
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001372 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 return getPackageInfo(ai, null, false, true);
1374 }
1375
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001376 private final LoadedApk getPackageInfo(ApplicationInfo aInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
1378 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001379 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 if (includeCode) {
1381 ref = mPackages.get(aInfo.packageName);
1382 } else {
1383 ref = mResourcePackages.get(aInfo.packageName);
1384 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001385 LoadedApk packageInfo = ref != null ? ref.get() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 if (packageInfo == null || (packageInfo.mResources != null
1387 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001388 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 : "Loading resource-only package ") + aInfo.packageName
1390 + " (in " + (mBoundApplication != null
1391 ? mBoundApplication.processName : null)
1392 + ")");
1393 packageInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001394 new LoadedApk(this, aInfo, this, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 securityViolation, includeCode &&
1396 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
1397 if (includeCode) {
1398 mPackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001399 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 } else {
1401 mResourcePackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001402 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 }
1404 }
1405 return packageInfo;
1406 }
1407 }
1408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 ActivityThread() {
1410 }
1411
1412 public ApplicationThread getApplicationThread()
1413 {
1414 return mAppThread;
1415 }
1416
1417 public Instrumentation getInstrumentation()
1418 {
1419 return mInstrumentation;
1420 }
1421
1422 public Configuration getConfiguration() {
1423 return mConfiguration;
1424 }
1425
1426 public boolean isProfiling() {
1427 return mBoundApplication != null && mBoundApplication.profileFile != null;
1428 }
1429
1430 public String getProfileFilePath() {
1431 return mBoundApplication.profileFile;
1432 }
1433
1434 public Looper getLooper() {
1435 return mLooper;
1436 }
1437
1438 public Application getApplication() {
1439 return mInitialApplication;
1440 }
Bob Leee5408332009-09-04 18:31:17 -07001441
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07001442 public String getProcessName() {
1443 return mBoundApplication.processName;
1444 }
Bob Leee5408332009-09-04 18:31:17 -07001445
Dianne Hackborn21556372010-02-04 16:34:40 -08001446 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 synchronized (this) {
1448 if (mSystemContext == null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001449 ContextImpl context =
1450 ContextImpl.createSystemContext(this);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001451 LoadedApk info = new LoadedApk(this, "android", context, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 context.init(info, null, this);
1453 context.getResources().updateConfiguration(
1454 getConfiguration(), getDisplayMetricsLocked(false));
1455 mSystemContext = context;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001456 //Slog.i(TAG, "Created system resources " + context.getResources()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 // + ": " + context.getResources().getConfiguration());
1458 }
1459 }
1460 return mSystemContext;
1461 }
1462
Mike Cleron432b7132009-09-24 15:28:29 -07001463 public void installSystemApplicationInfo(ApplicationInfo info) {
1464 synchronized (this) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001465 ContextImpl context = getSystemContext();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001466 context.init(new LoadedApk(this, "android", context, info), null, this);
Mike Cleron432b7132009-09-24 15:28:29 -07001467 }
1468 }
1469
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001470 void ensureJitEnabled() {
1471 if (!mJitEnabled) {
1472 mJitEnabled = true;
1473 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
1474 }
1475 }
1476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 void scheduleGcIdler() {
1478 if (!mGcIdlerScheduled) {
1479 mGcIdlerScheduled = true;
1480 Looper.myQueue().addIdleHandler(mGcIdler);
1481 }
1482 mH.removeMessages(H.GC_WHEN_IDLE);
1483 }
1484
1485 void unscheduleGcIdler() {
1486 if (mGcIdlerScheduled) {
1487 mGcIdlerScheduled = false;
1488 Looper.myQueue().removeIdleHandler(mGcIdler);
1489 }
1490 mH.removeMessages(H.GC_WHEN_IDLE);
1491 }
1492
1493 void doGcIfNeeded() {
1494 mGcIdlerScheduled = false;
1495 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001496 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 // + "m now=" + now);
1498 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001499 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 BinderInternal.forceGc("bg");
1501 }
1502 }
1503
1504 public final ActivityInfo resolveActivityInfo(Intent intent) {
1505 ActivityInfo aInfo = intent.resolveActivityInfo(
1506 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
1507 if (aInfo == null) {
1508 // Throw an exception.
1509 Instrumentation.checkStartActivityResult(
1510 IActivityManager.START_CLASS_NOT_FOUND, intent);
1511 }
1512 return aInfo;
1513 }
Bob Leee5408332009-09-04 18:31:17 -07001514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001517 Activity.NonConfigurationInstances lastNonConfigurationInstances) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001518 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001520 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 r.intent = intent;
1522 r.state = state;
1523 r.parent = parent;
1524 r.embeddedID = id;
1525 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001526 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 if (localLOGV) {
1528 ComponentName compname = intent.getComponent();
1529 String name;
1530 if (compname != null) {
1531 name = compname.toShortString();
1532 } else {
1533 name = "(Intent " + intent + ").getComponent() returned null";
1534 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001535 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 + ", comp=" + name
1537 + ", token=" + token);
1538 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07001539 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 }
1541
1542 public final Activity getActivity(IBinder token) {
1543 return mActivities.get(token).activity;
1544 }
1545
1546 public final void sendActivityResult(
1547 IBinder token, String id, int requestCode,
1548 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001549 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07001550 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
1552 list.add(new ResultInfo(id, requestCode, resultCode, data));
1553 mAppThread.scheduleSendResult(token, list);
1554 }
1555
1556 // if the thread hasn't started yet, we don't have the handler, so just
1557 // save the messages until we're ready.
1558 private final void queueOrSendMessage(int what, Object obj) {
1559 queueOrSendMessage(what, obj, 0, 0);
1560 }
1561
1562 private final void queueOrSendMessage(int what, Object obj, int arg1) {
1563 queueOrSendMessage(what, obj, arg1, 0);
1564 }
1565
1566 private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
1567 synchronized (this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001568 if (DEBUG_MESSAGES) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
1570 + ": " + arg1 + " / " + obj);
1571 Message msg = Message.obtain();
1572 msg.what = what;
1573 msg.obj = obj;
1574 msg.arg1 = arg1;
1575 msg.arg2 = arg2;
1576 mH.sendMessage(msg);
1577 }
1578 }
1579
Dianne Hackborn21556372010-02-04 16:34:40 -08001580 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 String what) {
1582 ContextCleanupInfo cci = new ContextCleanupInfo();
1583 cci.context = context;
1584 cci.who = who;
1585 cci.what = what;
1586 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
1587 }
1588
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001589 private final Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
1591
1592 ActivityInfo aInfo = r.activityInfo;
1593 if (r.packageInfo == null) {
1594 r.packageInfo = getPackageInfo(aInfo.applicationInfo,
1595 Context.CONTEXT_INCLUDE_CODE);
1596 }
Bob Leee5408332009-09-04 18:31:17 -07001597
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 ComponentName component = r.intent.getComponent();
1599 if (component == null) {
1600 component = r.intent.resolveActivity(
1601 mInitialApplication.getPackageManager());
1602 r.intent.setComponent(component);
1603 }
1604
1605 if (r.activityInfo.targetActivity != null) {
1606 component = new ComponentName(r.activityInfo.packageName,
1607 r.activityInfo.targetActivity);
1608 }
1609
1610 Activity activity = null;
1611 try {
1612 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
1613 activity = mInstrumentation.newActivity(
1614 cl, component.getClassName(), r.intent);
1615 r.intent.setExtrasClassLoader(cl);
1616 if (r.state != null) {
1617 r.state.setClassLoader(cl);
1618 }
1619 } catch (Exception e) {
1620 if (!mInstrumentation.onException(activity, e)) {
1621 throw new RuntimeException(
1622 "Unable to instantiate activity " + component
1623 + ": " + e.toString(), e);
1624 }
1625 }
1626
1627 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001628 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001629
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001630 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
1631 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 TAG, r + ": app=" + app
1633 + ", appName=" + app.getPackageName()
1634 + ", pkg=" + r.packageInfo.getPackageName()
1635 + ", comp=" + r.intent.getComponent().toShortString()
1636 + ", dir=" + r.packageInfo.getAppDir());
1637
1638 if (activity != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001639 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 appContext.init(r.packageInfo, r.token, this);
1641 appContext.setOuterContext(activity);
1642 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
1643 Configuration config = new Configuration(mConfiguration);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001644 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07001645 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001646 activity.attach(appContext, this, getInstrumentation(), r.token,
1647 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001648 r.embeddedID, r.lastNonConfigurationInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07001649
Christopher Tateb70f3df2009-04-07 16:07:59 -07001650 if (customIntent != null) {
1651 activity.mIntent = customIntent;
1652 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001653 r.lastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 activity.mStartedActivity = false;
1655 int theme = r.activityInfo.getThemeResource();
1656 if (theme != 0) {
1657 activity.setTheme(theme);
1658 }
1659
1660 activity.mCalled = false;
1661 mInstrumentation.callActivityOnCreate(activity, r.state);
1662 if (!activity.mCalled) {
1663 throw new SuperNotCalledException(
1664 "Activity " + r.intent.getComponent().toShortString() +
1665 " did not call through to super.onCreate()");
1666 }
1667 r.activity = activity;
1668 r.stopped = true;
1669 if (!r.activity.mFinished) {
1670 activity.performStart();
1671 r.stopped = false;
1672 }
1673 if (!r.activity.mFinished) {
1674 if (r.state != null) {
1675 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
1676 }
1677 }
1678 if (!r.activity.mFinished) {
1679 activity.mCalled = false;
1680 mInstrumentation.callActivityOnPostCreate(activity, r.state);
1681 if (!activity.mCalled) {
1682 throw new SuperNotCalledException(
1683 "Activity " + r.intent.getComponent().toShortString() +
1684 " did not call through to super.onPostCreate()");
1685 }
1686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 }
1688 r.paused = true;
1689
1690 mActivities.put(r.token, r);
1691
1692 } catch (SuperNotCalledException e) {
1693 throw e;
1694
1695 } catch (Exception e) {
1696 if (!mInstrumentation.onException(activity, e)) {
1697 throw new RuntimeException(
1698 "Unable to start activity " + component
1699 + ": " + e.toString(), e);
1700 }
1701 }
1702
1703 return activity;
1704 }
1705
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001706 private final void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 // If we are getting ready to gc after going to the background, well
1708 // we are back active so skip it.
1709 unscheduleGcIdler();
1710
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001711 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001713 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714
1715 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08001716 r.createdConfig = new Configuration(mConfiguration);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001717 Bundle oldState = r.state;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 handleResumeActivity(r.token, false, r.isForward);
1719
1720 if (!r.activity.mFinished && r.startsNotResumed) {
1721 // The activity manager actually wants this one to start out
1722 // paused, because it needs to be visible but isn't in the
1723 // foreground. We accomplish this by going through the
1724 // normal startup (because activities expect to go through
1725 // onResume() the first time they run, before their window
1726 // is displayed), and then pausing it. However, in this case
1727 // we do -not- need to do the full pause cycle (of freezing
1728 // and such) because the activity manager assumes it can just
1729 // retain the current state it has.
1730 try {
1731 r.activity.mCalled = false;
1732 mInstrumentation.callActivityOnPause(r.activity);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001733 // We need to keep around the original state, in case
1734 // we need to be created again.
1735 r.state = oldState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 if (!r.activity.mCalled) {
1737 throw new SuperNotCalledException(
1738 "Activity " + r.intent.getComponent().toShortString() +
1739 " did not call through to super.onPause()");
1740 }
1741
1742 } catch (SuperNotCalledException e) {
1743 throw e;
1744
1745 } catch (Exception e) {
1746 if (!mInstrumentation.onException(r.activity, e)) {
1747 throw new RuntimeException(
1748 "Unable to pause activity "
1749 + r.intent.getComponent().toShortString()
1750 + ": " + e.toString(), e);
1751 }
1752 }
1753 r.paused = true;
1754 }
1755 } else {
1756 // If there was an error, for any reason, tell the activity
1757 // manager to stop us.
1758 try {
1759 ActivityManagerNative.getDefault()
1760 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
1761 } catch (RemoteException ex) {
1762 }
1763 }
1764 }
1765
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001766 private final void deliverNewIntents(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 List<Intent> intents) {
1768 final int N = intents.size();
1769 for (int i=0; i<N; i++) {
1770 Intent intent = intents.get(i);
1771 intent.setExtrasClassLoader(r.activity.getClassLoader());
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001772 r.activity.mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
1774 }
1775 }
1776
1777 public final void performNewIntents(IBinder token,
1778 List<Intent> intents) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001779 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 if (r != null) {
1781 final boolean resumed = !r.paused;
1782 if (resumed) {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001783 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 mInstrumentation.callActivityOnPause(r.activity);
1785 }
1786 deliverNewIntents(r, intents);
1787 if (resumed) {
1788 mInstrumentation.callActivityOnResume(r.activity);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001789 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 }
1791 }
1792 }
Bob Leee5408332009-09-04 18:31:17 -07001793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 private final void handleNewIntent(NewIntentData data) {
1795 performNewIntents(data.token, data.intents);
1796 }
1797
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07001798 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
1799
1800 /**
1801 * Return the Intent that's currently being handled by a
1802 * BroadcastReceiver on this thread, or null if none.
1803 * @hide
1804 */
1805 public static Intent getIntentBeingBroadcast() {
1806 return sCurrentBroadcastIntent.get();
1807 }
1808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 private final void handleReceiver(ReceiverData data) {
1810 // If we are getting ready to gc after going to the background, well
1811 // we are back active so skip it.
1812 unscheduleGcIdler();
1813
1814 String component = data.intent.getComponent().getClassName();
1815
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001816 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 data.info.applicationInfo);
1818
1819 IActivityManager mgr = ActivityManagerNative.getDefault();
1820
1821 BroadcastReceiver receiver = null;
1822 try {
1823 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1824 data.intent.setExtrasClassLoader(cl);
Dianne Hackborne829fef2010-10-26 17:44:01 -07001825 data.setExtrasClassLoader(cl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
1827 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07001828 if (DEBUG_BROADCAST) Slog.i(TAG,
1829 "Finishing failed broadcast to " + data.intent.getComponent());
1830 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 throw new RuntimeException(
1832 "Unable to instantiate receiver " + component
1833 + ": " + e.toString(), e);
1834 }
1835
1836 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001837 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001838
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001839 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 TAG, "Performing receive of " + data.intent
1841 + ": app=" + app
1842 + ", appName=" + app.getPackageName()
1843 + ", pkg=" + packageInfo.getPackageName()
1844 + ", comp=" + data.intent.getComponent().toShortString()
1845 + ", dir=" + packageInfo.getAppDir());
1846
Dianne Hackborn21556372010-02-04 16:34:40 -08001847 ContextImpl context = (ContextImpl)app.getBaseContext();
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07001848 sCurrentBroadcastIntent.set(data.intent);
Dianne Hackborne829fef2010-10-26 17:44:01 -07001849 receiver.setPendingResult(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 receiver.onReceive(context.getReceiverRestrictedContext(),
1851 data.intent);
1852 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07001853 if (DEBUG_BROADCAST) Slog.i(TAG,
1854 "Finishing failed broadcast to " + data.intent.getComponent());
1855 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 if (!mInstrumentation.onException(receiver, e)) {
1857 throw new RuntimeException(
1858 "Unable to start receiver " + component
1859 + ": " + e.toString(), e);
1860 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07001861 } finally {
1862 sCurrentBroadcastIntent.set(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 }
1864
Dianne Hackborne829fef2010-10-26 17:44:01 -07001865 if (receiver.getPendingResult() != null) {
1866 data.finish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 }
1868 }
1869
Christopher Tate181fafa2009-05-14 11:12:14 -07001870 // Instantiate a BackupAgent and tell it that it's alive
1871 private final void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001872 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001873
1874 // no longer idle; we have backup work to do
1875 unscheduleGcIdler();
1876
1877 // instantiate the BackupAgent class named in the manifest
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001878 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001879 String packageName = packageInfo.mPackageName;
1880 if (mBackupAgents.get(packageName) != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001881 Slog.d(TAG, "BackupAgent " + " for " + packageName
Christopher Tate181fafa2009-05-14 11:12:14 -07001882 + " already exists");
1883 return;
1884 }
Bob Leee5408332009-09-04 18:31:17 -07001885
Christopher Tate181fafa2009-05-14 11:12:14 -07001886 BackupAgent agent = null;
1887 String classname = data.appInfo.backupAgentName;
1888 if (classname == null) {
1889 if (data.backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001890 Slog.e(TAG, "Attempted incremental backup but no defined agent for "
Christopher Tate181fafa2009-05-14 11:12:14 -07001891 + packageName);
1892 return;
1893 }
1894 classname = "android.app.FullBackupAgent";
1895 }
1896 try {
Christopher Tated1475e02009-07-09 15:36:17 -07001897 IBinder binder = null;
1898 try {
1899 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1900 agent = (BackupAgent) cl.loadClass(data.appInfo.backupAgentName).newInstance();
1901
1902 // set up the agent's context
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001903 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing BackupAgent "
Christopher Tated1475e02009-07-09 15:36:17 -07001904 + data.appInfo.backupAgentName);
1905
Dianne Hackborn21556372010-02-04 16:34:40 -08001906 ContextImpl context = new ContextImpl();
Christopher Tated1475e02009-07-09 15:36:17 -07001907 context.init(packageInfo, null, this);
1908 context.setOuterContext(agent);
1909 agent.attach(context);
1910
1911 agent.onCreate();
1912 binder = agent.onBind();
1913 mBackupAgents.put(packageName, agent);
1914 } catch (Exception e) {
1915 // If this is during restore, fail silently; otherwise go
1916 // ahead and let the user see the crash.
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001917 Slog.e(TAG, "Agent threw during creation: " + e);
Christopher Tated1475e02009-07-09 15:36:17 -07001918 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE) {
1919 throw e;
1920 }
1921 // falling through with 'binder' still null
1922 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001923
1924 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07001925 try {
1926 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
1927 } catch (RemoteException e) {
1928 // nothing to do.
1929 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001930 } catch (Exception e) {
1931 throw new RuntimeException("Unable to create BackupAgent "
1932 + data.appInfo.backupAgentName + ": " + e.toString(), e);
1933 }
1934 }
1935
1936 // Tear down a BackupAgent
1937 private final void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001938 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07001939
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001940 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001941 String packageName = packageInfo.mPackageName;
1942 BackupAgent agent = mBackupAgents.get(packageName);
1943 if (agent != null) {
1944 try {
1945 agent.onDestroy();
1946 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001947 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001948 e.printStackTrace();
1949 }
1950 mBackupAgents.remove(packageName);
1951 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001952 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001953 }
1954 }
1955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 private final void handleCreateService(CreateServiceData data) {
1957 // If we are getting ready to gc after going to the background, well
1958 // we are back active so skip it.
1959 unscheduleGcIdler();
1960
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001961 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 data.info.applicationInfo);
1963 Service service = null;
1964 try {
1965 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1966 service = (Service) cl.loadClass(data.info.name).newInstance();
1967 } catch (Exception e) {
1968 if (!mInstrumentation.onException(service, e)) {
1969 throw new RuntimeException(
1970 "Unable to instantiate service " + data.info.name
1971 + ": " + e.toString(), e);
1972 }
1973 }
1974
1975 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001976 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977
Dianne Hackborn21556372010-02-04 16:34:40 -08001978 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001979 context.init(packageInfo, null, this);
1980
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001981 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982 context.setOuterContext(service);
1983 service.attach(context, this, data.info.name, data.token, app,
1984 ActivityManagerNative.getDefault());
1985 service.onCreate();
1986 mServices.put(data.token, service);
1987 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001988 ActivityManagerNative.getDefault().serviceDoneExecuting(
1989 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 } catch (RemoteException e) {
1991 // nothing to do.
1992 }
1993 } catch (Exception e) {
1994 if (!mInstrumentation.onException(service, e)) {
1995 throw new RuntimeException(
1996 "Unable to create service " + data.info.name
1997 + ": " + e.toString(), e);
1998 }
1999 }
2000 }
2001
2002 private final void handleBindService(BindServiceData data) {
2003 Service s = mServices.get(data.token);
2004 if (s != null) {
2005 try {
2006 data.intent.setExtrasClassLoader(s.getClassLoader());
2007 try {
2008 if (!data.rebind) {
2009 IBinder binder = s.onBind(data.intent);
2010 ActivityManagerNative.getDefault().publishService(
2011 data.token, data.intent, binder);
2012 } else {
2013 s.onRebind(data.intent);
2014 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002015 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002017 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002018 } catch (RemoteException ex) {
2019 }
2020 } catch (Exception e) {
2021 if (!mInstrumentation.onException(s, e)) {
2022 throw new RuntimeException(
2023 "Unable to bind to service " + s
2024 + " with " + data.intent + ": " + e.toString(), e);
2025 }
2026 }
2027 }
2028 }
2029
2030 private final void handleUnbindService(BindServiceData data) {
2031 Service s = mServices.get(data.token);
2032 if (s != null) {
2033 try {
2034 data.intent.setExtrasClassLoader(s.getClassLoader());
2035 boolean doRebind = s.onUnbind(data.intent);
2036 try {
2037 if (doRebind) {
2038 ActivityManagerNative.getDefault().unbindFinished(
2039 data.token, data.intent, doRebind);
2040 } else {
2041 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002042 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002043 }
2044 } catch (RemoteException ex) {
2045 }
2046 } catch (Exception e) {
2047 if (!mInstrumentation.onException(s, e)) {
2048 throw new RuntimeException(
2049 "Unable to unbind to service " + s
2050 + " with " + data.intent + ": " + e.toString(), e);
2051 }
2052 }
2053 }
2054 }
2055
Dianne Hackborn625ac272010-09-17 18:29:22 -07002056 private void handleDumpService(DumpComponentInfo info) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057 try {
Dianne Hackborn625ac272010-09-17 18:29:22 -07002058 Service s = mServices.get(info.token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 if (s != null) {
2060 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
2061 s.dump(info.fd, pw, info.args);
2062 pw.close();
2063 }
2064 } finally {
2065 synchronized (info) {
2066 info.dumped = true;
2067 info.notifyAll();
2068 }
2069 }
2070 }
2071
Dianne Hackborn625ac272010-09-17 18:29:22 -07002072 private void handleDumpActivity(DumpComponentInfo info) {
2073 try {
2074 ActivityClientRecord r = mActivities.get(info.token);
2075 if (r != null && r.activity != null) {
2076 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
2077 r.activity.dump(info.fd, pw, info.args);
2078 pw.close();
2079 }
2080 } finally {
2081 synchronized (info) {
2082 info.dumped = true;
2083 info.notifyAll();
2084 }
2085 }
2086 }
2087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 private final void handleServiceArgs(ServiceArgsData data) {
2089 Service s = mServices.get(data.token);
2090 if (s != null) {
2091 try {
2092 if (data.args != null) {
2093 data.args.setExtrasClassLoader(s.getClassLoader());
2094 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002095 int res = s.onStartCommand(data.args, data.flags, data.startId);
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002096
2097 QueuedWork.waitToFinish();
2098
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002099 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002100 ActivityManagerNative.getDefault().serviceDoneExecuting(
2101 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002102 } catch (RemoteException e) {
2103 // nothing to do.
2104 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002105 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106 } catch (Exception e) {
2107 if (!mInstrumentation.onException(s, e)) {
2108 throw new RuntimeException(
2109 "Unable to start service " + s
2110 + " with " + data.args + ": " + e.toString(), e);
2111 }
2112 }
2113 }
2114 }
2115
2116 private final void handleStopService(IBinder token) {
2117 Service s = mServices.remove(token);
2118 if (s != null) {
2119 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002120 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121 s.onDestroy();
2122 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002123 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08002125 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002127
2128 QueuedWork.waitToFinish();
2129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002131 ActivityManagerNative.getDefault().serviceDoneExecuting(
2132 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002133 } catch (RemoteException e) {
2134 // nothing to do.
2135 }
2136 } catch (Exception e) {
2137 if (!mInstrumentation.onException(s, e)) {
2138 throw new RuntimeException(
2139 "Unable to stop service " + s
2140 + ": " + e.toString(), e);
2141 }
2142 }
2143 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002144 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002145 }
2146
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002147 public final ActivityClientRecord performResumeActivity(IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002148 boolean clearHide) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002149 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002150 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002151 + " finished=" + r.activity.mFinished);
2152 if (r != null && !r.activity.mFinished) {
2153 if (clearHide) {
2154 r.hideForNow = false;
2155 r.activity.mStartedActivity = false;
2156 }
2157 try {
2158 if (r.pendingIntents != null) {
2159 deliverNewIntents(r, r.pendingIntents);
2160 r.pendingIntents = null;
2161 }
2162 if (r.pendingResults != null) {
2163 deliverResults(r, r.pendingResults);
2164 r.pendingResults = null;
2165 }
2166 r.activity.performResume();
2167
Bob Leee5408332009-09-04 18:31:17 -07002168 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002169 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002171 r.paused = false;
2172 r.stopped = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173 r.state = null;
2174 } catch (Exception e) {
2175 if (!mInstrumentation.onException(r.activity, e)) {
2176 throw new RuntimeException(
2177 "Unable to resume activity "
2178 + r.intent.getComponent().toShortString()
2179 + ": " + e.toString(), e);
2180 }
2181 }
2182 }
2183 return r;
2184 }
2185
2186 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2187 // If we are getting ready to gc after going to the background, well
2188 // we are back active so skip it.
2189 unscheduleGcIdler();
2190
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002191 ActivityClientRecord r = performResumeActivity(token, clearHide);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002192
2193 if (r != null) {
2194 final Activity a = r.activity;
2195
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002196 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002197 TAG, "Resume " + r + " started activity: " +
2198 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2199 + ", finished: " + a.mFinished);
2200
2201 final int forwardBit = isForward ?
2202 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 // If the window hasn't yet been added to the window manager,
2205 // and this guy didn't finish itself or start another activity,
2206 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002207 boolean willBeVisible = !a.mStartedActivity;
2208 if (!willBeVisible) {
2209 try {
2210 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
2211 a.getActivityToken());
2212 } catch (RemoteException e) {
2213 }
2214 }
2215 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002216 r.window = r.activity.getWindow();
2217 View decor = r.window.getDecorView();
2218 decor.setVisibility(View.INVISIBLE);
2219 ViewManager wm = a.getWindowManager();
2220 WindowManager.LayoutParams l = r.window.getAttributes();
2221 a.mDecor = decor;
2222 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2223 l.softInputMode |= forwardBit;
2224 if (a.mVisibleFromClient) {
2225 a.mWindowAdded = true;
2226 wm.addView(decor, l);
2227 }
2228
2229 // If the window has already been added, but during resume
2230 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002231 // window visible.
2232 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002233 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234 TAG, "Launch " + r + " mStartedActivity set");
2235 r.hideForNow = true;
2236 }
2237
2238 // The window is now visible if it has been added, we are not
2239 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002240 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002241 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002242 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002243 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002244 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002245 performConfigurationChanged(r.activity, r.newConfig);
2246 r.newConfig = null;
2247 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002248 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002249 + isForward);
2250 WindowManager.LayoutParams l = r.window.getAttributes();
2251 if ((l.softInputMode
2252 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2253 != forwardBit) {
2254 l.softInputMode = (l.softInputMode
2255 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2256 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002257 if (r.activity.mVisibleFromClient) {
2258 ViewManager wm = a.getWindowManager();
2259 View decor = r.window.getDecorView();
2260 wm.updateViewLayout(decor, l);
2261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002262 }
2263 r.activity.mVisibleFromServer = true;
2264 mNumVisibleActivities++;
2265 if (r.activity.mVisibleFromClient) {
2266 r.activity.makeVisible();
2267 }
2268 }
2269
2270 r.nextIdle = mNewActivities;
2271 mNewActivities = r;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002272 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002273 TAG, "Scheduling idle handler for " + r);
2274 Looper.myQueue().addIdleHandler(new Idler());
2275
2276 } else {
2277 // If an exception was thrown when trying to resume, then
2278 // just end this activity.
2279 try {
2280 ActivityManagerNative.getDefault()
2281 .finishActivity(token, Activity.RESULT_CANCELED, null);
2282 } catch (RemoteException ex) {
2283 }
2284 }
2285 }
2286
2287 private int mThumbnailWidth = -1;
2288 private int mThumbnailHeight = -1;
2289
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002290 private final Bitmap createThumbnailBitmap(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002291 Bitmap thumbnail = null;
2292 try {
2293 int w = mThumbnailWidth;
2294 int h;
2295 if (w < 0) {
2296 Resources res = r.activity.getResources();
2297 mThumbnailHeight = h =
2298 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
2299
2300 mThumbnailWidth = w =
2301 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
2302 } else {
2303 h = mThumbnailHeight;
2304 }
2305
Jim Miller0b2a6d02010-07-13 18:01:29 -07002306 // On platforms where we don't want thumbnails, set dims to (0,0)
2307 if ((w > 0) && (h > 0)) {
2308 View topView = r.activity.getWindow().getDecorView();
2309
2310 // Maximize bitmap by capturing in native aspect.
2311 if (topView.getWidth() >= topView.getHeight()) {
2312 thumbnail = Bitmap.createBitmap(w, h, THUMBNAIL_FORMAT);
2313 } else {
2314 thumbnail = Bitmap.createBitmap(h, w, THUMBNAIL_FORMAT);
2315 }
2316
2317 thumbnail.eraseColor(0);
2318 Canvas cv = new Canvas(thumbnail);
2319 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
2320 thumbnail = null;
2321 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002322 }
Jim Miller0b2a6d02010-07-13 18:01:29 -07002323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002324 } catch (Exception e) {
2325 if (!mInstrumentation.onException(r.activity, e)) {
2326 throw new RuntimeException(
2327 "Unable to create thumbnail of "
2328 + r.intent.getComponent().toShortString()
2329 + ": " + e.toString(), e);
2330 }
2331 thumbnail = null;
2332 }
2333
2334 return thumbnail;
2335 }
2336
2337 private final void handlePauseActivity(IBinder token, boolean finished,
2338 boolean userLeaving, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002339 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002340 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002341 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002342 if (userLeaving) {
2343 performUserLeavingActivity(r);
2344 }
Bob Leee5408332009-09-04 18:31:17 -07002345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002346 r.activity.mConfigChangeFlags |= configChanges;
2347 Bundle state = performPauseActivity(token, finished, true);
2348
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07002349 // Make sure any pending writes are now committed.
2350 QueuedWork.waitToFinish();
2351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002352 // Tell the activity manager we have paused.
2353 try {
2354 ActivityManagerNative.getDefault().activityPaused(token, state);
2355 } catch (RemoteException ex) {
2356 }
2357 }
2358 }
2359
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002360 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361 mInstrumentation.callActivityOnUserLeaving(r.activity);
2362 }
2363
2364 final Bundle performPauseActivity(IBinder token, boolean finished,
2365 boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002366 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367 return r != null ? performPauseActivity(r, finished, saveState) : null;
2368 }
2369
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002370 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002371 boolean saveState) {
2372 if (r.paused) {
2373 if (r.activity.mFinished) {
2374 // If we are finishing, we won't call onResume() in certain cases.
2375 // So here we likewise don't want to call onPause() if the activity
2376 // isn't resumed.
2377 return null;
2378 }
2379 RuntimeException e = new RuntimeException(
2380 "Performing pause of activity that is not resumed: "
2381 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002382 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002383 }
2384 Bundle state = null;
2385 if (finished) {
2386 r.activity.mFinished = true;
2387 }
2388 try {
2389 // Next have the activity save its current state and managed dialogs...
2390 if (!r.activity.mFinished && saveState) {
2391 state = new Bundle();
2392 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2393 r.state = state;
2394 }
2395 // Now we are idle.
2396 r.activity.mCalled = false;
2397 mInstrumentation.callActivityOnPause(r.activity);
2398 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
2399 if (!r.activity.mCalled) {
2400 throw new SuperNotCalledException(
2401 "Activity " + r.intent.getComponent().toShortString() +
2402 " did not call through to super.onPause()");
2403 }
2404
2405 } catch (SuperNotCalledException e) {
2406 throw e;
2407
2408 } catch (Exception e) {
2409 if (!mInstrumentation.onException(r.activity, e)) {
2410 throw new RuntimeException(
2411 "Unable to pause activity "
2412 + r.intent.getComponent().toShortString()
2413 + ": " + e.toString(), e);
2414 }
2415 }
2416 r.paused = true;
2417 return state;
2418 }
2419
2420 final void performStopActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002421 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002422 performStopActivityInner(r, null, false);
2423 }
2424
2425 private static class StopInfo {
2426 Bitmap thumbnail;
2427 CharSequence description;
2428 }
2429
2430 private final class ProviderRefCount {
2431 public int count;
2432 ProviderRefCount(int pCount) {
2433 count = pCount;
2434 }
2435 }
2436
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002437 private final void performStopActivityInner(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002438 StopInfo info, boolean keepShown) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002439 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002440 if (r != null) {
2441 if (!keepShown && r.stopped) {
2442 if (r.activity.mFinished) {
2443 // If we are finishing, we won't call onResume() in certain
2444 // cases. So here we likewise don't want to call onStop()
2445 // if the activity isn't resumed.
2446 return;
2447 }
2448 RuntimeException e = new RuntimeException(
2449 "Performing stop of activity that is not resumed: "
2450 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002451 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002452 }
2453
2454 if (info != null) {
2455 try {
2456 // First create a thumbnail for the activity...
Jim Miller0b2a6d02010-07-13 18:01:29 -07002457 info.thumbnail = createThumbnailBitmap(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002458 info.description = r.activity.onCreateDescription();
2459 } catch (Exception e) {
2460 if (!mInstrumentation.onException(r.activity, e)) {
2461 throw new RuntimeException(
2462 "Unable to save state of activity "
2463 + r.intent.getComponent().toShortString()
2464 + ": " + e.toString(), e);
2465 }
2466 }
2467 }
2468
2469 if (!keepShown) {
2470 try {
2471 // Now we are idle.
2472 r.activity.performStop();
2473 } catch (Exception e) {
2474 if (!mInstrumentation.onException(r.activity, e)) {
2475 throw new RuntimeException(
2476 "Unable to stop activity "
2477 + r.intent.getComponent().toShortString()
2478 + ": " + e.toString(), e);
2479 }
2480 }
2481 r.stopped = true;
2482 }
2483
2484 r.paused = true;
2485 }
2486 }
2487
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002488 private final void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 View v = r.activity.mDecor;
2490 if (v != null) {
2491 if (show) {
2492 if (!r.activity.mVisibleFromServer) {
2493 r.activity.mVisibleFromServer = true;
2494 mNumVisibleActivities++;
2495 if (r.activity.mVisibleFromClient) {
2496 r.activity.makeVisible();
2497 }
2498 }
2499 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002500 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002501 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002502 performConfigurationChanged(r.activity, r.newConfig);
2503 r.newConfig = null;
2504 }
2505 } else {
2506 if (r.activity.mVisibleFromServer) {
2507 r.activity.mVisibleFromServer = false;
2508 mNumVisibleActivities--;
2509 v.setVisibility(View.INVISIBLE);
2510 }
2511 }
2512 }
2513 }
2514
2515 private final void handleStopActivity(IBinder token, boolean show, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002516 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 r.activity.mConfigChangeFlags |= configChanges;
2518
2519 StopInfo info = new StopInfo();
2520 performStopActivityInner(r, info, show);
2521
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002522 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 TAG, "Finishing stop of " + r + ": show=" + show
2524 + " win=" + r.window);
2525
2526 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07002527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002528 // Tell activity manager we have been stopped.
2529 try {
2530 ActivityManagerNative.getDefault().activityStopped(
2531 r.token, info.thumbnail, info.description);
2532 } catch (RemoteException ex) {
2533 }
2534 }
2535
2536 final void performRestartActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002537 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002538 if (r.stopped) {
2539 r.activity.performRestart();
2540 r.stopped = false;
2541 }
2542 }
2543
2544 private final void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002545 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 if (!show && !r.stopped) {
2547 performStopActivityInner(r, null, show);
2548 } else if (show && r.stopped) {
2549 // If we are getting ready to gc after going to the background, well
2550 // we are back active so skip it.
2551 unscheduleGcIdler();
2552
2553 r.activity.performRestart();
2554 r.stopped = false;
2555 }
2556 if (r.activity.mDecor != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002557 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 TAG, "Handle window " + r + " visibility: " + show);
2559 updateVisibility(r, show);
2560 }
2561 }
2562
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002563 private final void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 final int N = results.size();
2565 for (int i=0; i<N; i++) {
2566 ResultInfo ri = results.get(i);
2567 try {
2568 if (ri.mData != null) {
2569 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
2570 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002571 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07002572 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 r.activity.dispatchActivityResult(ri.mResultWho,
2574 ri.mRequestCode, ri.mResultCode, ri.mData);
2575 } catch (Exception e) {
2576 if (!mInstrumentation.onException(r.activity, e)) {
2577 throw new RuntimeException(
2578 "Failure delivering result " + ri + " to activity "
2579 + r.intent.getComponent().toShortString()
2580 + ": " + e.toString(), e);
2581 }
2582 }
2583 }
2584 }
2585
2586 private final void handleSendResult(ResultData res) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002587 ActivityClientRecord r = mActivities.get(res.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002588 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 if (r != null) {
2590 final boolean resumed = !r.paused;
2591 if (!r.activity.mFinished && r.activity.mDecor != null
2592 && r.hideForNow && resumed) {
2593 // We had hidden the activity because it started another
2594 // one... we have gotten a result back and we are not
2595 // paused, so make sure our window is visible.
2596 updateVisibility(r, true);
2597 }
2598 if (resumed) {
2599 try {
2600 // Now we are idle.
2601 r.activity.mCalled = false;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002602 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002603 mInstrumentation.callActivityOnPause(r.activity);
2604 if (!r.activity.mCalled) {
2605 throw new SuperNotCalledException(
2606 "Activity " + r.intent.getComponent().toShortString()
2607 + " did not call through to super.onPause()");
2608 }
2609 } catch (SuperNotCalledException e) {
2610 throw e;
2611 } catch (Exception e) {
2612 if (!mInstrumentation.onException(r.activity, e)) {
2613 throw new RuntimeException(
2614 "Unable to pause activity "
2615 + r.intent.getComponent().toShortString()
2616 + ": " + e.toString(), e);
2617 }
2618 }
2619 }
2620 deliverResults(r, res.results);
2621 if (resumed) {
2622 mInstrumentation.callActivityOnResume(r.activity);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002623 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 }
2625 }
2626 }
2627
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002628 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 return performDestroyActivity(token, finishing, 0, false);
2630 }
2631
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002632 private final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002633 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002634 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002635 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636 if (r != null) {
2637 r.activity.mConfigChangeFlags |= configChanges;
2638 if (finishing) {
2639 r.activity.mFinished = true;
2640 }
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -05002641 if (getNonConfigInstance) {
2642 r.activity.mChangingConfigurations = true;
2643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002644 if (!r.paused) {
2645 try {
2646 r.activity.mCalled = false;
2647 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07002648 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 r.activity.getComponentName().getClassName());
2650 if (!r.activity.mCalled) {
2651 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002652 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653 + " did not call through to super.onPause()");
2654 }
2655 } catch (SuperNotCalledException e) {
2656 throw e;
2657 } catch (Exception e) {
2658 if (!mInstrumentation.onException(r.activity, e)) {
2659 throw new RuntimeException(
2660 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002661 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662 + ": " + e.toString(), e);
2663 }
2664 }
2665 r.paused = true;
2666 }
2667 if (!r.stopped) {
2668 try {
2669 r.activity.performStop();
2670 } catch (SuperNotCalledException e) {
2671 throw e;
2672 } catch (Exception e) {
2673 if (!mInstrumentation.onException(r.activity, e)) {
2674 throw new RuntimeException(
2675 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002676 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 + ": " + e.toString(), e);
2678 }
2679 }
2680 r.stopped = true;
2681 }
2682 if (getNonConfigInstance) {
2683 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002684 r.lastNonConfigurationInstances
2685 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 } catch (Exception e) {
2687 if (!mInstrumentation.onException(r.activity, e)) {
2688 throw new RuntimeException(
2689 "Unable to retain activity "
2690 + r.intent.getComponent().toShortString()
2691 + ": " + e.toString(), e);
2692 }
2693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 }
2695 try {
2696 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07002697 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 if (!r.activity.mCalled) {
2699 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002700 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002701 " did not call through to super.onDestroy()");
2702 }
2703 if (r.window != null) {
2704 r.window.closeAllPanels();
2705 }
2706 } catch (SuperNotCalledException e) {
2707 throw e;
2708 } catch (Exception e) {
2709 if (!mInstrumentation.onException(r.activity, e)) {
2710 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002711 "Unable to destroy activity " + safeToComponentShortString(r.intent)
2712 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002713 }
2714 }
2715 }
2716 mActivities.remove(token);
2717
2718 return r;
2719 }
2720
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002721 private static String safeToComponentShortString(Intent intent) {
2722 ComponentName component = intent.getComponent();
2723 return component == null ? "[Unknown]" : component.toShortString();
2724 }
2725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002726 private final void handleDestroyActivity(IBinder token, boolean finishing,
2727 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002728 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 configChanges, getNonConfigInstance);
2730 if (r != null) {
2731 WindowManager wm = r.activity.getWindowManager();
2732 View v = r.activity.mDecor;
2733 if (v != null) {
2734 if (r.activity.mVisibleFromServer) {
2735 mNumVisibleActivities--;
2736 }
2737 IBinder wtoken = v.getWindowToken();
2738 if (r.activity.mWindowAdded) {
2739 wm.removeViewImmediate(v);
2740 }
2741 if (wtoken != null) {
2742 WindowManagerImpl.getDefault().closeAll(wtoken,
2743 r.activity.getClass().getName(), "Activity");
2744 }
2745 r.activity.mDecor = null;
2746 }
2747 WindowManagerImpl.getDefault().closeAll(token,
2748 r.activity.getClass().getName(), "Activity");
2749
2750 // Mocked out contexts won't be participating in the normal
2751 // process lifecycle, but if we're running with a proper
2752 // ApplicationContext we need to have it tear down things
2753 // cleanly.
2754 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002755 if (c instanceof ContextImpl) {
2756 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002757 r.activity.getClass().getName(), "Activity");
2758 }
2759 }
2760 if (finishing) {
2761 try {
2762 ActivityManagerNative.getDefault().activityDestroyed(token);
2763 } catch (RemoteException ex) {
2764 // If the system process has died, it's game over for everyone.
2765 }
2766 }
2767 }
2768
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002769 private final void handleRelaunchActivity(ActivityClientRecord tmp, int configChanges) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002770 // If we are getting ready to gc after going to the background, well
2771 // we are back active so skip it.
2772 unscheduleGcIdler();
2773
2774 Configuration changedConfig = null;
Bob Leee5408332009-09-04 18:31:17 -07002775
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002776 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002777 + tmp.token + " with configChanges=0x"
2778 + Integer.toHexString(configChanges));
2779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002780 // First: make sure we have the most recent configuration and most
2781 // recent version of the activity, or skip it if some previous call
2782 // had taken a more recent version.
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002783 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784 int N = mRelaunchingActivities.size();
2785 IBinder token = tmp.token;
2786 tmp = null;
2787 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002788 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002789 if (r.token == token) {
2790 tmp = r;
2791 mRelaunchingActivities.remove(i);
2792 i--;
2793 N--;
2794 }
2795 }
Bob Leee5408332009-09-04 18:31:17 -07002796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002797 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002798 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002799 return;
2800 }
Bob Leee5408332009-09-04 18:31:17 -07002801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002802 if (mPendingConfiguration != null) {
2803 changedConfig = mPendingConfiguration;
2804 mPendingConfiguration = null;
2805 }
2806 }
Bob Leee5408332009-09-04 18:31:17 -07002807
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002808 if (tmp.createdConfig != null) {
2809 // If the activity manager is passing us its current config,
2810 // assume that is really what we want regardless of what we
2811 // may have pending.
2812 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002813 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
2814 && mConfiguration.diff(tmp.createdConfig) != 0)) {
2815 if (changedConfig == null
2816 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
2817 changedConfig = tmp.createdConfig;
2818 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002819 }
2820 }
2821
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002822 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002823 + tmp.token + ": changedConfig=" + changedConfig);
2824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 // If there was a pending configuration change, execute it first.
2826 if (changedConfig != null) {
2827 handleConfigurationChanged(changedConfig);
2828 }
Bob Leee5408332009-09-04 18:31:17 -07002829
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002830 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002831 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 if (r == null) {
2833 return;
2834 }
Bob Leee5408332009-09-04 18:31:17 -07002835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 r.activity.mConfigChangeFlags |= configChanges;
Christopher Tateb70f3df2009-04-07 16:07:59 -07002837 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07002838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002839 Bundle savedState = null;
2840 if (!r.paused) {
2841 savedState = performPauseActivity(r.token, false, true);
2842 }
Bob Leee5408332009-09-04 18:31:17 -07002843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002844 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07002845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002846 r.activity = null;
2847 r.window = null;
2848 r.hideForNow = false;
2849 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07002850 // Merge any pending results and pending intents; don't just replace them
2851 if (tmp.pendingResults != null) {
2852 if (r.pendingResults == null) {
2853 r.pendingResults = tmp.pendingResults;
2854 } else {
2855 r.pendingResults.addAll(tmp.pendingResults);
2856 }
2857 }
2858 if (tmp.pendingIntents != null) {
2859 if (r.pendingIntents == null) {
2860 r.pendingIntents = tmp.pendingIntents;
2861 } else {
2862 r.pendingIntents.addAll(tmp.pendingIntents);
2863 }
2864 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002865 r.startsNotResumed = tmp.startsNotResumed;
2866 if (savedState != null) {
2867 r.state = savedState;
2868 }
Bob Leee5408332009-09-04 18:31:17 -07002869
Christopher Tateb70f3df2009-04-07 16:07:59 -07002870 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002871 }
2872
2873 private final void handleRequestThumbnail(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002874 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002875 Bitmap thumbnail = createThumbnailBitmap(r);
2876 CharSequence description = null;
2877 try {
2878 description = r.activity.onCreateDescription();
2879 } catch (Exception e) {
2880 if (!mInstrumentation.onException(r.activity, e)) {
2881 throw new RuntimeException(
2882 "Unable to create description of activity "
2883 + r.intent.getComponent().toShortString()
2884 + ": " + e.toString(), e);
2885 }
2886 }
2887 //System.out.println("Reporting top thumbnail " + thumbnail);
2888 try {
2889 ActivityManagerNative.getDefault().reportThumbnail(
2890 token, thumbnail, description);
2891 } catch (RemoteException ex) {
2892 }
2893 }
2894
2895 ArrayList<ComponentCallbacks> collectComponentCallbacksLocked(
2896 boolean allActivities, Configuration newConfig) {
2897 ArrayList<ComponentCallbacks> callbacks
2898 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07002899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002900 if (mActivities.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002901 Iterator<ActivityClientRecord> it = mActivities.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902 while (it.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002903 ActivityClientRecord ar = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002904 Activity a = ar.activity;
2905 if (a != null) {
2906 if (!ar.activity.mFinished && (allActivities ||
2907 (a != null && !ar.paused))) {
2908 // If the activity is currently resumed, its configuration
2909 // needs to change right now.
2910 callbacks.add(a);
2911 } else if (newConfig != null) {
2912 // Otherwise, we will tell it about the change
2913 // the next time it is resumed or shown. Note that
2914 // the activity manager may, before then, decide the
2915 // activity needs to be destroyed to handle its new
2916 // configuration.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002917 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Setting activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002918 + ar.activityInfo.name + " newConfig=" + newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002919 ar.newConfig = newConfig;
2920 }
2921 }
2922 }
2923 }
2924 if (mServices.size() > 0) {
2925 Iterator<Service> it = mServices.values().iterator();
2926 while (it.hasNext()) {
2927 callbacks.add(it.next());
2928 }
2929 }
2930 synchronized (mProviderMap) {
2931 if (mLocalProviders.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002932 Iterator<ProviderClientRecord> it = mLocalProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002933 while (it.hasNext()) {
2934 callbacks.add(it.next().mLocalProvider);
2935 }
2936 }
2937 }
2938 final int N = mAllApplications.size();
2939 for (int i=0; i<N; i++) {
2940 callbacks.add(mAllApplications.get(i));
2941 }
Bob Leee5408332009-09-04 18:31:17 -07002942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002943 return callbacks;
2944 }
Bob Leee5408332009-09-04 18:31:17 -07002945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002946 private final void performConfigurationChanged(
2947 ComponentCallbacks cb, Configuration config) {
2948 // Only for Activity objects, check that they actually call up to their
2949 // superclass implementation. ComponentCallbacks is an interface, so
2950 // we check the runtime type and act accordingly.
2951 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
2952 if (activity != null) {
2953 activity.mCalled = false;
2954 }
Bob Leee5408332009-09-04 18:31:17 -07002955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002956 boolean shouldChangeConfig = false;
2957 if ((activity == null) || (activity.mCurrentConfig == null)) {
2958 shouldChangeConfig = true;
2959 } else {
Bob Leee5408332009-09-04 18:31:17 -07002960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002961 // If the new config is the same as the config this Activity
2962 // is already running with then don't bother calling
2963 // onConfigurationChanged
2964 int diff = activity.mCurrentConfig.diff(config);
2965 if (diff != 0) {
Bob Leee5408332009-09-04 18:31:17 -07002966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002967 // If this activity doesn't handle any of the config changes
2968 // then don't bother calling onConfigurationChanged as we're
2969 // going to destroy it.
2970 if ((~activity.mActivityInfo.configChanges & diff) == 0) {
2971 shouldChangeConfig = true;
2972 }
2973 }
2974 }
Bob Leee5408332009-09-04 18:31:17 -07002975
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002976 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002977 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002978 if (shouldChangeConfig) {
2979 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07002980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002981 if (activity != null) {
2982 if (!activity.mCalled) {
2983 throw new SuperNotCalledException(
2984 "Activity " + activity.getLocalClassName() +
2985 " did not call through to super.onConfigurationChanged()");
2986 }
2987 activity.mConfigChangeFlags = 0;
2988 activity.mCurrentConfig = new Configuration(config);
2989 }
2990 }
2991 }
2992
Dianne Hackbornae078162010-03-18 11:29:37 -07002993 final boolean applyConfigurationToResourcesLocked(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002994 if (mResConfiguration == null) {
2995 mResConfiguration = new Configuration();
2996 }
2997 if (!mResConfiguration.isOtherSeqNewer(config)) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002998 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq="
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002999 + mResConfiguration.seq + ", newSeq=" + config.seq);
Dianne Hackbornae078162010-03-18 11:29:37 -07003000 return false;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003001 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003002 int changes = mResConfiguration.updateFrom(config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003003 DisplayMetrics dm = getDisplayMetricsLocked(true);
Bob Leee5408332009-09-04 18:31:17 -07003004
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003005 // set it for java, this also affects newly created Resources
3006 if (config.locale != null) {
3007 Locale.setDefault(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003008 }
Bob Leee5408332009-09-04 18:31:17 -07003009
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003010 Resources.updateSystemConfiguration(config, dm);
Bob Leee5408332009-09-04 18:31:17 -07003011
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003012 ApplicationPackageManager.configurationChanged();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003013 //Slog.i(TAG, "Configuration changed in " + currentPackageName());
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003014
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003015 Iterator<WeakReference<Resources>> it =
3016 mActiveResources.values().iterator();
3017 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
3018 // mActiveResources.entrySet().iterator();
3019 while (it.hasNext()) {
3020 WeakReference<Resources> v = it.next();
3021 Resources r = v.get();
3022 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003023 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources "
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003024 + r + " config to: " + config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003025 r.updateConfiguration(config, dm);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003026 //Slog.i(TAG, "Updated app resources " + v.getKey()
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003027 // + " " + r + ": " + r.getConfiguration());
3028 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003029 //Slog.i(TAG, "Removing old resources " + v.getKey());
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003030 it.remove();
3031 }
3032 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003033
3034 return changes != 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003035 }
3036
3037 final void handleConfigurationChanged(Configuration config) {
3038
3039 ArrayList<ComponentCallbacks> callbacks = null;
3040
3041 synchronized (mPackages) {
3042 if (mPendingConfiguration != null) {
3043 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
3044 config = mPendingConfiguration;
3045 }
3046 mPendingConfiguration = null;
3047 }
3048
3049 if (config == null) {
3050 return;
3051 }
3052
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003053 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003054 + config);
3055
3056 applyConfigurationToResourcesLocked(config);
3057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003058 if (mConfiguration == null) {
3059 mConfiguration = new Configuration();
3060 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003061 if (!mConfiguration.isOtherSeqNewer(config)) {
3062 return;
3063 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003064 mConfiguration.updateFrom(config);
Bob Leee5408332009-09-04 18:31:17 -07003065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003066 callbacks = collectComponentCallbacksLocked(false, config);
3067 }
Bob Leee5408332009-09-04 18:31:17 -07003068
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003069 if (callbacks != null) {
3070 final int N = callbacks.size();
3071 for (int i=0; i<N; i++) {
3072 performConfigurationChanged(callbacks.get(i), config);
3073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003074 }
3075 }
3076
3077 final void handleActivityConfigurationChanged(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003078 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003079 if (r == null || r.activity == null) {
3080 return;
3081 }
Bob Leee5408332009-09-04 18:31:17 -07003082
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003083 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003084 + r.activityInfo.name);
3085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003086 performConfigurationChanged(r.activity, mConfiguration);
3087 }
3088
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003089 final void handleProfilerControl(boolean start, ProfilerControlData pcd) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003090 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003091 try {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003092 Debug.startMethodTracing(pcd.path, pcd.fd.getFileDescriptor(),
3093 8 * 1024 * 1024, 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003094 } catch (RuntimeException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003095 Slog.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003096 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003097 } finally {
3098 try {
3099 pcd.fd.close();
3100 } catch (IOException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003101 Slog.w(TAG, "Failure closing profile fd", e);
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003102 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003103 }
3104 } else {
3105 Debug.stopMethodTracing();
3106 }
3107 }
Bob Leee5408332009-09-04 18:31:17 -07003108
Andy McFadden824c5102010-07-09 16:26:57 -07003109 final void handleDumpHeap(boolean managed, DumpHeapData dhd) {
3110 if (managed) {
3111 try {
3112 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor());
3113 } catch (IOException e) {
3114 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
3115 + " -- can the process access this path?");
3116 } finally {
3117 try {
3118 dhd.fd.close();
3119 } catch (IOException e) {
3120 Slog.w(TAG, "Failure closing profile fd", e);
3121 }
3122 }
3123 } else {
Andy McFadden06a6b552010-07-13 16:28:09 -07003124 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07003125 }
3126 }
3127
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003128 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
3129 boolean hasPkgInfo = false;
3130 if (packages != null) {
3131 for (int i=packages.length-1; i>=0; i--) {
3132 //Slog.i(TAG, "Cleaning old package: " + packages[i]);
3133 if (!hasPkgInfo) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003134 WeakReference<LoadedApk> ref;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003135 ref = mPackages.get(packages[i]);
3136 if (ref != null && ref.get() != null) {
3137 hasPkgInfo = true;
3138 } else {
3139 ref = mResourcePackages.get(packages[i]);
3140 if (ref != null && ref.get() != null) {
3141 hasPkgInfo = true;
3142 }
3143 }
3144 }
3145 mPackages.remove(packages[i]);
3146 mResourcePackages.remove(packages[i]);
3147 }
3148 }
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003149 ApplicationPackageManager.handlePackageBroadcast(cmd, packages,
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003150 hasPkgInfo);
3151 }
3152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003153 final void handleLowMemory() {
3154 ArrayList<ComponentCallbacks> callbacks
3155 = new ArrayList<ComponentCallbacks>();
3156
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003157 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003158 callbacks = collectComponentCallbacksLocked(true, null);
3159 }
Bob Leee5408332009-09-04 18:31:17 -07003160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003161 final int N = callbacks.size();
3162 for (int i=0; i<N; i++) {
3163 callbacks.get(i).onLowMemory();
3164 }
3165
Chris Tatece229052009-03-25 16:44:52 -07003166 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3167 if (Process.myUid() != Process.SYSTEM_UID) {
3168 int sqliteReleased = SQLiteDatabase.releaseMemory();
3169 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3170 }
Bob Leee5408332009-09-04 18:31:17 -07003171
Mike Reedcaf0df12009-04-27 14:32:05 -04003172 // Ask graphics to free up as much as possible (font/image caches)
3173 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003174
3175 BinderInternal.forceGc("mem");
3176 }
3177
3178 private final void handleBindApplication(AppBindData data) {
3179 mBoundApplication = data;
3180 mConfiguration = new Configuration(data.config);
3181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003183 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003184 android.ddm.DdmHandleAppName.setAppName(data.processName);
3185
3186 /*
3187 * Before spawning a new process, reset the time zone to be the system time zone.
3188 * This needs to be done because the system time zone could have changed after the
3189 * the spawning of this process. Without doing this this process would have the incorrect
3190 * system time zone.
3191 */
3192 TimeZone.setDefault(null);
3193
3194 /*
3195 * Initialize the default locale in this process for the reasons we set the time zone.
3196 */
3197 Locale.setDefault(data.config.locale);
3198
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003199 /*
3200 * Update the system configuration since its preloaded and might not
3201 * reflect configuration changes. The configuration object passed
3202 * in AppBindData can be safely assumed to be up to date
3203 */
3204 Resources.getSystem().updateConfiguration(mConfiguration, null);
3205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003206 data.info = getPackageInfoNoCheck(data.appInfo);
3207
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003208 /**
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003209 * For system applications on userdebug/eng builds, log stack
3210 * traces of disk and network access to dropbox for analysis.
3211 */
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07003212 if ((data.appInfo.flags &
3213 (ApplicationInfo.FLAG_SYSTEM |
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07003214 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0) {
3215 StrictMode.conditionallyEnableDebugLogging();
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003216 }
3217
3218 /**
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07003219 * For apps targetting SDK Honeycomb or later, we don't allow
3220 * network usage on the main event loop / UI thread.
3221 *
3222 * Note to those grepping: this is what ultimately throws
3223 * NetworkOnMainThreadException ...
3224 */
3225 if (data.appInfo.targetSdkVersion > 9) {
3226 StrictMode.enableDeathOnNetwork();
3227 }
3228
3229 /**
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003230 * Switch this process to density compatibility mode if needed.
3231 */
3232 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3233 == 0) {
3234 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3235 }
Bob Leee5408332009-09-04 18:31:17 -07003236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003237 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3238 // XXX should have option to change the port.
3239 Debug.changeDebugPort(8100);
3240 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003241 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003242 + " is waiting for the debugger on port 8100...");
3243
3244 IActivityManager mgr = ActivityManagerNative.getDefault();
3245 try {
3246 mgr.showWaitingForDebugger(mAppThread, true);
3247 } catch (RemoteException ex) {
3248 }
3249
3250 Debug.waitForDebugger();
3251
3252 try {
3253 mgr.showWaitingForDebugger(mAppThread, false);
3254 } catch (RemoteException ex) {
3255 }
3256
3257 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003258 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003259 + " can be debugged on port 8100...");
3260 }
3261 }
3262
Robert Greenwalt434203a2010-10-11 16:00:27 -07003263 /**
3264 * Initialize the default http proxy in this process for the reasons we set the time zone.
3265 */
3266 IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
3267 IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
3268 try {
3269 ProxyProperties proxyProperties = service.getProxy();
3270 Proxy.setHttpProxySystemProperty(proxyProperties);
3271 } catch (RemoteException e) {}
3272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003273 if (data.instrumentationName != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08003274 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003275 appContext.init(data.info, null, this);
3276 InstrumentationInfo ii = null;
3277 try {
3278 ii = appContext.getPackageManager().
3279 getInstrumentationInfo(data.instrumentationName, 0);
3280 } catch (PackageManager.NameNotFoundException e) {
3281 }
3282 if (ii == null) {
3283 throw new RuntimeException(
3284 "Unable to find instrumentation info for: "
3285 + data.instrumentationName);
3286 }
3287
3288 mInstrumentationAppDir = ii.sourceDir;
3289 mInstrumentationAppPackage = ii.packageName;
3290 mInstrumentedAppDir = data.info.getAppDir();
3291
3292 ApplicationInfo instrApp = new ApplicationInfo();
3293 instrApp.packageName = ii.packageName;
3294 instrApp.sourceDir = ii.sourceDir;
3295 instrApp.publicSourceDir = ii.publicSourceDir;
3296 instrApp.dataDir = ii.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003297 instrApp.nativeLibraryDir = ii.nativeLibraryDir;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003298 LoadedApk pi = getPackageInfo(instrApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003299 appContext.getClassLoader(), false, true);
Dianne Hackborn21556372010-02-04 16:34:40 -08003300 ContextImpl instrContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301 instrContext.init(pi, null, this);
3302
3303 try {
3304 java.lang.ClassLoader cl = instrContext.getClassLoader();
3305 mInstrumentation = (Instrumentation)
3306 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3307 } catch (Exception e) {
3308 throw new RuntimeException(
3309 "Unable to instantiate instrumentation "
3310 + data.instrumentationName + ": " + e.toString(), e);
3311 }
3312
3313 mInstrumentation.init(this, instrContext, appContext,
3314 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3315
3316 if (data.profileFile != null && !ii.handleProfiling) {
3317 data.handlingProfiling = true;
3318 File file = new File(data.profileFile);
3319 file.getParentFile().mkdirs();
3320 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3321 }
3322
3323 try {
3324 mInstrumentation.onCreate(data.instrumentationArgs);
3325 }
3326 catch (Exception e) {
3327 throw new RuntimeException(
3328 "Exception thrown in onCreate() of "
3329 + data.instrumentationName + ": " + e.toString(), e);
3330 }
3331
3332 } else {
3333 mInstrumentation = new Instrumentation();
3334 }
3335
Christopher Tate181fafa2009-05-14 11:12:14 -07003336 // If the app is being launched for full backup or restore, bring it up in
3337 // a restricted environment with the base application class.
Dianne Hackborn0be1f782009-11-09 12:30:12 -08003338 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003339 mInitialApplication = app;
3340
3341 List<ProviderInfo> providers = data.providers;
3342 if (providers != null) {
3343 installContentProviders(app, providers);
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003344 // For process that contain content providers, we want to
3345 // ensure that the JIT is enabled "at some point".
3346 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003347 }
3348
3349 try {
3350 mInstrumentation.callApplicationOnCreate(app);
3351 } catch (Exception e) {
3352 if (!mInstrumentation.onException(app, e)) {
3353 throw new RuntimeException(
3354 "Unable to create application " + app.getClass().getName()
3355 + ": " + e.toString(), e);
3356 }
3357 }
3358 }
3359
3360 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
3361 IActivityManager am = ActivityManagerNative.getDefault();
3362 if (mBoundApplication.profileFile != null && mBoundApplication.handlingProfiling) {
3363 Debug.stopMethodTracing();
3364 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003365 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366 // + ", app thr: " + mAppThread);
3367 try {
3368 am.finishInstrumentation(mAppThread, resultCode, results);
3369 } catch (RemoteException ex) {
3370 }
3371 }
3372
3373 private final void installContentProviders(
3374 Context context, List<ProviderInfo> providers) {
3375 final ArrayList<IActivityManager.ContentProviderHolder> results =
3376 new ArrayList<IActivityManager.ContentProviderHolder>();
3377
3378 Iterator<ProviderInfo> i = providers.iterator();
3379 while (i.hasNext()) {
3380 ProviderInfo cpi = i.next();
3381 StringBuilder buf = new StringBuilder(128);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07003382 buf.append("Pub ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003383 buf.append(cpi.authority);
3384 buf.append(": ");
3385 buf.append(cpi.name);
3386 Log.i(TAG, buf.toString());
3387 IContentProvider cp = installProvider(context, null, cpi, false);
3388 if (cp != null) {
3389 IActivityManager.ContentProviderHolder cph =
3390 new IActivityManager.ContentProviderHolder(cpi);
3391 cph.provider = cp;
3392 results.add(cph);
3393 // Don't ever unload this provider from the process.
3394 synchronized(mProviderMap) {
3395 mProviderRefCountMap.put(cp.asBinder(), new ProviderRefCount(10000));
3396 }
3397 }
3398 }
3399
3400 try {
3401 ActivityManagerNative.getDefault().publishContentProviders(
3402 getApplicationThread(), results);
3403 } catch (RemoteException ex) {
3404 }
3405 }
3406
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003407 private final IContentProvider getExistingProvider(Context context, String name) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003408 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003409 final ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003410 if (pr != null) {
3411 return pr.mProvider;
3412 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003413 return null;
3414 }
3415 }
3416
3417 private final IContentProvider getProvider(Context context, String name) {
3418 IContentProvider existing = getExistingProvider(context, name);
3419 if (existing != null) {
3420 return existing;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003421 }
3422
3423 IActivityManager.ContentProviderHolder holder = null;
3424 try {
3425 holder = ActivityManagerNative.getDefault().getContentProvider(
3426 getApplicationThread(), name);
3427 } catch (RemoteException ex) {
3428 }
3429 if (holder == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003430 Slog.e(TAG, "Failed to find provider info for " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431 return null;
3432 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003433
3434 IContentProvider prov = installProvider(context, holder.provider,
3435 holder.info, true);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003436 //Slog.i(TAG, "noReleaseNeeded=" + holder.noReleaseNeeded);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437 if (holder.noReleaseNeeded || holder.provider == null) {
3438 // We are not going to release the provider if it is an external
3439 // provider that doesn't care about being released, or if it is
3440 // a local provider running in this process.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003441 //Slog.i(TAG, "*** NO RELEASE NEEDED");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003442 synchronized(mProviderMap) {
3443 mProviderRefCountMap.put(prov.asBinder(), new ProviderRefCount(10000));
3444 }
3445 }
3446 return prov;
3447 }
3448
3449 public final IContentProvider acquireProvider(Context c, String name) {
3450 IContentProvider provider = getProvider(c, name);
3451 if(provider == null)
3452 return null;
3453 IBinder jBinder = provider.asBinder();
3454 synchronized(mProviderMap) {
3455 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3456 if(prc == null) {
3457 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3458 } else {
3459 prc.count++;
3460 } //end else
3461 } //end synchronized
3462 return provider;
3463 }
3464
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003465 public final IContentProvider acquireExistingProvider(Context c, String name) {
3466 IContentProvider provider = getExistingProvider(c, name);
3467 if(provider == null)
3468 return null;
3469 IBinder jBinder = provider.asBinder();
3470 synchronized(mProviderMap) {
3471 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3472 if(prc == null) {
3473 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3474 } else {
3475 prc.count++;
3476 } //end else
3477 } //end synchronized
3478 return provider;
3479 }
3480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003481 public final boolean releaseProvider(IContentProvider provider) {
3482 if(provider == null) {
3483 return false;
3484 }
3485 IBinder jBinder = provider.asBinder();
3486 synchronized(mProviderMap) {
3487 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3488 if(prc == null) {
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003489 if(localLOGV) Slog.v(TAG, "releaseProvider::Weird shouldn't be here");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003490 return false;
3491 } else {
3492 prc.count--;
3493 if(prc.count == 0) {
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003494 // Schedule the actual remove asynchronously, since we
3495 // don't know the context this will be called in.
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003496 // TODO: it would be nice to post a delayed message, so
3497 // if we come back and need the same provider quickly
3498 // we will still have it available.
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003499 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
3500 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003501 } //end if
3502 } //end else
3503 } //end synchronized
3504 return true;
3505 }
3506
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003507 final void completeRemoveProvider(IContentProvider provider) {
3508 IBinder jBinder = provider.asBinder();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003509 String name = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003510 synchronized(mProviderMap) {
3511 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3512 if(prc != null && prc.count == 0) {
3513 mProviderRefCountMap.remove(jBinder);
3514 //invoke removeProvider to dereference provider
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003515 name = removeProviderLocked(provider);
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003516 }
3517 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003518
3519 if (name != null) {
3520 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003521 if(localLOGV) Slog.v(TAG, "removeProvider::Invoking " +
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003522 "ActivityManagerNative.removeContentProvider(" + name);
3523 ActivityManagerNative.getDefault().removeContentProvider(
3524 getApplicationThread(), name);
3525 } catch (RemoteException e) {
3526 //do nothing content provider object is dead any way
3527 } //end catch
3528 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003529 }
3530
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003531 public final String removeProviderLocked(IContentProvider provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003532 if (provider == null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003533 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003534 }
3535 IBinder providerBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003536
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003537 String name = null;
3538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003539 // remove the provider from mProviderMap
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003540 Iterator<ProviderClientRecord> iter = mProviderMap.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003541 while (iter.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003542 ProviderClientRecord pr = iter.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003543 IBinder myBinder = pr.mProvider.asBinder();
3544 if (myBinder == providerBinder) {
3545 //find if its published by this process itself
3546 if(pr.mLocalProvider != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003547 if(localLOGV) Slog.i(TAG, "removeProvider::found local provider returning");
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003548 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003550 if(localLOGV) Slog.v(TAG, "removeProvider::Not local provider Unlinking " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003551 "death recipient");
3552 //content provider is in another process
3553 myBinder.unlinkToDeath(pr, 0);
3554 iter.remove();
3555 //invoke remove only once for the very first name seen
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003556 if(name == null) {
3557 name = pr.mName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003558 }
3559 } //end if myBinder
3560 } //end while iter
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003561
3562 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003563 }
3564
3565 final void removeDeadProvider(String name, IContentProvider provider) {
3566 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003567 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003569 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003570 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003571 if (removed != null) {
3572 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3573 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003574 }
3575 }
3576 }
3577
3578 final void removeDeadProviderLocked(String name, IContentProvider provider) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003579 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003580 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003581 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003582 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003583 if (removed != null) {
3584 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3585 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003586 }
3587 }
3588
3589 private final IContentProvider installProvider(Context context,
3590 IContentProvider provider, ProviderInfo info, boolean noisy) {
3591 ContentProvider localProvider = null;
3592 if (provider == null) {
3593 if (noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003594 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003595 + info.name);
3596 }
3597 Context c = null;
3598 ApplicationInfo ai = info.applicationInfo;
3599 if (context.getPackageName().equals(ai.packageName)) {
3600 c = context;
3601 } else if (mInitialApplication != null &&
3602 mInitialApplication.getPackageName().equals(ai.packageName)) {
3603 c = mInitialApplication;
3604 } else {
3605 try {
3606 c = context.createPackageContext(ai.packageName,
3607 Context.CONTEXT_INCLUDE_CODE);
3608 } catch (PackageManager.NameNotFoundException e) {
3609 }
3610 }
3611 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003612 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003613 ai.packageName +
3614 " while loading content provider " +
3615 info.name);
3616 return null;
3617 }
3618 try {
3619 final java.lang.ClassLoader cl = c.getClassLoader();
3620 localProvider = (ContentProvider)cl.
3621 loadClass(info.name).newInstance();
3622 provider = localProvider.getIContentProvider();
3623 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003624 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003625 info.name + " from sourceDir " +
3626 info.applicationInfo.sourceDir);
3627 return null;
3628 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003629 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003630 TAG, "Instantiating local provider " + info.name);
3631 // XXX Need to create the correct context for this provider.
3632 localProvider.attachInfo(c, info);
3633 } catch (java.lang.Exception e) {
3634 if (!mInstrumentation.onException(null, e)) {
3635 throw new RuntimeException(
3636 "Unable to get provider " + info.name
3637 + ": " + e.toString(), e);
3638 }
3639 return null;
3640 }
3641 } else if (localLOGV) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003642 Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003643 + info.name);
3644 }
3645
3646 synchronized (mProviderMap) {
3647 // Cache the pointer for the remote provider.
3648 String names[] = PATTERN_SEMICOLON.split(info.authority);
3649 for (int i=0; i<names.length; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003650 ProviderClientRecord pr = new ProviderClientRecord(names[i], provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003651 localProvider);
3652 try {
3653 provider.asBinder().linkToDeath(pr, 0);
3654 mProviderMap.put(names[i], pr);
3655 } catch (RemoteException e) {
3656 return null;
3657 }
3658 }
3659 if (localProvider != null) {
3660 mLocalProviders.put(provider.asBinder(),
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003661 new ProviderClientRecord(null, provider, localProvider));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003662 }
3663 }
3664
3665 return provider;
3666 }
3667
3668 private final void attach(boolean system) {
3669 sThreadLocal.set(this);
3670 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003671 if (!system) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003672 ViewRoot.addFirstDrawHandler(new Runnable() {
3673 public void run() {
3674 ensureJitEnabled();
3675 }
3676 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003677 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
3678 RuntimeInit.setApplicationObject(mAppThread.asBinder());
3679 IActivityManager mgr = ActivityManagerNative.getDefault();
3680 try {
3681 mgr.attachApplication(mAppThread);
3682 } catch (RemoteException ex) {
3683 }
3684 } else {
3685 // Don't set application object here -- if the system crashes,
3686 // we can't display an alert, we just want to die die die.
3687 android.ddm.DdmHandleAppName.setAppName("system_process");
3688 try {
3689 mInstrumentation = new Instrumentation();
Dianne Hackborn21556372010-02-04 16:34:40 -08003690 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003691 context.init(getSystemContext().mPackageInfo, null, this);
3692 Application app = Instrumentation.newApplication(Application.class, context);
3693 mAllApplications.add(app);
3694 mInitialApplication = app;
3695 app.onCreate();
3696 } catch (Exception e) {
3697 throw new RuntimeException(
3698 "Unable to instantiate Application():" + e.toString(), e);
3699 }
3700 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003701
3702 ViewRoot.addConfigCallback(new ComponentCallbacks() {
3703 public void onConfigurationChanged(Configuration newConfig) {
3704 synchronized (mPackages) {
Dianne Hackbornae078162010-03-18 11:29:37 -07003705 // We need to apply this change to the resources
3706 // immediately, because upon returning the view
3707 // hierarchy will be informed about it.
3708 if (applyConfigurationToResourcesLocked(newConfig)) {
3709 // This actually changed the resources! Tell
3710 // everyone about it.
3711 if (mPendingConfiguration == null ||
3712 mPendingConfiguration.isOtherSeqNewer(newConfig)) {
3713 mPendingConfiguration = newConfig;
3714
3715 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
3716 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003717 }
3718 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003719 }
3720 public void onLowMemory() {
3721 }
3722 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003723 }
3724
3725 private final void detach()
3726 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003727 sThreadLocal.set(null);
3728 }
3729
3730 public static final ActivityThread systemMain() {
Romain Guy52339202010-09-03 16:04:46 -07003731 HardwareRenderer.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003732 ActivityThread thread = new ActivityThread();
3733 thread.attach(true);
3734 return thread;
3735 }
3736
3737 public final void installSystemProviders(List providers) {
3738 if (providers != null) {
3739 installContentProviders(mInitialApplication,
3740 (List<ProviderInfo>)providers);
3741 }
3742 }
3743
3744 public static final void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07003745 SamplingProfilerIntegration.start();
3746
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -08003747 // CloseGuard defaults to true and can be quite spammy. We
3748 // disable it here, but selectively enable it later (via
3749 // StrictMode) on debug builds, but using DropBox, not logs.
3750 CloseGuard.setEnabled(false);
3751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003752 Process.setArgV0("<pre-initialized>");
3753
3754 Looper.prepareMainLooper();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07003755 if (sMainThreadHandler == null) {
3756 sMainThreadHandler = new Handler();
3757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003758
3759 ActivityThread thread = new ActivityThread();
3760 thread.attach(false);
3761
Dianne Hackborn287952c2010-09-22 22:34:31 -07003762 if (false) {
3763 Looper.myLooper().setMessageLogging(new
3764 LogPrinter(Log.DEBUG, "ActivityThread"));
3765 }
3766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003767 Looper.loop();
3768
3769 if (Process.supportsProcesses()) {
3770 throw new RuntimeException("Main thread loop unexpectedly exited");
3771 }
3772
3773 thread.detach();
Bob Leeeec2f412009-09-10 11:01:24 +02003774 String name = (thread.mInitialApplication != null)
3775 ? thread.mInitialApplication.getPackageName()
3776 : "<unknown>";
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003777 Slog.i(TAG, "Main thread of " + name + " is now exiting");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003778 }
3779}