blob: 449992e52f58bb4e7af5f10eab0d5c6019a45f88 [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;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800227 int pendingConfigChanges;
228 boolean onlyLocalRequest;
229
230 View mPendingRemoveWindow;
231 WindowManager mPendingRemoveWindowManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700233 ActivityClientRecord() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 parent = null;
235 embeddedID = null;
236 paused = false;
237 stopped = false;
238 hideForNow = false;
239 nextIdle = null;
240 }
241
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800242 public boolean isPreHoneycomb() {
243 if (activity != null) {
244 return activity.getApplicationInfo().targetSdkVersion
245 < android.os.Build.VERSION_CODES.HONEYCOMB;
246 }
247 return false;
248 }
249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 public String toString() {
251 ComponentName componentName = intent.getComponent();
252 return "ActivityRecord{"
253 + Integer.toHexString(System.identityHashCode(this))
254 + " token=" + token + " " + (componentName == null
255 ? "no component name" : componentName.toShortString())
256 + "}";
257 }
258 }
259
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700260 private final class ProviderClientRecord implements IBinder.DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261 final String mName;
262 final IContentProvider mProvider;
263 final ContentProvider mLocalProvider;
264
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700265 ProviderClientRecord(String name, IContentProvider provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266 ContentProvider localProvider) {
267 mName = name;
268 mProvider = provider;
269 mLocalProvider = localProvider;
270 }
271
272 public void binderDied() {
273 removeDeadProvider(mName, mProvider);
274 }
275 }
276
277 private static final class NewIntentData {
278 List<Intent> intents;
279 IBinder token;
280 public String toString() {
281 return "NewIntentData{intents=" + intents + " token=" + token + "}";
282 }
283 }
284
Dianne Hackborne829fef2010-10-26 17:44:01 -0700285 private static final class ReceiverData extends BroadcastReceiver.PendingResult {
286 public ReceiverData(Intent intent, int resultCode, String resultData, Bundle resultExtras,
287 boolean ordered, boolean sticky, IBinder token) {
288 super(resultCode, resultData, resultExtras, TYPE_COMPONENT, ordered, sticky, token);
289 this.intent = intent;
290 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800292 Intent intent;
293 ActivityInfo info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294 public String toString() {
295 return "ReceiverData{intent=" + intent + " packageName=" +
Dianne Hackborne829fef2010-10-26 17:44:01 -0700296 info.packageName + " resultCode=" + getResultCode()
297 + " resultData=" + getResultData() + " resultExtras="
298 + getResultExtras(false) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299 }
300 }
301
Christopher Tate181fafa2009-05-14 11:12:14 -0700302 private static final class CreateBackupAgentData {
303 ApplicationInfo appInfo;
304 int backupMode;
305 public String toString() {
306 return "CreateBackupAgentData{appInfo=" + appInfo
307 + " backupAgent=" + appInfo.backupAgentName
308 + " mode=" + backupMode + "}";
309 }
310 }
Bob Leee5408332009-09-04 18:31:17 -0700311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312 private static final class CreateServiceData {
313 IBinder token;
314 ServiceInfo info;
315 Intent intent;
316 public String toString() {
317 return "CreateServiceData{token=" + token + " className="
318 + info.name + " packageName=" + info.packageName
319 + " intent=" + intent + "}";
320 }
321 }
322
323 private static final class BindServiceData {
324 IBinder token;
325 Intent intent;
326 boolean rebind;
327 public String toString() {
328 return "BindServiceData{token=" + token + " intent=" + intent + "}";
329 }
330 }
331
332 private static final class ServiceArgsData {
333 IBinder token;
334 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700335 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336 Intent args;
337 public String toString() {
338 return "ServiceArgsData{token=" + token + " startId=" + startId
339 + " args=" + args + "}";
340 }
341 }
342
343 private static final class AppBindData {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700344 LoadedApk info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 String processName;
346 ApplicationInfo appInfo;
347 List<ProviderInfo> providers;
348 ComponentName instrumentationName;
349 String profileFile;
350 Bundle instrumentationArgs;
351 IInstrumentationWatcher instrumentationWatcher;
352 int debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700353 boolean restrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800354 Configuration config;
355 boolean handlingProfiling;
356 public String toString() {
357 return "AppBindData{appInfo=" + appInfo + "}";
358 }
359 }
360
Dianne Hackborn625ac272010-09-17 18:29:22 -0700361 private static final class DumpComponentInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362 FileDescriptor fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700363 IBinder token;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364 String[] args;
365 boolean dumped;
366 }
367
368 private static final class ResultData {
369 IBinder token;
370 List<ResultInfo> results;
371 public String toString() {
372 return "ResultData{token=" + token + " results" + results + "}";
373 }
374 }
375
376 private static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800377 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800378 String what;
379 String who;
380 }
381
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700382 private static final class ProfilerControlData {
383 String path;
384 ParcelFileDescriptor fd;
385 }
386
Andy McFadden824c5102010-07-09 16:26:57 -0700387 private static final class DumpHeapData {
388 String path;
389 ParcelFileDescriptor fd;
390 }
391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392 private final class ApplicationThread extends ApplicationThreadNative {
393 private static final String HEAP_COLUMN = "%17s %8s %8s %8s %8s";
394 private static final String ONE_COUNT_COLUMN = "%17s %8d";
395 private static final String TWO_COUNT_COLUMNS = "%17s %8d %17s %8d";
Vasu Nori3c7131f2010-09-21 14:36:57 -0700396 private static final String TWO_COUNT_COLUMNS_DB = "%20s %8d %20s %8d";
397 private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
Bob Leee5408332009-09-04 18:31:17 -0700398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399 // Formatting for checkin service - update version if row format changes
400 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;
Bob Leee5408332009-09-04 18:31:17 -0700401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800402 public final void schedulePauseActivity(IBinder token, boolean finished,
403 boolean userLeaving, int configChanges) {
404 queueOrSendMessage(
405 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
406 token,
407 (userLeaving ? 1 : 0),
408 configChanges);
409 }
410
411 public final void scheduleStopActivity(IBinder token, boolean showWindow,
412 int configChanges) {
413 queueOrSendMessage(
414 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
415 token, 0, configChanges);
416 }
417
418 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
419 queueOrSendMessage(
420 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
421 token);
422 }
423
424 public final void scheduleResumeActivity(IBinder token, boolean isForward) {
425 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
426 }
427
428 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
429 ResultData res = new ResultData();
430 res.token = token;
431 res.results = results;
432 queueOrSendMessage(H.SEND_RESULT, res);
433 }
434
435 // we use token to identify this activity without having to send the
436 // activity itself back to the activity manager. (matters more with ipc)
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700437 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800438 ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
439 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700440 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800441
442 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700443 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800444 r.intent = intent;
445 r.activityInfo = info;
446 r.state = state;
447
448 r.pendingResults = pendingResults;
449 r.pendingIntents = pendingNewIntents;
450
451 r.startsNotResumed = notResumed;
452 r.isForward = isForward;
453
454 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
455 }
456
457 public final void scheduleRelaunchActivity(IBinder token,
458 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800459 int configChanges, boolean notResumed, Configuration config) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800460 requestRelaunchActivity(token, pendingResults, pendingNewIntents,
461 configChanges, notResumed, config, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 }
463
464 public final void scheduleNewIntent(List<Intent> intents, IBinder token) {
465 NewIntentData data = new NewIntentData();
466 data.intents = intents;
467 data.token = token;
468
469 queueOrSendMessage(H.NEW_INTENT, data);
470 }
471
472 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
473 int configChanges) {
474 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
475 configChanges);
476 }
477
478 public final void scheduleReceiver(Intent intent, ActivityInfo info,
479 int resultCode, String data, Bundle extras, boolean sync) {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700480 ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
481 sync, false, mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482 r.info = info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483 queueOrSendMessage(H.RECEIVER, r);
484 }
485
Christopher Tate181fafa2009-05-14 11:12:14 -0700486 public final void scheduleCreateBackupAgent(ApplicationInfo app, int backupMode) {
487 CreateBackupAgentData d = new CreateBackupAgentData();
488 d.appInfo = app;
489 d.backupMode = backupMode;
490
491 queueOrSendMessage(H.CREATE_BACKUP_AGENT, d);
492 }
493
494 public final void scheduleDestroyBackupAgent(ApplicationInfo app) {
495 CreateBackupAgentData d = new CreateBackupAgentData();
496 d.appInfo = app;
497
498 queueOrSendMessage(H.DESTROY_BACKUP_AGENT, d);
499 }
500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501 public final void scheduleCreateService(IBinder token,
502 ServiceInfo info) {
503 CreateServiceData s = new CreateServiceData();
504 s.token = token;
505 s.info = info;
506
507 queueOrSendMessage(H.CREATE_SERVICE, s);
508 }
509
510 public final void scheduleBindService(IBinder token, Intent intent,
511 boolean rebind) {
512 BindServiceData s = new BindServiceData();
513 s.token = token;
514 s.intent = intent;
515 s.rebind = rebind;
516
517 queueOrSendMessage(H.BIND_SERVICE, s);
518 }
519
520 public final void scheduleUnbindService(IBinder token, Intent intent) {
521 BindServiceData s = new BindServiceData();
522 s.token = token;
523 s.intent = intent;
524
525 queueOrSendMessage(H.UNBIND_SERVICE, s);
526 }
527
528 public final void scheduleServiceArgs(IBinder token, int startId,
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700529 int flags ,Intent args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 ServiceArgsData s = new ServiceArgsData();
531 s.token = token;
532 s.startId = startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700533 s.flags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534 s.args = args;
535
536 queueOrSendMessage(H.SERVICE_ARGS, s);
537 }
538
539 public final void scheduleStopService(IBinder token) {
540 queueOrSendMessage(H.STOP_SERVICE, token);
541 }
542
543 public final void bindApplication(String processName,
544 ApplicationInfo appInfo, List<ProviderInfo> providers,
545 ComponentName instrumentationName, String profileFile,
546 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
Christopher Tate181fafa2009-05-14 11:12:14 -0700547 int debugMode, boolean isRestrictedBackupMode, Configuration config,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800548 Map<String, IBinder> services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549
550 if (services != null) {
551 // Setup the service cache in the ServiceManager
552 ServiceManager.initServiceCache(services);
553 }
554
555 AppBindData data = new AppBindData();
556 data.processName = processName;
557 data.appInfo = appInfo;
558 data.providers = providers;
559 data.instrumentationName = instrumentationName;
560 data.profileFile = profileFile;
561 data.instrumentationArgs = instrumentationArgs;
562 data.instrumentationWatcher = instrumentationWatcher;
563 data.debugMode = debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700564 data.restrictedBackupMode = isRestrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565 data.config = config;
566 queueOrSendMessage(H.BIND_APPLICATION, data);
567 }
568
569 public final void scheduleExit() {
570 queueOrSendMessage(H.EXIT_APPLICATION, null);
571 }
572
Christopher Tate5e1ab332009-09-01 20:32:49 -0700573 public final void scheduleSuicide() {
574 queueOrSendMessage(H.SUICIDE, null);
575 }
576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577 public void requestThumbnail(IBinder token) {
578 queueOrSendMessage(H.REQUEST_THUMBNAIL, token);
579 }
580
581 public void scheduleConfigurationChanged(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800582 synchronized (mPackages) {
583 if (mPendingConfiguration == null ||
584 mPendingConfiguration.isOtherSeqNewer(config)) {
585 mPendingConfiguration = config;
586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587 }
588 queueOrSendMessage(H.CONFIGURATION_CHANGED, config);
589 }
590
591 public void updateTimeZone() {
592 TimeZone.setDefault(null);
593 }
594
Robert Greenwalt03595d02010-11-02 14:08:23 -0700595 public void clearDnsCache() {
596 // a non-standard API to get this to libcore
597 InetAddress.clearDnsCache();
598 }
599
Robert Greenwalt434203a2010-10-11 16:00:27 -0700600 public void setHttpProxy(String host, String port, String exclList) {
601 Proxy.setHttpProxySystemProperty(host, port, exclList);
602 }
603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 public void processInBackground() {
605 mH.removeMessages(H.GC_WHEN_IDLE);
606 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
607 }
608
609 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700610 DumpComponentInfo data = new DumpComponentInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 data.fd = fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700612 data.token = servicetoken;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 data.args = args;
614 data.dumped = false;
615 queueOrSendMessage(H.DUMP_SERVICE, data);
616 synchronized (data) {
617 while (!data.dumped) {
618 try {
619 data.wait();
620 } catch (InterruptedException e) {
621 // no need to do anything here, we will keep waiting until
622 // dumped is set
623 }
624 }
625 }
626 }
627
628 // This function exists to make sure all receiver dispatching is
629 // correctly ordered, since these are one-way calls and the binder driver
630 // applies transaction ordering per object for such calls.
631 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700632 int resultCode, String dataStr, Bundle extras, boolean ordered,
633 boolean sticky) throws RemoteException {
634 receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 }
Bob Leee5408332009-09-04 18:31:17 -0700636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800637 public void scheduleLowMemory() {
638 queueOrSendMessage(H.LOW_MEMORY, null);
639 }
640
641 public void scheduleActivityConfigurationChanged(IBinder token) {
642 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token);
643 }
644
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700645 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd) {
646 ProfilerControlData pcd = new ProfilerControlData();
647 pcd.path = path;
648 pcd.fd = fd;
649 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800650 }
651
Andy McFadden824c5102010-07-09 16:26:57 -0700652 public void dumpHeap(boolean managed, String path, ParcelFileDescriptor fd) {
653 DumpHeapData dhd = new DumpHeapData();
654 dhd.path = path;
655 dhd.fd = fd;
656 queueOrSendMessage(H.DUMP_HEAP, dhd, managed ? 1 : 0);
657 }
658
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700659 public void setSchedulingGroup(int group) {
660 // Note: do this immediately, since going into the foreground
661 // should happen regardless of what pending work we have to do
662 // and the activity manager will wait for us to report back that
663 // we are done before sending us to the background.
664 try {
665 Process.setProcessGroup(Process.myPid(), group);
666 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800667 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700668 }
669 }
Bob Leee5408332009-09-04 18:31:17 -0700670
Dianne Hackborn3025ef32009-08-31 21:31:47 -0700671 public void getMemoryInfo(Debug.MemoryInfo outInfo) {
672 Debug.getMemoryInfo(outInfo);
673 }
Bob Leee5408332009-09-04 18:31:17 -0700674
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700675 public void dispatchPackageBroadcast(int cmd, String[] packages) {
676 queueOrSendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
677 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700678
679 public void scheduleCrash(String msg) {
680 queueOrSendMessage(H.SCHEDULE_CRASH, msg);
681 }
Dianne Hackborn625ac272010-09-17 18:29:22 -0700682
683 public void dumpActivity(FileDescriptor fd, IBinder activitytoken, String[] args) {
684 DumpComponentInfo data = new DumpComponentInfo();
685 data.fd = fd;
686 data.token = activitytoken;
687 data.args = args;
688 data.dumped = false;
689 queueOrSendMessage(H.DUMP_ACTIVITY, data);
690 synchronized (data) {
691 while (!data.dumped) {
692 try {
693 data.wait();
694 } catch (InterruptedException e) {
695 // no need to do anything here, we will keep waiting until
696 // dumped is set
697 }
698 }
699 }
700 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 @Override
703 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
704 long nativeMax = Debug.getNativeHeapSize() / 1024;
705 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
706 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
707
708 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
709 Debug.getMemoryInfo(memInfo);
710
711 final int nativeShared = memInfo.nativeSharedDirty;
712 final int dalvikShared = memInfo.dalvikSharedDirty;
713 final int otherShared = memInfo.otherSharedDirty;
714
715 final int nativePrivate = memInfo.nativePrivateDirty;
716 final int dalvikPrivate = memInfo.dalvikPrivateDirty;
717 final int otherPrivate = memInfo.otherPrivateDirty;
718
719 Runtime runtime = Runtime.getRuntime();
720
721 long dalvikMax = runtime.totalMemory() / 1024;
722 long dalvikFree = runtime.freeMemory() / 1024;
723 long dalvikAllocated = dalvikMax - dalvikFree;
724 long viewInstanceCount = ViewDebug.getViewInstanceCount();
725 long viewRootInstanceCount = ViewDebug.getViewRootInstanceCount();
Brian Carlstromc21550a2010-10-05 21:34:06 -0700726 long appContextInstanceCount = Debug.countInstancesOfClass(ContextImpl.class);
727 long activityInstanceCount = Debug.countInstancesOfClass(Activity.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 int globalAssetCount = AssetManager.getGlobalAssetCount();
729 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
730 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
731 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
732 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
Brian Carlstromc9d5b312010-10-05 22:23:41 -0700733 long openSslSocketCount = Debug.countInstancesOfClass(OpenSSLSocketImpl.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024;
Vasu Noric3849202010-03-09 10:47:25 -0800735 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -0700736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 // Check to see if we were called by checkin server. If so, print terse format.
738 boolean doCheckinFormat = false;
739 if (args != null) {
740 for (String arg : args) {
741 if ("-c".equals(arg)) doCheckinFormat = true;
742 }
743 }
Bob Leee5408332009-09-04 18:31:17 -0700744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 // For checkin, we print one long comma-separated list of values
746 if (doCheckinFormat) {
747 // NOTE: if you change anything significant below, also consider changing
748 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -0700749 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -0700751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 // Header
753 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
754 pw.print(Process.myPid()); pw.print(',');
755 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757 // Heap info - max
758 pw.print(nativeMax); pw.print(',');
759 pw.print(dalvikMax); pw.print(',');
760 pw.print("N/A,");
761 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763 // Heap info - allocated
764 pw.print(nativeAllocated); pw.print(',');
765 pw.print(dalvikAllocated); pw.print(',');
766 pw.print("N/A,");
767 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 // Heap info - free
770 pw.print(nativeFree); pw.print(',');
771 pw.print(dalvikFree); pw.print(',');
772 pw.print("N/A,");
773 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 // Heap info - proportional set size
776 pw.print(memInfo.nativePss); pw.print(',');
777 pw.print(memInfo.dalvikPss); pw.print(',');
778 pw.print(memInfo.otherPss); pw.print(',');
779 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 // Heap info - shared
Bob Leee5408332009-09-04 18:31:17 -0700782 pw.print(nativeShared); pw.print(',');
783 pw.print(dalvikShared); pw.print(',');
784 pw.print(otherShared); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 pw.print(nativeShared + dalvikShared + otherShared); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 // Heap info - private
Bob Leee5408332009-09-04 18:31:17 -0700788 pw.print(nativePrivate); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 pw.print(dalvikPrivate); pw.print(',');
790 pw.print(otherPrivate); pw.print(',');
791 pw.print(nativePrivate + dalvikPrivate + otherPrivate); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 // Object counts
794 pw.print(viewInstanceCount); pw.print(',');
795 pw.print(viewRootInstanceCount); pw.print(',');
796 pw.print(appContextInstanceCount); pw.print(',');
797 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 pw.print(globalAssetCount); pw.print(',');
800 pw.print(globalAssetManagerCount); pw.print(',');
801 pw.print(binderLocalObjectCount); pw.print(',');
802 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 pw.print(binderDeathObjectCount); pw.print(',');
805 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 // SQL
808 pw.print(sqliteAllocated); pw.print(',');
Vasu Noric3849202010-03-09 10:47:25 -0800809 pw.print(stats.memoryUsed / 1024); pw.print(',');
810 pw.print(stats.pageCacheOverflo / 1024); pw.print(',');
811 pw.print(stats.largestMemAlloc / 1024); pw.print(',');
812 for (int i = 0; i < stats.dbStats.size(); i++) {
813 DbStats dbStats = stats.dbStats.get(i);
814 printRow(pw, DB_INFO_FORMAT, dbStats.pageSize, dbStats.dbSize,
Vasu Nori90a367262010-04-12 12:49:09 -0700815 dbStats.lookaside, dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -0800816 pw.print(',');
817 }
Bob Leee5408332009-09-04 18:31:17 -0700818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 return;
820 }
Bob Leee5408332009-09-04 18:31:17 -0700821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800822 // otherwise, show human-readable format
823 printRow(pw, HEAP_COLUMN, "", "native", "dalvik", "other", "total");
824 printRow(pw, HEAP_COLUMN, "size:", nativeMax, dalvikMax, "N/A", nativeMax + dalvikMax);
825 printRow(pw, HEAP_COLUMN, "allocated:", nativeAllocated, dalvikAllocated, "N/A",
826 nativeAllocated + dalvikAllocated);
827 printRow(pw, HEAP_COLUMN, "free:", nativeFree, dalvikFree, "N/A",
828 nativeFree + dalvikFree);
829
830 printRow(pw, HEAP_COLUMN, "(Pss):", memInfo.nativePss, memInfo.dalvikPss,
831 memInfo.otherPss, memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss);
832
833 printRow(pw, HEAP_COLUMN, "(shared dirty):", nativeShared, dalvikShared, otherShared,
834 nativeShared + dalvikShared + otherShared);
835 printRow(pw, HEAP_COLUMN, "(priv dirty):", nativePrivate, dalvikPrivate, otherPrivate,
836 nativePrivate + dalvikPrivate + otherPrivate);
837
838 pw.println(" ");
839 pw.println(" Objects");
840 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRoots:",
841 viewRootInstanceCount);
842
843 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
844 "Activities:", activityInstanceCount);
845
846 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
847 "AssetManagers:", globalAssetManagerCount);
848
849 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
850 "Proxy Binders:", binderProxyObjectCount);
851 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
852
853 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -0700854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 // SQLite mem info
856 pw.println(" ");
857 pw.println(" SQL");
Vasu Nori3c7131f2010-09-21 14:36:57 -0700858 printRow(pw, TWO_COUNT_COLUMNS_DB, "heap:", sqliteAllocated, "MEMORY_USED:",
Vasu Noric3849202010-03-09 10:47:25 -0800859 stats.memoryUsed / 1024);
Vasu Nori3c7131f2010-09-21 14:36:57 -0700860 printRow(pw, TWO_COUNT_COLUMNS_DB, "PAGECACHE_OVERFLOW:",
861 stats.pageCacheOverflo / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -0800862 pw.println(" ");
863 int N = stats.dbStats.size();
864 if (N > 0) {
865 pw.println(" DATABASES");
Vasu Nori3c7131f2010-09-21 14:36:57 -0700866 printRow(pw, " %8s %8s %14s %14s %s", "pgsz", "dbsz", "Lookaside(b)", "cache",
867 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -0800868 for (int i = 0; i < N; i++) {
869 DbStats dbStats = stats.dbStats.get(i);
Vasu Nori3c7131f2010-09-21 14:36:57 -0700870 printRow(pw, DB_INFO_FORMAT,
871 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
872 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
873 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
874 dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -0800875 }
876 }
Bob Leee5408332009-09-04 18:31:17 -0700877
Dianne Hackborn82e1ee92009-08-11 18:56:41 -0700878 // Asset details.
879 String assetAlloc = AssetManager.getAssetAllocations();
880 if (assetAlloc != null) {
881 pw.println(" ");
882 pw.println(" Asset Allocations");
883 pw.print(assetAlloc);
884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 }
886
887 private void printRow(PrintWriter pw, String format, Object...objs) {
888 pw.println(String.format(format, objs));
889 }
890 }
891
892 private final class H extends Handler {
893 public static final int LAUNCH_ACTIVITY = 100;
894 public static final int PAUSE_ACTIVITY = 101;
895 public static final int PAUSE_ACTIVITY_FINISHING= 102;
896 public static final int STOP_ACTIVITY_SHOW = 103;
897 public static final int STOP_ACTIVITY_HIDE = 104;
898 public static final int SHOW_WINDOW = 105;
899 public static final int HIDE_WINDOW = 106;
900 public static final int RESUME_ACTIVITY = 107;
901 public static final int SEND_RESULT = 108;
902 public static final int DESTROY_ACTIVITY = 109;
903 public static final int BIND_APPLICATION = 110;
904 public static final int EXIT_APPLICATION = 111;
905 public static final int NEW_INTENT = 112;
906 public static final int RECEIVER = 113;
907 public static final int CREATE_SERVICE = 114;
908 public static final int SERVICE_ARGS = 115;
909 public static final int STOP_SERVICE = 116;
910 public static final int REQUEST_THUMBNAIL = 117;
911 public static final int CONFIGURATION_CHANGED = 118;
912 public static final int CLEAN_UP_CONTEXT = 119;
913 public static final int GC_WHEN_IDLE = 120;
914 public static final int BIND_SERVICE = 121;
915 public static final int UNBIND_SERVICE = 122;
916 public static final int DUMP_SERVICE = 123;
917 public static final int LOW_MEMORY = 124;
918 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
919 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800920 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -0700921 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -0700922 public static final int DESTROY_BACKUP_AGENT = 129;
923 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700924 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800925 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700926 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700927 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -0700928 public static final int DUMP_HEAP = 135;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700929 public static final int DUMP_ACTIVITY = 136;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 String codeToString(int code) {
Dianne Hackborn287952c2010-09-22 22:34:31 -0700931 if (DEBUG_MESSAGES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 switch (code) {
933 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
934 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
935 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
936 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
937 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
938 case SHOW_WINDOW: return "SHOW_WINDOW";
939 case HIDE_WINDOW: return "HIDE_WINDOW";
940 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
941 case SEND_RESULT: return "SEND_RESULT";
942 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
943 case BIND_APPLICATION: return "BIND_APPLICATION";
944 case EXIT_APPLICATION: return "EXIT_APPLICATION";
945 case NEW_INTENT: return "NEW_INTENT";
946 case RECEIVER: return "RECEIVER";
947 case CREATE_SERVICE: return "CREATE_SERVICE";
948 case SERVICE_ARGS: return "SERVICE_ARGS";
949 case STOP_SERVICE: return "STOP_SERVICE";
950 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
951 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
952 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
953 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
954 case BIND_SERVICE: return "BIND_SERVICE";
955 case UNBIND_SERVICE: return "UNBIND_SERVICE";
956 case DUMP_SERVICE: return "DUMP_SERVICE";
957 case LOW_MEMORY: return "LOW_MEMORY";
958 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
959 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800960 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -0700961 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
962 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -0700963 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700964 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800965 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700966 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700967 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -0700968 case DUMP_HEAP: return "DUMP_HEAP";
Dianne Hackborn625ac272010-09-17 18:29:22 -0700969 case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 }
971 }
972 return "(unknown)";
973 }
974 public void handleMessage(Message msg) {
Dianne Hackborn287952c2010-09-22 22:34:31 -0700975 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 switch (msg.what) {
977 case LAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700978 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979
980 r.packageInfo = getPackageInfoNoCheck(
981 r.activityInfo.applicationInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -0700982 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 } break;
984 case RELAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700985 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800986 handleRelaunchActivity(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 } break;
988 case PAUSE_ACTIVITY:
989 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -0700990 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 break;
992 case PAUSE_ACTIVITY_FINISHING:
993 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
994 break;
995 case STOP_ACTIVITY_SHOW:
996 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
997 break;
998 case STOP_ACTIVITY_HIDE:
999 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
1000 break;
1001 case SHOW_WINDOW:
1002 handleWindowVisibility((IBinder)msg.obj, true);
1003 break;
1004 case HIDE_WINDOW:
1005 handleWindowVisibility((IBinder)msg.obj, false);
1006 break;
1007 case RESUME_ACTIVITY:
1008 handleResumeActivity((IBinder)msg.obj, true,
1009 msg.arg1 != 0);
1010 break;
1011 case SEND_RESULT:
1012 handleSendResult((ResultData)msg.obj);
1013 break;
1014 case DESTROY_ACTIVITY:
1015 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
1016 msg.arg2, false);
1017 break;
1018 case BIND_APPLICATION:
1019 AppBindData data = (AppBindData)msg.obj;
1020 handleBindApplication(data);
1021 break;
1022 case EXIT_APPLICATION:
1023 if (mInitialApplication != null) {
1024 mInitialApplication.onTerminate();
1025 }
1026 Looper.myLooper().quit();
1027 break;
1028 case NEW_INTENT:
1029 handleNewIntent((NewIntentData)msg.obj);
1030 break;
1031 case RECEIVER:
1032 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001033 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 break;
1035 case CREATE_SERVICE:
1036 handleCreateService((CreateServiceData)msg.obj);
1037 break;
1038 case BIND_SERVICE:
1039 handleBindService((BindServiceData)msg.obj);
1040 break;
1041 case UNBIND_SERVICE:
1042 handleUnbindService((BindServiceData)msg.obj);
1043 break;
1044 case SERVICE_ARGS:
1045 handleServiceArgs((ServiceArgsData)msg.obj);
1046 break;
1047 case STOP_SERVICE:
1048 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001049 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 break;
1051 case REQUEST_THUMBNAIL:
1052 handleRequestThumbnail((IBinder)msg.obj);
1053 break;
1054 case CONFIGURATION_CHANGED:
1055 handleConfigurationChanged((Configuration)msg.obj);
1056 break;
1057 case CLEAN_UP_CONTEXT:
1058 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1059 cci.context.performFinalCleanup(cci.who, cci.what);
1060 break;
1061 case GC_WHEN_IDLE:
1062 scheduleGcIdler();
1063 break;
1064 case DUMP_SERVICE:
Dianne Hackborn625ac272010-09-17 18:29:22 -07001065 handleDumpService((DumpComponentInfo)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 break;
1067 case LOW_MEMORY:
1068 handleLowMemory();
1069 break;
1070 case ACTIVITY_CONFIGURATION_CHANGED:
1071 handleActivityConfigurationChanged((IBinder)msg.obj);
1072 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001073 case PROFILER_CONTROL:
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001074 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001075 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001076 case CREATE_BACKUP_AGENT:
1077 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1078 break;
1079 case DESTROY_BACKUP_AGENT:
1080 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1081 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001082 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001083 Process.killProcess(Process.myPid());
1084 break;
1085 case REMOVE_PROVIDER:
1086 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001087 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001088 case ENABLE_JIT:
1089 ensureJitEnabled();
1090 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001091 case DISPATCH_PACKAGE_BROADCAST:
1092 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
1093 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001094 case SCHEDULE_CRASH:
1095 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001096 case DUMP_HEAP:
1097 handleDumpHeap(msg.arg1 != 0, (DumpHeapData)msg.obj);
1098 break;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001099 case DUMP_ACTIVITY:
1100 handleDumpActivity((DumpComponentInfo)msg.obj);
1101 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07001103 if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 }
Bob Leee5408332009-09-04 18:31:17 -07001105
1106 void maybeSnapshot() {
1107 if (mBoundApplication != null) {
Sen Hubde75702010-05-28 01:54:03 -07001108 // convert the *private* ActivityThread.PackageInfo to *public* known
1109 // android.content.pm.PackageInfo
1110 String packageName = mBoundApplication.info.mPackageName;
1111 android.content.pm.PackageInfo packageInfo = null;
1112 try {
1113 Context context = getSystemContext();
1114 if(context == null) {
1115 Log.e(TAG, "cannot get a valid context");
1116 return;
1117 }
1118 PackageManager pm = context.getPackageManager();
1119 if(pm == null) {
1120 Log.e(TAG, "cannot get a valid PackageManager");
1121 return;
1122 }
1123 packageInfo = pm.getPackageInfo(
1124 packageName, PackageManager.GET_ACTIVITIES);
1125 } catch (NameNotFoundException e) {
1126 Log.e(TAG, "cannot get package info for " + packageName, e);
1127 }
1128 SamplingProfilerIntegration.writeSnapshot(mBoundApplication.processName, packageInfo);
Bob Leee5408332009-09-04 18:31:17 -07001129 }
1130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 }
1132
1133 private final class Idler implements MessageQueue.IdleHandler {
1134 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001135 ActivityClientRecord a = mNewActivities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 if (a != null) {
1137 mNewActivities = null;
1138 IActivityManager am = ActivityManagerNative.getDefault();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001139 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001141 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 TAG, "Reporting idle of " + a +
1143 " finished=" +
1144 (a.activity != null ? a.activity.mFinished : false));
1145 if (a.activity != null && !a.activity.mFinished) {
1146 try {
Dianne Hackborne88846e2009-09-30 21:34:25 -07001147 am.activityIdle(a.token, a.createdConfig);
1148 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 } catch (RemoteException ex) {
1150 }
1151 }
1152 prev = a;
1153 a = a.nextIdle;
1154 prev.nextIdle = null;
1155 } while (a != null);
1156 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001157 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 return false;
1159 }
1160 }
1161
1162 final class GcIdler implements MessageQueue.IdleHandler {
1163 public final boolean queueIdle() {
1164 doGcIfNeeded();
1165 return false;
1166 }
1167 }
1168
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001169 private final static class ResourcesKey {
1170 final private String mResDir;
1171 final private float mScale;
1172 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07001173
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001174 ResourcesKey(String resDir, float scale) {
1175 mResDir = resDir;
1176 mScale = scale;
1177 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
1178 }
Bob Leee5408332009-09-04 18:31:17 -07001179
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001180 @Override
1181 public int hashCode() {
1182 return mHash;
1183 }
1184
1185 @Override
1186 public boolean equals(Object obj) {
1187 if (!(obj instanceof ResourcesKey)) {
1188 return false;
1189 }
1190 ResourcesKey peer = (ResourcesKey) obj;
1191 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
1192 }
1193 }
1194
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001195 public static final ActivityThread currentActivityThread() {
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07001196 return sThreadLocal.get();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001199 public static final String currentPackageName() {
1200 ActivityThread am = currentActivityThread();
1201 return (am != null && am.mBoundApplication != null)
1202 ? am.mBoundApplication.processName : null;
1203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001205 public static final Application currentApplication() {
1206 ActivityThread am = currentActivityThread();
1207 return am != null ? am.mInitialApplication : null;
1208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001210 public static IPackageManager getPackageManager() {
1211 if (sPackageManager != null) {
1212 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1213 return sPackageManager;
1214 }
1215 IBinder b = ServiceManager.getService("package");
1216 //Slog.v("PackageManager", "default service binder = " + b);
1217 sPackageManager = IPackageManager.Stub.asInterface(b);
1218 //Slog.v("PackageManager", "default service = " + sPackageManager);
1219 return sPackageManager;
1220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001222 DisplayMetrics getDisplayMetricsLocked(boolean forceUpdate) {
1223 if (mDisplayMetrics != null && !forceUpdate) {
1224 return mDisplayMetrics;
1225 }
1226 if (mDisplay == null) {
1227 WindowManager wm = WindowManagerImpl.getDefault();
1228 mDisplay = wm.getDefaultDisplay();
1229 }
1230 DisplayMetrics metrics = mDisplayMetrics = new DisplayMetrics();
1231 mDisplay.getMetrics(metrics);
1232 //Slog.i("foo", "New metrics: w=" + metrics.widthPixels + " h="
1233 // + metrics.heightPixels + " den=" + metrics.density
1234 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi);
1235 return metrics;
1236 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001238 /**
1239 * Creates the top level Resources for applications with the given compatibility info.
1240 *
1241 * @param resDir the resource directory.
1242 * @param compInfo the compability info. It will use the default compatibility info when it's
1243 * null.
1244 */
1245 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
1246 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
1247 Resources r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001249 // Resources is app scale dependent.
1250 if (false) {
1251 Slog.w(TAG, "getTopLevelResources: " + resDir + " / "
1252 + compInfo.applicationScale);
1253 }
1254 WeakReference<Resources> wr = mActiveResources.get(key);
1255 r = wr != null ? wr.get() : null;
1256 //if (r != null) Slog.i(TAG, "isUpToDate " + resDir + ": " + r.getAssets().isUpToDate());
1257 if (r != null && r.getAssets().isUpToDate()) {
1258 if (false) {
1259 Slog.w(TAG, "Returning cached resources " + r + " " + resDir
1260 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
1261 }
1262 return r;
1263 }
1264 }
1265
1266 //if (r != null) {
1267 // Slog.w(TAG, "Throwing away out-of-date resources!!!! "
1268 // + r + " " + resDir);
1269 //}
1270
1271 AssetManager assets = new AssetManager();
1272 if (assets.addAssetPath(resDir) == 0) {
1273 return null;
1274 }
1275
1276 //Slog.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
1277 DisplayMetrics metrics = getDisplayMetricsLocked(false);
1278 r = new Resources(assets, metrics, getConfiguration(), compInfo);
1279 if (false) {
1280 Slog.i(TAG, "Created app resources " + resDir + " " + r + ": "
1281 + r.getConfiguration() + " appScale="
1282 + r.getCompatibilityInfo().applicationScale);
1283 }
1284
1285 synchronized (mPackages) {
1286 WeakReference<Resources> wr = mActiveResources.get(key);
1287 Resources existing = wr != null ? wr.get() : null;
1288 if (existing != null && existing.getAssets().isUpToDate()) {
1289 // Someone else already created the resources while we were
1290 // unlocked; go ahead and use theirs.
1291 r.getAssets().close();
1292 return existing;
1293 }
1294
1295 // XXX need to remove entries when weak references go away
1296 mActiveResources.put(key, new WeakReference<Resources>(r));
1297 return r;
1298 }
1299 }
1300
1301 /**
1302 * Creates the top level resources for the given package.
1303 */
1304 Resources getTopLevelResources(String resDir, LoadedApk pkgInfo) {
1305 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo);
1306 }
1307
1308 final Handler getHandler() {
1309 return mH;
1310 }
1311
1312 public final LoadedApk getPackageInfo(String packageName, int flags) {
1313 synchronized (mPackages) {
1314 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
1316 ref = mPackages.get(packageName);
1317 } else {
1318 ref = mResourcePackages.get(packageName);
1319 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001320 LoadedApk packageInfo = ref != null ? ref.get() : null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001321 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001322 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
1323 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 if (packageInfo != null && (packageInfo.mResources == null
1325 || packageInfo.mResources.getAssets().isUpToDate())) {
1326 if (packageInfo.isSecurityViolation()
1327 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
1328 throw new SecurityException(
1329 "Requesting code from " + packageName
1330 + " to be run in process "
1331 + mBoundApplication.processName
1332 + "/" + mBoundApplication.appInfo.uid);
1333 }
1334 return packageInfo;
1335 }
1336 }
1337
1338 ApplicationInfo ai = null;
1339 try {
1340 ai = getPackageManager().getApplicationInfo(packageName,
1341 PackageManager.GET_SHARED_LIBRARY_FILES);
1342 } catch (RemoteException e) {
1343 }
1344
1345 if (ai != null) {
1346 return getPackageInfo(ai, flags);
1347 }
1348
1349 return null;
1350 }
1351
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001352 public final LoadedApk getPackageInfo(ApplicationInfo ai, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
1354 boolean securityViolation = includeCode && ai.uid != 0
1355 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
1356 ? ai.uid != mBoundApplication.appInfo.uid : true);
1357 if ((flags&(Context.CONTEXT_INCLUDE_CODE
1358 |Context.CONTEXT_IGNORE_SECURITY))
1359 == Context.CONTEXT_INCLUDE_CODE) {
1360 if (securityViolation) {
1361 String msg = "Requesting code from " + ai.packageName
1362 + " (with uid " + ai.uid + ")";
1363 if (mBoundApplication != null) {
1364 msg = msg + " to be run in process "
1365 + mBoundApplication.processName + " (with uid "
1366 + mBoundApplication.appInfo.uid + ")";
1367 }
1368 throw new SecurityException(msg);
1369 }
1370 }
1371 return getPackageInfo(ai, null, securityViolation, includeCode);
1372 }
1373
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001374 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 return getPackageInfo(ai, null, false, true);
1376 }
1377
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001378 private final LoadedApk getPackageInfo(ApplicationInfo aInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
1380 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001381 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 if (includeCode) {
1383 ref = mPackages.get(aInfo.packageName);
1384 } else {
1385 ref = mResourcePackages.get(aInfo.packageName);
1386 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001387 LoadedApk packageInfo = ref != null ? ref.get() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 if (packageInfo == null || (packageInfo.mResources != null
1389 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001390 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 : "Loading resource-only package ") + aInfo.packageName
1392 + " (in " + (mBoundApplication != null
1393 ? mBoundApplication.processName : null)
1394 + ")");
1395 packageInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001396 new LoadedApk(this, aInfo, this, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 securityViolation, includeCode &&
1398 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
1399 if (includeCode) {
1400 mPackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001401 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 } else {
1403 mResourcePackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001404 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 }
1406 }
1407 return packageInfo;
1408 }
1409 }
1410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 ActivityThread() {
1412 }
1413
1414 public ApplicationThread getApplicationThread()
1415 {
1416 return mAppThread;
1417 }
1418
1419 public Instrumentation getInstrumentation()
1420 {
1421 return mInstrumentation;
1422 }
1423
1424 public Configuration getConfiguration() {
1425 return mConfiguration;
1426 }
1427
1428 public boolean isProfiling() {
1429 return mBoundApplication != null && mBoundApplication.profileFile != null;
1430 }
1431
1432 public String getProfileFilePath() {
1433 return mBoundApplication.profileFile;
1434 }
1435
1436 public Looper getLooper() {
1437 return mLooper;
1438 }
1439
1440 public Application getApplication() {
1441 return mInitialApplication;
1442 }
Bob Leee5408332009-09-04 18:31:17 -07001443
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07001444 public String getProcessName() {
1445 return mBoundApplication.processName;
1446 }
Bob Leee5408332009-09-04 18:31:17 -07001447
Dianne Hackborn21556372010-02-04 16:34:40 -08001448 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 synchronized (this) {
1450 if (mSystemContext == null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001451 ContextImpl context =
1452 ContextImpl.createSystemContext(this);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001453 LoadedApk info = new LoadedApk(this, "android", context, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 context.init(info, null, this);
1455 context.getResources().updateConfiguration(
1456 getConfiguration(), getDisplayMetricsLocked(false));
1457 mSystemContext = context;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001458 //Slog.i(TAG, "Created system resources " + context.getResources()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 // + ": " + context.getResources().getConfiguration());
1460 }
1461 }
1462 return mSystemContext;
1463 }
1464
Mike Cleron432b7132009-09-24 15:28:29 -07001465 public void installSystemApplicationInfo(ApplicationInfo info) {
1466 synchronized (this) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001467 ContextImpl context = getSystemContext();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001468 context.init(new LoadedApk(this, "android", context, info), null, this);
Mike Cleron432b7132009-09-24 15:28:29 -07001469 }
1470 }
1471
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001472 void ensureJitEnabled() {
1473 if (!mJitEnabled) {
1474 mJitEnabled = true;
1475 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
1476 }
1477 }
1478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 void scheduleGcIdler() {
1480 if (!mGcIdlerScheduled) {
1481 mGcIdlerScheduled = true;
1482 Looper.myQueue().addIdleHandler(mGcIdler);
1483 }
1484 mH.removeMessages(H.GC_WHEN_IDLE);
1485 }
1486
1487 void unscheduleGcIdler() {
1488 if (mGcIdlerScheduled) {
1489 mGcIdlerScheduled = false;
1490 Looper.myQueue().removeIdleHandler(mGcIdler);
1491 }
1492 mH.removeMessages(H.GC_WHEN_IDLE);
1493 }
1494
1495 void doGcIfNeeded() {
1496 mGcIdlerScheduled = false;
1497 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001498 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 // + "m now=" + now);
1500 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001501 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 BinderInternal.forceGc("bg");
1503 }
1504 }
1505
1506 public final ActivityInfo resolveActivityInfo(Intent intent) {
1507 ActivityInfo aInfo = intent.resolveActivityInfo(
1508 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
1509 if (aInfo == null) {
1510 // Throw an exception.
1511 Instrumentation.checkStartActivityResult(
1512 IActivityManager.START_CLASS_NOT_FOUND, intent);
1513 }
1514 return aInfo;
1515 }
Bob Leee5408332009-09-04 18:31:17 -07001516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001519 Activity.NonConfigurationInstances lastNonConfigurationInstances) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001520 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001522 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 r.intent = intent;
1524 r.state = state;
1525 r.parent = parent;
1526 r.embeddedID = id;
1527 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001528 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 if (localLOGV) {
1530 ComponentName compname = intent.getComponent();
1531 String name;
1532 if (compname != null) {
1533 name = compname.toShortString();
1534 } else {
1535 name = "(Intent " + intent + ").getComponent() returned null";
1536 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001537 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 + ", comp=" + name
1539 + ", token=" + token);
1540 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07001541 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 }
1543
1544 public final Activity getActivity(IBinder token) {
1545 return mActivities.get(token).activity;
1546 }
1547
1548 public final void sendActivityResult(
1549 IBinder token, String id, int requestCode,
1550 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001551 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07001552 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
1554 list.add(new ResultInfo(id, requestCode, resultCode, data));
1555 mAppThread.scheduleSendResult(token, list);
1556 }
1557
1558 // if the thread hasn't started yet, we don't have the handler, so just
1559 // save the messages until we're ready.
1560 private final void queueOrSendMessage(int what, Object obj) {
1561 queueOrSendMessage(what, obj, 0, 0);
1562 }
1563
1564 private final void queueOrSendMessage(int what, Object obj, int arg1) {
1565 queueOrSendMessage(what, obj, arg1, 0);
1566 }
1567
1568 private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
1569 synchronized (this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001570 if (DEBUG_MESSAGES) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
1572 + ": " + arg1 + " / " + obj);
1573 Message msg = Message.obtain();
1574 msg.what = what;
1575 msg.obj = obj;
1576 msg.arg1 = arg1;
1577 msg.arg2 = arg2;
1578 mH.sendMessage(msg);
1579 }
1580 }
1581
Dianne Hackborn21556372010-02-04 16:34:40 -08001582 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 String what) {
1584 ContextCleanupInfo cci = new ContextCleanupInfo();
1585 cci.context = context;
1586 cci.who = who;
1587 cci.what = what;
1588 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
1589 }
1590
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001591 private final Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
1593
1594 ActivityInfo aInfo = r.activityInfo;
1595 if (r.packageInfo == null) {
1596 r.packageInfo = getPackageInfo(aInfo.applicationInfo,
1597 Context.CONTEXT_INCLUDE_CODE);
1598 }
Bob Leee5408332009-09-04 18:31:17 -07001599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 ComponentName component = r.intent.getComponent();
1601 if (component == null) {
1602 component = r.intent.resolveActivity(
1603 mInitialApplication.getPackageManager());
1604 r.intent.setComponent(component);
1605 }
1606
1607 if (r.activityInfo.targetActivity != null) {
1608 component = new ComponentName(r.activityInfo.packageName,
1609 r.activityInfo.targetActivity);
1610 }
1611
1612 Activity activity = null;
1613 try {
1614 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
1615 activity = mInstrumentation.newActivity(
1616 cl, component.getClassName(), r.intent);
1617 r.intent.setExtrasClassLoader(cl);
1618 if (r.state != null) {
1619 r.state.setClassLoader(cl);
1620 }
1621 } catch (Exception e) {
1622 if (!mInstrumentation.onException(activity, e)) {
1623 throw new RuntimeException(
1624 "Unable to instantiate activity " + component
1625 + ": " + e.toString(), e);
1626 }
1627 }
1628
1629 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001630 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001631
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001632 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
1633 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 TAG, r + ": app=" + app
1635 + ", appName=" + app.getPackageName()
1636 + ", pkg=" + r.packageInfo.getPackageName()
1637 + ", comp=" + r.intent.getComponent().toShortString()
1638 + ", dir=" + r.packageInfo.getAppDir());
1639
1640 if (activity != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001641 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 appContext.init(r.packageInfo, r.token, this);
1643 appContext.setOuterContext(activity);
1644 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
1645 Configuration config = new Configuration(mConfiguration);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001646 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07001647 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001648 activity.attach(appContext, this, getInstrumentation(), r.token,
1649 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001650 r.embeddedID, r.lastNonConfigurationInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07001651
Christopher Tateb70f3df2009-04-07 16:07:59 -07001652 if (customIntent != null) {
1653 activity.mIntent = customIntent;
1654 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001655 r.lastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 activity.mStartedActivity = false;
1657 int theme = r.activityInfo.getThemeResource();
1658 if (theme != 0) {
1659 activity.setTheme(theme);
1660 }
1661
1662 activity.mCalled = false;
1663 mInstrumentation.callActivityOnCreate(activity, r.state);
1664 if (!activity.mCalled) {
1665 throw new SuperNotCalledException(
1666 "Activity " + r.intent.getComponent().toShortString() +
1667 " did not call through to super.onCreate()");
1668 }
1669 r.activity = activity;
1670 r.stopped = true;
1671 if (!r.activity.mFinished) {
1672 activity.performStart();
1673 r.stopped = false;
1674 }
1675 if (!r.activity.mFinished) {
1676 if (r.state != null) {
1677 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
1678 }
1679 }
1680 if (!r.activity.mFinished) {
1681 activity.mCalled = false;
1682 mInstrumentation.callActivityOnPostCreate(activity, r.state);
1683 if (!activity.mCalled) {
1684 throw new SuperNotCalledException(
1685 "Activity " + r.intent.getComponent().toShortString() +
1686 " did not call through to super.onPostCreate()");
1687 }
1688 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 }
1690 r.paused = true;
1691
1692 mActivities.put(r.token, r);
1693
1694 } catch (SuperNotCalledException e) {
1695 throw e;
1696
1697 } catch (Exception e) {
1698 if (!mInstrumentation.onException(activity, e)) {
1699 throw new RuntimeException(
1700 "Unable to start activity " + component
1701 + ": " + e.toString(), e);
1702 }
1703 }
1704
1705 return activity;
1706 }
1707
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001708 private final void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 // If we are getting ready to gc after going to the background, well
1710 // we are back active so skip it.
1711 unscheduleGcIdler();
1712
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001713 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001715 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716
1717 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08001718 r.createdConfig = new Configuration(mConfiguration);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001719 Bundle oldState = r.state;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 handleResumeActivity(r.token, false, r.isForward);
1721
1722 if (!r.activity.mFinished && r.startsNotResumed) {
1723 // The activity manager actually wants this one to start out
1724 // paused, because it needs to be visible but isn't in the
1725 // foreground. We accomplish this by going through the
1726 // normal startup (because activities expect to go through
1727 // onResume() the first time they run, before their window
1728 // is displayed), and then pausing it. However, in this case
1729 // we do -not- need to do the full pause cycle (of freezing
1730 // and such) because the activity manager assumes it can just
1731 // retain the current state it has.
1732 try {
1733 r.activity.mCalled = false;
1734 mInstrumentation.callActivityOnPause(r.activity);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001735 // We need to keep around the original state, in case
1736 // we need to be created again.
1737 r.state = oldState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 if (!r.activity.mCalled) {
1739 throw new SuperNotCalledException(
1740 "Activity " + r.intent.getComponent().toShortString() +
1741 " did not call through to super.onPause()");
1742 }
1743
1744 } catch (SuperNotCalledException e) {
1745 throw e;
1746
1747 } catch (Exception e) {
1748 if (!mInstrumentation.onException(r.activity, e)) {
1749 throw new RuntimeException(
1750 "Unable to pause activity "
1751 + r.intent.getComponent().toShortString()
1752 + ": " + e.toString(), e);
1753 }
1754 }
1755 r.paused = true;
1756 }
1757 } else {
1758 // If there was an error, for any reason, tell the activity
1759 // manager to stop us.
1760 try {
1761 ActivityManagerNative.getDefault()
1762 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
1763 } catch (RemoteException ex) {
1764 }
1765 }
1766 }
1767
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001768 private final void deliverNewIntents(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 List<Intent> intents) {
1770 final int N = intents.size();
1771 for (int i=0; i<N; i++) {
1772 Intent intent = intents.get(i);
1773 intent.setExtrasClassLoader(r.activity.getClassLoader());
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001774 r.activity.mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001775 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
1776 }
1777 }
1778
1779 public final void performNewIntents(IBinder token,
1780 List<Intent> intents) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001781 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 if (r != null) {
1783 final boolean resumed = !r.paused;
1784 if (resumed) {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001785 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 mInstrumentation.callActivityOnPause(r.activity);
1787 }
1788 deliverNewIntents(r, intents);
1789 if (resumed) {
1790 mInstrumentation.callActivityOnResume(r.activity);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001791 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 }
1793 }
1794 }
Bob Leee5408332009-09-04 18:31:17 -07001795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 private final void handleNewIntent(NewIntentData data) {
1797 performNewIntents(data.token, data.intents);
1798 }
1799
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07001800 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
1801
1802 /**
1803 * Return the Intent that's currently being handled by a
1804 * BroadcastReceiver on this thread, or null if none.
1805 * @hide
1806 */
1807 public static Intent getIntentBeingBroadcast() {
1808 return sCurrentBroadcastIntent.get();
1809 }
1810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 private final void handleReceiver(ReceiverData data) {
1812 // If we are getting ready to gc after going to the background, well
1813 // we are back active so skip it.
1814 unscheduleGcIdler();
1815
1816 String component = data.intent.getComponent().getClassName();
1817
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001818 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 data.info.applicationInfo);
1820
1821 IActivityManager mgr = ActivityManagerNative.getDefault();
1822
1823 BroadcastReceiver receiver = null;
1824 try {
1825 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1826 data.intent.setExtrasClassLoader(cl);
Dianne Hackborne829fef2010-10-26 17:44:01 -07001827 data.setExtrasClassLoader(cl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
1829 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07001830 if (DEBUG_BROADCAST) Slog.i(TAG,
1831 "Finishing failed broadcast to " + data.intent.getComponent());
1832 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 throw new RuntimeException(
1834 "Unable to instantiate receiver " + component
1835 + ": " + e.toString(), e);
1836 }
1837
1838 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001839 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001840
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001841 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 TAG, "Performing receive of " + data.intent
1843 + ": app=" + app
1844 + ", appName=" + app.getPackageName()
1845 + ", pkg=" + packageInfo.getPackageName()
1846 + ", comp=" + data.intent.getComponent().toShortString()
1847 + ", dir=" + packageInfo.getAppDir());
1848
Dianne Hackborn21556372010-02-04 16:34:40 -08001849 ContextImpl context = (ContextImpl)app.getBaseContext();
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07001850 sCurrentBroadcastIntent.set(data.intent);
Dianne Hackborne829fef2010-10-26 17:44:01 -07001851 receiver.setPendingResult(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 receiver.onReceive(context.getReceiverRestrictedContext(),
1853 data.intent);
1854 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07001855 if (DEBUG_BROADCAST) Slog.i(TAG,
1856 "Finishing failed broadcast to " + data.intent.getComponent());
1857 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 if (!mInstrumentation.onException(receiver, e)) {
1859 throw new RuntimeException(
1860 "Unable to start receiver " + component
1861 + ": " + e.toString(), e);
1862 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07001863 } finally {
1864 sCurrentBroadcastIntent.set(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 }
1866
Dianne Hackborne829fef2010-10-26 17:44:01 -07001867 if (receiver.getPendingResult() != null) {
1868 data.finish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 }
1870 }
1871
Christopher Tate181fafa2009-05-14 11:12:14 -07001872 // Instantiate a BackupAgent and tell it that it's alive
1873 private final void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001874 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001875
1876 // no longer idle; we have backup work to do
1877 unscheduleGcIdler();
1878
1879 // instantiate the BackupAgent class named in the manifest
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001880 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001881 String packageName = packageInfo.mPackageName;
1882 if (mBackupAgents.get(packageName) != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001883 Slog.d(TAG, "BackupAgent " + " for " + packageName
Christopher Tate181fafa2009-05-14 11:12:14 -07001884 + " already exists");
1885 return;
1886 }
Bob Leee5408332009-09-04 18:31:17 -07001887
Christopher Tate181fafa2009-05-14 11:12:14 -07001888 BackupAgent agent = null;
1889 String classname = data.appInfo.backupAgentName;
1890 if (classname == null) {
1891 if (data.backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001892 Slog.e(TAG, "Attempted incremental backup but no defined agent for "
Christopher Tate181fafa2009-05-14 11:12:14 -07001893 + packageName);
1894 return;
1895 }
1896 classname = "android.app.FullBackupAgent";
1897 }
1898 try {
Christopher Tated1475e02009-07-09 15:36:17 -07001899 IBinder binder = null;
1900 try {
1901 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1902 agent = (BackupAgent) cl.loadClass(data.appInfo.backupAgentName).newInstance();
1903
1904 // set up the agent's context
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001905 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing BackupAgent "
Christopher Tated1475e02009-07-09 15:36:17 -07001906 + data.appInfo.backupAgentName);
1907
Dianne Hackborn21556372010-02-04 16:34:40 -08001908 ContextImpl context = new ContextImpl();
Christopher Tated1475e02009-07-09 15:36:17 -07001909 context.init(packageInfo, null, this);
1910 context.setOuterContext(agent);
1911 agent.attach(context);
1912
1913 agent.onCreate();
1914 binder = agent.onBind();
1915 mBackupAgents.put(packageName, agent);
1916 } catch (Exception e) {
1917 // If this is during restore, fail silently; otherwise go
1918 // ahead and let the user see the crash.
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001919 Slog.e(TAG, "Agent threw during creation: " + e);
Christopher Tated1475e02009-07-09 15:36:17 -07001920 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE) {
1921 throw e;
1922 }
1923 // falling through with 'binder' still null
1924 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001925
1926 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07001927 try {
1928 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
1929 } catch (RemoteException e) {
1930 // nothing to do.
1931 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001932 } catch (Exception e) {
1933 throw new RuntimeException("Unable to create BackupAgent "
1934 + data.appInfo.backupAgentName + ": " + e.toString(), e);
1935 }
1936 }
1937
1938 // Tear down a BackupAgent
1939 private final void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001940 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07001941
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001942 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001943 String packageName = packageInfo.mPackageName;
1944 BackupAgent agent = mBackupAgents.get(packageName);
1945 if (agent != null) {
1946 try {
1947 agent.onDestroy();
1948 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001949 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001950 e.printStackTrace();
1951 }
1952 mBackupAgents.remove(packageName);
1953 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001954 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001955 }
1956 }
1957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 private final void handleCreateService(CreateServiceData data) {
1959 // If we are getting ready to gc after going to the background, well
1960 // we are back active so skip it.
1961 unscheduleGcIdler();
1962
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001963 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 data.info.applicationInfo);
1965 Service service = null;
1966 try {
1967 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1968 service = (Service) cl.loadClass(data.info.name).newInstance();
1969 } catch (Exception e) {
1970 if (!mInstrumentation.onException(service, e)) {
1971 throw new RuntimeException(
1972 "Unable to instantiate service " + data.info.name
1973 + ": " + e.toString(), e);
1974 }
1975 }
1976
1977 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001978 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001979
Dianne Hackborn21556372010-02-04 16:34:40 -08001980 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981 context.init(packageInfo, null, this);
1982
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001983 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 context.setOuterContext(service);
1985 service.attach(context, this, data.info.name, data.token, app,
1986 ActivityManagerNative.getDefault());
1987 service.onCreate();
1988 mServices.put(data.token, service);
1989 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001990 ActivityManagerNative.getDefault().serviceDoneExecuting(
1991 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 } catch (RemoteException e) {
1993 // nothing to do.
1994 }
1995 } catch (Exception e) {
1996 if (!mInstrumentation.onException(service, e)) {
1997 throw new RuntimeException(
1998 "Unable to create service " + data.info.name
1999 + ": " + e.toString(), e);
2000 }
2001 }
2002 }
2003
2004 private final void handleBindService(BindServiceData data) {
2005 Service s = mServices.get(data.token);
2006 if (s != null) {
2007 try {
2008 data.intent.setExtrasClassLoader(s.getClassLoader());
2009 try {
2010 if (!data.rebind) {
2011 IBinder binder = s.onBind(data.intent);
2012 ActivityManagerNative.getDefault().publishService(
2013 data.token, data.intent, binder);
2014 } else {
2015 s.onRebind(data.intent);
2016 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002017 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002018 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002019 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 } catch (RemoteException ex) {
2021 }
2022 } catch (Exception e) {
2023 if (!mInstrumentation.onException(s, e)) {
2024 throw new RuntimeException(
2025 "Unable to bind to service " + s
2026 + " with " + data.intent + ": " + e.toString(), e);
2027 }
2028 }
2029 }
2030 }
2031
2032 private final void handleUnbindService(BindServiceData data) {
2033 Service s = mServices.get(data.token);
2034 if (s != null) {
2035 try {
2036 data.intent.setExtrasClassLoader(s.getClassLoader());
2037 boolean doRebind = s.onUnbind(data.intent);
2038 try {
2039 if (doRebind) {
2040 ActivityManagerNative.getDefault().unbindFinished(
2041 data.token, data.intent, doRebind);
2042 } else {
2043 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002044 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 }
2046 } catch (RemoteException ex) {
2047 }
2048 } catch (Exception e) {
2049 if (!mInstrumentation.onException(s, e)) {
2050 throw new RuntimeException(
2051 "Unable to unbind to service " + s
2052 + " with " + data.intent + ": " + e.toString(), e);
2053 }
2054 }
2055 }
2056 }
2057
Dianne Hackborn625ac272010-09-17 18:29:22 -07002058 private void handleDumpService(DumpComponentInfo info) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 try {
Dianne Hackborn625ac272010-09-17 18:29:22 -07002060 Service s = mServices.get(info.token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061 if (s != null) {
2062 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
2063 s.dump(info.fd, pw, info.args);
2064 pw.close();
2065 }
2066 } finally {
2067 synchronized (info) {
2068 info.dumped = true;
2069 info.notifyAll();
2070 }
2071 }
2072 }
2073
Dianne Hackborn625ac272010-09-17 18:29:22 -07002074 private void handleDumpActivity(DumpComponentInfo info) {
2075 try {
2076 ActivityClientRecord r = mActivities.get(info.token);
2077 if (r != null && r.activity != null) {
2078 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
2079 r.activity.dump(info.fd, pw, info.args);
2080 pw.close();
2081 }
2082 } finally {
2083 synchronized (info) {
2084 info.dumped = true;
2085 info.notifyAll();
2086 }
2087 }
2088 }
2089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 private final void handleServiceArgs(ServiceArgsData data) {
2091 Service s = mServices.get(data.token);
2092 if (s != null) {
2093 try {
2094 if (data.args != null) {
2095 data.args.setExtrasClassLoader(s.getClassLoader());
2096 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002097 int res = s.onStartCommand(data.args, data.flags, data.startId);
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002098
2099 QueuedWork.waitToFinish();
2100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002101 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002102 ActivityManagerNative.getDefault().serviceDoneExecuting(
2103 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104 } catch (RemoteException e) {
2105 // nothing to do.
2106 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002107 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002108 } catch (Exception e) {
2109 if (!mInstrumentation.onException(s, e)) {
2110 throw new RuntimeException(
2111 "Unable to start service " + s
2112 + " with " + data.args + ": " + e.toString(), e);
2113 }
2114 }
2115 }
2116 }
2117
2118 private final void handleStopService(IBinder token) {
2119 Service s = mServices.remove(token);
2120 if (s != null) {
2121 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002122 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 s.onDestroy();
2124 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002125 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08002127 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002128 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002129
2130 QueuedWork.waitToFinish();
2131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002133 ActivityManagerNative.getDefault().serviceDoneExecuting(
2134 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 } catch (RemoteException e) {
2136 // nothing to do.
2137 }
2138 } catch (Exception e) {
2139 if (!mInstrumentation.onException(s, e)) {
2140 throw new RuntimeException(
2141 "Unable to stop service " + s
2142 + ": " + e.toString(), e);
2143 }
2144 }
2145 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002146 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002147 }
2148
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002149 public final ActivityClientRecord performResumeActivity(IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002150 boolean clearHide) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002151 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002152 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002153 + " finished=" + r.activity.mFinished);
2154 if (r != null && !r.activity.mFinished) {
2155 if (clearHide) {
2156 r.hideForNow = false;
2157 r.activity.mStartedActivity = false;
2158 }
2159 try {
2160 if (r.pendingIntents != null) {
2161 deliverNewIntents(r, r.pendingIntents);
2162 r.pendingIntents = null;
2163 }
2164 if (r.pendingResults != null) {
2165 deliverResults(r, r.pendingResults);
2166 r.pendingResults = null;
2167 }
2168 r.activity.performResume();
2169
Bob Leee5408332009-09-04 18:31:17 -07002170 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002171 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173 r.paused = false;
2174 r.stopped = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002175 r.state = null;
2176 } catch (Exception e) {
2177 if (!mInstrumentation.onException(r.activity, e)) {
2178 throw new RuntimeException(
2179 "Unable to resume activity "
2180 + r.intent.getComponent().toShortString()
2181 + ": " + e.toString(), e);
2182 }
2183 }
2184 }
2185 return r;
2186 }
2187
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002188 final void cleanUpPendingRemoveWindows(ActivityClientRecord r) {
2189 if (r.mPendingRemoveWindow != null) {
2190 r.mPendingRemoveWindowManager.removeViewImmediate(r.mPendingRemoveWindow);
2191 IBinder wtoken = r.mPendingRemoveWindow.getWindowToken();
2192 if (wtoken != null) {
2193 WindowManagerImpl.getDefault().closeAll(wtoken,
2194 r.activity.getClass().getName(), "Activity");
2195 }
2196 }
2197 r.mPendingRemoveWindow = null;
2198 r.mPendingRemoveWindowManager = null;
2199 }
2200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002201 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2202 // If we are getting ready to gc after going to the background, well
2203 // we are back active so skip it.
2204 unscheduleGcIdler();
2205
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002206 ActivityClientRecord r = performResumeActivity(token, clearHide);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002207
2208 if (r != null) {
2209 final Activity a = r.activity;
2210
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002211 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002212 TAG, "Resume " + r + " started activity: " +
2213 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2214 + ", finished: " + a.mFinished);
2215
2216 final int forwardBit = isForward ?
2217 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002219 // If the window hasn't yet been added to the window manager,
2220 // and this guy didn't finish itself or start another activity,
2221 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002222 boolean willBeVisible = !a.mStartedActivity;
2223 if (!willBeVisible) {
2224 try {
2225 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
2226 a.getActivityToken());
2227 } catch (RemoteException e) {
2228 }
2229 }
2230 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002231 r.window = r.activity.getWindow();
2232 View decor = r.window.getDecorView();
2233 decor.setVisibility(View.INVISIBLE);
2234 ViewManager wm = a.getWindowManager();
2235 WindowManager.LayoutParams l = r.window.getAttributes();
2236 a.mDecor = decor;
2237 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2238 l.softInputMode |= forwardBit;
2239 if (a.mVisibleFromClient) {
2240 a.mWindowAdded = true;
2241 wm.addView(decor, l);
2242 }
2243
2244 // If the window has already been added, but during resume
2245 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002246 // window visible.
2247 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002248 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002249 TAG, "Launch " + r + " mStartedActivity set");
2250 r.hideForNow = true;
2251 }
2252
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002253 // Get rid of anything left hanging around.
2254 cleanUpPendingRemoveWindows(r);
2255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002256 // The window is now visible if it has been added, we are not
2257 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002258 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002259 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002260 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002261 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002262 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 performConfigurationChanged(r.activity, r.newConfig);
2264 r.newConfig = null;
2265 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002266 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267 + isForward);
2268 WindowManager.LayoutParams l = r.window.getAttributes();
2269 if ((l.softInputMode
2270 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2271 != forwardBit) {
2272 l.softInputMode = (l.softInputMode
2273 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2274 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002275 if (r.activity.mVisibleFromClient) {
2276 ViewManager wm = a.getWindowManager();
2277 View decor = r.window.getDecorView();
2278 wm.updateViewLayout(decor, l);
2279 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002280 }
2281 r.activity.mVisibleFromServer = true;
2282 mNumVisibleActivities++;
2283 if (r.activity.mVisibleFromClient) {
2284 r.activity.makeVisible();
2285 }
2286 }
2287
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002288 if (!r.onlyLocalRequest) {
2289 r.nextIdle = mNewActivities;
2290 mNewActivities = r;
2291 if (localLOGV) Slog.v(
2292 TAG, "Scheduling idle handler for " + r);
2293 Looper.myQueue().addIdleHandler(new Idler());
2294 }
2295 r.onlyLocalRequest = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002296
2297 } else {
2298 // If an exception was thrown when trying to resume, then
2299 // just end this activity.
2300 try {
2301 ActivityManagerNative.getDefault()
2302 .finishActivity(token, Activity.RESULT_CANCELED, null);
2303 } catch (RemoteException ex) {
2304 }
2305 }
2306 }
2307
2308 private int mThumbnailWidth = -1;
2309 private int mThumbnailHeight = -1;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002310 private Bitmap mAvailThumbnailBitmap = null;
2311 private Canvas mThumbnailCanvas = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002312
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002313 private final Bitmap createThumbnailBitmap(ActivityClientRecord r) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002314 Bitmap thumbnail = mAvailThumbnailBitmap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002315 try {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002316 if (thumbnail == null) {
2317 int w = mThumbnailWidth;
2318 int h;
2319 if (w < 0) {
2320 Resources res = r.activity.getResources();
2321 mThumbnailHeight = h =
2322 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002323
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002324 mThumbnailWidth = w =
2325 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
2326 } else {
2327 h = mThumbnailHeight;
2328 }
2329
2330 // On platforms where we don't want thumbnails, set dims to (0,0)
2331 if ((w > 0) && (h > 0)) {
2332 thumbnail = Bitmap.createBitmap(w, h, THUMBNAIL_FORMAT);
2333 thumbnail.eraseColor(0);
2334 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002335 }
2336
Dianne Hackbornfb3806d2010-12-09 13:14:12 -08002337 if (thumbnail != null) {
2338 Canvas cv = mThumbnailCanvas;
2339 if (cv == null) {
2340 mThumbnailCanvas = cv = new Canvas();
2341 }
2342
2343 cv.setBitmap(thumbnail);
2344 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
2345 mAvailThumbnailBitmap = thumbnail;
2346 thumbnail = null;
2347 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348 }
Jim Miller0b2a6d02010-07-13 18:01:29 -07002349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002350 } catch (Exception e) {
2351 if (!mInstrumentation.onException(r.activity, e)) {
2352 throw new RuntimeException(
2353 "Unable to create thumbnail of "
2354 + r.intent.getComponent().toShortString()
2355 + ": " + e.toString(), e);
2356 }
2357 thumbnail = null;
2358 }
2359
2360 return thumbnail;
2361 }
2362
2363 private final void handlePauseActivity(IBinder token, boolean finished,
2364 boolean userLeaving, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002365 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002367 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 if (userLeaving) {
2369 performUserLeavingActivity(r);
2370 }
Bob Leee5408332009-09-04 18:31:17 -07002371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002372 r.activity.mConfigChangeFlags |= configChanges;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002373 performPauseActivity(token, finished, r.isPreHoneycomb());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002374
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07002375 // Make sure any pending writes are now committed.
2376 QueuedWork.waitToFinish();
2377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002378 // Tell the activity manager we have paused.
2379 try {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002380 ActivityManagerNative.getDefault().activityPaused(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002381 } catch (RemoteException ex) {
2382 }
2383 }
2384 }
2385
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002386 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002387 mInstrumentation.callActivityOnUserLeaving(r.activity);
2388 }
2389
2390 final Bundle performPauseActivity(IBinder token, boolean finished,
2391 boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002392 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002393 return r != null ? performPauseActivity(r, finished, saveState) : null;
2394 }
2395
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002396 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 boolean saveState) {
2398 if (r.paused) {
2399 if (r.activity.mFinished) {
2400 // If we are finishing, we won't call onResume() in certain cases.
2401 // So here we likewise don't want to call onPause() if the activity
2402 // isn't resumed.
2403 return null;
2404 }
2405 RuntimeException e = new RuntimeException(
2406 "Performing pause of activity that is not resumed: "
2407 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002408 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002409 }
2410 Bundle state = null;
2411 if (finished) {
2412 r.activity.mFinished = true;
2413 }
2414 try {
2415 // Next have the activity save its current state and managed dialogs...
2416 if (!r.activity.mFinished && saveState) {
2417 state = new Bundle();
2418 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2419 r.state = state;
2420 }
2421 // Now we are idle.
2422 r.activity.mCalled = false;
2423 mInstrumentation.callActivityOnPause(r.activity);
2424 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
2425 if (!r.activity.mCalled) {
2426 throw new SuperNotCalledException(
2427 "Activity " + r.intent.getComponent().toShortString() +
2428 " did not call through to super.onPause()");
2429 }
2430
2431 } catch (SuperNotCalledException e) {
2432 throw e;
2433
2434 } catch (Exception e) {
2435 if (!mInstrumentation.onException(r.activity, e)) {
2436 throw new RuntimeException(
2437 "Unable to pause activity "
2438 + r.intent.getComponent().toShortString()
2439 + ": " + e.toString(), e);
2440 }
2441 }
2442 r.paused = true;
2443 return state;
2444 }
2445
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002446 final void performStopActivity(IBinder token, boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002447 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002448 performStopActivityInner(r, null, false, saveState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002449 }
2450
2451 private static class StopInfo {
2452 Bitmap thumbnail;
2453 CharSequence description;
2454 }
2455
2456 private final class ProviderRefCount {
2457 public int count;
2458 ProviderRefCount(int pCount) {
2459 count = pCount;
2460 }
2461 }
2462
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002463 /**
2464 * Core implementation of stopping an activity. Note this is a little
2465 * tricky because the server's meaning of stop is slightly different
2466 * than our client -- for the server, stop means to save state and give
2467 * it the result when it is done, but the window may still be visible.
2468 * For the client, we want to call onStop()/onStart() to indicate when
2469 * the activity's UI visibillity changes.
2470 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002471 private final void performStopActivityInner(ActivityClientRecord r,
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002472 StopInfo info, boolean keepShown, boolean saveState) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002473 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002474 Bundle state = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002475 if (r != null) {
2476 if (!keepShown && r.stopped) {
2477 if (r.activity.mFinished) {
2478 // If we are finishing, we won't call onResume() in certain
2479 // cases. So here we likewise don't want to call onStop()
2480 // if the activity isn't resumed.
2481 return;
2482 }
2483 RuntimeException e = new RuntimeException(
2484 "Performing stop of activity that is not resumed: "
2485 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002486 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 }
2488
2489 if (info != null) {
2490 try {
2491 // First create a thumbnail for the activity...
Jim Miller0b2a6d02010-07-13 18:01:29 -07002492 info.thumbnail = createThumbnailBitmap(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493 info.description = r.activity.onCreateDescription();
2494 } catch (Exception e) {
2495 if (!mInstrumentation.onException(r.activity, e)) {
2496 throw new RuntimeException(
2497 "Unable to save state of activity "
2498 + r.intent.getComponent().toShortString()
2499 + ": " + e.toString(), e);
2500 }
2501 }
2502 }
2503
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002504 // Next have the activity save its current state and managed dialogs...
2505 if (!r.activity.mFinished && saveState) {
2506 if (r.state == null) {
2507 state = new Bundle();
2508 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2509 r.state = state;
2510 } else {
2511 state = r.state;
2512 }
2513 }
2514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 if (!keepShown) {
2516 try {
2517 // Now we are idle.
2518 r.activity.performStop();
2519 } catch (Exception e) {
2520 if (!mInstrumentation.onException(r.activity, e)) {
2521 throw new RuntimeException(
2522 "Unable to stop activity "
2523 + r.intent.getComponent().toShortString()
2524 + ": " + e.toString(), e);
2525 }
2526 }
2527 r.stopped = true;
2528 }
2529
2530 r.paused = true;
2531 }
2532 }
2533
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002534 private final void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535 View v = r.activity.mDecor;
2536 if (v != null) {
2537 if (show) {
2538 if (!r.activity.mVisibleFromServer) {
2539 r.activity.mVisibleFromServer = true;
2540 mNumVisibleActivities++;
2541 if (r.activity.mVisibleFromClient) {
2542 r.activity.makeVisible();
2543 }
2544 }
2545 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002546 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002547 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002548 performConfigurationChanged(r.activity, r.newConfig);
2549 r.newConfig = null;
2550 }
2551 } else {
2552 if (r.activity.mVisibleFromServer) {
2553 r.activity.mVisibleFromServer = false;
2554 mNumVisibleActivities--;
2555 v.setVisibility(View.INVISIBLE);
2556 }
2557 }
2558 }
2559 }
2560
2561 private final void handleStopActivity(IBinder token, boolean show, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002562 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002563 r.activity.mConfigChangeFlags |= configChanges;
2564
2565 StopInfo info = new StopInfo();
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002566 performStopActivityInner(r, info, show, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002568 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 TAG, "Finishing stop of " + r + ": show=" + show
2570 + " win=" + r.window);
2571
2572 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07002573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 // Tell activity manager we have been stopped.
2575 try {
2576 ActivityManagerNative.getDefault().activityStopped(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002577 r.token, r.state, info.thumbnail, info.description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 } catch (RemoteException ex) {
2579 }
2580 }
2581
2582 final void performRestartActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002583 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 if (r.stopped) {
2585 r.activity.performRestart();
2586 r.stopped = false;
2587 }
2588 }
2589
2590 private final void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002591 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002592 if (!show && !r.stopped) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002593 performStopActivityInner(r, null, show, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594 } else if (show && r.stopped) {
2595 // If we are getting ready to gc after going to the background, well
2596 // we are back active so skip it.
2597 unscheduleGcIdler();
2598
2599 r.activity.performRestart();
2600 r.stopped = false;
2601 }
2602 if (r.activity.mDecor != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002603 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 TAG, "Handle window " + r + " visibility: " + show);
2605 updateVisibility(r, show);
2606 }
2607 }
2608
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002609 private final void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002610 final int N = results.size();
2611 for (int i=0; i<N; i++) {
2612 ResultInfo ri = results.get(i);
2613 try {
2614 if (ri.mData != null) {
2615 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
2616 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002617 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07002618 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619 r.activity.dispatchActivityResult(ri.mResultWho,
2620 ri.mRequestCode, ri.mResultCode, ri.mData);
2621 } catch (Exception e) {
2622 if (!mInstrumentation.onException(r.activity, e)) {
2623 throw new RuntimeException(
2624 "Failure delivering result " + ri + " to activity "
2625 + r.intent.getComponent().toShortString()
2626 + ": " + e.toString(), e);
2627 }
2628 }
2629 }
2630 }
2631
2632 private final void handleSendResult(ResultData res) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002633 ActivityClientRecord r = mActivities.get(res.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002634 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 if (r != null) {
2636 final boolean resumed = !r.paused;
2637 if (!r.activity.mFinished && r.activity.mDecor != null
2638 && r.hideForNow && resumed) {
2639 // We had hidden the activity because it started another
2640 // one... we have gotten a result back and we are not
2641 // paused, so make sure our window is visible.
2642 updateVisibility(r, true);
2643 }
2644 if (resumed) {
2645 try {
2646 // Now we are idle.
2647 r.activity.mCalled = false;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002648 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 mInstrumentation.callActivityOnPause(r.activity);
2650 if (!r.activity.mCalled) {
2651 throw new SuperNotCalledException(
2652 "Activity " + r.intent.getComponent().toShortString()
2653 + " 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 "
2661 + r.intent.getComponent().toShortString()
2662 + ": " + e.toString(), e);
2663 }
2664 }
2665 }
2666 deliverResults(r, res.results);
2667 if (resumed) {
2668 mInstrumentation.callActivityOnResume(r.activity);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002669 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002670 }
2671 }
2672 }
2673
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002674 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 return performDestroyActivity(token, finishing, 0, false);
2676 }
2677
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002678 private final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002680 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002681 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 if (r != null) {
2683 r.activity.mConfigChangeFlags |= configChanges;
2684 if (finishing) {
2685 r.activity.mFinished = true;
2686 }
2687 if (!r.paused) {
2688 try {
2689 r.activity.mCalled = false;
2690 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07002691 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 r.activity.getComponentName().getClassName());
2693 if (!r.activity.mCalled) {
2694 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002695 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002696 + " did not call through to super.onPause()");
2697 }
2698 } catch (SuperNotCalledException e) {
2699 throw e;
2700 } catch (Exception e) {
2701 if (!mInstrumentation.onException(r.activity, e)) {
2702 throw new RuntimeException(
2703 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002704 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002705 + ": " + e.toString(), e);
2706 }
2707 }
2708 r.paused = true;
2709 }
2710 if (!r.stopped) {
2711 try {
2712 r.activity.performStop();
2713 } catch (SuperNotCalledException e) {
2714 throw e;
2715 } catch (Exception e) {
2716 if (!mInstrumentation.onException(r.activity, e)) {
2717 throw new RuntimeException(
2718 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002719 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 + ": " + e.toString(), e);
2721 }
2722 }
2723 r.stopped = true;
2724 }
2725 if (getNonConfigInstance) {
2726 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002727 r.lastNonConfigurationInstances
2728 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 } catch (Exception e) {
2730 if (!mInstrumentation.onException(r.activity, e)) {
2731 throw new RuntimeException(
2732 "Unable to retain activity "
2733 + r.intent.getComponent().toShortString()
2734 + ": " + e.toString(), e);
2735 }
2736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002737 }
2738 try {
2739 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07002740 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002741 if (!r.activity.mCalled) {
2742 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002743 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744 " did not call through to super.onDestroy()");
2745 }
2746 if (r.window != null) {
2747 r.window.closeAllPanels();
2748 }
2749 } catch (SuperNotCalledException e) {
2750 throw e;
2751 } catch (Exception e) {
2752 if (!mInstrumentation.onException(r.activity, e)) {
2753 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002754 "Unable to destroy activity " + safeToComponentShortString(r.intent)
2755 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002756 }
2757 }
2758 }
2759 mActivities.remove(token);
2760
2761 return r;
2762 }
2763
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002764 private static String safeToComponentShortString(Intent intent) {
2765 ComponentName component = intent.getComponent();
2766 return component == null ? "[Unknown]" : component.toShortString();
2767 }
2768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 private final void handleDestroyActivity(IBinder token, boolean finishing,
2770 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002771 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002772 configChanges, getNonConfigInstance);
2773 if (r != null) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002774 cleanUpPendingRemoveWindows(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775 WindowManager wm = r.activity.getWindowManager();
2776 View v = r.activity.mDecor;
2777 if (v != null) {
2778 if (r.activity.mVisibleFromServer) {
2779 mNumVisibleActivities--;
2780 }
2781 IBinder wtoken = v.getWindowToken();
2782 if (r.activity.mWindowAdded) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002783 if (r.onlyLocalRequest) {
2784 // Hold off on removing this until the new activity's
2785 // window is being added.
2786 r.mPendingRemoveWindow = v;
2787 r.mPendingRemoveWindowManager = wm;
2788 } else {
2789 wm.removeViewImmediate(v);
2790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002791 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002792 if (wtoken != null && r.mPendingRemoveWindow == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793 WindowManagerImpl.getDefault().closeAll(wtoken,
2794 r.activity.getClass().getName(), "Activity");
2795 }
2796 r.activity.mDecor = null;
2797 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002798 if (r.mPendingRemoveWindow == null) {
2799 // If we are delaying the removal of the activity window, then
2800 // we can't clean up all windows here. Note that we can't do
2801 // so later either, which means any windows that aren't closed
2802 // by the app will leak. Well we try to warning them a lot
2803 // about leaking windows, because that is a bug, so if they are
2804 // using this recreate facility then they get to live with leaks.
2805 WindowManagerImpl.getDefault().closeAll(token,
2806 r.activity.getClass().getName(), "Activity");
2807 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808
2809 // Mocked out contexts won't be participating in the normal
2810 // process lifecycle, but if we're running with a proper
2811 // ApplicationContext we need to have it tear down things
2812 // cleanly.
2813 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002814 if (c instanceof ContextImpl) {
2815 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 r.activity.getClass().getName(), "Activity");
2817 }
2818 }
2819 if (finishing) {
2820 try {
2821 ActivityManagerNative.getDefault().activityDestroyed(token);
2822 } catch (RemoteException ex) {
2823 // If the system process has died, it's game over for everyone.
2824 }
2825 }
2826 }
2827
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002828 public final void requestRelaunchActivity(IBinder token,
2829 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
2830 int configChanges, boolean notResumed, Configuration config,
2831 boolean fromServer) {
2832 ActivityClientRecord target = null;
2833
2834 synchronized (mPackages) {
2835 for (int i=0; i<mRelaunchingActivities.size(); i++) {
2836 ActivityClientRecord r = mRelaunchingActivities.get(i);
2837 if (r.token == token) {
2838 target = r;
2839 if (pendingResults != null) {
2840 if (r.pendingResults != null) {
2841 r.pendingResults.addAll(pendingResults);
2842 } else {
2843 r.pendingResults = pendingResults;
2844 }
2845 }
2846 if (pendingNewIntents != null) {
2847 if (r.pendingIntents != null) {
2848 r.pendingIntents.addAll(pendingNewIntents);
2849 } else {
2850 r.pendingIntents = pendingNewIntents;
2851 }
2852 }
2853 break;
2854 }
2855 }
2856
2857 if (target == null) {
2858 target = new ActivityClientRecord();
2859 target.token = token;
2860 target.pendingResults = pendingResults;
2861 target.pendingIntents = pendingNewIntents;
2862 if (!fromServer) {
2863 ActivityClientRecord existing = mActivities.get(token);
2864 if (existing != null) {
2865 target.startsNotResumed = existing.paused;
2866 }
2867 target.onlyLocalRequest = true;
2868 }
2869 mRelaunchingActivities.add(target);
2870 queueOrSendMessage(H.RELAUNCH_ACTIVITY, target);
2871 }
2872
2873 if (fromServer) {
2874 target.startsNotResumed = notResumed;
2875 target.onlyLocalRequest = false;
2876 }
2877 if (config != null) {
2878 target.createdConfig = config;
2879 }
2880 target.pendingConfigChanges |= configChanges;
2881 }
2882 }
2883
2884 private final void handleRelaunchActivity(ActivityClientRecord tmp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002885 // If we are getting ready to gc after going to the background, well
2886 // we are back active so skip it.
2887 unscheduleGcIdler();
2888
2889 Configuration changedConfig = null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002890 int configChanges = 0;
Bob Leee5408332009-09-04 18:31:17 -07002891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892 // First: make sure we have the most recent configuration and most
2893 // recent version of the activity, or skip it if some previous call
2894 // had taken a more recent version.
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002895 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002896 int N = mRelaunchingActivities.size();
2897 IBinder token = tmp.token;
2898 tmp = null;
2899 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002900 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002901 if (r.token == token) {
2902 tmp = r;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002903 configChanges |= tmp.pendingConfigChanges;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002904 mRelaunchingActivities.remove(i);
2905 i--;
2906 N--;
2907 }
2908 }
Bob Leee5408332009-09-04 18:31:17 -07002909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002910 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002911 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002912 return;
2913 }
Bob Leee5408332009-09-04 18:31:17 -07002914
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002915 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
2916 + tmp.token + " with configChanges=0x"
2917 + Integer.toHexString(configChanges));
2918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002919 if (mPendingConfiguration != null) {
2920 changedConfig = mPendingConfiguration;
2921 mPendingConfiguration = null;
2922 }
2923 }
Bob Leee5408332009-09-04 18:31:17 -07002924
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002925 if (tmp.createdConfig != null) {
2926 // If the activity manager is passing us its current config,
2927 // assume that is really what we want regardless of what we
2928 // may have pending.
2929 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002930 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
2931 && mConfiguration.diff(tmp.createdConfig) != 0)) {
2932 if (changedConfig == null
2933 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
2934 changedConfig = tmp.createdConfig;
2935 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002936 }
2937 }
2938
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002939 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002940 + tmp.token + ": changedConfig=" + changedConfig);
2941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002942 // If there was a pending configuration change, execute it first.
2943 if (changedConfig != null) {
2944 handleConfigurationChanged(changedConfig);
2945 }
Bob Leee5408332009-09-04 18:31:17 -07002946
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002947 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002948 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002949 if (r == null) {
2950 return;
2951 }
Bob Leee5408332009-09-04 18:31:17 -07002952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002953 r.activity.mConfigChangeFlags |= configChanges;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002954 r.onlyLocalRequest = tmp.onlyLocalRequest;
Christopher Tateb70f3df2009-04-07 16:07:59 -07002955 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07002956
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002957 r.activity.mChangingConfigurations = true;
2958
Dianne Hackborne2b04802010-12-09 09:24:55 -08002959 // Need to ensure state is saved.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002960 if (!r.paused) {
Dianne Hackborne2b04802010-12-09 09:24:55 -08002961 performPauseActivity(r.token, false, r.isPreHoneycomb());
2962 }
2963 if (r.state == null && !r.stopped && !r.isPreHoneycomb()) {
2964 r.state = new Bundle();
2965 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002966 }
Bob Leee5408332009-09-04 18:31:17 -07002967
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002968 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07002969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002970 r.activity = null;
2971 r.window = null;
2972 r.hideForNow = false;
2973 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07002974 // Merge any pending results and pending intents; don't just replace them
2975 if (tmp.pendingResults != null) {
2976 if (r.pendingResults == null) {
2977 r.pendingResults = tmp.pendingResults;
2978 } else {
2979 r.pendingResults.addAll(tmp.pendingResults);
2980 }
2981 }
2982 if (tmp.pendingIntents != null) {
2983 if (r.pendingIntents == null) {
2984 r.pendingIntents = tmp.pendingIntents;
2985 } else {
2986 r.pendingIntents.addAll(tmp.pendingIntents);
2987 }
2988 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002989 r.startsNotResumed = tmp.startsNotResumed;
Bob Leee5408332009-09-04 18:31:17 -07002990
Christopher Tateb70f3df2009-04-07 16:07:59 -07002991 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992 }
2993
2994 private final void handleRequestThumbnail(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002995 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002996 Bitmap thumbnail = createThumbnailBitmap(r);
2997 CharSequence description = null;
2998 try {
2999 description = r.activity.onCreateDescription();
3000 } catch (Exception e) {
3001 if (!mInstrumentation.onException(r.activity, e)) {
3002 throw new RuntimeException(
3003 "Unable to create description of activity "
3004 + r.intent.getComponent().toShortString()
3005 + ": " + e.toString(), e);
3006 }
3007 }
3008 //System.out.println("Reporting top thumbnail " + thumbnail);
3009 try {
3010 ActivityManagerNative.getDefault().reportThumbnail(
3011 token, thumbnail, description);
3012 } catch (RemoteException ex) {
3013 }
3014 }
3015
3016 ArrayList<ComponentCallbacks> collectComponentCallbacksLocked(
3017 boolean allActivities, Configuration newConfig) {
3018 ArrayList<ComponentCallbacks> callbacks
3019 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07003020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003021 if (mActivities.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003022 Iterator<ActivityClientRecord> it = mActivities.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003023 while (it.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003024 ActivityClientRecord ar = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003025 Activity a = ar.activity;
3026 if (a != null) {
3027 if (!ar.activity.mFinished && (allActivities ||
3028 (a != null && !ar.paused))) {
3029 // If the activity is currently resumed, its configuration
3030 // needs to change right now.
3031 callbacks.add(a);
3032 } else if (newConfig != null) {
3033 // Otherwise, we will tell it about the change
3034 // the next time it is resumed or shown. Note that
3035 // the activity manager may, before then, decide the
3036 // activity needs to be destroyed to handle its new
3037 // configuration.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003038 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Setting activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003039 + ar.activityInfo.name + " newConfig=" + newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003040 ar.newConfig = newConfig;
3041 }
3042 }
3043 }
3044 }
3045 if (mServices.size() > 0) {
3046 Iterator<Service> it = mServices.values().iterator();
3047 while (it.hasNext()) {
3048 callbacks.add(it.next());
3049 }
3050 }
3051 synchronized (mProviderMap) {
3052 if (mLocalProviders.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003053 Iterator<ProviderClientRecord> it = mLocalProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003054 while (it.hasNext()) {
3055 callbacks.add(it.next().mLocalProvider);
3056 }
3057 }
3058 }
3059 final int N = mAllApplications.size();
3060 for (int i=0; i<N; i++) {
3061 callbacks.add(mAllApplications.get(i));
3062 }
Bob Leee5408332009-09-04 18:31:17 -07003063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003064 return callbacks;
3065 }
Bob Leee5408332009-09-04 18:31:17 -07003066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003067 private final void performConfigurationChanged(
3068 ComponentCallbacks cb, Configuration config) {
3069 // Only for Activity objects, check that they actually call up to their
3070 // superclass implementation. ComponentCallbacks is an interface, so
3071 // we check the runtime type and act accordingly.
3072 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
3073 if (activity != null) {
3074 activity.mCalled = false;
3075 }
Bob Leee5408332009-09-04 18:31:17 -07003076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003077 boolean shouldChangeConfig = false;
3078 if ((activity == null) || (activity.mCurrentConfig == null)) {
3079 shouldChangeConfig = true;
3080 } else {
Bob Leee5408332009-09-04 18:31:17 -07003081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003082 // If the new config is the same as the config this Activity
3083 // is already running with then don't bother calling
3084 // onConfigurationChanged
3085 int diff = activity.mCurrentConfig.diff(config);
3086 if (diff != 0) {
Bob Leee5408332009-09-04 18:31:17 -07003087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003088 // If this activity doesn't handle any of the config changes
3089 // then don't bother calling onConfigurationChanged as we're
3090 // going to destroy it.
3091 if ((~activity.mActivityInfo.configChanges & diff) == 0) {
3092 shouldChangeConfig = true;
3093 }
3094 }
3095 }
Bob Leee5408332009-09-04 18:31:17 -07003096
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003097 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003098 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003099 if (shouldChangeConfig) {
3100 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07003101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003102 if (activity != null) {
3103 if (!activity.mCalled) {
3104 throw new SuperNotCalledException(
3105 "Activity " + activity.getLocalClassName() +
3106 " did not call through to super.onConfigurationChanged()");
3107 }
3108 activity.mConfigChangeFlags = 0;
3109 activity.mCurrentConfig = new Configuration(config);
3110 }
3111 }
3112 }
3113
Dianne Hackbornae078162010-03-18 11:29:37 -07003114 final boolean applyConfigurationToResourcesLocked(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003115 if (mResConfiguration == null) {
3116 mResConfiguration = new Configuration();
3117 }
3118 if (!mResConfiguration.isOtherSeqNewer(config)) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003119 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq="
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003120 + mResConfiguration.seq + ", newSeq=" + config.seq);
Dianne Hackbornae078162010-03-18 11:29:37 -07003121 return false;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003122 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003123 int changes = mResConfiguration.updateFrom(config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003124 DisplayMetrics dm = getDisplayMetricsLocked(true);
Bob Leee5408332009-09-04 18:31:17 -07003125
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003126 // set it for java, this also affects newly created Resources
3127 if (config.locale != null) {
3128 Locale.setDefault(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003129 }
Bob Leee5408332009-09-04 18:31:17 -07003130
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003131 Resources.updateSystemConfiguration(config, dm);
Bob Leee5408332009-09-04 18:31:17 -07003132
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003133 ApplicationPackageManager.configurationChanged();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003134 //Slog.i(TAG, "Configuration changed in " + currentPackageName());
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003135
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003136 Iterator<WeakReference<Resources>> it =
3137 mActiveResources.values().iterator();
3138 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
3139 // mActiveResources.entrySet().iterator();
3140 while (it.hasNext()) {
3141 WeakReference<Resources> v = it.next();
3142 Resources r = v.get();
3143 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003144 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources "
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003145 + r + " config to: " + config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003146 r.updateConfiguration(config, dm);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003147 //Slog.i(TAG, "Updated app resources " + v.getKey()
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003148 // + " " + r + ": " + r.getConfiguration());
3149 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003150 //Slog.i(TAG, "Removing old resources " + v.getKey());
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003151 it.remove();
3152 }
3153 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003154
3155 return changes != 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003156 }
3157
3158 final void handleConfigurationChanged(Configuration config) {
3159
3160 ArrayList<ComponentCallbacks> callbacks = null;
3161
3162 synchronized (mPackages) {
3163 if (mPendingConfiguration != null) {
3164 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
3165 config = mPendingConfiguration;
3166 }
3167 mPendingConfiguration = null;
3168 }
3169
3170 if (config == null) {
3171 return;
3172 }
3173
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003174 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003175 + config);
3176
3177 applyConfigurationToResourcesLocked(config);
3178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003179 if (mConfiguration == null) {
3180 mConfiguration = new Configuration();
3181 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003182 if (!mConfiguration.isOtherSeqNewer(config)) {
3183 return;
3184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003185 mConfiguration.updateFrom(config);
Bob Leee5408332009-09-04 18:31:17 -07003186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003187 callbacks = collectComponentCallbacksLocked(false, config);
3188 }
Bob Leee5408332009-09-04 18:31:17 -07003189
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003190 if (callbacks != null) {
3191 final int N = callbacks.size();
3192 for (int i=0; i<N; i++) {
3193 performConfigurationChanged(callbacks.get(i), config);
3194 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003195 }
3196 }
3197
3198 final void handleActivityConfigurationChanged(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003199 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003200 if (r == null || r.activity == null) {
3201 return;
3202 }
Bob Leee5408332009-09-04 18:31:17 -07003203
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003204 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003205 + r.activityInfo.name);
3206
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003207 performConfigurationChanged(r.activity, mConfiguration);
3208 }
3209
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003210 final void handleProfilerControl(boolean start, ProfilerControlData pcd) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003211 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003212 try {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003213 Debug.startMethodTracing(pcd.path, pcd.fd.getFileDescriptor(),
3214 8 * 1024 * 1024, 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003215 } catch (RuntimeException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003216 Slog.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003217 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003218 } finally {
3219 try {
3220 pcd.fd.close();
3221 } catch (IOException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003222 Slog.w(TAG, "Failure closing profile fd", e);
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003223 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003224 }
3225 } else {
3226 Debug.stopMethodTracing();
3227 }
3228 }
Bob Leee5408332009-09-04 18:31:17 -07003229
Andy McFadden824c5102010-07-09 16:26:57 -07003230 final void handleDumpHeap(boolean managed, DumpHeapData dhd) {
3231 if (managed) {
3232 try {
3233 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor());
3234 } catch (IOException e) {
3235 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
3236 + " -- can the process access this path?");
3237 } finally {
3238 try {
3239 dhd.fd.close();
3240 } catch (IOException e) {
3241 Slog.w(TAG, "Failure closing profile fd", e);
3242 }
3243 }
3244 } else {
Andy McFadden06a6b552010-07-13 16:28:09 -07003245 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07003246 }
3247 }
3248
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003249 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
3250 boolean hasPkgInfo = false;
3251 if (packages != null) {
3252 for (int i=packages.length-1; i>=0; i--) {
3253 //Slog.i(TAG, "Cleaning old package: " + packages[i]);
3254 if (!hasPkgInfo) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003255 WeakReference<LoadedApk> ref;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003256 ref = mPackages.get(packages[i]);
3257 if (ref != null && ref.get() != null) {
3258 hasPkgInfo = true;
3259 } else {
3260 ref = mResourcePackages.get(packages[i]);
3261 if (ref != null && ref.get() != null) {
3262 hasPkgInfo = true;
3263 }
3264 }
3265 }
3266 mPackages.remove(packages[i]);
3267 mResourcePackages.remove(packages[i]);
3268 }
3269 }
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003270 ApplicationPackageManager.handlePackageBroadcast(cmd, packages,
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003271 hasPkgInfo);
3272 }
3273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003274 final void handleLowMemory() {
3275 ArrayList<ComponentCallbacks> callbacks
3276 = new ArrayList<ComponentCallbacks>();
3277
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003278 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279 callbacks = collectComponentCallbacksLocked(true, null);
3280 }
Bob Leee5408332009-09-04 18:31:17 -07003281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003282 final int N = callbacks.size();
3283 for (int i=0; i<N; i++) {
3284 callbacks.get(i).onLowMemory();
3285 }
3286
Chris Tatece229052009-03-25 16:44:52 -07003287 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3288 if (Process.myUid() != Process.SYSTEM_UID) {
3289 int sqliteReleased = SQLiteDatabase.releaseMemory();
3290 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3291 }
Bob Leee5408332009-09-04 18:31:17 -07003292
Mike Reedcaf0df12009-04-27 14:32:05 -04003293 // Ask graphics to free up as much as possible (font/image caches)
3294 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003295
3296 BinderInternal.forceGc("mem");
3297 }
3298
3299 private final void handleBindApplication(AppBindData data) {
3300 mBoundApplication = data;
3301 mConfiguration = new Configuration(data.config);
3302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003304 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003305 android.ddm.DdmHandleAppName.setAppName(data.processName);
3306
3307 /*
3308 * Before spawning a new process, reset the time zone to be the system time zone.
3309 * This needs to be done because the system time zone could have changed after the
3310 * the spawning of this process. Without doing this this process would have the incorrect
3311 * system time zone.
3312 */
3313 TimeZone.setDefault(null);
3314
3315 /*
3316 * Initialize the default locale in this process for the reasons we set the time zone.
3317 */
3318 Locale.setDefault(data.config.locale);
3319
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003320 /*
3321 * Update the system configuration since its preloaded and might not
3322 * reflect configuration changes. The configuration object passed
3323 * in AppBindData can be safely assumed to be up to date
3324 */
3325 Resources.getSystem().updateConfiguration(mConfiguration, null);
3326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003327 data.info = getPackageInfoNoCheck(data.appInfo);
3328
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003329 /**
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003330 * For system applications on userdebug/eng builds, log stack
3331 * traces of disk and network access to dropbox for analysis.
3332 */
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07003333 if ((data.appInfo.flags &
3334 (ApplicationInfo.FLAG_SYSTEM |
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07003335 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0) {
3336 StrictMode.conditionallyEnableDebugLogging();
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003337 }
3338
3339 /**
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07003340 * For apps targetting SDK Honeycomb or later, we don't allow
3341 * network usage on the main event loop / UI thread.
3342 *
3343 * Note to those grepping: this is what ultimately throws
3344 * NetworkOnMainThreadException ...
3345 */
3346 if (data.appInfo.targetSdkVersion > 9) {
3347 StrictMode.enableDeathOnNetwork();
3348 }
3349
3350 /**
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003351 * Switch this process to density compatibility mode if needed.
3352 */
3353 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3354 == 0) {
3355 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3356 }
Bob Leee5408332009-09-04 18:31:17 -07003357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3359 // XXX should have option to change the port.
3360 Debug.changeDebugPort(8100);
3361 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003362 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 + " is waiting for the debugger on port 8100...");
3364
3365 IActivityManager mgr = ActivityManagerNative.getDefault();
3366 try {
3367 mgr.showWaitingForDebugger(mAppThread, true);
3368 } catch (RemoteException ex) {
3369 }
3370
3371 Debug.waitForDebugger();
3372
3373 try {
3374 mgr.showWaitingForDebugger(mAppThread, false);
3375 } catch (RemoteException ex) {
3376 }
3377
3378 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003379 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 + " can be debugged on port 8100...");
3381 }
3382 }
3383
Robert Greenwalt434203a2010-10-11 16:00:27 -07003384 /**
3385 * Initialize the default http proxy in this process for the reasons we set the time zone.
3386 */
3387 IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
3388 IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
3389 try {
3390 ProxyProperties proxyProperties = service.getProxy();
3391 Proxy.setHttpProxySystemProperty(proxyProperties);
3392 } catch (RemoteException e) {}
3393
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003394 if (data.instrumentationName != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08003395 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003396 appContext.init(data.info, null, this);
3397 InstrumentationInfo ii = null;
3398 try {
3399 ii = appContext.getPackageManager().
3400 getInstrumentationInfo(data.instrumentationName, 0);
3401 } catch (PackageManager.NameNotFoundException e) {
3402 }
3403 if (ii == null) {
3404 throw new RuntimeException(
3405 "Unable to find instrumentation info for: "
3406 + data.instrumentationName);
3407 }
3408
3409 mInstrumentationAppDir = ii.sourceDir;
3410 mInstrumentationAppPackage = ii.packageName;
3411 mInstrumentedAppDir = data.info.getAppDir();
3412
3413 ApplicationInfo instrApp = new ApplicationInfo();
3414 instrApp.packageName = ii.packageName;
3415 instrApp.sourceDir = ii.sourceDir;
3416 instrApp.publicSourceDir = ii.publicSourceDir;
3417 instrApp.dataDir = ii.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003418 instrApp.nativeLibraryDir = ii.nativeLibraryDir;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003419 LoadedApk pi = getPackageInfo(instrApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420 appContext.getClassLoader(), false, true);
Dianne Hackborn21556372010-02-04 16:34:40 -08003421 ContextImpl instrContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003422 instrContext.init(pi, null, this);
3423
3424 try {
3425 java.lang.ClassLoader cl = instrContext.getClassLoader();
3426 mInstrumentation = (Instrumentation)
3427 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3428 } catch (Exception e) {
3429 throw new RuntimeException(
3430 "Unable to instantiate instrumentation "
3431 + data.instrumentationName + ": " + e.toString(), e);
3432 }
3433
3434 mInstrumentation.init(this, instrContext, appContext,
3435 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3436
3437 if (data.profileFile != null && !ii.handleProfiling) {
3438 data.handlingProfiling = true;
3439 File file = new File(data.profileFile);
3440 file.getParentFile().mkdirs();
3441 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3442 }
3443
3444 try {
3445 mInstrumentation.onCreate(data.instrumentationArgs);
3446 }
3447 catch (Exception e) {
3448 throw new RuntimeException(
3449 "Exception thrown in onCreate() of "
3450 + data.instrumentationName + ": " + e.toString(), e);
3451 }
3452
3453 } else {
3454 mInstrumentation = new Instrumentation();
3455 }
3456
Christopher Tate181fafa2009-05-14 11:12:14 -07003457 // If the app is being launched for full backup or restore, bring it up in
3458 // a restricted environment with the base application class.
Dianne Hackborn0be1f782009-11-09 12:30:12 -08003459 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003460 mInitialApplication = app;
3461
3462 List<ProviderInfo> providers = data.providers;
3463 if (providers != null) {
3464 installContentProviders(app, providers);
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003465 // For process that contain content providers, we want to
3466 // ensure that the JIT is enabled "at some point".
3467 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468 }
3469
3470 try {
3471 mInstrumentation.callApplicationOnCreate(app);
3472 } catch (Exception e) {
3473 if (!mInstrumentation.onException(app, e)) {
3474 throw new RuntimeException(
3475 "Unable to create application " + app.getClass().getName()
3476 + ": " + e.toString(), e);
3477 }
3478 }
3479 }
3480
3481 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
3482 IActivityManager am = ActivityManagerNative.getDefault();
3483 if (mBoundApplication.profileFile != null && mBoundApplication.handlingProfiling) {
3484 Debug.stopMethodTracing();
3485 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003486 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003487 // + ", app thr: " + mAppThread);
3488 try {
3489 am.finishInstrumentation(mAppThread, resultCode, results);
3490 } catch (RemoteException ex) {
3491 }
3492 }
3493
3494 private final void installContentProviders(
3495 Context context, List<ProviderInfo> providers) {
3496 final ArrayList<IActivityManager.ContentProviderHolder> results =
3497 new ArrayList<IActivityManager.ContentProviderHolder>();
3498
3499 Iterator<ProviderInfo> i = providers.iterator();
3500 while (i.hasNext()) {
3501 ProviderInfo cpi = i.next();
3502 StringBuilder buf = new StringBuilder(128);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07003503 buf.append("Pub ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003504 buf.append(cpi.authority);
3505 buf.append(": ");
3506 buf.append(cpi.name);
3507 Log.i(TAG, buf.toString());
3508 IContentProvider cp = installProvider(context, null, cpi, false);
3509 if (cp != null) {
3510 IActivityManager.ContentProviderHolder cph =
3511 new IActivityManager.ContentProviderHolder(cpi);
3512 cph.provider = cp;
3513 results.add(cph);
3514 // Don't ever unload this provider from the process.
3515 synchronized(mProviderMap) {
3516 mProviderRefCountMap.put(cp.asBinder(), new ProviderRefCount(10000));
3517 }
3518 }
3519 }
3520
3521 try {
3522 ActivityManagerNative.getDefault().publishContentProviders(
3523 getApplicationThread(), results);
3524 } catch (RemoteException ex) {
3525 }
3526 }
3527
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003528 private final IContentProvider getExistingProvider(Context context, String name) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003529 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003530 final ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003531 if (pr != null) {
3532 return pr.mProvider;
3533 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003534 return null;
3535 }
3536 }
3537
3538 private final IContentProvider getProvider(Context context, String name) {
3539 IContentProvider existing = getExistingProvider(context, name);
3540 if (existing != null) {
3541 return existing;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003542 }
3543
3544 IActivityManager.ContentProviderHolder holder = null;
3545 try {
3546 holder = ActivityManagerNative.getDefault().getContentProvider(
3547 getApplicationThread(), name);
3548 } catch (RemoteException ex) {
3549 }
3550 if (holder == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003551 Slog.e(TAG, "Failed to find provider info for " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003552 return null;
3553 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003554
3555 IContentProvider prov = installProvider(context, holder.provider,
3556 holder.info, true);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003557 //Slog.i(TAG, "noReleaseNeeded=" + holder.noReleaseNeeded);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003558 if (holder.noReleaseNeeded || holder.provider == null) {
3559 // We are not going to release the provider if it is an external
3560 // provider that doesn't care about being released, or if it is
3561 // a local provider running in this process.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003562 //Slog.i(TAG, "*** NO RELEASE NEEDED");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003563 synchronized(mProviderMap) {
3564 mProviderRefCountMap.put(prov.asBinder(), new ProviderRefCount(10000));
3565 }
3566 }
3567 return prov;
3568 }
3569
3570 public final IContentProvider acquireProvider(Context c, String name) {
3571 IContentProvider provider = getProvider(c, name);
3572 if(provider == null)
3573 return null;
3574 IBinder jBinder = provider.asBinder();
3575 synchronized(mProviderMap) {
3576 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3577 if(prc == null) {
3578 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3579 } else {
3580 prc.count++;
3581 } //end else
3582 } //end synchronized
3583 return provider;
3584 }
3585
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003586 public final IContentProvider acquireExistingProvider(Context c, String name) {
3587 IContentProvider provider = getExistingProvider(c, name);
3588 if(provider == null)
3589 return null;
3590 IBinder jBinder = provider.asBinder();
3591 synchronized(mProviderMap) {
3592 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3593 if(prc == null) {
3594 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3595 } else {
3596 prc.count++;
3597 } //end else
3598 } //end synchronized
3599 return provider;
3600 }
3601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003602 public final boolean releaseProvider(IContentProvider provider) {
3603 if(provider == null) {
3604 return false;
3605 }
3606 IBinder jBinder = provider.asBinder();
3607 synchronized(mProviderMap) {
3608 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3609 if(prc == null) {
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003610 if(localLOGV) Slog.v(TAG, "releaseProvider::Weird shouldn't be here");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003611 return false;
3612 } else {
3613 prc.count--;
3614 if(prc.count == 0) {
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003615 // Schedule the actual remove asynchronously, since we
3616 // don't know the context this will be called in.
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003617 // TODO: it would be nice to post a delayed message, so
3618 // if we come back and need the same provider quickly
3619 // we will still have it available.
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003620 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
3621 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003622 } //end if
3623 } //end else
3624 } //end synchronized
3625 return true;
3626 }
3627
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003628 final void completeRemoveProvider(IContentProvider provider) {
3629 IBinder jBinder = provider.asBinder();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003630 String name = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003631 synchronized(mProviderMap) {
3632 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3633 if(prc != null && prc.count == 0) {
3634 mProviderRefCountMap.remove(jBinder);
3635 //invoke removeProvider to dereference provider
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003636 name = removeProviderLocked(provider);
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003637 }
3638 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003639
3640 if (name != null) {
3641 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003642 if(localLOGV) Slog.v(TAG, "removeProvider::Invoking " +
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003643 "ActivityManagerNative.removeContentProvider(" + name);
3644 ActivityManagerNative.getDefault().removeContentProvider(
3645 getApplicationThread(), name);
3646 } catch (RemoteException e) {
3647 //do nothing content provider object is dead any way
3648 } //end catch
3649 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003650 }
3651
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003652 public final String removeProviderLocked(IContentProvider provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003653 if (provider == null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003654 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003655 }
3656 IBinder providerBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003657
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003658 String name = null;
3659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003660 // remove the provider from mProviderMap
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003661 Iterator<ProviderClientRecord> iter = mProviderMap.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003662 while (iter.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003663 ProviderClientRecord pr = iter.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003664 IBinder myBinder = pr.mProvider.asBinder();
3665 if (myBinder == providerBinder) {
3666 //find if its published by this process itself
3667 if(pr.mLocalProvider != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003668 if(localLOGV) Slog.i(TAG, "removeProvider::found local provider returning");
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003669 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003670 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003671 if(localLOGV) Slog.v(TAG, "removeProvider::Not local provider Unlinking " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003672 "death recipient");
3673 //content provider is in another process
3674 myBinder.unlinkToDeath(pr, 0);
3675 iter.remove();
3676 //invoke remove only once for the very first name seen
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003677 if(name == null) {
3678 name = pr.mName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003679 }
3680 } //end if myBinder
3681 } //end while iter
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003682
3683 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003684 }
3685
3686 final void removeDeadProvider(String name, IContentProvider provider) {
3687 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003688 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003689 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003690 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003691 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003692 if (removed != null) {
3693 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3694 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003695 }
3696 }
3697 }
3698
3699 final void removeDeadProviderLocked(String name, IContentProvider provider) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003700 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003701 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003702 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003703 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003704 if (removed != null) {
3705 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3706 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003707 }
3708 }
3709
3710 private final IContentProvider installProvider(Context context,
3711 IContentProvider provider, ProviderInfo info, boolean noisy) {
3712 ContentProvider localProvider = null;
3713 if (provider == null) {
3714 if (noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003715 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003716 + info.name);
3717 }
3718 Context c = null;
3719 ApplicationInfo ai = info.applicationInfo;
3720 if (context.getPackageName().equals(ai.packageName)) {
3721 c = context;
3722 } else if (mInitialApplication != null &&
3723 mInitialApplication.getPackageName().equals(ai.packageName)) {
3724 c = mInitialApplication;
3725 } else {
3726 try {
3727 c = context.createPackageContext(ai.packageName,
3728 Context.CONTEXT_INCLUDE_CODE);
3729 } catch (PackageManager.NameNotFoundException e) {
3730 }
3731 }
3732 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003733 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003734 ai.packageName +
3735 " while loading content provider " +
3736 info.name);
3737 return null;
3738 }
3739 try {
3740 final java.lang.ClassLoader cl = c.getClassLoader();
3741 localProvider = (ContentProvider)cl.
3742 loadClass(info.name).newInstance();
3743 provider = localProvider.getIContentProvider();
3744 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003745 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 info.name + " from sourceDir " +
3747 info.applicationInfo.sourceDir);
3748 return null;
3749 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003750 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003751 TAG, "Instantiating local provider " + info.name);
3752 // XXX Need to create the correct context for this provider.
3753 localProvider.attachInfo(c, info);
3754 } catch (java.lang.Exception e) {
3755 if (!mInstrumentation.onException(null, e)) {
3756 throw new RuntimeException(
3757 "Unable to get provider " + info.name
3758 + ": " + e.toString(), e);
3759 }
3760 return null;
3761 }
3762 } else if (localLOGV) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003763 Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003764 + info.name);
3765 }
3766
3767 synchronized (mProviderMap) {
3768 // Cache the pointer for the remote provider.
3769 String names[] = PATTERN_SEMICOLON.split(info.authority);
3770 for (int i=0; i<names.length; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003771 ProviderClientRecord pr = new ProviderClientRecord(names[i], provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003772 localProvider);
3773 try {
3774 provider.asBinder().linkToDeath(pr, 0);
3775 mProviderMap.put(names[i], pr);
3776 } catch (RemoteException e) {
3777 return null;
3778 }
3779 }
3780 if (localProvider != null) {
3781 mLocalProviders.put(provider.asBinder(),
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003782 new ProviderClientRecord(null, provider, localProvider));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003783 }
3784 }
3785
3786 return provider;
3787 }
3788
3789 private final void attach(boolean system) {
3790 sThreadLocal.set(this);
3791 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003792 if (!system) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003793 ViewRoot.addFirstDrawHandler(new Runnable() {
3794 public void run() {
3795 ensureJitEnabled();
3796 }
3797 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003798 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
3799 RuntimeInit.setApplicationObject(mAppThread.asBinder());
3800 IActivityManager mgr = ActivityManagerNative.getDefault();
3801 try {
3802 mgr.attachApplication(mAppThread);
3803 } catch (RemoteException ex) {
3804 }
3805 } else {
3806 // Don't set application object here -- if the system crashes,
3807 // we can't display an alert, we just want to die die die.
3808 android.ddm.DdmHandleAppName.setAppName("system_process");
3809 try {
3810 mInstrumentation = new Instrumentation();
Dianne Hackborn21556372010-02-04 16:34:40 -08003811 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003812 context.init(getSystemContext().mPackageInfo, null, this);
3813 Application app = Instrumentation.newApplication(Application.class, context);
3814 mAllApplications.add(app);
3815 mInitialApplication = app;
3816 app.onCreate();
3817 } catch (Exception e) {
3818 throw new RuntimeException(
3819 "Unable to instantiate Application():" + e.toString(), e);
3820 }
3821 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003822
3823 ViewRoot.addConfigCallback(new ComponentCallbacks() {
3824 public void onConfigurationChanged(Configuration newConfig) {
3825 synchronized (mPackages) {
Dianne Hackbornae078162010-03-18 11:29:37 -07003826 // We need to apply this change to the resources
3827 // immediately, because upon returning the view
3828 // hierarchy will be informed about it.
3829 if (applyConfigurationToResourcesLocked(newConfig)) {
3830 // This actually changed the resources! Tell
3831 // everyone about it.
3832 if (mPendingConfiguration == null ||
3833 mPendingConfiguration.isOtherSeqNewer(newConfig)) {
3834 mPendingConfiguration = newConfig;
3835
3836 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
3837 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003838 }
3839 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003840 }
3841 public void onLowMemory() {
3842 }
3843 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003844 }
3845
3846 private final void detach()
3847 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003848 sThreadLocal.set(null);
3849 }
3850
3851 public static final ActivityThread systemMain() {
Romain Guy52339202010-09-03 16:04:46 -07003852 HardwareRenderer.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003853 ActivityThread thread = new ActivityThread();
3854 thread.attach(true);
3855 return thread;
3856 }
3857
3858 public final void installSystemProviders(List providers) {
3859 if (providers != null) {
3860 installContentProviders(mInitialApplication,
3861 (List<ProviderInfo>)providers);
3862 }
3863 }
3864
3865 public static final void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07003866 SamplingProfilerIntegration.start();
3867
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -08003868 // CloseGuard defaults to true and can be quite spammy. We
3869 // disable it here, but selectively enable it later (via
3870 // StrictMode) on debug builds, but using DropBox, not logs.
3871 CloseGuard.setEnabled(false);
3872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003873 Process.setArgV0("<pre-initialized>");
3874
3875 Looper.prepareMainLooper();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07003876 if (sMainThreadHandler == null) {
3877 sMainThreadHandler = new Handler();
3878 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003879
3880 ActivityThread thread = new ActivityThread();
3881 thread.attach(false);
3882
Dianne Hackborn287952c2010-09-22 22:34:31 -07003883 if (false) {
3884 Looper.myLooper().setMessageLogging(new
3885 LogPrinter(Log.DEBUG, "ActivityThread"));
3886 }
3887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 Looper.loop();
3889
3890 if (Process.supportsProcesses()) {
3891 throw new RuntimeException("Main thread loop unexpectedly exited");
3892 }
3893
3894 thread.detach();
Bob Leeeec2f412009-09-10 11:01:24 +02003895 String name = (thread.mInitialApplication != null)
3896 ? thread.mInitialApplication.getPackageName()
3897 : "<unknown>";
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003898 Slog.i(TAG, "Main thread of " + name + " is now exiting");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003899 }
3900}