blob: db046ef73597460b5df735b33badf27b5dc55d90 [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.os.Bundle;
49import android.os.Debug;
50import android.os.Handler;
51import android.os.IBinder;
52import android.os.Looper;
53import android.os.Message;
54import android.os.MessageQueue;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070055import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.os.Process;
57import android.os.RemoteException;
58import android.os.ServiceManager;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070059import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.os.SystemClock;
61import android.util.AndroidRuntimeException;
62import android.util.Config;
63import android.util.DisplayMetrics;
64import android.util.EventLog;
65import android.util.Log;
Dianne Hackborn287952c2010-09-22 22:34:31 -070066import android.util.LogPrinter;
Dianne Hackbornc9421ba2010-03-11 22:23:46 -080067import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.view.Display;
Romain Guy52339202010-09-03 16:04:46 -070069import android.view.HardwareRenderer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.view.View;
71import android.view.ViewDebug;
72import android.view.ViewManager;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -080073import android.view.ViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import android.view.Window;
75import android.view.WindowManager;
76import android.view.WindowManagerImpl;
77
78import com.android.internal.os.BinderInternal;
79import com.android.internal.os.RuntimeInit;
Bob Leee5408332009-09-04 18:31:17 -070080import com.android.internal.os.SamplingProfilerIntegration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081
82import org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl;
83
84import java.io.File;
85import java.io.FileDescriptor;
86import java.io.FileOutputStream;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070087import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import java.io.PrintWriter;
89import java.lang.ref.WeakReference;
Robert Greenwalt03595d02010-11-02 14:08:23 -070090import java.net.InetAddress;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import java.util.ArrayList;
92import java.util.HashMap;
93import java.util.Iterator;
94import java.util.List;
95import java.util.Locale;
96import java.util.Map;
97import java.util.TimeZone;
98import java.util.regex.Pattern;
99
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -0800100import dalvik.system.CloseGuard;
Bob Leee5408332009-09-04 18:31:17 -0700101import dalvik.system.SamplingProfiler;
102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103final class SuperNotCalledException extends AndroidRuntimeException {
104 public SuperNotCalledException(String msg) {
105 super(msg);
106 }
107}
108
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700109final class RemoteServiceException extends AndroidRuntimeException {
110 public RemoteServiceException(String msg) {
111 super(msg);
112 }
113}
114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115/**
116 * This manages the execution of the main thread in an
117 * application process, scheduling and executing activities,
118 * broadcasts, and other operations on it as the activity
119 * manager requests.
120 *
121 * {@hide}
122 */
123public final class ActivityThread {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700124 /** @hide */
125 public static final String TAG = "ActivityThread";
Jim Miller0b2a6d02010-07-13 18:01:29 -0700126 private static final android.graphics.Bitmap.Config THUMBNAIL_FORMAT = Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 private static final boolean DEBUG = false;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700128 static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700129 static final boolean DEBUG_MESSAGES = false;
Dianne Hackborne829fef2010-10-26 17:44:01 -0700130 /** @hide */
131 public static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700132 private static final boolean DEBUG_RESULTS = false;
Christopher Tate436344a2009-09-30 16:17:37 -0700133 private static final boolean DEBUG_BACKUP = false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700134 private static final boolean DEBUG_CONFIGURATION = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
136 private static final Pattern PATTERN_SEMICOLON = Pattern.compile(";");
137 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
138 private static final int LOG_ON_PAUSE_CALLED = 30021;
139 private static final int LOG_ON_RESUME_CALLED = 30022;
140
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700141 static ContextImpl mSystemContext = null;
Bob Leee5408332009-09-04 18:31:17 -0700142
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700143 static IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700145 final ApplicationThread mAppThread = new ApplicationThread();
146 final Looper mLooper = Looper.myLooper();
147 final H mH = new H();
148 final HashMap<IBinder, ActivityClientRecord> mActivities
149 = new HashMap<IBinder, ActivityClientRecord>();
150 // List of new activities (via ActivityRecord.nextIdle) that should
151 // be reported when next we idle.
152 ActivityClientRecord mNewActivities = null;
153 // Number of activities that are currently visible on-screen.
154 int mNumVisibleActivities = 0;
155 final HashMap<IBinder, Service> mServices
156 = new HashMap<IBinder, Service>();
157 AppBindData mBoundApplication;
158 Configuration mConfiguration;
159 Configuration mResConfiguration;
160 Application mInitialApplication;
161 final ArrayList<Application> mAllApplications
162 = new ArrayList<Application>();
163 // set of instantiated backup agents, keyed by package name
164 final HashMap<String, BackupAgent> mBackupAgents = new HashMap<String, BackupAgent>();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700165 static final ThreadLocal<ActivityThread> sThreadLocal = new ThreadLocal();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700166 Instrumentation mInstrumentation;
167 String mInstrumentationAppDir = null;
168 String mInstrumentationAppPackage = null;
169 String mInstrumentedAppDir = null;
170 boolean mSystemThread = false;
171 boolean mJitEnabled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700173 // These can be accessed by multiple threads; mPackages is the lock.
174 // XXX For now we keep around information about all packages we have
175 // seen, not removing entries from this map.
176 final HashMap<String, WeakReference<LoadedApk>> mPackages
177 = new HashMap<String, WeakReference<LoadedApk>>();
178 final HashMap<String, WeakReference<LoadedApk>> mResourcePackages
179 = new HashMap<String, WeakReference<LoadedApk>>();
180 Display mDisplay = null;
181 DisplayMetrics mDisplayMetrics = null;
182 final HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources
183 = new HashMap<ResourcesKey, WeakReference<Resources> >();
184 final ArrayList<ActivityClientRecord> mRelaunchingActivities
185 = new ArrayList<ActivityClientRecord>();
186 Configuration mPendingConfiguration = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700188 // The lock of mProviderMap protects the following variables.
189 final HashMap<String, ProviderClientRecord> mProviderMap
190 = new HashMap<String, ProviderClientRecord>();
191 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap
192 = new HashMap<IBinder, ProviderRefCount>();
193 final HashMap<IBinder, ProviderClientRecord> mLocalProviders
194 = new HashMap<IBinder, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700196 final GcIdler mGcIdler = new GcIdler();
197 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700199 static Handler sMainThreadHandler; // set once in main()
200
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700201 private static final class ActivityClientRecord {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700203 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 Intent intent;
205 Bundle state;
206 Activity activity;
207 Window window;
208 Activity parent;
209 String embeddedID;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700210 Activity.NonConfigurationInstances lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 boolean paused;
212 boolean stopped;
213 boolean hideForNow;
214 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700215 Configuration createdConfig;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700216 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217
218 ActivityInfo activityInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700219 LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220
221 List<ResultInfo> pendingResults;
222 List<Intent> pendingIntents;
223
224 boolean startsNotResumed;
225 boolean isForward;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800226 int pendingConfigChanges;
227 boolean onlyLocalRequest;
228
229 View mPendingRemoveWindow;
230 WindowManager mPendingRemoveWindowManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700232 ActivityClientRecord() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 parent = null;
234 embeddedID = null;
235 paused = false;
236 stopped = false;
237 hideForNow = false;
238 nextIdle = null;
239 }
240
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800241 public boolean isPreHoneycomb() {
242 if (activity != null) {
243 return activity.getApplicationInfo().targetSdkVersion
244 < android.os.Build.VERSION_CODES.HONEYCOMB;
245 }
246 return false;
247 }
248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249 public String toString() {
250 ComponentName componentName = intent.getComponent();
251 return "ActivityRecord{"
252 + Integer.toHexString(System.identityHashCode(this))
253 + " token=" + token + " " + (componentName == null
254 ? "no component name" : componentName.toShortString())
255 + "}";
256 }
257 }
258
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700259 private final class ProviderClientRecord implements IBinder.DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 final String mName;
261 final IContentProvider mProvider;
262 final ContentProvider mLocalProvider;
263
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700264 ProviderClientRecord(String name, IContentProvider provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 ContentProvider localProvider) {
266 mName = name;
267 mProvider = provider;
268 mLocalProvider = localProvider;
269 }
270
271 public void binderDied() {
272 removeDeadProvider(mName, mProvider);
273 }
274 }
275
276 private static final class NewIntentData {
277 List<Intent> intents;
278 IBinder token;
279 public String toString() {
280 return "NewIntentData{intents=" + intents + " token=" + token + "}";
281 }
282 }
283
Dianne Hackborne829fef2010-10-26 17:44:01 -0700284 private static final class ReceiverData extends BroadcastReceiver.PendingResult {
285 public ReceiverData(Intent intent, int resultCode, String resultData, Bundle resultExtras,
286 boolean ordered, boolean sticky, IBinder token) {
287 super(resultCode, resultData, resultExtras, TYPE_COMPONENT, ordered, sticky, token);
288 this.intent = intent;
289 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291 Intent intent;
292 ActivityInfo info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800293 public String toString() {
294 return "ReceiverData{intent=" + intent + " packageName=" +
Dianne Hackborne829fef2010-10-26 17:44:01 -0700295 info.packageName + " resultCode=" + getResultCode()
296 + " resultData=" + getResultData() + " resultExtras="
297 + getResultExtras(false) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298 }
299 }
300
Christopher Tate181fafa2009-05-14 11:12:14 -0700301 private static final class CreateBackupAgentData {
302 ApplicationInfo appInfo;
303 int backupMode;
304 public String toString() {
305 return "CreateBackupAgentData{appInfo=" + appInfo
306 + " backupAgent=" + appInfo.backupAgentName
307 + " mode=" + backupMode + "}";
308 }
309 }
Bob Leee5408332009-09-04 18:31:17 -0700310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 private static final class CreateServiceData {
312 IBinder token;
313 ServiceInfo info;
314 Intent intent;
315 public String toString() {
316 return "CreateServiceData{token=" + token + " className="
317 + info.name + " packageName=" + info.packageName
318 + " intent=" + intent + "}";
319 }
320 }
321
322 private static final class BindServiceData {
323 IBinder token;
324 Intent intent;
325 boolean rebind;
326 public String toString() {
327 return "BindServiceData{token=" + token + " intent=" + intent + "}";
328 }
329 }
330
331 private static final class ServiceArgsData {
332 IBinder token;
333 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700334 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335 Intent args;
336 public String toString() {
337 return "ServiceArgsData{token=" + token + " startId=" + startId
338 + " args=" + args + "}";
339 }
340 }
341
342 private static final class AppBindData {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700343 LoadedApk info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344 String processName;
345 ApplicationInfo appInfo;
346 List<ProviderInfo> providers;
347 ComponentName instrumentationName;
348 String profileFile;
349 Bundle instrumentationArgs;
350 IInstrumentationWatcher instrumentationWatcher;
351 int debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700352 boolean restrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 Configuration config;
354 boolean handlingProfiling;
355 public String toString() {
356 return "AppBindData{appInfo=" + appInfo + "}";
357 }
358 }
359
Dianne Hackborn625ac272010-09-17 18:29:22 -0700360 private static final class DumpComponentInfo {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 FileDescriptor fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700362 IBinder token;
Dianne Hackborn30d71892010-12-11 10:37:55 -0800363 String prefix;
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
Dianne Hackborn30d71892010-12-11 10:37:55 -0800683 public void dumpActivity(FileDescriptor fd, IBinder activitytoken,
684 String prefix, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700685 DumpComponentInfo data = new DumpComponentInfo();
686 data.fd = fd;
687 data.token = activitytoken;
Dianne Hackborn30d71892010-12-11 10:37:55 -0800688 data.prefix = prefix;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700689 data.args = args;
690 data.dumped = false;
691 queueOrSendMessage(H.DUMP_ACTIVITY, data);
692 synchronized (data) {
693 while (!data.dumped) {
694 try {
695 data.wait();
696 } catch (InterruptedException e) {
697 // no need to do anything here, we will keep waiting until
698 // dumped is set
699 }
700 }
701 }
702 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 @Override
705 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
706 long nativeMax = Debug.getNativeHeapSize() / 1024;
707 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
708 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
709
710 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
711 Debug.getMemoryInfo(memInfo);
712
713 final int nativeShared = memInfo.nativeSharedDirty;
714 final int dalvikShared = memInfo.dalvikSharedDirty;
715 final int otherShared = memInfo.otherSharedDirty;
716
717 final int nativePrivate = memInfo.nativePrivateDirty;
718 final int dalvikPrivate = memInfo.dalvikPrivateDirty;
719 final int otherPrivate = memInfo.otherPrivateDirty;
720
721 Runtime runtime = Runtime.getRuntime();
722
723 long dalvikMax = runtime.totalMemory() / 1024;
724 long dalvikFree = runtime.freeMemory() / 1024;
725 long dalvikAllocated = dalvikMax - dalvikFree;
726 long viewInstanceCount = ViewDebug.getViewInstanceCount();
727 long viewRootInstanceCount = ViewDebug.getViewRootInstanceCount();
Brian Carlstromc21550a2010-10-05 21:34:06 -0700728 long appContextInstanceCount = Debug.countInstancesOfClass(ContextImpl.class);
729 long activityInstanceCount = Debug.countInstancesOfClass(Activity.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 int globalAssetCount = AssetManager.getGlobalAssetCount();
731 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
732 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
733 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
734 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
Brian Carlstromc9d5b312010-10-05 22:23:41 -0700735 long openSslSocketCount = Debug.countInstancesOfClass(OpenSSLSocketImpl.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024;
Vasu Noric3849202010-03-09 10:47:25 -0800737 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -0700738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 // Check to see if we were called by checkin server. If so, print terse format.
740 boolean doCheckinFormat = false;
741 if (args != null) {
742 for (String arg : args) {
743 if ("-c".equals(arg)) doCheckinFormat = true;
744 }
745 }
Bob Leee5408332009-09-04 18:31:17 -0700746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 // For checkin, we print one long comma-separated list of values
748 if (doCheckinFormat) {
749 // NOTE: if you change anything significant below, also consider changing
750 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -0700751 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -0700753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 // Header
755 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
756 pw.print(Process.myPid()); pw.print(',');
757 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 // Heap info - max
760 pw.print(nativeMax); pw.print(',');
761 pw.print(dalvikMax); pw.print(',');
762 pw.print("N/A,");
763 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 // Heap info - allocated
766 pw.print(nativeAllocated); pw.print(',');
767 pw.print(dalvikAllocated); pw.print(',');
768 pw.print("N/A,");
769 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 // Heap info - free
772 pw.print(nativeFree); pw.print(',');
773 pw.print(dalvikFree); pw.print(',');
774 pw.print("N/A,");
775 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 // Heap info - proportional set size
778 pw.print(memInfo.nativePss); pw.print(',');
779 pw.print(memInfo.dalvikPss); pw.print(',');
780 pw.print(memInfo.otherPss); pw.print(',');
781 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800783 // Heap info - shared
Bob Leee5408332009-09-04 18:31:17 -0700784 pw.print(nativeShared); pw.print(',');
785 pw.print(dalvikShared); pw.print(',');
786 pw.print(otherShared); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 pw.print(nativeShared + dalvikShared + otherShared); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 // Heap info - private
Bob Leee5408332009-09-04 18:31:17 -0700790 pw.print(nativePrivate); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 pw.print(dalvikPrivate); pw.print(',');
792 pw.print(otherPrivate); pw.print(',');
793 pw.print(nativePrivate + dalvikPrivate + otherPrivate); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 // Object counts
796 pw.print(viewInstanceCount); pw.print(',');
797 pw.print(viewRootInstanceCount); pw.print(',');
798 pw.print(appContextInstanceCount); pw.print(',');
799 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 pw.print(globalAssetCount); pw.print(',');
802 pw.print(globalAssetManagerCount); pw.print(',');
803 pw.print(binderLocalObjectCount); pw.print(',');
804 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 pw.print(binderDeathObjectCount); pw.print(',');
807 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 // SQL
810 pw.print(sqliteAllocated); pw.print(',');
Vasu Noric3849202010-03-09 10:47:25 -0800811 pw.print(stats.memoryUsed / 1024); pw.print(',');
812 pw.print(stats.pageCacheOverflo / 1024); pw.print(',');
813 pw.print(stats.largestMemAlloc / 1024); pw.print(',');
814 for (int i = 0; i < stats.dbStats.size(); i++) {
815 DbStats dbStats = stats.dbStats.get(i);
816 printRow(pw, DB_INFO_FORMAT, dbStats.pageSize, dbStats.dbSize,
Vasu Nori90a367262010-04-12 12:49:09 -0700817 dbStats.lookaside, dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -0800818 pw.print(',');
819 }
Bob Leee5408332009-09-04 18:31:17 -0700820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 return;
822 }
Bob Leee5408332009-09-04 18:31:17 -0700823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 // otherwise, show human-readable format
825 printRow(pw, HEAP_COLUMN, "", "native", "dalvik", "other", "total");
826 printRow(pw, HEAP_COLUMN, "size:", nativeMax, dalvikMax, "N/A", nativeMax + dalvikMax);
827 printRow(pw, HEAP_COLUMN, "allocated:", nativeAllocated, dalvikAllocated, "N/A",
828 nativeAllocated + dalvikAllocated);
829 printRow(pw, HEAP_COLUMN, "free:", nativeFree, dalvikFree, "N/A",
830 nativeFree + dalvikFree);
831
832 printRow(pw, HEAP_COLUMN, "(Pss):", memInfo.nativePss, memInfo.dalvikPss,
833 memInfo.otherPss, memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss);
834
835 printRow(pw, HEAP_COLUMN, "(shared dirty):", nativeShared, dalvikShared, otherShared,
836 nativeShared + dalvikShared + otherShared);
837 printRow(pw, HEAP_COLUMN, "(priv dirty):", nativePrivate, dalvikPrivate, otherPrivate,
838 nativePrivate + dalvikPrivate + otherPrivate);
839
840 pw.println(" ");
841 pw.println(" Objects");
842 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRoots:",
843 viewRootInstanceCount);
844
845 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
846 "Activities:", activityInstanceCount);
847
848 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
849 "AssetManagers:", globalAssetManagerCount);
850
851 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
852 "Proxy Binders:", binderProxyObjectCount);
853 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
854
855 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -0700856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 // SQLite mem info
858 pw.println(" ");
859 pw.println(" SQL");
Vasu Nori3c7131f2010-09-21 14:36:57 -0700860 printRow(pw, TWO_COUNT_COLUMNS_DB, "heap:", sqliteAllocated, "MEMORY_USED:",
Vasu Noric3849202010-03-09 10:47:25 -0800861 stats.memoryUsed / 1024);
Vasu Nori3c7131f2010-09-21 14:36:57 -0700862 printRow(pw, TWO_COUNT_COLUMNS_DB, "PAGECACHE_OVERFLOW:",
863 stats.pageCacheOverflo / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -0800864 pw.println(" ");
865 int N = stats.dbStats.size();
866 if (N > 0) {
867 pw.println(" DATABASES");
Vasu Nori3c7131f2010-09-21 14:36:57 -0700868 printRow(pw, " %8s %8s %14s %14s %s", "pgsz", "dbsz", "Lookaside(b)", "cache",
869 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -0800870 for (int i = 0; i < N; i++) {
871 DbStats dbStats = stats.dbStats.get(i);
Vasu Nori3c7131f2010-09-21 14:36:57 -0700872 printRow(pw, DB_INFO_FORMAT,
873 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
874 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
875 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
876 dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -0800877 }
878 }
Bob Leee5408332009-09-04 18:31:17 -0700879
Dianne Hackborn82e1ee92009-08-11 18:56:41 -0700880 // Asset details.
881 String assetAlloc = AssetManager.getAssetAllocations();
882 if (assetAlloc != null) {
883 pw.println(" ");
884 pw.println(" Asset Allocations");
885 pw.print(assetAlloc);
886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 }
888
889 private void printRow(PrintWriter pw, String format, Object...objs) {
890 pw.println(String.format(format, objs));
891 }
892 }
893
894 private final class H extends Handler {
895 public static final int LAUNCH_ACTIVITY = 100;
896 public static final int PAUSE_ACTIVITY = 101;
897 public static final int PAUSE_ACTIVITY_FINISHING= 102;
898 public static final int STOP_ACTIVITY_SHOW = 103;
899 public static final int STOP_ACTIVITY_HIDE = 104;
900 public static final int SHOW_WINDOW = 105;
901 public static final int HIDE_WINDOW = 106;
902 public static final int RESUME_ACTIVITY = 107;
903 public static final int SEND_RESULT = 108;
904 public static final int DESTROY_ACTIVITY = 109;
905 public static final int BIND_APPLICATION = 110;
906 public static final int EXIT_APPLICATION = 111;
907 public static final int NEW_INTENT = 112;
908 public static final int RECEIVER = 113;
909 public static final int CREATE_SERVICE = 114;
910 public static final int SERVICE_ARGS = 115;
911 public static final int STOP_SERVICE = 116;
912 public static final int REQUEST_THUMBNAIL = 117;
913 public static final int CONFIGURATION_CHANGED = 118;
914 public static final int CLEAN_UP_CONTEXT = 119;
915 public static final int GC_WHEN_IDLE = 120;
916 public static final int BIND_SERVICE = 121;
917 public static final int UNBIND_SERVICE = 122;
918 public static final int DUMP_SERVICE = 123;
919 public static final int LOW_MEMORY = 124;
920 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
921 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800922 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -0700923 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -0700924 public static final int DESTROY_BACKUP_AGENT = 129;
925 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700926 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800927 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700928 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700929 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -0700930 public static final int DUMP_HEAP = 135;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700931 public static final int DUMP_ACTIVITY = 136;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 String codeToString(int code) {
Dianne Hackborn287952c2010-09-22 22:34:31 -0700933 if (DEBUG_MESSAGES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 switch (code) {
935 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
936 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
937 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
938 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
939 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
940 case SHOW_WINDOW: return "SHOW_WINDOW";
941 case HIDE_WINDOW: return "HIDE_WINDOW";
942 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
943 case SEND_RESULT: return "SEND_RESULT";
944 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
945 case BIND_APPLICATION: return "BIND_APPLICATION";
946 case EXIT_APPLICATION: return "EXIT_APPLICATION";
947 case NEW_INTENT: return "NEW_INTENT";
948 case RECEIVER: return "RECEIVER";
949 case CREATE_SERVICE: return "CREATE_SERVICE";
950 case SERVICE_ARGS: return "SERVICE_ARGS";
951 case STOP_SERVICE: return "STOP_SERVICE";
952 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
953 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
954 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
955 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
956 case BIND_SERVICE: return "BIND_SERVICE";
957 case UNBIND_SERVICE: return "UNBIND_SERVICE";
958 case DUMP_SERVICE: return "DUMP_SERVICE";
959 case LOW_MEMORY: return "LOW_MEMORY";
960 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
961 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800962 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -0700963 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
964 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -0700965 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700966 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800967 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700968 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700969 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -0700970 case DUMP_HEAP: return "DUMP_HEAP";
Dianne Hackborn625ac272010-09-17 18:29:22 -0700971 case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 }
973 }
974 return "(unknown)";
975 }
976 public void handleMessage(Message msg) {
Dianne Hackborn287952c2010-09-22 22:34:31 -0700977 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 switch (msg.what) {
979 case LAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700980 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981
982 r.packageInfo = getPackageInfoNoCheck(
983 r.activityInfo.applicationInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -0700984 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 } break;
986 case RELAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700987 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800988 handleRelaunchActivity(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 } break;
990 case PAUSE_ACTIVITY:
991 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -0700992 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 break;
994 case PAUSE_ACTIVITY_FINISHING:
995 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
996 break;
997 case STOP_ACTIVITY_SHOW:
998 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
999 break;
1000 case STOP_ACTIVITY_HIDE:
1001 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
1002 break;
1003 case SHOW_WINDOW:
1004 handleWindowVisibility((IBinder)msg.obj, true);
1005 break;
1006 case HIDE_WINDOW:
1007 handleWindowVisibility((IBinder)msg.obj, false);
1008 break;
1009 case RESUME_ACTIVITY:
1010 handleResumeActivity((IBinder)msg.obj, true,
1011 msg.arg1 != 0);
1012 break;
1013 case SEND_RESULT:
1014 handleSendResult((ResultData)msg.obj);
1015 break;
1016 case DESTROY_ACTIVITY:
1017 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
1018 msg.arg2, false);
1019 break;
1020 case BIND_APPLICATION:
1021 AppBindData data = (AppBindData)msg.obj;
1022 handleBindApplication(data);
1023 break;
1024 case EXIT_APPLICATION:
1025 if (mInitialApplication != null) {
1026 mInitialApplication.onTerminate();
1027 }
1028 Looper.myLooper().quit();
1029 break;
1030 case NEW_INTENT:
1031 handleNewIntent((NewIntentData)msg.obj);
1032 break;
1033 case RECEIVER:
1034 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001035 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 break;
1037 case CREATE_SERVICE:
1038 handleCreateService((CreateServiceData)msg.obj);
1039 break;
1040 case BIND_SERVICE:
1041 handleBindService((BindServiceData)msg.obj);
1042 break;
1043 case UNBIND_SERVICE:
1044 handleUnbindService((BindServiceData)msg.obj);
1045 break;
1046 case SERVICE_ARGS:
1047 handleServiceArgs((ServiceArgsData)msg.obj);
1048 break;
1049 case STOP_SERVICE:
1050 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001051 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 break;
1053 case REQUEST_THUMBNAIL:
1054 handleRequestThumbnail((IBinder)msg.obj);
1055 break;
1056 case CONFIGURATION_CHANGED:
1057 handleConfigurationChanged((Configuration)msg.obj);
1058 break;
1059 case CLEAN_UP_CONTEXT:
1060 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1061 cci.context.performFinalCleanup(cci.who, cci.what);
1062 break;
1063 case GC_WHEN_IDLE:
1064 scheduleGcIdler();
1065 break;
1066 case DUMP_SERVICE:
Dianne Hackborn625ac272010-09-17 18:29:22 -07001067 handleDumpService((DumpComponentInfo)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 break;
1069 case LOW_MEMORY:
1070 handleLowMemory();
1071 break;
1072 case ACTIVITY_CONFIGURATION_CHANGED:
1073 handleActivityConfigurationChanged((IBinder)msg.obj);
1074 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001075 case PROFILER_CONTROL:
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001076 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001077 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001078 case CREATE_BACKUP_AGENT:
1079 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1080 break;
1081 case DESTROY_BACKUP_AGENT:
1082 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1083 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001084 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001085 Process.killProcess(Process.myPid());
1086 break;
1087 case REMOVE_PROVIDER:
1088 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001089 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001090 case ENABLE_JIT:
1091 ensureJitEnabled();
1092 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001093 case DISPATCH_PACKAGE_BROADCAST:
1094 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
1095 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001096 case SCHEDULE_CRASH:
1097 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001098 case DUMP_HEAP:
1099 handleDumpHeap(msg.arg1 != 0, (DumpHeapData)msg.obj);
1100 break;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001101 case DUMP_ACTIVITY:
1102 handleDumpActivity((DumpComponentInfo)msg.obj);
1103 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07001105 if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + msg.what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 }
Bob Leee5408332009-09-04 18:31:17 -07001107
1108 void maybeSnapshot() {
1109 if (mBoundApplication != null) {
Sen Hubde75702010-05-28 01:54:03 -07001110 // convert the *private* ActivityThread.PackageInfo to *public* known
1111 // android.content.pm.PackageInfo
1112 String packageName = mBoundApplication.info.mPackageName;
1113 android.content.pm.PackageInfo packageInfo = null;
1114 try {
1115 Context context = getSystemContext();
1116 if(context == null) {
1117 Log.e(TAG, "cannot get a valid context");
1118 return;
1119 }
1120 PackageManager pm = context.getPackageManager();
1121 if(pm == null) {
1122 Log.e(TAG, "cannot get a valid PackageManager");
1123 return;
1124 }
1125 packageInfo = pm.getPackageInfo(
1126 packageName, PackageManager.GET_ACTIVITIES);
1127 } catch (NameNotFoundException e) {
1128 Log.e(TAG, "cannot get package info for " + packageName, e);
1129 }
1130 SamplingProfilerIntegration.writeSnapshot(mBoundApplication.processName, packageInfo);
Bob Leee5408332009-09-04 18:31:17 -07001131 }
1132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 }
1134
1135 private final class Idler implements MessageQueue.IdleHandler {
1136 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001137 ActivityClientRecord a = mNewActivities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 if (a != null) {
1139 mNewActivities = null;
1140 IActivityManager am = ActivityManagerNative.getDefault();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001141 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001143 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 TAG, "Reporting idle of " + a +
1145 " finished=" +
1146 (a.activity != null ? a.activity.mFinished : false));
1147 if (a.activity != null && !a.activity.mFinished) {
1148 try {
Dianne Hackborne88846e2009-09-30 21:34:25 -07001149 am.activityIdle(a.token, a.createdConfig);
1150 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 } catch (RemoteException ex) {
1152 }
1153 }
1154 prev = a;
1155 a = a.nextIdle;
1156 prev.nextIdle = null;
1157 } while (a != null);
1158 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001159 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 return false;
1161 }
1162 }
1163
1164 final class GcIdler implements MessageQueue.IdleHandler {
1165 public final boolean queueIdle() {
1166 doGcIfNeeded();
1167 return false;
1168 }
1169 }
1170
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001171 private final static class ResourcesKey {
1172 final private String mResDir;
1173 final private float mScale;
1174 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07001175
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001176 ResourcesKey(String resDir, float scale) {
1177 mResDir = resDir;
1178 mScale = scale;
1179 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
1180 }
Bob Leee5408332009-09-04 18:31:17 -07001181
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001182 @Override
1183 public int hashCode() {
1184 return mHash;
1185 }
1186
1187 @Override
1188 public boolean equals(Object obj) {
1189 if (!(obj instanceof ResourcesKey)) {
1190 return false;
1191 }
1192 ResourcesKey peer = (ResourcesKey) obj;
1193 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
1194 }
1195 }
1196
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001197 public static final ActivityThread currentActivityThread() {
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07001198 return sThreadLocal.get();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001201 public static final String currentPackageName() {
1202 ActivityThread am = currentActivityThread();
1203 return (am != null && am.mBoundApplication != null)
1204 ? am.mBoundApplication.processName : null;
1205 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001207 public static final Application currentApplication() {
1208 ActivityThread am = currentActivityThread();
1209 return am != null ? am.mInitialApplication : null;
1210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001212 public static IPackageManager getPackageManager() {
1213 if (sPackageManager != null) {
1214 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1215 return sPackageManager;
1216 }
1217 IBinder b = ServiceManager.getService("package");
1218 //Slog.v("PackageManager", "default service binder = " + b);
1219 sPackageManager = IPackageManager.Stub.asInterface(b);
1220 //Slog.v("PackageManager", "default service = " + sPackageManager);
1221 return sPackageManager;
1222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001224 DisplayMetrics getDisplayMetricsLocked(boolean forceUpdate) {
1225 if (mDisplayMetrics != null && !forceUpdate) {
1226 return mDisplayMetrics;
1227 }
1228 if (mDisplay == null) {
1229 WindowManager wm = WindowManagerImpl.getDefault();
1230 mDisplay = wm.getDefaultDisplay();
1231 }
1232 DisplayMetrics metrics = mDisplayMetrics = new DisplayMetrics();
1233 mDisplay.getMetrics(metrics);
1234 //Slog.i("foo", "New metrics: w=" + metrics.widthPixels + " h="
1235 // + metrics.heightPixels + " den=" + metrics.density
1236 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi);
1237 return metrics;
1238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001240 /**
1241 * Creates the top level Resources for applications with the given compatibility info.
1242 *
1243 * @param resDir the resource directory.
1244 * @param compInfo the compability info. It will use the default compatibility info when it's
1245 * null.
1246 */
1247 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
1248 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
1249 Resources r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001251 // Resources is app scale dependent.
1252 if (false) {
1253 Slog.w(TAG, "getTopLevelResources: " + resDir + " / "
1254 + compInfo.applicationScale);
1255 }
1256 WeakReference<Resources> wr = mActiveResources.get(key);
1257 r = wr != null ? wr.get() : null;
1258 //if (r != null) Slog.i(TAG, "isUpToDate " + resDir + ": " + r.getAssets().isUpToDate());
1259 if (r != null && r.getAssets().isUpToDate()) {
1260 if (false) {
1261 Slog.w(TAG, "Returning cached resources " + r + " " + resDir
1262 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
1263 }
1264 return r;
1265 }
1266 }
1267
1268 //if (r != null) {
1269 // Slog.w(TAG, "Throwing away out-of-date resources!!!! "
1270 // + r + " " + resDir);
1271 //}
1272
1273 AssetManager assets = new AssetManager();
1274 if (assets.addAssetPath(resDir) == 0) {
1275 return null;
1276 }
1277
1278 //Slog.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
1279 DisplayMetrics metrics = getDisplayMetricsLocked(false);
1280 r = new Resources(assets, metrics, getConfiguration(), compInfo);
1281 if (false) {
1282 Slog.i(TAG, "Created app resources " + resDir + " " + r + ": "
1283 + r.getConfiguration() + " appScale="
1284 + r.getCompatibilityInfo().applicationScale);
1285 }
1286
1287 synchronized (mPackages) {
1288 WeakReference<Resources> wr = mActiveResources.get(key);
1289 Resources existing = wr != null ? wr.get() : null;
1290 if (existing != null && existing.getAssets().isUpToDate()) {
1291 // Someone else already created the resources while we were
1292 // unlocked; go ahead and use theirs.
1293 r.getAssets().close();
1294 return existing;
1295 }
1296
1297 // XXX need to remove entries when weak references go away
1298 mActiveResources.put(key, new WeakReference<Resources>(r));
1299 return r;
1300 }
1301 }
1302
1303 /**
1304 * Creates the top level resources for the given package.
1305 */
1306 Resources getTopLevelResources(String resDir, LoadedApk pkgInfo) {
1307 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo);
1308 }
1309
1310 final Handler getHandler() {
1311 return mH;
1312 }
1313
1314 public final LoadedApk getPackageInfo(String packageName, int flags) {
1315 synchronized (mPackages) {
1316 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
1318 ref = mPackages.get(packageName);
1319 } else {
1320 ref = mResourcePackages.get(packageName);
1321 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001322 LoadedApk packageInfo = ref != null ? ref.get() : null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001323 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001324 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
1325 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 if (packageInfo != null && (packageInfo.mResources == null
1327 || packageInfo.mResources.getAssets().isUpToDate())) {
1328 if (packageInfo.isSecurityViolation()
1329 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
1330 throw new SecurityException(
1331 "Requesting code from " + packageName
1332 + " to be run in process "
1333 + mBoundApplication.processName
1334 + "/" + mBoundApplication.appInfo.uid);
1335 }
1336 return packageInfo;
1337 }
1338 }
1339
1340 ApplicationInfo ai = null;
1341 try {
1342 ai = getPackageManager().getApplicationInfo(packageName,
1343 PackageManager.GET_SHARED_LIBRARY_FILES);
1344 } catch (RemoteException e) {
1345 }
1346
1347 if (ai != null) {
1348 return getPackageInfo(ai, flags);
1349 }
1350
1351 return null;
1352 }
1353
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001354 public final LoadedApk getPackageInfo(ApplicationInfo ai, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
1356 boolean securityViolation = includeCode && ai.uid != 0
1357 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
1358 ? ai.uid != mBoundApplication.appInfo.uid : true);
1359 if ((flags&(Context.CONTEXT_INCLUDE_CODE
1360 |Context.CONTEXT_IGNORE_SECURITY))
1361 == Context.CONTEXT_INCLUDE_CODE) {
1362 if (securityViolation) {
1363 String msg = "Requesting code from " + ai.packageName
1364 + " (with uid " + ai.uid + ")";
1365 if (mBoundApplication != null) {
1366 msg = msg + " to be run in process "
1367 + mBoundApplication.processName + " (with uid "
1368 + mBoundApplication.appInfo.uid + ")";
1369 }
1370 throw new SecurityException(msg);
1371 }
1372 }
1373 return getPackageInfo(ai, null, securityViolation, includeCode);
1374 }
1375
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001376 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 return getPackageInfo(ai, null, false, true);
1378 }
1379
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001380 private final LoadedApk getPackageInfo(ApplicationInfo aInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
1382 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001383 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 if (includeCode) {
1385 ref = mPackages.get(aInfo.packageName);
1386 } else {
1387 ref = mResourcePackages.get(aInfo.packageName);
1388 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001389 LoadedApk packageInfo = ref != null ? ref.get() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 if (packageInfo == null || (packageInfo.mResources != null
1391 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001392 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 : "Loading resource-only package ") + aInfo.packageName
1394 + " (in " + (mBoundApplication != null
1395 ? mBoundApplication.processName : null)
1396 + ")");
1397 packageInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001398 new LoadedApk(this, aInfo, this, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 securityViolation, includeCode &&
1400 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
1401 if (includeCode) {
1402 mPackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001403 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 } else {
1405 mResourcePackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001406 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 }
1408 }
1409 return packageInfo;
1410 }
1411 }
1412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 ActivityThread() {
1414 }
1415
1416 public ApplicationThread getApplicationThread()
1417 {
1418 return mAppThread;
1419 }
1420
1421 public Instrumentation getInstrumentation()
1422 {
1423 return mInstrumentation;
1424 }
1425
1426 public Configuration getConfiguration() {
1427 return mConfiguration;
1428 }
1429
1430 public boolean isProfiling() {
1431 return mBoundApplication != null && mBoundApplication.profileFile != null;
1432 }
1433
1434 public String getProfileFilePath() {
1435 return mBoundApplication.profileFile;
1436 }
1437
1438 public Looper getLooper() {
1439 return mLooper;
1440 }
1441
1442 public Application getApplication() {
1443 return mInitialApplication;
1444 }
Bob Leee5408332009-09-04 18:31:17 -07001445
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07001446 public String getProcessName() {
1447 return mBoundApplication.processName;
1448 }
Bob Leee5408332009-09-04 18:31:17 -07001449
Dianne Hackborn21556372010-02-04 16:34:40 -08001450 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 synchronized (this) {
1452 if (mSystemContext == null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001453 ContextImpl context =
1454 ContextImpl.createSystemContext(this);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001455 LoadedApk info = new LoadedApk(this, "android", context, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 context.init(info, null, this);
1457 context.getResources().updateConfiguration(
1458 getConfiguration(), getDisplayMetricsLocked(false));
1459 mSystemContext = context;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001460 //Slog.i(TAG, "Created system resources " + context.getResources()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 // + ": " + context.getResources().getConfiguration());
1462 }
1463 }
1464 return mSystemContext;
1465 }
1466
Mike Cleron432b7132009-09-24 15:28:29 -07001467 public void installSystemApplicationInfo(ApplicationInfo info) {
1468 synchronized (this) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001469 ContextImpl context = getSystemContext();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001470 context.init(new LoadedApk(this, "android", context, info), null, this);
Mike Cleron432b7132009-09-24 15:28:29 -07001471 }
1472 }
1473
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001474 void ensureJitEnabled() {
1475 if (!mJitEnabled) {
1476 mJitEnabled = true;
1477 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
1478 }
1479 }
1480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 void scheduleGcIdler() {
1482 if (!mGcIdlerScheduled) {
1483 mGcIdlerScheduled = true;
1484 Looper.myQueue().addIdleHandler(mGcIdler);
1485 }
1486 mH.removeMessages(H.GC_WHEN_IDLE);
1487 }
1488
1489 void unscheduleGcIdler() {
1490 if (mGcIdlerScheduled) {
1491 mGcIdlerScheduled = false;
1492 Looper.myQueue().removeIdleHandler(mGcIdler);
1493 }
1494 mH.removeMessages(H.GC_WHEN_IDLE);
1495 }
1496
1497 void doGcIfNeeded() {
1498 mGcIdlerScheduled = false;
1499 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001500 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 // + "m now=" + now);
1502 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001503 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 BinderInternal.forceGc("bg");
1505 }
1506 }
1507
1508 public final ActivityInfo resolveActivityInfo(Intent intent) {
1509 ActivityInfo aInfo = intent.resolveActivityInfo(
1510 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
1511 if (aInfo == null) {
1512 // Throw an exception.
1513 Instrumentation.checkStartActivityResult(
1514 IActivityManager.START_CLASS_NOT_FOUND, intent);
1515 }
1516 return aInfo;
1517 }
Bob Leee5408332009-09-04 18:31:17 -07001518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001521 Activity.NonConfigurationInstances lastNonConfigurationInstances) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001522 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001524 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 r.intent = intent;
1526 r.state = state;
1527 r.parent = parent;
1528 r.embeddedID = id;
1529 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001530 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 if (localLOGV) {
1532 ComponentName compname = intent.getComponent();
1533 String name;
1534 if (compname != null) {
1535 name = compname.toShortString();
1536 } else {
1537 name = "(Intent " + intent + ").getComponent() returned null";
1538 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001539 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 + ", comp=" + name
1541 + ", token=" + token);
1542 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07001543 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 }
1545
1546 public final Activity getActivity(IBinder token) {
1547 return mActivities.get(token).activity;
1548 }
1549
1550 public final void sendActivityResult(
1551 IBinder token, String id, int requestCode,
1552 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001553 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07001554 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
1556 list.add(new ResultInfo(id, requestCode, resultCode, data));
1557 mAppThread.scheduleSendResult(token, list);
1558 }
1559
1560 // if the thread hasn't started yet, we don't have the handler, so just
1561 // save the messages until we're ready.
1562 private final void queueOrSendMessage(int what, Object obj) {
1563 queueOrSendMessage(what, obj, 0, 0);
1564 }
1565
1566 private final void queueOrSendMessage(int what, Object obj, int arg1) {
1567 queueOrSendMessage(what, obj, arg1, 0);
1568 }
1569
1570 private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
1571 synchronized (this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001572 if (DEBUG_MESSAGES) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
1574 + ": " + arg1 + " / " + obj);
1575 Message msg = Message.obtain();
1576 msg.what = what;
1577 msg.obj = obj;
1578 msg.arg1 = arg1;
1579 msg.arg2 = arg2;
1580 mH.sendMessage(msg);
1581 }
1582 }
1583
Dianne Hackborn21556372010-02-04 16:34:40 -08001584 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 String what) {
1586 ContextCleanupInfo cci = new ContextCleanupInfo();
1587 cci.context = context;
1588 cci.who = who;
1589 cci.what = what;
1590 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
1591 }
1592
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001593 private final Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
1595
1596 ActivityInfo aInfo = r.activityInfo;
1597 if (r.packageInfo == null) {
1598 r.packageInfo = getPackageInfo(aInfo.applicationInfo,
1599 Context.CONTEXT_INCLUDE_CODE);
1600 }
Bob Leee5408332009-09-04 18:31:17 -07001601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 ComponentName component = r.intent.getComponent();
1603 if (component == null) {
1604 component = r.intent.resolveActivity(
1605 mInitialApplication.getPackageManager());
1606 r.intent.setComponent(component);
1607 }
1608
1609 if (r.activityInfo.targetActivity != null) {
1610 component = new ComponentName(r.activityInfo.packageName,
1611 r.activityInfo.targetActivity);
1612 }
1613
1614 Activity activity = null;
1615 try {
1616 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
1617 activity = mInstrumentation.newActivity(
1618 cl, component.getClassName(), r.intent);
1619 r.intent.setExtrasClassLoader(cl);
1620 if (r.state != null) {
1621 r.state.setClassLoader(cl);
1622 }
1623 } catch (Exception e) {
1624 if (!mInstrumentation.onException(activity, e)) {
1625 throw new RuntimeException(
1626 "Unable to instantiate activity " + component
1627 + ": " + e.toString(), e);
1628 }
1629 }
1630
1631 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001632 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001633
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001634 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
1635 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 TAG, r + ": app=" + app
1637 + ", appName=" + app.getPackageName()
1638 + ", pkg=" + r.packageInfo.getPackageName()
1639 + ", comp=" + r.intent.getComponent().toShortString()
1640 + ", dir=" + r.packageInfo.getAppDir());
1641
1642 if (activity != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001643 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 appContext.init(r.packageInfo, r.token, this);
1645 appContext.setOuterContext(activity);
1646 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
1647 Configuration config = new Configuration(mConfiguration);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001648 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07001649 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001650 activity.attach(appContext, this, getInstrumentation(), r.token,
1651 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001652 r.embeddedID, r.lastNonConfigurationInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07001653
Christopher Tateb70f3df2009-04-07 16:07:59 -07001654 if (customIntent != null) {
1655 activity.mIntent = customIntent;
1656 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001657 r.lastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 activity.mStartedActivity = false;
1659 int theme = r.activityInfo.getThemeResource();
1660 if (theme != 0) {
1661 activity.setTheme(theme);
1662 }
1663
1664 activity.mCalled = false;
1665 mInstrumentation.callActivityOnCreate(activity, r.state);
1666 if (!activity.mCalled) {
1667 throw new SuperNotCalledException(
1668 "Activity " + r.intent.getComponent().toShortString() +
1669 " did not call through to super.onCreate()");
1670 }
1671 r.activity = activity;
1672 r.stopped = true;
1673 if (!r.activity.mFinished) {
1674 activity.performStart();
1675 r.stopped = false;
1676 }
1677 if (!r.activity.mFinished) {
1678 if (r.state != null) {
1679 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
1680 }
1681 }
1682 if (!r.activity.mFinished) {
1683 activity.mCalled = false;
1684 mInstrumentation.callActivityOnPostCreate(activity, r.state);
1685 if (!activity.mCalled) {
1686 throw new SuperNotCalledException(
1687 "Activity " + r.intent.getComponent().toShortString() +
1688 " did not call through to super.onPostCreate()");
1689 }
1690 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 }
1692 r.paused = true;
1693
1694 mActivities.put(r.token, r);
1695
1696 } catch (SuperNotCalledException e) {
1697 throw e;
1698
1699 } catch (Exception e) {
1700 if (!mInstrumentation.onException(activity, e)) {
1701 throw new RuntimeException(
1702 "Unable to start activity " + component
1703 + ": " + e.toString(), e);
1704 }
1705 }
1706
1707 return activity;
1708 }
1709
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001710 private final void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 // If we are getting ready to gc after going to the background, well
1712 // we are back active so skip it.
1713 unscheduleGcIdler();
1714
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001715 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001717 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718
1719 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08001720 r.createdConfig = new Configuration(mConfiguration);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001721 Bundle oldState = r.state;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 handleResumeActivity(r.token, false, r.isForward);
1723
1724 if (!r.activity.mFinished && r.startsNotResumed) {
1725 // The activity manager actually wants this one to start out
1726 // paused, because it needs to be visible but isn't in the
1727 // foreground. We accomplish this by going through the
1728 // normal startup (because activities expect to go through
1729 // onResume() the first time they run, before their window
1730 // is displayed), and then pausing it. However, in this case
1731 // we do -not- need to do the full pause cycle (of freezing
1732 // and such) because the activity manager assumes it can just
1733 // retain the current state it has.
1734 try {
1735 r.activity.mCalled = false;
1736 mInstrumentation.callActivityOnPause(r.activity);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001737 // We need to keep around the original state, in case
1738 // we need to be created again.
1739 r.state = oldState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 if (!r.activity.mCalled) {
1741 throw new SuperNotCalledException(
1742 "Activity " + r.intent.getComponent().toShortString() +
1743 " did not call through to super.onPause()");
1744 }
1745
1746 } catch (SuperNotCalledException e) {
1747 throw e;
1748
1749 } catch (Exception e) {
1750 if (!mInstrumentation.onException(r.activity, e)) {
1751 throw new RuntimeException(
1752 "Unable to pause activity "
1753 + r.intent.getComponent().toShortString()
1754 + ": " + e.toString(), e);
1755 }
1756 }
1757 r.paused = true;
1758 }
1759 } else {
1760 // If there was an error, for any reason, tell the activity
1761 // manager to stop us.
1762 try {
1763 ActivityManagerNative.getDefault()
1764 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
1765 } catch (RemoteException ex) {
1766 }
1767 }
1768 }
1769
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001770 private final void deliverNewIntents(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 List<Intent> intents) {
1772 final int N = intents.size();
1773 for (int i=0; i<N; i++) {
1774 Intent intent = intents.get(i);
1775 intent.setExtrasClassLoader(r.activity.getClassLoader());
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001776 r.activity.mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
1778 }
1779 }
1780
1781 public final void performNewIntents(IBinder token,
1782 List<Intent> intents) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001783 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 if (r != null) {
1785 final boolean resumed = !r.paused;
1786 if (resumed) {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001787 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 mInstrumentation.callActivityOnPause(r.activity);
1789 }
1790 deliverNewIntents(r, intents);
1791 if (resumed) {
1792 mInstrumentation.callActivityOnResume(r.activity);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001793 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 }
1795 }
1796 }
Bob Leee5408332009-09-04 18:31:17 -07001797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 private final void handleNewIntent(NewIntentData data) {
1799 performNewIntents(data.token, data.intents);
1800 }
1801
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07001802 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
1803
1804 /**
1805 * Return the Intent that's currently being handled by a
1806 * BroadcastReceiver on this thread, or null if none.
1807 * @hide
1808 */
1809 public static Intent getIntentBeingBroadcast() {
1810 return sCurrentBroadcastIntent.get();
1811 }
1812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 private final void handleReceiver(ReceiverData data) {
1814 // If we are getting ready to gc after going to the background, well
1815 // we are back active so skip it.
1816 unscheduleGcIdler();
1817
1818 String component = data.intent.getComponent().getClassName();
1819
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001820 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 data.info.applicationInfo);
1822
1823 IActivityManager mgr = ActivityManagerNative.getDefault();
1824
1825 BroadcastReceiver receiver = null;
1826 try {
1827 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1828 data.intent.setExtrasClassLoader(cl);
Dianne Hackborne829fef2010-10-26 17:44:01 -07001829 data.setExtrasClassLoader(cl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
1831 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07001832 if (DEBUG_BROADCAST) Slog.i(TAG,
1833 "Finishing failed broadcast to " + data.intent.getComponent());
1834 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 throw new RuntimeException(
1836 "Unable to instantiate receiver " + component
1837 + ": " + e.toString(), e);
1838 }
1839
1840 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001841 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001842
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001843 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 TAG, "Performing receive of " + data.intent
1845 + ": app=" + app
1846 + ", appName=" + app.getPackageName()
1847 + ", pkg=" + packageInfo.getPackageName()
1848 + ", comp=" + data.intent.getComponent().toShortString()
1849 + ", dir=" + packageInfo.getAppDir());
1850
Dianne Hackborn21556372010-02-04 16:34:40 -08001851 ContextImpl context = (ContextImpl)app.getBaseContext();
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07001852 sCurrentBroadcastIntent.set(data.intent);
Dianne Hackborne829fef2010-10-26 17:44:01 -07001853 receiver.setPendingResult(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 receiver.onReceive(context.getReceiverRestrictedContext(),
1855 data.intent);
1856 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07001857 if (DEBUG_BROADCAST) Slog.i(TAG,
1858 "Finishing failed broadcast to " + data.intent.getComponent());
1859 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 if (!mInstrumentation.onException(receiver, e)) {
1861 throw new RuntimeException(
1862 "Unable to start receiver " + component
1863 + ": " + e.toString(), e);
1864 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07001865 } finally {
1866 sCurrentBroadcastIntent.set(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 }
1868
Dianne Hackborne829fef2010-10-26 17:44:01 -07001869 if (receiver.getPendingResult() != null) {
1870 data.finish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 }
1872 }
1873
Christopher Tate181fafa2009-05-14 11:12:14 -07001874 // Instantiate a BackupAgent and tell it that it's alive
1875 private final void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001876 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001877
1878 // no longer idle; we have backup work to do
1879 unscheduleGcIdler();
1880
1881 // instantiate the BackupAgent class named in the manifest
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001882 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001883 String packageName = packageInfo.mPackageName;
1884 if (mBackupAgents.get(packageName) != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001885 Slog.d(TAG, "BackupAgent " + " for " + packageName
Christopher Tate181fafa2009-05-14 11:12:14 -07001886 + " already exists");
1887 return;
1888 }
Bob Leee5408332009-09-04 18:31:17 -07001889
Christopher Tate181fafa2009-05-14 11:12:14 -07001890 BackupAgent agent = null;
1891 String classname = data.appInfo.backupAgentName;
1892 if (classname == null) {
1893 if (data.backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001894 Slog.e(TAG, "Attempted incremental backup but no defined agent for "
Christopher Tate181fafa2009-05-14 11:12:14 -07001895 + packageName);
1896 return;
1897 }
1898 classname = "android.app.FullBackupAgent";
1899 }
1900 try {
Christopher Tated1475e02009-07-09 15:36:17 -07001901 IBinder binder = null;
1902 try {
1903 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1904 agent = (BackupAgent) cl.loadClass(data.appInfo.backupAgentName).newInstance();
1905
1906 // set up the agent's context
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001907 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing BackupAgent "
Christopher Tated1475e02009-07-09 15:36:17 -07001908 + data.appInfo.backupAgentName);
1909
Dianne Hackborn21556372010-02-04 16:34:40 -08001910 ContextImpl context = new ContextImpl();
Christopher Tated1475e02009-07-09 15:36:17 -07001911 context.init(packageInfo, null, this);
1912 context.setOuterContext(agent);
1913 agent.attach(context);
1914
1915 agent.onCreate();
1916 binder = agent.onBind();
1917 mBackupAgents.put(packageName, agent);
1918 } catch (Exception e) {
1919 // If this is during restore, fail silently; otherwise go
1920 // ahead and let the user see the crash.
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001921 Slog.e(TAG, "Agent threw during creation: " + e);
Christopher Tated1475e02009-07-09 15:36:17 -07001922 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE) {
1923 throw e;
1924 }
1925 // falling through with 'binder' still null
1926 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001927
1928 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07001929 try {
1930 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
1931 } catch (RemoteException e) {
1932 // nothing to do.
1933 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001934 } catch (Exception e) {
1935 throw new RuntimeException("Unable to create BackupAgent "
1936 + data.appInfo.backupAgentName + ": " + e.toString(), e);
1937 }
1938 }
1939
1940 // Tear down a BackupAgent
1941 private final void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001942 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07001943
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001944 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001945 String packageName = packageInfo.mPackageName;
1946 BackupAgent agent = mBackupAgents.get(packageName);
1947 if (agent != null) {
1948 try {
1949 agent.onDestroy();
1950 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001951 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001952 e.printStackTrace();
1953 }
1954 mBackupAgents.remove(packageName);
1955 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001956 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001957 }
1958 }
1959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 private final void handleCreateService(CreateServiceData data) {
1961 // If we are getting ready to gc after going to the background, well
1962 // we are back active so skip it.
1963 unscheduleGcIdler();
1964
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001965 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 data.info.applicationInfo);
1967 Service service = null;
1968 try {
1969 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1970 service = (Service) cl.loadClass(data.info.name).newInstance();
1971 } catch (Exception e) {
1972 if (!mInstrumentation.onException(service, e)) {
1973 throw new RuntimeException(
1974 "Unable to instantiate service " + data.info.name
1975 + ": " + e.toString(), e);
1976 }
1977 }
1978
1979 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001980 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981
Dianne Hackborn21556372010-02-04 16:34:40 -08001982 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001983 context.init(packageInfo, null, this);
1984
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001985 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 context.setOuterContext(service);
1987 service.attach(context, this, data.info.name, data.token, app,
1988 ActivityManagerNative.getDefault());
1989 service.onCreate();
1990 mServices.put(data.token, service);
1991 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001992 ActivityManagerNative.getDefault().serviceDoneExecuting(
1993 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 } catch (RemoteException e) {
1995 // nothing to do.
1996 }
1997 } catch (Exception e) {
1998 if (!mInstrumentation.onException(service, e)) {
1999 throw new RuntimeException(
2000 "Unable to create service " + data.info.name
2001 + ": " + e.toString(), e);
2002 }
2003 }
2004 }
2005
2006 private final void handleBindService(BindServiceData data) {
2007 Service s = mServices.get(data.token);
2008 if (s != null) {
2009 try {
2010 data.intent.setExtrasClassLoader(s.getClassLoader());
2011 try {
2012 if (!data.rebind) {
2013 IBinder binder = s.onBind(data.intent);
2014 ActivityManagerNative.getDefault().publishService(
2015 data.token, data.intent, binder);
2016 } else {
2017 s.onRebind(data.intent);
2018 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002019 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002021 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002022 } catch (RemoteException ex) {
2023 }
2024 } catch (Exception e) {
2025 if (!mInstrumentation.onException(s, e)) {
2026 throw new RuntimeException(
2027 "Unable to bind to service " + s
2028 + " with " + data.intent + ": " + e.toString(), e);
2029 }
2030 }
2031 }
2032 }
2033
2034 private final void handleUnbindService(BindServiceData data) {
2035 Service s = mServices.get(data.token);
2036 if (s != null) {
2037 try {
2038 data.intent.setExtrasClassLoader(s.getClassLoader());
2039 boolean doRebind = s.onUnbind(data.intent);
2040 try {
2041 if (doRebind) {
2042 ActivityManagerNative.getDefault().unbindFinished(
2043 data.token, data.intent, doRebind);
2044 } else {
2045 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002046 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 }
2048 } catch (RemoteException ex) {
2049 }
2050 } catch (Exception e) {
2051 if (!mInstrumentation.onException(s, e)) {
2052 throw new RuntimeException(
2053 "Unable to unbind to service " + s
2054 + " with " + data.intent + ": " + e.toString(), e);
2055 }
2056 }
2057 }
2058 }
2059
Dianne Hackborn625ac272010-09-17 18:29:22 -07002060 private void handleDumpService(DumpComponentInfo info) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061 try {
Dianne Hackborn625ac272010-09-17 18:29:22 -07002062 Service s = mServices.get(info.token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 if (s != null) {
2064 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
2065 s.dump(info.fd, pw, info.args);
2066 pw.close();
2067 }
2068 } finally {
2069 synchronized (info) {
2070 info.dumped = true;
2071 info.notifyAll();
2072 }
2073 }
2074 }
2075
Dianne Hackborn625ac272010-09-17 18:29:22 -07002076 private void handleDumpActivity(DumpComponentInfo info) {
2077 try {
2078 ActivityClientRecord r = mActivities.get(info.token);
2079 if (r != null && r.activity != null) {
2080 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
Dianne Hackborn30d71892010-12-11 10:37:55 -08002081 r.activity.dump(info.prefix, info.fd, pw, info.args);
Dianne Hackborn625ac272010-09-17 18:29:22 -07002082 pw.close();
2083 }
2084 } finally {
2085 synchronized (info) {
2086 info.dumped = true;
2087 info.notifyAll();
2088 }
2089 }
2090 }
2091
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002092 private final void handleServiceArgs(ServiceArgsData data) {
2093 Service s = mServices.get(data.token);
2094 if (s != null) {
2095 try {
2096 if (data.args != null) {
2097 data.args.setExtrasClassLoader(s.getClassLoader());
2098 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002099 int res = s.onStartCommand(data.args, data.flags, data.startId);
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002100
2101 QueuedWork.waitToFinish();
2102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002103 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002104 ActivityManagerNative.getDefault().serviceDoneExecuting(
2105 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106 } catch (RemoteException e) {
2107 // nothing to do.
2108 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002109 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002110 } catch (Exception e) {
2111 if (!mInstrumentation.onException(s, e)) {
2112 throw new RuntimeException(
2113 "Unable to start service " + s
2114 + " with " + data.args + ": " + e.toString(), e);
2115 }
2116 }
2117 }
2118 }
2119
2120 private final void handleStopService(IBinder token) {
2121 Service s = mServices.remove(token);
2122 if (s != null) {
2123 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002124 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002125 s.onDestroy();
2126 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002127 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002128 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08002129 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002131
2132 QueuedWork.waitToFinish();
2133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002135 ActivityManagerNative.getDefault().serviceDoneExecuting(
2136 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002137 } catch (RemoteException e) {
2138 // nothing to do.
2139 }
2140 } catch (Exception e) {
2141 if (!mInstrumentation.onException(s, e)) {
2142 throw new RuntimeException(
2143 "Unable to stop service " + s
2144 + ": " + e.toString(), e);
2145 }
2146 }
2147 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002148 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149 }
2150
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002151 public final ActivityClientRecord performResumeActivity(IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152 boolean clearHide) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002153 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002154 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002155 + " finished=" + r.activity.mFinished);
2156 if (r != null && !r.activity.mFinished) {
2157 if (clearHide) {
2158 r.hideForNow = false;
2159 r.activity.mStartedActivity = false;
2160 }
2161 try {
2162 if (r.pendingIntents != null) {
2163 deliverNewIntents(r, r.pendingIntents);
2164 r.pendingIntents = null;
2165 }
2166 if (r.pendingResults != null) {
2167 deliverResults(r, r.pendingResults);
2168 r.pendingResults = null;
2169 }
2170 r.activity.performResume();
2171
Bob Leee5408332009-09-04 18:31:17 -07002172 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002175 r.paused = false;
2176 r.stopped = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002177 r.state = null;
2178 } catch (Exception e) {
2179 if (!mInstrumentation.onException(r.activity, e)) {
2180 throw new RuntimeException(
2181 "Unable to resume activity "
2182 + r.intent.getComponent().toShortString()
2183 + ": " + e.toString(), e);
2184 }
2185 }
2186 }
2187 return r;
2188 }
2189
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002190 final void cleanUpPendingRemoveWindows(ActivityClientRecord r) {
2191 if (r.mPendingRemoveWindow != null) {
2192 r.mPendingRemoveWindowManager.removeViewImmediate(r.mPendingRemoveWindow);
2193 IBinder wtoken = r.mPendingRemoveWindow.getWindowToken();
2194 if (wtoken != null) {
2195 WindowManagerImpl.getDefault().closeAll(wtoken,
2196 r.activity.getClass().getName(), "Activity");
2197 }
2198 }
2199 r.mPendingRemoveWindow = null;
2200 r.mPendingRemoveWindowManager = null;
2201 }
2202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002203 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2204 // If we are getting ready to gc after going to the background, well
2205 // we are back active so skip it.
2206 unscheduleGcIdler();
2207
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002208 ActivityClientRecord r = performResumeActivity(token, clearHide);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002209
2210 if (r != null) {
2211 final Activity a = r.activity;
2212
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002213 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002214 TAG, "Resume " + r + " started activity: " +
2215 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2216 + ", finished: " + a.mFinished);
2217
2218 final int forwardBit = isForward ?
2219 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002221 // If the window hasn't yet been added to the window manager,
2222 // and this guy didn't finish itself or start another activity,
2223 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002224 boolean willBeVisible = !a.mStartedActivity;
2225 if (!willBeVisible) {
2226 try {
2227 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
2228 a.getActivityToken());
2229 } catch (RemoteException e) {
2230 }
2231 }
2232 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002233 r.window = r.activity.getWindow();
2234 View decor = r.window.getDecorView();
2235 decor.setVisibility(View.INVISIBLE);
2236 ViewManager wm = a.getWindowManager();
2237 WindowManager.LayoutParams l = r.window.getAttributes();
2238 a.mDecor = decor;
2239 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2240 l.softInputMode |= forwardBit;
2241 if (a.mVisibleFromClient) {
2242 a.mWindowAdded = true;
2243 wm.addView(decor, l);
2244 }
2245
2246 // If the window has already been added, but during resume
2247 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002248 // window visible.
2249 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002250 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002251 TAG, "Launch " + r + " mStartedActivity set");
2252 r.hideForNow = true;
2253 }
2254
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002255 // Get rid of anything left hanging around.
2256 cleanUpPendingRemoveWindows(r);
2257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002258 // The window is now visible if it has been added, we are not
2259 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002260 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002261 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002262 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002263 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002264 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002265 performConfigurationChanged(r.activity, r.newConfig);
2266 r.newConfig = null;
2267 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002268 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 + isForward);
2270 WindowManager.LayoutParams l = r.window.getAttributes();
2271 if ((l.softInputMode
2272 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2273 != forwardBit) {
2274 l.softInputMode = (l.softInputMode
2275 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2276 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002277 if (r.activity.mVisibleFromClient) {
2278 ViewManager wm = a.getWindowManager();
2279 View decor = r.window.getDecorView();
2280 wm.updateViewLayout(decor, l);
2281 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002282 }
2283 r.activity.mVisibleFromServer = true;
2284 mNumVisibleActivities++;
2285 if (r.activity.mVisibleFromClient) {
2286 r.activity.makeVisible();
2287 }
2288 }
2289
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002290 if (!r.onlyLocalRequest) {
2291 r.nextIdle = mNewActivities;
2292 mNewActivities = r;
2293 if (localLOGV) Slog.v(
2294 TAG, "Scheduling idle handler for " + r);
2295 Looper.myQueue().addIdleHandler(new Idler());
2296 }
2297 r.onlyLocalRequest = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002298
2299 } else {
2300 // If an exception was thrown when trying to resume, then
2301 // just end this activity.
2302 try {
2303 ActivityManagerNative.getDefault()
2304 .finishActivity(token, Activity.RESULT_CANCELED, null);
2305 } catch (RemoteException ex) {
2306 }
2307 }
2308 }
2309
2310 private int mThumbnailWidth = -1;
2311 private int mThumbnailHeight = -1;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002312 private Bitmap mAvailThumbnailBitmap = null;
2313 private Canvas mThumbnailCanvas = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002314
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002315 private final Bitmap createThumbnailBitmap(ActivityClientRecord r) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002316 Bitmap thumbnail = mAvailThumbnailBitmap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 try {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002318 if (thumbnail == null) {
2319 int w = mThumbnailWidth;
2320 int h;
2321 if (w < 0) {
2322 Resources res = r.activity.getResources();
2323 mThumbnailHeight = h =
2324 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002326 mThumbnailWidth = w =
2327 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
2328 } else {
2329 h = mThumbnailHeight;
2330 }
2331
2332 // On platforms where we don't want thumbnails, set dims to (0,0)
2333 if ((w > 0) && (h > 0)) {
2334 thumbnail = Bitmap.createBitmap(w, h, THUMBNAIL_FORMAT);
2335 thumbnail.eraseColor(0);
2336 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002337 }
2338
Dianne Hackbornfb3806d2010-12-09 13:14:12 -08002339 if (thumbnail != null) {
2340 Canvas cv = mThumbnailCanvas;
2341 if (cv == null) {
2342 mThumbnailCanvas = cv = new Canvas();
2343 }
2344
2345 cv.setBitmap(thumbnail);
2346 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
2347 mAvailThumbnailBitmap = thumbnail;
2348 thumbnail = null;
2349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002350 }
Jim Miller0b2a6d02010-07-13 18:01:29 -07002351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002352 } catch (Exception e) {
2353 if (!mInstrumentation.onException(r.activity, e)) {
2354 throw new RuntimeException(
2355 "Unable to create thumbnail of "
2356 + r.intent.getComponent().toShortString()
2357 + ": " + e.toString(), e);
2358 }
2359 thumbnail = null;
2360 }
2361
2362 return thumbnail;
2363 }
2364
2365 private final void handlePauseActivity(IBinder token, boolean finished,
2366 boolean userLeaving, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002367 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002369 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002370 if (userLeaving) {
2371 performUserLeavingActivity(r);
2372 }
Bob Leee5408332009-09-04 18:31:17 -07002373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002374 r.activity.mConfigChangeFlags |= configChanges;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002375 performPauseActivity(token, finished, r.isPreHoneycomb());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07002377 // Make sure any pending writes are now committed.
2378 QueuedWork.waitToFinish();
2379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002380 // Tell the activity manager we have paused.
2381 try {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002382 ActivityManagerNative.getDefault().activityPaused(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002383 } catch (RemoteException ex) {
2384 }
2385 }
2386 }
2387
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002388 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002389 mInstrumentation.callActivityOnUserLeaving(r.activity);
2390 }
2391
2392 final Bundle performPauseActivity(IBinder token, boolean finished,
2393 boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002394 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002395 return r != null ? performPauseActivity(r, finished, saveState) : null;
2396 }
2397
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002398 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002399 boolean saveState) {
2400 if (r.paused) {
2401 if (r.activity.mFinished) {
2402 // If we are finishing, we won't call onResume() in certain cases.
2403 // So here we likewise don't want to call onPause() if the activity
2404 // isn't resumed.
2405 return null;
2406 }
2407 RuntimeException e = new RuntimeException(
2408 "Performing pause of activity that is not resumed: "
2409 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002410 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002411 }
2412 Bundle state = null;
2413 if (finished) {
2414 r.activity.mFinished = true;
2415 }
2416 try {
2417 // Next have the activity save its current state and managed dialogs...
2418 if (!r.activity.mFinished && saveState) {
2419 state = new Bundle();
2420 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2421 r.state = state;
2422 }
2423 // Now we are idle.
2424 r.activity.mCalled = false;
2425 mInstrumentation.callActivityOnPause(r.activity);
2426 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
2427 if (!r.activity.mCalled) {
2428 throw new SuperNotCalledException(
2429 "Activity " + r.intent.getComponent().toShortString() +
2430 " did not call through to super.onPause()");
2431 }
2432
2433 } catch (SuperNotCalledException e) {
2434 throw e;
2435
2436 } catch (Exception e) {
2437 if (!mInstrumentation.onException(r.activity, e)) {
2438 throw new RuntimeException(
2439 "Unable to pause activity "
2440 + r.intent.getComponent().toShortString()
2441 + ": " + e.toString(), e);
2442 }
2443 }
2444 r.paused = true;
2445 return state;
2446 }
2447
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002448 final void performStopActivity(IBinder token, boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002449 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002450 performStopActivityInner(r, null, false, saveState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451 }
2452
2453 private static class StopInfo {
2454 Bitmap thumbnail;
2455 CharSequence description;
2456 }
2457
2458 private final class ProviderRefCount {
2459 public int count;
2460 ProviderRefCount(int pCount) {
2461 count = pCount;
2462 }
2463 }
2464
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002465 /**
2466 * Core implementation of stopping an activity. Note this is a little
2467 * tricky because the server's meaning of stop is slightly different
2468 * than our client -- for the server, stop means to save state and give
2469 * it the result when it is done, but the window may still be visible.
2470 * For the client, we want to call onStop()/onStart() to indicate when
2471 * the activity's UI visibillity changes.
2472 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002473 private final void performStopActivityInner(ActivityClientRecord r,
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002474 StopInfo info, boolean keepShown, boolean saveState) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002475 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002476 Bundle state = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002477 if (r != null) {
2478 if (!keepShown && r.stopped) {
2479 if (r.activity.mFinished) {
2480 // If we are finishing, we won't call onResume() in certain
2481 // cases. So here we likewise don't want to call onStop()
2482 // if the activity isn't resumed.
2483 return;
2484 }
2485 RuntimeException e = new RuntimeException(
2486 "Performing stop of activity that is not resumed: "
2487 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002488 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 }
2490
2491 if (info != null) {
2492 try {
2493 // First create a thumbnail for the activity...
Jim Miller0b2a6d02010-07-13 18:01:29 -07002494 info.thumbnail = createThumbnailBitmap(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 info.description = r.activity.onCreateDescription();
2496 } catch (Exception e) {
2497 if (!mInstrumentation.onException(r.activity, e)) {
2498 throw new RuntimeException(
2499 "Unable to save state of activity "
2500 + r.intent.getComponent().toShortString()
2501 + ": " + e.toString(), e);
2502 }
2503 }
2504 }
2505
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002506 // Next have the activity save its current state and managed dialogs...
2507 if (!r.activity.mFinished && saveState) {
2508 if (r.state == null) {
2509 state = new Bundle();
2510 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2511 r.state = state;
2512 } else {
2513 state = r.state;
2514 }
2515 }
2516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 if (!keepShown) {
2518 try {
2519 // Now we are idle.
2520 r.activity.performStop();
2521 } catch (Exception e) {
2522 if (!mInstrumentation.onException(r.activity, e)) {
2523 throw new RuntimeException(
2524 "Unable to stop activity "
2525 + r.intent.getComponent().toShortString()
2526 + ": " + e.toString(), e);
2527 }
2528 }
2529 r.stopped = true;
2530 }
2531
2532 r.paused = true;
2533 }
2534 }
2535
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002536 private final void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 View v = r.activity.mDecor;
2538 if (v != null) {
2539 if (show) {
2540 if (!r.activity.mVisibleFromServer) {
2541 r.activity.mVisibleFromServer = true;
2542 mNumVisibleActivities++;
2543 if (r.activity.mVisibleFromClient) {
2544 r.activity.makeVisible();
2545 }
2546 }
2547 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002548 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002549 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 performConfigurationChanged(r.activity, r.newConfig);
2551 r.newConfig = null;
2552 }
2553 } else {
2554 if (r.activity.mVisibleFromServer) {
2555 r.activity.mVisibleFromServer = false;
2556 mNumVisibleActivities--;
2557 v.setVisibility(View.INVISIBLE);
2558 }
2559 }
2560 }
2561 }
2562
2563 private final void handleStopActivity(IBinder token, boolean show, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002564 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 r.activity.mConfigChangeFlags |= configChanges;
2566
2567 StopInfo info = new StopInfo();
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002568 performStopActivityInner(r, info, show, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002570 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 TAG, "Finishing stop of " + r + ": show=" + show
2572 + " win=" + r.window);
2573
2574 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07002575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 // Tell activity manager we have been stopped.
2577 try {
2578 ActivityManagerNative.getDefault().activityStopped(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002579 r.token, r.state, info.thumbnail, info.description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 } catch (RemoteException ex) {
2581 }
2582 }
2583
2584 final void performRestartActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002585 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 if (r.stopped) {
2587 r.activity.performRestart();
2588 r.stopped = false;
2589 }
2590 }
2591
2592 private final void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002593 ActivityClientRecord r = mActivities.get(token);
Dianne Hackbornbfddc0f2010-12-14 11:28:01 -08002594
2595 if (r == null) {
2596 Log.w(TAG, "handleWindowVisibility: no activity for token " + token);
2597 return;
2598 }
2599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600 if (!show && !r.stopped) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002601 performStopActivityInner(r, null, show, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 } else if (show && r.stopped) {
2603 // If we are getting ready to gc after going to the background, well
2604 // we are back active so skip it.
2605 unscheduleGcIdler();
2606
2607 r.activity.performRestart();
2608 r.stopped = false;
2609 }
2610 if (r.activity.mDecor != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002611 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612 TAG, "Handle window " + r + " visibility: " + show);
2613 updateVisibility(r, show);
2614 }
2615 }
2616
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002617 private final void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002618 final int N = results.size();
2619 for (int i=0; i<N; i++) {
2620 ResultInfo ri = results.get(i);
2621 try {
2622 if (ri.mData != null) {
2623 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
2624 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002625 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07002626 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002627 r.activity.dispatchActivityResult(ri.mResultWho,
2628 ri.mRequestCode, ri.mResultCode, ri.mData);
2629 } catch (Exception e) {
2630 if (!mInstrumentation.onException(r.activity, e)) {
2631 throw new RuntimeException(
2632 "Failure delivering result " + ri + " to activity "
2633 + r.intent.getComponent().toShortString()
2634 + ": " + e.toString(), e);
2635 }
2636 }
2637 }
2638 }
2639
2640 private final void handleSendResult(ResultData res) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002641 ActivityClientRecord r = mActivities.get(res.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002642 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002643 if (r != null) {
2644 final boolean resumed = !r.paused;
2645 if (!r.activity.mFinished && r.activity.mDecor != null
2646 && r.hideForNow && resumed) {
2647 // We had hidden the activity because it started another
2648 // one... we have gotten a result back and we are not
2649 // paused, so make sure our window is visible.
2650 updateVisibility(r, true);
2651 }
2652 if (resumed) {
2653 try {
2654 // Now we are idle.
2655 r.activity.mCalled = false;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002656 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002657 mInstrumentation.callActivityOnPause(r.activity);
2658 if (!r.activity.mCalled) {
2659 throw new SuperNotCalledException(
2660 "Activity " + r.intent.getComponent().toShortString()
2661 + " did not call through to super.onPause()");
2662 }
2663 } catch (SuperNotCalledException e) {
2664 throw e;
2665 } catch (Exception e) {
2666 if (!mInstrumentation.onException(r.activity, e)) {
2667 throw new RuntimeException(
2668 "Unable to pause activity "
2669 + r.intent.getComponent().toShortString()
2670 + ": " + e.toString(), e);
2671 }
2672 }
2673 }
2674 deliverResults(r, res.results);
2675 if (resumed) {
2676 mInstrumentation.callActivityOnResume(r.activity);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002677 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678 }
2679 }
2680 }
2681
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002682 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683 return performDestroyActivity(token, finishing, 0, false);
2684 }
2685
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002686 private final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002687 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002688 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002689 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 if (r != null) {
2691 r.activity.mConfigChangeFlags |= configChanges;
2692 if (finishing) {
2693 r.activity.mFinished = true;
2694 }
2695 if (!r.paused) {
2696 try {
2697 r.activity.mCalled = false;
2698 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07002699 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002700 r.activity.getComponentName().getClassName());
2701 if (!r.activity.mCalled) {
2702 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002703 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002704 + " did not call through to super.onPause()");
2705 }
2706 } catch (SuperNotCalledException e) {
2707 throw e;
2708 } catch (Exception e) {
2709 if (!mInstrumentation.onException(r.activity, e)) {
2710 throw new RuntimeException(
2711 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002712 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002713 + ": " + e.toString(), e);
2714 }
2715 }
2716 r.paused = true;
2717 }
2718 if (!r.stopped) {
2719 try {
2720 r.activity.performStop();
2721 } catch (SuperNotCalledException e) {
2722 throw e;
2723 } catch (Exception e) {
2724 if (!mInstrumentation.onException(r.activity, e)) {
2725 throw new RuntimeException(
2726 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002727 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002728 + ": " + e.toString(), e);
2729 }
2730 }
2731 r.stopped = true;
2732 }
2733 if (getNonConfigInstance) {
2734 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002735 r.lastNonConfigurationInstances
2736 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002737 } catch (Exception e) {
2738 if (!mInstrumentation.onException(r.activity, e)) {
2739 throw new RuntimeException(
2740 "Unable to retain activity "
2741 + r.intent.getComponent().toShortString()
2742 + ": " + e.toString(), e);
2743 }
2744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002745 }
2746 try {
2747 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07002748 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002749 if (!r.activity.mCalled) {
2750 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002751 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 " did not call through to super.onDestroy()");
2753 }
2754 if (r.window != null) {
2755 r.window.closeAllPanels();
2756 }
2757 } catch (SuperNotCalledException e) {
2758 throw e;
2759 } catch (Exception e) {
2760 if (!mInstrumentation.onException(r.activity, e)) {
2761 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002762 "Unable to destroy activity " + safeToComponentShortString(r.intent)
2763 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002764 }
2765 }
2766 }
2767 mActivities.remove(token);
2768
2769 return r;
2770 }
2771
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002772 private static String safeToComponentShortString(Intent intent) {
2773 ComponentName component = intent.getComponent();
2774 return component == null ? "[Unknown]" : component.toShortString();
2775 }
2776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002777 private final void handleDestroyActivity(IBinder token, boolean finishing,
2778 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002779 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002780 configChanges, getNonConfigInstance);
2781 if (r != null) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002782 cleanUpPendingRemoveWindows(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002783 WindowManager wm = r.activity.getWindowManager();
2784 View v = r.activity.mDecor;
2785 if (v != null) {
2786 if (r.activity.mVisibleFromServer) {
2787 mNumVisibleActivities--;
2788 }
2789 IBinder wtoken = v.getWindowToken();
2790 if (r.activity.mWindowAdded) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002791 if (r.onlyLocalRequest) {
2792 // Hold off on removing this until the new activity's
2793 // window is being added.
2794 r.mPendingRemoveWindow = v;
2795 r.mPendingRemoveWindowManager = wm;
2796 } else {
2797 wm.removeViewImmediate(v);
2798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002799 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002800 if (wtoken != null && r.mPendingRemoveWindow == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002801 WindowManagerImpl.getDefault().closeAll(wtoken,
2802 r.activity.getClass().getName(), "Activity");
2803 }
2804 r.activity.mDecor = null;
2805 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002806 if (r.mPendingRemoveWindow == null) {
2807 // If we are delaying the removal of the activity window, then
2808 // we can't clean up all windows here. Note that we can't do
2809 // so later either, which means any windows that aren't closed
2810 // by the app will leak. Well we try to warning them a lot
2811 // about leaking windows, because that is a bug, so if they are
2812 // using this recreate facility then they get to live with leaks.
2813 WindowManagerImpl.getDefault().closeAll(token,
2814 r.activity.getClass().getName(), "Activity");
2815 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816
2817 // Mocked out contexts won't be participating in the normal
2818 // process lifecycle, but if we're running with a proper
2819 // ApplicationContext we need to have it tear down things
2820 // cleanly.
2821 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002822 if (c instanceof ContextImpl) {
2823 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 r.activity.getClass().getName(), "Activity");
2825 }
2826 }
2827 if (finishing) {
2828 try {
2829 ActivityManagerNative.getDefault().activityDestroyed(token);
2830 } catch (RemoteException ex) {
2831 // If the system process has died, it's game over for everyone.
2832 }
2833 }
2834 }
2835
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002836 public final void requestRelaunchActivity(IBinder token,
2837 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
2838 int configChanges, boolean notResumed, Configuration config,
2839 boolean fromServer) {
2840 ActivityClientRecord target = null;
2841
2842 synchronized (mPackages) {
2843 for (int i=0; i<mRelaunchingActivities.size(); i++) {
2844 ActivityClientRecord r = mRelaunchingActivities.get(i);
2845 if (r.token == token) {
2846 target = r;
2847 if (pendingResults != null) {
2848 if (r.pendingResults != null) {
2849 r.pendingResults.addAll(pendingResults);
2850 } else {
2851 r.pendingResults = pendingResults;
2852 }
2853 }
2854 if (pendingNewIntents != null) {
2855 if (r.pendingIntents != null) {
2856 r.pendingIntents.addAll(pendingNewIntents);
2857 } else {
2858 r.pendingIntents = pendingNewIntents;
2859 }
2860 }
2861 break;
2862 }
2863 }
2864
2865 if (target == null) {
2866 target = new ActivityClientRecord();
2867 target.token = token;
2868 target.pendingResults = pendingResults;
2869 target.pendingIntents = pendingNewIntents;
2870 if (!fromServer) {
2871 ActivityClientRecord existing = mActivities.get(token);
2872 if (existing != null) {
2873 target.startsNotResumed = existing.paused;
2874 }
2875 target.onlyLocalRequest = true;
2876 }
2877 mRelaunchingActivities.add(target);
2878 queueOrSendMessage(H.RELAUNCH_ACTIVITY, target);
2879 }
2880
2881 if (fromServer) {
2882 target.startsNotResumed = notResumed;
2883 target.onlyLocalRequest = false;
2884 }
2885 if (config != null) {
2886 target.createdConfig = config;
2887 }
2888 target.pendingConfigChanges |= configChanges;
2889 }
2890 }
2891
2892 private final void handleRelaunchActivity(ActivityClientRecord tmp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 // If we are getting ready to gc after going to the background, well
2894 // we are back active so skip it.
2895 unscheduleGcIdler();
2896
2897 Configuration changedConfig = null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002898 int configChanges = 0;
Bob Leee5408332009-09-04 18:31:17 -07002899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002900 // First: make sure we have the most recent configuration and most
2901 // recent version of the activity, or skip it if some previous call
2902 // had taken a more recent version.
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002903 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002904 int N = mRelaunchingActivities.size();
2905 IBinder token = tmp.token;
2906 tmp = null;
2907 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002908 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002909 if (r.token == token) {
2910 tmp = r;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002911 configChanges |= tmp.pendingConfigChanges;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002912 mRelaunchingActivities.remove(i);
2913 i--;
2914 N--;
2915 }
2916 }
Bob Leee5408332009-09-04 18:31:17 -07002917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002918 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002919 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002920 return;
2921 }
Bob Leee5408332009-09-04 18:31:17 -07002922
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002923 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
2924 + tmp.token + " with configChanges=0x"
2925 + Integer.toHexString(configChanges));
2926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002927 if (mPendingConfiguration != null) {
2928 changedConfig = mPendingConfiguration;
2929 mPendingConfiguration = null;
2930 }
2931 }
Bob Leee5408332009-09-04 18:31:17 -07002932
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002933 if (tmp.createdConfig != null) {
2934 // If the activity manager is passing us its current config,
2935 // assume that is really what we want regardless of what we
2936 // may have pending.
2937 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002938 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
2939 && mConfiguration.diff(tmp.createdConfig) != 0)) {
2940 if (changedConfig == null
2941 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
2942 changedConfig = tmp.createdConfig;
2943 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002944 }
2945 }
2946
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002947 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002948 + tmp.token + ": changedConfig=" + changedConfig);
2949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 // If there was a pending configuration change, execute it first.
2951 if (changedConfig != null) {
2952 handleConfigurationChanged(changedConfig);
2953 }
Bob Leee5408332009-09-04 18:31:17 -07002954
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002955 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002956 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 if (r == null) {
2958 return;
2959 }
Bob Leee5408332009-09-04 18:31:17 -07002960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002961 r.activity.mConfigChangeFlags |= configChanges;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002962 r.onlyLocalRequest = tmp.onlyLocalRequest;
Christopher Tateb70f3df2009-04-07 16:07:59 -07002963 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07002964
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002965 r.activity.mChangingConfigurations = true;
2966
Dianne Hackborne2b04802010-12-09 09:24:55 -08002967 // Need to ensure state is saved.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002968 if (!r.paused) {
Dianne Hackborne2b04802010-12-09 09:24:55 -08002969 performPauseActivity(r.token, false, r.isPreHoneycomb());
2970 }
2971 if (r.state == null && !r.stopped && !r.isPreHoneycomb()) {
2972 r.state = new Bundle();
2973 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974 }
Bob Leee5408332009-09-04 18:31:17 -07002975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07002977
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002978 r.activity = null;
2979 r.window = null;
2980 r.hideForNow = false;
2981 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07002982 // Merge any pending results and pending intents; don't just replace them
2983 if (tmp.pendingResults != null) {
2984 if (r.pendingResults == null) {
2985 r.pendingResults = tmp.pendingResults;
2986 } else {
2987 r.pendingResults.addAll(tmp.pendingResults);
2988 }
2989 }
2990 if (tmp.pendingIntents != null) {
2991 if (r.pendingIntents == null) {
2992 r.pendingIntents = tmp.pendingIntents;
2993 } else {
2994 r.pendingIntents.addAll(tmp.pendingIntents);
2995 }
2996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002997 r.startsNotResumed = tmp.startsNotResumed;
Bob Leee5408332009-09-04 18:31:17 -07002998
Christopher Tateb70f3df2009-04-07 16:07:59 -07002999 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003000 }
3001
3002 private final void handleRequestThumbnail(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003003 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003004 Bitmap thumbnail = createThumbnailBitmap(r);
3005 CharSequence description = null;
3006 try {
3007 description = r.activity.onCreateDescription();
3008 } catch (Exception e) {
3009 if (!mInstrumentation.onException(r.activity, e)) {
3010 throw new RuntimeException(
3011 "Unable to create description of activity "
3012 + r.intent.getComponent().toShortString()
3013 + ": " + e.toString(), e);
3014 }
3015 }
3016 //System.out.println("Reporting top thumbnail " + thumbnail);
3017 try {
3018 ActivityManagerNative.getDefault().reportThumbnail(
3019 token, thumbnail, description);
3020 } catch (RemoteException ex) {
3021 }
3022 }
3023
3024 ArrayList<ComponentCallbacks> collectComponentCallbacksLocked(
3025 boolean allActivities, Configuration newConfig) {
3026 ArrayList<ComponentCallbacks> callbacks
3027 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07003028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003029 if (mActivities.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003030 Iterator<ActivityClientRecord> it = mActivities.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 while (it.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003032 ActivityClientRecord ar = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033 Activity a = ar.activity;
3034 if (a != null) {
3035 if (!ar.activity.mFinished && (allActivities ||
3036 (a != null && !ar.paused))) {
3037 // If the activity is currently resumed, its configuration
3038 // needs to change right now.
3039 callbacks.add(a);
3040 } else if (newConfig != null) {
3041 // Otherwise, we will tell it about the change
3042 // the next time it is resumed or shown. Note that
3043 // the activity manager may, before then, decide the
3044 // activity needs to be destroyed to handle its new
3045 // configuration.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003046 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Setting activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003047 + ar.activityInfo.name + " newConfig=" + newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003048 ar.newConfig = newConfig;
3049 }
3050 }
3051 }
3052 }
3053 if (mServices.size() > 0) {
3054 Iterator<Service> it = mServices.values().iterator();
3055 while (it.hasNext()) {
3056 callbacks.add(it.next());
3057 }
3058 }
3059 synchronized (mProviderMap) {
3060 if (mLocalProviders.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003061 Iterator<ProviderClientRecord> it = mLocalProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003062 while (it.hasNext()) {
3063 callbacks.add(it.next().mLocalProvider);
3064 }
3065 }
3066 }
3067 final int N = mAllApplications.size();
3068 for (int i=0; i<N; i++) {
3069 callbacks.add(mAllApplications.get(i));
3070 }
Bob Leee5408332009-09-04 18:31:17 -07003071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003072 return callbacks;
3073 }
Bob Leee5408332009-09-04 18:31:17 -07003074
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003075 private final void performConfigurationChanged(
3076 ComponentCallbacks cb, Configuration config) {
3077 // Only for Activity objects, check that they actually call up to their
3078 // superclass implementation. ComponentCallbacks is an interface, so
3079 // we check the runtime type and act accordingly.
3080 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
3081 if (activity != null) {
3082 activity.mCalled = false;
3083 }
Bob Leee5408332009-09-04 18:31:17 -07003084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003085 boolean shouldChangeConfig = false;
3086 if ((activity == null) || (activity.mCurrentConfig == null)) {
3087 shouldChangeConfig = true;
3088 } else {
Bob Leee5408332009-09-04 18:31:17 -07003089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003090 // If the new config is the same as the config this Activity
3091 // is already running with then don't bother calling
3092 // onConfigurationChanged
3093 int diff = activity.mCurrentConfig.diff(config);
3094 if (diff != 0) {
Bob Leee5408332009-09-04 18:31:17 -07003095
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003096 // If this activity doesn't handle any of the config changes
3097 // then don't bother calling onConfigurationChanged as we're
3098 // going to destroy it.
3099 if ((~activity.mActivityInfo.configChanges & diff) == 0) {
3100 shouldChangeConfig = true;
3101 }
3102 }
3103 }
Bob Leee5408332009-09-04 18:31:17 -07003104
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003105 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003106 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003107 if (shouldChangeConfig) {
3108 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07003109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003110 if (activity != null) {
3111 if (!activity.mCalled) {
3112 throw new SuperNotCalledException(
3113 "Activity " + activity.getLocalClassName() +
3114 " did not call through to super.onConfigurationChanged()");
3115 }
3116 activity.mConfigChangeFlags = 0;
3117 activity.mCurrentConfig = new Configuration(config);
3118 }
3119 }
3120 }
3121
Dianne Hackbornae078162010-03-18 11:29:37 -07003122 final boolean applyConfigurationToResourcesLocked(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003123 if (mResConfiguration == null) {
3124 mResConfiguration = new Configuration();
3125 }
3126 if (!mResConfiguration.isOtherSeqNewer(config)) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003127 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq="
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003128 + mResConfiguration.seq + ", newSeq=" + config.seq);
Dianne Hackbornae078162010-03-18 11:29:37 -07003129 return false;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003130 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003131 int changes = mResConfiguration.updateFrom(config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003132 DisplayMetrics dm = getDisplayMetricsLocked(true);
Bob Leee5408332009-09-04 18:31:17 -07003133
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003134 // set it for java, this also affects newly created Resources
3135 if (config.locale != null) {
3136 Locale.setDefault(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003137 }
Bob Leee5408332009-09-04 18:31:17 -07003138
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003139 Resources.updateSystemConfiguration(config, dm);
Bob Leee5408332009-09-04 18:31:17 -07003140
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003141 ApplicationPackageManager.configurationChanged();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003142 //Slog.i(TAG, "Configuration changed in " + currentPackageName());
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003143
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003144 Iterator<WeakReference<Resources>> it =
3145 mActiveResources.values().iterator();
3146 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
3147 // mActiveResources.entrySet().iterator();
3148 while (it.hasNext()) {
3149 WeakReference<Resources> v = it.next();
3150 Resources r = v.get();
3151 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003152 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources "
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003153 + r + " config to: " + config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003154 r.updateConfiguration(config, dm);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003155 //Slog.i(TAG, "Updated app resources " + v.getKey()
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003156 // + " " + r + ": " + r.getConfiguration());
3157 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003158 //Slog.i(TAG, "Removing old resources " + v.getKey());
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003159 it.remove();
3160 }
3161 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003162
3163 return changes != 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003164 }
3165
3166 final void handleConfigurationChanged(Configuration config) {
3167
3168 ArrayList<ComponentCallbacks> callbacks = null;
3169
3170 synchronized (mPackages) {
3171 if (mPendingConfiguration != null) {
3172 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
3173 config = mPendingConfiguration;
3174 }
3175 mPendingConfiguration = null;
3176 }
3177
3178 if (config == null) {
3179 return;
3180 }
3181
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003182 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003183 + config);
3184
3185 applyConfigurationToResourcesLocked(config);
3186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003187 if (mConfiguration == null) {
3188 mConfiguration = new Configuration();
3189 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003190 if (!mConfiguration.isOtherSeqNewer(config)) {
3191 return;
3192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003193 mConfiguration.updateFrom(config);
Bob Leee5408332009-09-04 18:31:17 -07003194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003195 callbacks = collectComponentCallbacksLocked(false, config);
3196 }
Bob Leee5408332009-09-04 18:31:17 -07003197
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003198 if (callbacks != null) {
3199 final int N = callbacks.size();
3200 for (int i=0; i<N; i++) {
3201 performConfigurationChanged(callbacks.get(i), config);
3202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003203 }
3204 }
3205
3206 final void handleActivityConfigurationChanged(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003207 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003208 if (r == null || r.activity == null) {
3209 return;
3210 }
Bob Leee5408332009-09-04 18:31:17 -07003211
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003212 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003213 + r.activityInfo.name);
3214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003215 performConfigurationChanged(r.activity, mConfiguration);
3216 }
3217
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003218 final void handleProfilerControl(boolean start, ProfilerControlData pcd) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003219 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003220 try {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003221 Debug.startMethodTracing(pcd.path, pcd.fd.getFileDescriptor(),
3222 8 * 1024 * 1024, 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003223 } catch (RuntimeException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003224 Slog.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003225 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003226 } finally {
3227 try {
3228 pcd.fd.close();
3229 } catch (IOException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003230 Slog.w(TAG, "Failure closing profile fd", e);
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003231 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003232 }
3233 } else {
3234 Debug.stopMethodTracing();
3235 }
3236 }
Bob Leee5408332009-09-04 18:31:17 -07003237
Andy McFadden824c5102010-07-09 16:26:57 -07003238 final void handleDumpHeap(boolean managed, DumpHeapData dhd) {
3239 if (managed) {
3240 try {
3241 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor());
3242 } catch (IOException e) {
3243 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
3244 + " -- can the process access this path?");
3245 } finally {
3246 try {
3247 dhd.fd.close();
3248 } catch (IOException e) {
3249 Slog.w(TAG, "Failure closing profile fd", e);
3250 }
3251 }
3252 } else {
Andy McFadden06a6b552010-07-13 16:28:09 -07003253 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07003254 }
3255 }
3256
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003257 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
3258 boolean hasPkgInfo = false;
3259 if (packages != null) {
3260 for (int i=packages.length-1; i>=0; i--) {
3261 //Slog.i(TAG, "Cleaning old package: " + packages[i]);
3262 if (!hasPkgInfo) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003263 WeakReference<LoadedApk> ref;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003264 ref = mPackages.get(packages[i]);
3265 if (ref != null && ref.get() != null) {
3266 hasPkgInfo = true;
3267 } else {
3268 ref = mResourcePackages.get(packages[i]);
3269 if (ref != null && ref.get() != null) {
3270 hasPkgInfo = true;
3271 }
3272 }
3273 }
3274 mPackages.remove(packages[i]);
3275 mResourcePackages.remove(packages[i]);
3276 }
3277 }
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003278 ApplicationPackageManager.handlePackageBroadcast(cmd, packages,
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003279 hasPkgInfo);
3280 }
3281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003282 final void handleLowMemory() {
3283 ArrayList<ComponentCallbacks> callbacks
3284 = new ArrayList<ComponentCallbacks>();
3285
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003286 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003287 callbacks = collectComponentCallbacksLocked(true, null);
3288 }
Bob Leee5408332009-09-04 18:31:17 -07003289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003290 final int N = callbacks.size();
3291 for (int i=0; i<N; i++) {
3292 callbacks.get(i).onLowMemory();
3293 }
3294
Chris Tatece229052009-03-25 16:44:52 -07003295 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3296 if (Process.myUid() != Process.SYSTEM_UID) {
3297 int sqliteReleased = SQLiteDatabase.releaseMemory();
3298 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3299 }
Bob Leee5408332009-09-04 18:31:17 -07003300
Mike Reedcaf0df12009-04-27 14:32:05 -04003301 // Ask graphics to free up as much as possible (font/image caches)
3302 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303
3304 BinderInternal.forceGc("mem");
3305 }
3306
3307 private final void handleBindApplication(AppBindData data) {
3308 mBoundApplication = data;
3309 mConfiguration = new Configuration(data.config);
3310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003311 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003312 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313 android.ddm.DdmHandleAppName.setAppName(data.processName);
3314
3315 /*
3316 * Before spawning a new process, reset the time zone to be the system time zone.
3317 * This needs to be done because the system time zone could have changed after the
3318 * the spawning of this process. Without doing this this process would have the incorrect
3319 * system time zone.
3320 */
3321 TimeZone.setDefault(null);
3322
3323 /*
3324 * Initialize the default locale in this process for the reasons we set the time zone.
3325 */
3326 Locale.setDefault(data.config.locale);
3327
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003328 /*
3329 * Update the system configuration since its preloaded and might not
3330 * reflect configuration changes. The configuration object passed
3331 * in AppBindData can be safely assumed to be up to date
3332 */
3333 Resources.getSystem().updateConfiguration(mConfiguration, null);
3334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003335 data.info = getPackageInfoNoCheck(data.appInfo);
3336
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003337 /**
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003338 * For system applications on userdebug/eng builds, log stack
3339 * traces of disk and network access to dropbox for analysis.
3340 */
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07003341 if ((data.appInfo.flags &
3342 (ApplicationInfo.FLAG_SYSTEM |
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07003343 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0) {
3344 StrictMode.conditionallyEnableDebugLogging();
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003345 }
3346
3347 /**
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07003348 * For apps targetting SDK Honeycomb or later, we don't allow
3349 * network usage on the main event loop / UI thread.
3350 *
3351 * Note to those grepping: this is what ultimately throws
3352 * NetworkOnMainThreadException ...
3353 */
3354 if (data.appInfo.targetSdkVersion > 9) {
3355 StrictMode.enableDeathOnNetwork();
3356 }
3357
3358 /**
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003359 * Switch this process to density compatibility mode if needed.
3360 */
3361 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3362 == 0) {
3363 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3364 }
Bob Leee5408332009-09-04 18:31:17 -07003365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3367 // XXX should have option to change the port.
3368 Debug.changeDebugPort(8100);
3369 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003370 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003371 + " is waiting for the debugger on port 8100...");
3372
3373 IActivityManager mgr = ActivityManagerNative.getDefault();
3374 try {
3375 mgr.showWaitingForDebugger(mAppThread, true);
3376 } catch (RemoteException ex) {
3377 }
3378
3379 Debug.waitForDebugger();
3380
3381 try {
3382 mgr.showWaitingForDebugger(mAppThread, false);
3383 } catch (RemoteException ex) {
3384 }
3385
3386 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003387 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003388 + " can be debugged on port 8100...");
3389 }
3390 }
3391
Robert Greenwalt434203a2010-10-11 16:00:27 -07003392 /**
3393 * Initialize the default http proxy in this process for the reasons we set the time zone.
3394 */
3395 IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
3396 IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
3397 try {
3398 ProxyProperties proxyProperties = service.getProxy();
3399 Proxy.setHttpProxySystemProperty(proxyProperties);
3400 } catch (RemoteException e) {}
3401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003402 if (data.instrumentationName != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08003403 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003404 appContext.init(data.info, null, this);
3405 InstrumentationInfo ii = null;
3406 try {
3407 ii = appContext.getPackageManager().
3408 getInstrumentationInfo(data.instrumentationName, 0);
3409 } catch (PackageManager.NameNotFoundException e) {
3410 }
3411 if (ii == null) {
3412 throw new RuntimeException(
3413 "Unable to find instrumentation info for: "
3414 + data.instrumentationName);
3415 }
3416
3417 mInstrumentationAppDir = ii.sourceDir;
3418 mInstrumentationAppPackage = ii.packageName;
3419 mInstrumentedAppDir = data.info.getAppDir();
3420
3421 ApplicationInfo instrApp = new ApplicationInfo();
3422 instrApp.packageName = ii.packageName;
3423 instrApp.sourceDir = ii.sourceDir;
3424 instrApp.publicSourceDir = ii.publicSourceDir;
3425 instrApp.dataDir = ii.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003426 instrApp.nativeLibraryDir = ii.nativeLibraryDir;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003427 LoadedApk pi = getPackageInfo(instrApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428 appContext.getClassLoader(), false, true);
Dianne Hackborn21556372010-02-04 16:34:40 -08003429 ContextImpl instrContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003430 instrContext.init(pi, null, this);
3431
3432 try {
3433 java.lang.ClassLoader cl = instrContext.getClassLoader();
3434 mInstrumentation = (Instrumentation)
3435 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3436 } catch (Exception e) {
3437 throw new RuntimeException(
3438 "Unable to instantiate instrumentation "
3439 + data.instrumentationName + ": " + e.toString(), e);
3440 }
3441
3442 mInstrumentation.init(this, instrContext, appContext,
3443 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3444
3445 if (data.profileFile != null && !ii.handleProfiling) {
3446 data.handlingProfiling = true;
3447 File file = new File(data.profileFile);
3448 file.getParentFile().mkdirs();
3449 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3450 }
3451
3452 try {
3453 mInstrumentation.onCreate(data.instrumentationArgs);
3454 }
3455 catch (Exception e) {
3456 throw new RuntimeException(
3457 "Exception thrown in onCreate() of "
3458 + data.instrumentationName + ": " + e.toString(), e);
3459 }
3460
3461 } else {
3462 mInstrumentation = new Instrumentation();
3463 }
3464
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08003465 if ((data.appInfo.flags&ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
3466 // XXX bump up Dalvik's heap.
3467 }
3468
Christopher Tate181fafa2009-05-14 11:12:14 -07003469 // If the app is being launched for full backup or restore, bring it up in
3470 // a restricted environment with the base application class.
Dianne Hackborn0be1f782009-11-09 12:30:12 -08003471 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003472 mInitialApplication = app;
3473
3474 List<ProviderInfo> providers = data.providers;
3475 if (providers != null) {
3476 installContentProviders(app, providers);
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08003477 // For process that contains content providers, we want to
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003478 // ensure that the JIT is enabled "at some point".
3479 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003480 }
3481
3482 try {
3483 mInstrumentation.callApplicationOnCreate(app);
3484 } catch (Exception e) {
3485 if (!mInstrumentation.onException(app, e)) {
3486 throw new RuntimeException(
3487 "Unable to create application " + app.getClass().getName()
3488 + ": " + e.toString(), e);
3489 }
3490 }
3491 }
3492
3493 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
3494 IActivityManager am = ActivityManagerNative.getDefault();
3495 if (mBoundApplication.profileFile != null && mBoundApplication.handlingProfiling) {
3496 Debug.stopMethodTracing();
3497 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003498 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003499 // + ", app thr: " + mAppThread);
3500 try {
3501 am.finishInstrumentation(mAppThread, resultCode, results);
3502 } catch (RemoteException ex) {
3503 }
3504 }
3505
3506 private final void installContentProviders(
3507 Context context, List<ProviderInfo> providers) {
3508 final ArrayList<IActivityManager.ContentProviderHolder> results =
3509 new ArrayList<IActivityManager.ContentProviderHolder>();
3510
3511 Iterator<ProviderInfo> i = providers.iterator();
3512 while (i.hasNext()) {
3513 ProviderInfo cpi = i.next();
3514 StringBuilder buf = new StringBuilder(128);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07003515 buf.append("Pub ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003516 buf.append(cpi.authority);
3517 buf.append(": ");
3518 buf.append(cpi.name);
3519 Log.i(TAG, buf.toString());
3520 IContentProvider cp = installProvider(context, null, cpi, false);
3521 if (cp != null) {
3522 IActivityManager.ContentProviderHolder cph =
3523 new IActivityManager.ContentProviderHolder(cpi);
3524 cph.provider = cp;
3525 results.add(cph);
3526 // Don't ever unload this provider from the process.
3527 synchronized(mProviderMap) {
3528 mProviderRefCountMap.put(cp.asBinder(), new ProviderRefCount(10000));
3529 }
3530 }
3531 }
3532
3533 try {
3534 ActivityManagerNative.getDefault().publishContentProviders(
3535 getApplicationThread(), results);
3536 } catch (RemoteException ex) {
3537 }
3538 }
3539
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003540 private final IContentProvider getExistingProvider(Context context, String name) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003541 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003542 final ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003543 if (pr != null) {
3544 return pr.mProvider;
3545 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003546 return null;
3547 }
3548 }
3549
3550 private final IContentProvider getProvider(Context context, String name) {
3551 IContentProvider existing = getExistingProvider(context, name);
3552 if (existing != null) {
3553 return existing;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003554 }
3555
3556 IActivityManager.ContentProviderHolder holder = null;
3557 try {
3558 holder = ActivityManagerNative.getDefault().getContentProvider(
3559 getApplicationThread(), name);
3560 } catch (RemoteException ex) {
3561 }
3562 if (holder == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003563 Slog.e(TAG, "Failed to find provider info for " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003564 return null;
3565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003566
3567 IContentProvider prov = installProvider(context, holder.provider,
3568 holder.info, true);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003569 //Slog.i(TAG, "noReleaseNeeded=" + holder.noReleaseNeeded);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003570 if (holder.noReleaseNeeded || holder.provider == null) {
3571 // We are not going to release the provider if it is an external
3572 // provider that doesn't care about being released, or if it is
3573 // a local provider running in this process.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003574 //Slog.i(TAG, "*** NO RELEASE NEEDED");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003575 synchronized(mProviderMap) {
3576 mProviderRefCountMap.put(prov.asBinder(), new ProviderRefCount(10000));
3577 }
3578 }
3579 return prov;
3580 }
3581
3582 public final IContentProvider acquireProvider(Context c, String name) {
3583 IContentProvider provider = getProvider(c, name);
3584 if(provider == null)
3585 return null;
3586 IBinder jBinder = provider.asBinder();
3587 synchronized(mProviderMap) {
3588 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3589 if(prc == null) {
3590 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3591 } else {
3592 prc.count++;
3593 } //end else
3594 } //end synchronized
3595 return provider;
3596 }
3597
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003598 public final IContentProvider acquireExistingProvider(Context c, String name) {
3599 IContentProvider provider = getExistingProvider(c, name);
3600 if(provider == null)
3601 return null;
3602 IBinder jBinder = provider.asBinder();
3603 synchronized(mProviderMap) {
3604 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3605 if(prc == null) {
3606 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3607 } else {
3608 prc.count++;
3609 } //end else
3610 } //end synchronized
3611 return provider;
3612 }
3613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003614 public final boolean releaseProvider(IContentProvider provider) {
3615 if(provider == null) {
3616 return false;
3617 }
3618 IBinder jBinder = provider.asBinder();
3619 synchronized(mProviderMap) {
3620 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3621 if(prc == null) {
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003622 if(localLOGV) Slog.v(TAG, "releaseProvider::Weird shouldn't be here");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003623 return false;
3624 } else {
3625 prc.count--;
3626 if(prc.count == 0) {
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003627 // Schedule the actual remove asynchronously, since we
3628 // don't know the context this will be called in.
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003629 // TODO: it would be nice to post a delayed message, so
3630 // if we come back and need the same provider quickly
3631 // we will still have it available.
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003632 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
3633 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003634 } //end if
3635 } //end else
3636 } //end synchronized
3637 return true;
3638 }
3639
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003640 final void completeRemoveProvider(IContentProvider provider) {
3641 IBinder jBinder = provider.asBinder();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003642 String name = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003643 synchronized(mProviderMap) {
3644 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3645 if(prc != null && prc.count == 0) {
3646 mProviderRefCountMap.remove(jBinder);
3647 //invoke removeProvider to dereference provider
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003648 name = removeProviderLocked(provider);
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003649 }
3650 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003651
3652 if (name != null) {
3653 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003654 if(localLOGV) Slog.v(TAG, "removeProvider::Invoking " +
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003655 "ActivityManagerNative.removeContentProvider(" + name);
3656 ActivityManagerNative.getDefault().removeContentProvider(
3657 getApplicationThread(), name);
3658 } catch (RemoteException e) {
3659 //do nothing content provider object is dead any way
3660 } //end catch
3661 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003662 }
3663
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003664 public final String removeProviderLocked(IContentProvider provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003665 if (provider == null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003666 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003667 }
3668 IBinder providerBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003669
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003670 String name = null;
3671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003672 // remove the provider from mProviderMap
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003673 Iterator<ProviderClientRecord> iter = mProviderMap.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003674 while (iter.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003675 ProviderClientRecord pr = iter.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676 IBinder myBinder = pr.mProvider.asBinder();
3677 if (myBinder == providerBinder) {
3678 //find if its published by this process itself
3679 if(pr.mLocalProvider != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003680 if(localLOGV) Slog.i(TAG, "removeProvider::found local provider returning");
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003681 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003682 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003683 if(localLOGV) Slog.v(TAG, "removeProvider::Not local provider Unlinking " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003684 "death recipient");
3685 //content provider is in another process
3686 myBinder.unlinkToDeath(pr, 0);
3687 iter.remove();
3688 //invoke remove only once for the very first name seen
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003689 if(name == null) {
3690 name = pr.mName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003691 }
3692 } //end if myBinder
3693 } //end while iter
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003694
3695 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003696 }
3697
3698 final void removeDeadProvider(String name, IContentProvider provider) {
3699 synchronized(mProviderMap) {
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
3711 final void removeDeadProviderLocked(String name, IContentProvider provider) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003712 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003713 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003714 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003715 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003716 if (removed != null) {
3717 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3718 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003719 }
3720 }
3721
3722 private final IContentProvider installProvider(Context context,
3723 IContentProvider provider, ProviderInfo info, boolean noisy) {
3724 ContentProvider localProvider = null;
3725 if (provider == null) {
3726 if (noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003727 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003728 + info.name);
3729 }
3730 Context c = null;
3731 ApplicationInfo ai = info.applicationInfo;
3732 if (context.getPackageName().equals(ai.packageName)) {
3733 c = context;
3734 } else if (mInitialApplication != null &&
3735 mInitialApplication.getPackageName().equals(ai.packageName)) {
3736 c = mInitialApplication;
3737 } else {
3738 try {
3739 c = context.createPackageContext(ai.packageName,
3740 Context.CONTEXT_INCLUDE_CODE);
3741 } catch (PackageManager.NameNotFoundException e) {
3742 }
3743 }
3744 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003745 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 ai.packageName +
3747 " while loading content provider " +
3748 info.name);
3749 return null;
3750 }
3751 try {
3752 final java.lang.ClassLoader cl = c.getClassLoader();
3753 localProvider = (ContentProvider)cl.
3754 loadClass(info.name).newInstance();
3755 provider = localProvider.getIContentProvider();
3756 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003757 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003758 info.name + " from sourceDir " +
3759 info.applicationInfo.sourceDir);
3760 return null;
3761 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003762 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003763 TAG, "Instantiating local provider " + info.name);
3764 // XXX Need to create the correct context for this provider.
3765 localProvider.attachInfo(c, info);
3766 } catch (java.lang.Exception e) {
3767 if (!mInstrumentation.onException(null, e)) {
3768 throw new RuntimeException(
3769 "Unable to get provider " + info.name
3770 + ": " + e.toString(), e);
3771 }
3772 return null;
3773 }
3774 } else if (localLOGV) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003775 Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003776 + info.name);
3777 }
3778
3779 synchronized (mProviderMap) {
3780 // Cache the pointer for the remote provider.
3781 String names[] = PATTERN_SEMICOLON.split(info.authority);
3782 for (int i=0; i<names.length; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003783 ProviderClientRecord pr = new ProviderClientRecord(names[i], provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003784 localProvider);
3785 try {
3786 provider.asBinder().linkToDeath(pr, 0);
3787 mProviderMap.put(names[i], pr);
3788 } catch (RemoteException e) {
3789 return null;
3790 }
3791 }
3792 if (localProvider != null) {
3793 mLocalProviders.put(provider.asBinder(),
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003794 new ProviderClientRecord(null, provider, localProvider));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003795 }
3796 }
3797
3798 return provider;
3799 }
3800
3801 private final void attach(boolean system) {
3802 sThreadLocal.set(this);
3803 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804 if (!system) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003805 ViewRoot.addFirstDrawHandler(new Runnable() {
3806 public void run() {
3807 ensureJitEnabled();
3808 }
3809 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003810 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
3811 RuntimeInit.setApplicationObject(mAppThread.asBinder());
3812 IActivityManager mgr = ActivityManagerNative.getDefault();
3813 try {
3814 mgr.attachApplication(mAppThread);
3815 } catch (RemoteException ex) {
3816 }
3817 } else {
3818 // Don't set application object here -- if the system crashes,
3819 // we can't display an alert, we just want to die die die.
3820 android.ddm.DdmHandleAppName.setAppName("system_process");
3821 try {
3822 mInstrumentation = new Instrumentation();
Dianne Hackborn21556372010-02-04 16:34:40 -08003823 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003824 context.init(getSystemContext().mPackageInfo, null, this);
3825 Application app = Instrumentation.newApplication(Application.class, context);
3826 mAllApplications.add(app);
3827 mInitialApplication = app;
3828 app.onCreate();
3829 } catch (Exception e) {
3830 throw new RuntimeException(
3831 "Unable to instantiate Application():" + e.toString(), e);
3832 }
3833 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003834
3835 ViewRoot.addConfigCallback(new ComponentCallbacks() {
3836 public void onConfigurationChanged(Configuration newConfig) {
3837 synchronized (mPackages) {
Dianne Hackbornae078162010-03-18 11:29:37 -07003838 // We need to apply this change to the resources
3839 // immediately, because upon returning the view
3840 // hierarchy will be informed about it.
3841 if (applyConfigurationToResourcesLocked(newConfig)) {
3842 // This actually changed the resources! Tell
3843 // everyone about it.
3844 if (mPendingConfiguration == null ||
3845 mPendingConfiguration.isOtherSeqNewer(newConfig)) {
3846 mPendingConfiguration = newConfig;
3847
3848 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
3849 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003850 }
3851 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003852 }
3853 public void onLowMemory() {
3854 }
3855 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003856 }
3857
3858 private final void detach()
3859 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003860 sThreadLocal.set(null);
3861 }
3862
3863 public static final ActivityThread systemMain() {
Romain Guy52339202010-09-03 16:04:46 -07003864 HardwareRenderer.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003865 ActivityThread thread = new ActivityThread();
3866 thread.attach(true);
3867 return thread;
3868 }
3869
3870 public final void installSystemProviders(List providers) {
3871 if (providers != null) {
3872 installContentProviders(mInitialApplication,
3873 (List<ProviderInfo>)providers);
3874 }
3875 }
3876
3877 public static final void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07003878 SamplingProfilerIntegration.start();
3879
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -08003880 // CloseGuard defaults to true and can be quite spammy. We
3881 // disable it here, but selectively enable it later (via
3882 // StrictMode) on debug builds, but using DropBox, not logs.
3883 CloseGuard.setEnabled(false);
3884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003885 Process.setArgV0("<pre-initialized>");
3886
3887 Looper.prepareMainLooper();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07003888 if (sMainThreadHandler == null) {
3889 sMainThreadHandler = new Handler();
3890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003891
3892 ActivityThread thread = new ActivityThread();
3893 thread.attach(false);
3894
Dianne Hackborn287952c2010-09-22 22:34:31 -07003895 if (false) {
3896 Looper.myLooper().setMessageLogging(new
3897 LogPrinter(Log.DEBUG, "ActivityThread"));
3898 }
3899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 Looper.loop();
3901
3902 if (Process.supportsProcesses()) {
3903 throw new RuntimeException("Main thread loop unexpectedly exited");
3904 }
3905
3906 thread.detach();
Bob Leeeec2f412009-09-10 11:01:24 +02003907 String name = (thread.mInitialApplication != null)
3908 ? thread.mInitialApplication.getPackageName()
3909 : "<unknown>";
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003910 Slog.i(TAG, "Main thread of " + name + " is now exiting");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003911 }
3912}