blob: 2389f01cd54f3597702ce9250fa948f1a7b6824c [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);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08001619 StrictMode.incrementExpectedActivityCount(activity.getClass());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 r.intent.setExtrasClassLoader(cl);
1621 if (r.state != null) {
1622 r.state.setClassLoader(cl);
1623 }
1624 } catch (Exception e) {
1625 if (!mInstrumentation.onException(activity, e)) {
1626 throw new RuntimeException(
1627 "Unable to instantiate activity " + component
1628 + ": " + e.toString(), e);
1629 }
1630 }
1631
1632 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001633 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001634
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001635 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
1636 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 TAG, r + ": app=" + app
1638 + ", appName=" + app.getPackageName()
1639 + ", pkg=" + r.packageInfo.getPackageName()
1640 + ", comp=" + r.intent.getComponent().toShortString()
1641 + ", dir=" + r.packageInfo.getAppDir());
1642
1643 if (activity != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001644 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 appContext.init(r.packageInfo, r.token, this);
1646 appContext.setOuterContext(activity);
1647 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
1648 Configuration config = new Configuration(mConfiguration);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001649 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07001650 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001651 activity.attach(appContext, this, getInstrumentation(), r.token,
1652 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001653 r.embeddedID, r.lastNonConfigurationInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07001654
Christopher Tateb70f3df2009-04-07 16:07:59 -07001655 if (customIntent != null) {
1656 activity.mIntent = customIntent;
1657 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001658 r.lastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 activity.mStartedActivity = false;
1660 int theme = r.activityInfo.getThemeResource();
1661 if (theme != 0) {
1662 activity.setTheme(theme);
1663 }
1664
1665 activity.mCalled = false;
1666 mInstrumentation.callActivityOnCreate(activity, r.state);
1667 if (!activity.mCalled) {
1668 throw new SuperNotCalledException(
1669 "Activity " + r.intent.getComponent().toShortString() +
1670 " did not call through to super.onCreate()");
1671 }
1672 r.activity = activity;
1673 r.stopped = true;
1674 if (!r.activity.mFinished) {
1675 activity.performStart();
1676 r.stopped = false;
1677 }
1678 if (!r.activity.mFinished) {
1679 if (r.state != null) {
1680 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
1681 }
1682 }
1683 if (!r.activity.mFinished) {
1684 activity.mCalled = false;
1685 mInstrumentation.callActivityOnPostCreate(activity, r.state);
1686 if (!activity.mCalled) {
1687 throw new SuperNotCalledException(
1688 "Activity " + r.intent.getComponent().toShortString() +
1689 " did not call through to super.onPostCreate()");
1690 }
1691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 }
1693 r.paused = true;
1694
1695 mActivities.put(r.token, r);
1696
1697 } catch (SuperNotCalledException e) {
1698 throw e;
1699
1700 } catch (Exception e) {
1701 if (!mInstrumentation.onException(activity, e)) {
1702 throw new RuntimeException(
1703 "Unable to start activity " + component
1704 + ": " + e.toString(), e);
1705 }
1706 }
1707
1708 return activity;
1709 }
1710
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001711 private final void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 // If we are getting ready to gc after going to the background, well
1713 // we are back active so skip it.
1714 unscheduleGcIdler();
1715
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001716 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001718 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719
1720 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08001721 r.createdConfig = new Configuration(mConfiguration);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001722 Bundle oldState = r.state;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 handleResumeActivity(r.token, false, r.isForward);
1724
1725 if (!r.activity.mFinished && r.startsNotResumed) {
1726 // The activity manager actually wants this one to start out
1727 // paused, because it needs to be visible but isn't in the
1728 // foreground. We accomplish this by going through the
1729 // normal startup (because activities expect to go through
1730 // onResume() the first time they run, before their window
1731 // is displayed), and then pausing it. However, in this case
1732 // we do -not- need to do the full pause cycle (of freezing
1733 // and such) because the activity manager assumes it can just
1734 // retain the current state it has.
1735 try {
1736 r.activity.mCalled = false;
1737 mInstrumentation.callActivityOnPause(r.activity);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001738 // We need to keep around the original state, in case
1739 // we need to be created again.
1740 r.state = oldState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 if (!r.activity.mCalled) {
1742 throw new SuperNotCalledException(
1743 "Activity " + r.intent.getComponent().toShortString() +
1744 " did not call through to super.onPause()");
1745 }
1746
1747 } catch (SuperNotCalledException e) {
1748 throw e;
1749
1750 } catch (Exception e) {
1751 if (!mInstrumentation.onException(r.activity, e)) {
1752 throw new RuntimeException(
1753 "Unable to pause activity "
1754 + r.intent.getComponent().toShortString()
1755 + ": " + e.toString(), e);
1756 }
1757 }
1758 r.paused = true;
1759 }
1760 } else {
1761 // If there was an error, for any reason, tell the activity
1762 // manager to stop us.
1763 try {
1764 ActivityManagerNative.getDefault()
1765 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
1766 } catch (RemoteException ex) {
1767 }
1768 }
1769 }
1770
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001771 private final void deliverNewIntents(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 List<Intent> intents) {
1773 final int N = intents.size();
1774 for (int i=0; i<N; i++) {
1775 Intent intent = intents.get(i);
1776 intent.setExtrasClassLoader(r.activity.getClassLoader());
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001777 r.activity.mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
1779 }
1780 }
1781
1782 public final void performNewIntents(IBinder token,
1783 List<Intent> intents) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001784 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 if (r != null) {
1786 final boolean resumed = !r.paused;
1787 if (resumed) {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001788 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 mInstrumentation.callActivityOnPause(r.activity);
1790 }
1791 deliverNewIntents(r, intents);
1792 if (resumed) {
1793 mInstrumentation.callActivityOnResume(r.activity);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001794 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 }
1796 }
1797 }
Bob Leee5408332009-09-04 18:31:17 -07001798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001799 private final void handleNewIntent(NewIntentData data) {
1800 performNewIntents(data.token, data.intents);
1801 }
1802
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07001803 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
1804
1805 /**
1806 * Return the Intent that's currently being handled by a
1807 * BroadcastReceiver on this thread, or null if none.
1808 * @hide
1809 */
1810 public static Intent getIntentBeingBroadcast() {
1811 return sCurrentBroadcastIntent.get();
1812 }
1813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 private final void handleReceiver(ReceiverData data) {
1815 // If we are getting ready to gc after going to the background, well
1816 // we are back active so skip it.
1817 unscheduleGcIdler();
1818
1819 String component = data.intent.getComponent().getClassName();
1820
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001821 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 data.info.applicationInfo);
1823
1824 IActivityManager mgr = ActivityManagerNative.getDefault();
1825
1826 BroadcastReceiver receiver = null;
1827 try {
1828 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1829 data.intent.setExtrasClassLoader(cl);
Dianne Hackborne829fef2010-10-26 17:44:01 -07001830 data.setExtrasClassLoader(cl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
1832 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07001833 if (DEBUG_BROADCAST) Slog.i(TAG,
1834 "Finishing failed broadcast to " + data.intent.getComponent());
1835 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 throw new RuntimeException(
1837 "Unable to instantiate receiver " + component
1838 + ": " + e.toString(), e);
1839 }
1840
1841 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001842 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001843
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001844 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 TAG, "Performing receive of " + data.intent
1846 + ": app=" + app
1847 + ", appName=" + app.getPackageName()
1848 + ", pkg=" + packageInfo.getPackageName()
1849 + ", comp=" + data.intent.getComponent().toShortString()
1850 + ", dir=" + packageInfo.getAppDir());
1851
Dianne Hackborn21556372010-02-04 16:34:40 -08001852 ContextImpl context = (ContextImpl)app.getBaseContext();
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07001853 sCurrentBroadcastIntent.set(data.intent);
Dianne Hackborne829fef2010-10-26 17:44:01 -07001854 receiver.setPendingResult(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 receiver.onReceive(context.getReceiverRestrictedContext(),
1856 data.intent);
1857 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07001858 if (DEBUG_BROADCAST) Slog.i(TAG,
1859 "Finishing failed broadcast to " + data.intent.getComponent());
1860 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001861 if (!mInstrumentation.onException(receiver, e)) {
1862 throw new RuntimeException(
1863 "Unable to start receiver " + component
1864 + ": " + e.toString(), e);
1865 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07001866 } finally {
1867 sCurrentBroadcastIntent.set(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001868 }
1869
Dianne Hackborne829fef2010-10-26 17:44:01 -07001870 if (receiver.getPendingResult() != null) {
1871 data.finish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 }
1873 }
1874
Christopher Tate181fafa2009-05-14 11:12:14 -07001875 // Instantiate a BackupAgent and tell it that it's alive
1876 private final void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001877 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001878
1879 // no longer idle; we have backup work to do
1880 unscheduleGcIdler();
1881
1882 // instantiate the BackupAgent class named in the manifest
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001883 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001884 String packageName = packageInfo.mPackageName;
1885 if (mBackupAgents.get(packageName) != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001886 Slog.d(TAG, "BackupAgent " + " for " + packageName
Christopher Tate181fafa2009-05-14 11:12:14 -07001887 + " already exists");
1888 return;
1889 }
Bob Leee5408332009-09-04 18:31:17 -07001890
Christopher Tate181fafa2009-05-14 11:12:14 -07001891 BackupAgent agent = null;
1892 String classname = data.appInfo.backupAgentName;
1893 if (classname == null) {
1894 if (data.backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001895 Slog.e(TAG, "Attempted incremental backup but no defined agent for "
Christopher Tate181fafa2009-05-14 11:12:14 -07001896 + packageName);
1897 return;
1898 }
1899 classname = "android.app.FullBackupAgent";
1900 }
1901 try {
Christopher Tated1475e02009-07-09 15:36:17 -07001902 IBinder binder = null;
1903 try {
1904 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1905 agent = (BackupAgent) cl.loadClass(data.appInfo.backupAgentName).newInstance();
1906
1907 // set up the agent's context
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001908 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing BackupAgent "
Christopher Tated1475e02009-07-09 15:36:17 -07001909 + data.appInfo.backupAgentName);
1910
Dianne Hackborn21556372010-02-04 16:34:40 -08001911 ContextImpl context = new ContextImpl();
Christopher Tated1475e02009-07-09 15:36:17 -07001912 context.init(packageInfo, null, this);
1913 context.setOuterContext(agent);
1914 agent.attach(context);
1915
1916 agent.onCreate();
1917 binder = agent.onBind();
1918 mBackupAgents.put(packageName, agent);
1919 } catch (Exception e) {
1920 // If this is during restore, fail silently; otherwise go
1921 // ahead and let the user see the crash.
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001922 Slog.e(TAG, "Agent threw during creation: " + e);
Christopher Tated1475e02009-07-09 15:36:17 -07001923 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE) {
1924 throw e;
1925 }
1926 // falling through with 'binder' still null
1927 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001928
1929 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07001930 try {
1931 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
1932 } catch (RemoteException e) {
1933 // nothing to do.
1934 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001935 } catch (Exception e) {
1936 throw new RuntimeException("Unable to create BackupAgent "
1937 + data.appInfo.backupAgentName + ": " + e.toString(), e);
1938 }
1939 }
1940
1941 // Tear down a BackupAgent
1942 private final void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001943 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07001944
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001945 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001946 String packageName = packageInfo.mPackageName;
1947 BackupAgent agent = mBackupAgents.get(packageName);
1948 if (agent != null) {
1949 try {
1950 agent.onDestroy();
1951 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001952 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001953 e.printStackTrace();
1954 }
1955 mBackupAgents.remove(packageName);
1956 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001957 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001958 }
1959 }
1960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 private final void handleCreateService(CreateServiceData data) {
1962 // If we are getting ready to gc after going to the background, well
1963 // we are back active so skip it.
1964 unscheduleGcIdler();
1965
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001966 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 data.info.applicationInfo);
1968 Service service = null;
1969 try {
1970 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1971 service = (Service) cl.loadClass(data.info.name).newInstance();
1972 } catch (Exception e) {
1973 if (!mInstrumentation.onException(service, e)) {
1974 throw new RuntimeException(
1975 "Unable to instantiate service " + data.info.name
1976 + ": " + e.toString(), e);
1977 }
1978 }
1979
1980 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001981 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982
Dianne Hackborn21556372010-02-04 16:34:40 -08001983 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 context.init(packageInfo, null, this);
1985
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001986 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 context.setOuterContext(service);
1988 service.attach(context, this, data.info.name, data.token, app,
1989 ActivityManagerNative.getDefault());
1990 service.onCreate();
1991 mServices.put(data.token, service);
1992 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001993 ActivityManagerNative.getDefault().serviceDoneExecuting(
1994 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001995 } catch (RemoteException e) {
1996 // nothing to do.
1997 }
1998 } catch (Exception e) {
1999 if (!mInstrumentation.onException(service, e)) {
2000 throw new RuntimeException(
2001 "Unable to create service " + data.info.name
2002 + ": " + e.toString(), e);
2003 }
2004 }
2005 }
2006
2007 private final void handleBindService(BindServiceData data) {
2008 Service s = mServices.get(data.token);
2009 if (s != null) {
2010 try {
2011 data.intent.setExtrasClassLoader(s.getClassLoader());
2012 try {
2013 if (!data.rebind) {
2014 IBinder binder = s.onBind(data.intent);
2015 ActivityManagerNative.getDefault().publishService(
2016 data.token, data.intent, binder);
2017 } else {
2018 s.onRebind(data.intent);
2019 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002020 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002021 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002022 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 } catch (RemoteException ex) {
2024 }
2025 } catch (Exception e) {
2026 if (!mInstrumentation.onException(s, e)) {
2027 throw new RuntimeException(
2028 "Unable to bind to service " + s
2029 + " with " + data.intent + ": " + e.toString(), e);
2030 }
2031 }
2032 }
2033 }
2034
2035 private final void handleUnbindService(BindServiceData data) {
2036 Service s = mServices.get(data.token);
2037 if (s != null) {
2038 try {
2039 data.intent.setExtrasClassLoader(s.getClassLoader());
2040 boolean doRebind = s.onUnbind(data.intent);
2041 try {
2042 if (doRebind) {
2043 ActivityManagerNative.getDefault().unbindFinished(
2044 data.token, data.intent, doRebind);
2045 } else {
2046 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002047 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 }
2049 } catch (RemoteException ex) {
2050 }
2051 } catch (Exception e) {
2052 if (!mInstrumentation.onException(s, e)) {
2053 throw new RuntimeException(
2054 "Unable to unbind to service " + s
2055 + " with " + data.intent + ": " + e.toString(), e);
2056 }
2057 }
2058 }
2059 }
2060
Dianne Hackborn625ac272010-09-17 18:29:22 -07002061 private void handleDumpService(DumpComponentInfo info) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062 try {
Dianne Hackborn625ac272010-09-17 18:29:22 -07002063 Service s = mServices.get(info.token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 if (s != null) {
2065 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
2066 s.dump(info.fd, pw, info.args);
2067 pw.close();
2068 }
2069 } finally {
2070 synchronized (info) {
2071 info.dumped = true;
2072 info.notifyAll();
2073 }
2074 }
2075 }
2076
Dianne Hackborn625ac272010-09-17 18:29:22 -07002077 private void handleDumpActivity(DumpComponentInfo info) {
2078 try {
2079 ActivityClientRecord r = mActivities.get(info.token);
2080 if (r != null && r.activity != null) {
2081 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
Dianne Hackborn30d71892010-12-11 10:37:55 -08002082 r.activity.dump(info.prefix, info.fd, pw, info.args);
Dianne Hackborn625ac272010-09-17 18:29:22 -07002083 pw.close();
2084 }
2085 } finally {
2086 synchronized (info) {
2087 info.dumped = true;
2088 info.notifyAll();
2089 }
2090 }
2091 }
2092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 private final void handleServiceArgs(ServiceArgsData data) {
2094 Service s = mServices.get(data.token);
2095 if (s != null) {
2096 try {
2097 if (data.args != null) {
2098 data.args.setExtrasClassLoader(s.getClassLoader());
2099 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002100 int res = s.onStartCommand(data.args, data.flags, data.startId);
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002101
2102 QueuedWork.waitToFinish();
2103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002105 ActivityManagerNative.getDefault().serviceDoneExecuting(
2106 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107 } catch (RemoteException e) {
2108 // nothing to do.
2109 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002110 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 } catch (Exception e) {
2112 if (!mInstrumentation.onException(s, e)) {
2113 throw new RuntimeException(
2114 "Unable to start service " + s
2115 + " with " + data.args + ": " + e.toString(), e);
2116 }
2117 }
2118 }
2119 }
2120
2121 private final void handleStopService(IBinder token) {
2122 Service s = mServices.remove(token);
2123 if (s != null) {
2124 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002125 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 s.onDestroy();
2127 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002128 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002129 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08002130 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002131 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07002132
2133 QueuedWork.waitToFinish();
2134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002136 ActivityManagerNative.getDefault().serviceDoneExecuting(
2137 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002138 } catch (RemoteException e) {
2139 // nothing to do.
2140 }
2141 } catch (Exception e) {
2142 if (!mInstrumentation.onException(s, e)) {
2143 throw new RuntimeException(
2144 "Unable to stop service " + s
2145 + ": " + e.toString(), e);
2146 }
2147 }
2148 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002149 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002150 }
2151
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002152 public final ActivityClientRecord performResumeActivity(IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002153 boolean clearHide) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002154 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002155 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002156 + " finished=" + r.activity.mFinished);
2157 if (r != null && !r.activity.mFinished) {
2158 if (clearHide) {
2159 r.hideForNow = false;
2160 r.activity.mStartedActivity = false;
2161 }
2162 try {
2163 if (r.pendingIntents != null) {
2164 deliverNewIntents(r, r.pendingIntents);
2165 r.pendingIntents = null;
2166 }
2167 if (r.pendingResults != null) {
2168 deliverResults(r, r.pendingResults);
2169 r.pendingResults = null;
2170 }
2171 r.activity.performResume();
2172
Bob Leee5408332009-09-04 18:31:17 -07002173 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 r.paused = false;
2177 r.stopped = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002178 r.state = null;
2179 } catch (Exception e) {
2180 if (!mInstrumentation.onException(r.activity, e)) {
2181 throw new RuntimeException(
2182 "Unable to resume activity "
2183 + r.intent.getComponent().toShortString()
2184 + ": " + e.toString(), e);
2185 }
2186 }
2187 }
2188 return r;
2189 }
2190
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002191 final void cleanUpPendingRemoveWindows(ActivityClientRecord r) {
2192 if (r.mPendingRemoveWindow != null) {
2193 r.mPendingRemoveWindowManager.removeViewImmediate(r.mPendingRemoveWindow);
2194 IBinder wtoken = r.mPendingRemoveWindow.getWindowToken();
2195 if (wtoken != null) {
2196 WindowManagerImpl.getDefault().closeAll(wtoken,
2197 r.activity.getClass().getName(), "Activity");
2198 }
2199 }
2200 r.mPendingRemoveWindow = null;
2201 r.mPendingRemoveWindowManager = null;
2202 }
2203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2205 // If we are getting ready to gc after going to the background, well
2206 // we are back active so skip it.
2207 unscheduleGcIdler();
2208
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002209 ActivityClientRecord r = performResumeActivity(token, clearHide);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002210
2211 if (r != null) {
2212 final Activity a = r.activity;
2213
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002214 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002215 TAG, "Resume " + r + " started activity: " +
2216 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2217 + ", finished: " + a.mFinished);
2218
2219 final int forwardBit = isForward ?
2220 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002222 // If the window hasn't yet been added to the window manager,
2223 // and this guy didn't finish itself or start another activity,
2224 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002225 boolean willBeVisible = !a.mStartedActivity;
2226 if (!willBeVisible) {
2227 try {
2228 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
2229 a.getActivityToken());
2230 } catch (RemoteException e) {
2231 }
2232 }
2233 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234 r.window = r.activity.getWindow();
2235 View decor = r.window.getDecorView();
2236 decor.setVisibility(View.INVISIBLE);
2237 ViewManager wm = a.getWindowManager();
2238 WindowManager.LayoutParams l = r.window.getAttributes();
2239 a.mDecor = decor;
2240 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2241 l.softInputMode |= forwardBit;
2242 if (a.mVisibleFromClient) {
2243 a.mWindowAdded = true;
2244 wm.addView(decor, l);
2245 }
2246
2247 // If the window has already been added, but during resume
2248 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002249 // window visible.
2250 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002251 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002252 TAG, "Launch " + r + " mStartedActivity set");
2253 r.hideForNow = true;
2254 }
2255
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002256 // Get rid of anything left hanging around.
2257 cleanUpPendingRemoveWindows(r);
2258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002259 // The window is now visible if it has been added, we are not
2260 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002261 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002262 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002264 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002265 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002266 performConfigurationChanged(r.activity, r.newConfig);
2267 r.newConfig = null;
2268 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002269 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002270 + isForward);
2271 WindowManager.LayoutParams l = r.window.getAttributes();
2272 if ((l.softInputMode
2273 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2274 != forwardBit) {
2275 l.softInputMode = (l.softInputMode
2276 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2277 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002278 if (r.activity.mVisibleFromClient) {
2279 ViewManager wm = a.getWindowManager();
2280 View decor = r.window.getDecorView();
2281 wm.updateViewLayout(decor, l);
2282 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002283 }
2284 r.activity.mVisibleFromServer = true;
2285 mNumVisibleActivities++;
2286 if (r.activity.mVisibleFromClient) {
2287 r.activity.makeVisible();
2288 }
2289 }
2290
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002291 if (!r.onlyLocalRequest) {
2292 r.nextIdle = mNewActivities;
2293 mNewActivities = r;
2294 if (localLOGV) Slog.v(
2295 TAG, "Scheduling idle handler for " + r);
2296 Looper.myQueue().addIdleHandler(new Idler());
2297 }
2298 r.onlyLocalRequest = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002299
2300 } else {
2301 // If an exception was thrown when trying to resume, then
2302 // just end this activity.
2303 try {
2304 ActivityManagerNative.getDefault()
2305 .finishActivity(token, Activity.RESULT_CANCELED, null);
2306 } catch (RemoteException ex) {
2307 }
2308 }
2309 }
2310
2311 private int mThumbnailWidth = -1;
2312 private int mThumbnailHeight = -1;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002313 private Bitmap mAvailThumbnailBitmap = null;
2314 private Canvas mThumbnailCanvas = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002315
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002316 private final Bitmap createThumbnailBitmap(ActivityClientRecord r) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002317 Bitmap thumbnail = mAvailThumbnailBitmap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 try {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002319 if (thumbnail == null) {
2320 int w = mThumbnailWidth;
2321 int h;
2322 if (w < 0) {
2323 Resources res = r.activity.getResources();
2324 mThumbnailHeight = h =
2325 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002326
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002327 mThumbnailWidth = w =
2328 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
2329 } else {
2330 h = mThumbnailHeight;
2331 }
2332
2333 // On platforms where we don't want thumbnails, set dims to (0,0)
2334 if ((w > 0) && (h > 0)) {
2335 thumbnail = Bitmap.createBitmap(w, h, THUMBNAIL_FORMAT);
2336 thumbnail.eraseColor(0);
2337 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002338 }
2339
Dianne Hackbornfb3806d2010-12-09 13:14:12 -08002340 if (thumbnail != null) {
2341 Canvas cv = mThumbnailCanvas;
2342 if (cv == null) {
2343 mThumbnailCanvas = cv = new Canvas();
2344 }
2345
2346 cv.setBitmap(thumbnail);
2347 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
2348 mAvailThumbnailBitmap = thumbnail;
2349 thumbnail = null;
2350 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002351 }
Jim Miller0b2a6d02010-07-13 18:01:29 -07002352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 } catch (Exception e) {
2354 if (!mInstrumentation.onException(r.activity, e)) {
2355 throw new RuntimeException(
2356 "Unable to create thumbnail of "
2357 + r.intent.getComponent().toShortString()
2358 + ": " + e.toString(), e);
2359 }
2360 thumbnail = null;
2361 }
2362
2363 return thumbnail;
2364 }
2365
2366 private final void handlePauseActivity(IBinder token, boolean finished,
2367 boolean userLeaving, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002368 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002370 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002371 if (userLeaving) {
2372 performUserLeavingActivity(r);
2373 }
Bob Leee5408332009-09-04 18:31:17 -07002374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375 r.activity.mConfigChangeFlags |= configChanges;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002376 performPauseActivity(token, finished, r.isPreHoneycomb());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002377
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07002378 // Make sure any pending writes are now committed.
2379 QueuedWork.waitToFinish();
2380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002381 // Tell the activity manager we have paused.
2382 try {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002383 ActivityManagerNative.getDefault().activityPaused(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002384 } catch (RemoteException ex) {
2385 }
2386 }
2387 }
2388
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002389 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 mInstrumentation.callActivityOnUserLeaving(r.activity);
2391 }
2392
2393 final Bundle performPauseActivity(IBinder token, boolean finished,
2394 boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002395 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002396 return r != null ? performPauseActivity(r, finished, saveState) : null;
2397 }
2398
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002399 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002400 boolean saveState) {
2401 if (r.paused) {
2402 if (r.activity.mFinished) {
2403 // If we are finishing, we won't call onResume() in certain cases.
2404 // So here we likewise don't want to call onPause() if the activity
2405 // isn't resumed.
2406 return null;
2407 }
2408 RuntimeException e = new RuntimeException(
2409 "Performing pause of activity that is not resumed: "
2410 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002411 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412 }
2413 Bundle state = null;
2414 if (finished) {
2415 r.activity.mFinished = true;
2416 }
2417 try {
2418 // Next have the activity save its current state and managed dialogs...
2419 if (!r.activity.mFinished && saveState) {
2420 state = new Bundle();
2421 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2422 r.state = state;
2423 }
2424 // Now we are idle.
2425 r.activity.mCalled = false;
2426 mInstrumentation.callActivityOnPause(r.activity);
2427 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
2428 if (!r.activity.mCalled) {
2429 throw new SuperNotCalledException(
2430 "Activity " + r.intent.getComponent().toShortString() +
2431 " did not call through to super.onPause()");
2432 }
2433
2434 } catch (SuperNotCalledException e) {
2435 throw e;
2436
2437 } catch (Exception e) {
2438 if (!mInstrumentation.onException(r.activity, e)) {
2439 throw new RuntimeException(
2440 "Unable to pause activity "
2441 + r.intent.getComponent().toShortString()
2442 + ": " + e.toString(), e);
2443 }
2444 }
2445 r.paused = true;
2446 return state;
2447 }
2448
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002449 final void performStopActivity(IBinder token, boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002450 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002451 performStopActivityInner(r, null, false, saveState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002452 }
2453
2454 private static class StopInfo {
2455 Bitmap thumbnail;
2456 CharSequence description;
2457 }
2458
2459 private final class ProviderRefCount {
2460 public int count;
2461 ProviderRefCount(int pCount) {
2462 count = pCount;
2463 }
2464 }
2465
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002466 /**
2467 * Core implementation of stopping an activity. Note this is a little
2468 * tricky because the server's meaning of stop is slightly different
2469 * than our client -- for the server, stop means to save state and give
2470 * it the result when it is done, but the window may still be visible.
2471 * For the client, we want to call onStop()/onStart() to indicate when
2472 * the activity's UI visibillity changes.
2473 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002474 private final void performStopActivityInner(ActivityClientRecord r,
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002475 StopInfo info, boolean keepShown, boolean saveState) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002476 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002477 Bundle state = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 if (r != null) {
2479 if (!keepShown && r.stopped) {
2480 if (r.activity.mFinished) {
2481 // If we are finishing, we won't call onResume() in certain
2482 // cases. So here we likewise don't want to call onStop()
2483 // if the activity isn't resumed.
2484 return;
2485 }
2486 RuntimeException e = new RuntimeException(
2487 "Performing stop of activity that is not resumed: "
2488 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002489 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490 }
2491
2492 if (info != null) {
2493 try {
2494 // First create a thumbnail for the activity...
Jim Miller0b2a6d02010-07-13 18:01:29 -07002495 info.thumbnail = createThumbnailBitmap(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002496 info.description = r.activity.onCreateDescription();
2497 } catch (Exception e) {
2498 if (!mInstrumentation.onException(r.activity, e)) {
2499 throw new RuntimeException(
2500 "Unable to save state of activity "
2501 + r.intent.getComponent().toShortString()
2502 + ": " + e.toString(), e);
2503 }
2504 }
2505 }
2506
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002507 // Next have the activity save its current state and managed dialogs...
2508 if (!r.activity.mFinished && saveState) {
2509 if (r.state == null) {
2510 state = new Bundle();
2511 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2512 r.state = state;
2513 } else {
2514 state = r.state;
2515 }
2516 }
2517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 if (!keepShown) {
2519 try {
2520 // Now we are idle.
2521 r.activity.performStop();
2522 } catch (Exception e) {
2523 if (!mInstrumentation.onException(r.activity, e)) {
2524 throw new RuntimeException(
2525 "Unable to stop activity "
2526 + r.intent.getComponent().toShortString()
2527 + ": " + e.toString(), e);
2528 }
2529 }
2530 r.stopped = true;
2531 }
2532
2533 r.paused = true;
2534 }
2535 }
2536
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002537 private final void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002538 View v = r.activity.mDecor;
2539 if (v != null) {
2540 if (show) {
2541 if (!r.activity.mVisibleFromServer) {
2542 r.activity.mVisibleFromServer = true;
2543 mNumVisibleActivities++;
2544 if (r.activity.mVisibleFromClient) {
2545 r.activity.makeVisible();
2546 }
2547 }
2548 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002549 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002550 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002551 performConfigurationChanged(r.activity, r.newConfig);
2552 r.newConfig = null;
2553 }
2554 } else {
2555 if (r.activity.mVisibleFromServer) {
2556 r.activity.mVisibleFromServer = false;
2557 mNumVisibleActivities--;
2558 v.setVisibility(View.INVISIBLE);
2559 }
2560 }
2561 }
2562 }
2563
2564 private final void handleStopActivity(IBinder token, boolean show, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002565 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 r.activity.mConfigChangeFlags |= configChanges;
2567
2568 StopInfo info = new StopInfo();
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002569 performStopActivityInner(r, info, show, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002570
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002571 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002572 TAG, "Finishing stop of " + r + ": show=" + show
2573 + " win=" + r.window);
2574
2575 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07002576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577 // Tell activity manager we have been stopped.
2578 try {
2579 ActivityManagerNative.getDefault().activityStopped(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002580 r.token, r.state, info.thumbnail, info.description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 } catch (RemoteException ex) {
2582 }
2583 }
2584
2585 final void performRestartActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002586 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 if (r.stopped) {
2588 r.activity.performRestart();
2589 r.stopped = false;
2590 }
2591 }
2592
2593 private final void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002594 ActivityClientRecord r = mActivities.get(token);
Dianne Hackbornbfddc0f2010-12-14 11:28:01 -08002595
2596 if (r == null) {
2597 Log.w(TAG, "handleWindowVisibility: no activity for token " + token);
2598 return;
2599 }
2600
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 if (!show && !r.stopped) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002602 performStopActivityInner(r, null, show, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002603 } else if (show && r.stopped) {
2604 // If we are getting ready to gc after going to the background, well
2605 // we are back active so skip it.
2606 unscheduleGcIdler();
2607
2608 r.activity.performRestart();
2609 r.stopped = false;
2610 }
2611 if (r.activity.mDecor != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002612 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002613 TAG, "Handle window " + r + " visibility: " + show);
2614 updateVisibility(r, show);
2615 }
2616 }
2617
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002618 private final void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619 final int N = results.size();
2620 for (int i=0; i<N; i++) {
2621 ResultInfo ri = results.get(i);
2622 try {
2623 if (ri.mData != null) {
2624 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
2625 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002626 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07002627 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628 r.activity.dispatchActivityResult(ri.mResultWho,
2629 ri.mRequestCode, ri.mResultCode, ri.mData);
2630 } catch (Exception e) {
2631 if (!mInstrumentation.onException(r.activity, e)) {
2632 throw new RuntimeException(
2633 "Failure delivering result " + ri + " to activity "
2634 + r.intent.getComponent().toShortString()
2635 + ": " + e.toString(), e);
2636 }
2637 }
2638 }
2639 }
2640
2641 private final void handleSendResult(ResultData res) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002642 ActivityClientRecord r = mActivities.get(res.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002643 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002644 if (r != null) {
2645 final boolean resumed = !r.paused;
2646 if (!r.activity.mFinished && r.activity.mDecor != null
2647 && r.hideForNow && resumed) {
2648 // We had hidden the activity because it started another
2649 // one... we have gotten a result back and we are not
2650 // paused, so make sure our window is visible.
2651 updateVisibility(r, true);
2652 }
2653 if (resumed) {
2654 try {
2655 // Now we are idle.
2656 r.activity.mCalled = false;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002657 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002658 mInstrumentation.callActivityOnPause(r.activity);
2659 if (!r.activity.mCalled) {
2660 throw new SuperNotCalledException(
2661 "Activity " + r.intent.getComponent().toShortString()
2662 + " did not call through to super.onPause()");
2663 }
2664 } catch (SuperNotCalledException e) {
2665 throw e;
2666 } catch (Exception e) {
2667 if (!mInstrumentation.onException(r.activity, e)) {
2668 throw new RuntimeException(
2669 "Unable to pause activity "
2670 + r.intent.getComponent().toShortString()
2671 + ": " + e.toString(), e);
2672 }
2673 }
2674 }
2675 deliverResults(r, res.results);
2676 if (resumed) {
2677 mInstrumentation.callActivityOnResume(r.activity);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07002678 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 }
2680 }
2681 }
2682
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002683 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 return performDestroyActivity(token, finishing, 0, false);
2685 }
2686
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002687 private final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002689 ActivityClientRecord r = mActivities.get(token);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002690 Class activityClass = null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002691 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 if (r != null) {
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002693 activityClass = r.activity.getClass();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 r.activity.mConfigChangeFlags |= configChanges;
2695 if (finishing) {
2696 r.activity.mFinished = true;
2697 }
2698 if (!r.paused) {
2699 try {
2700 r.activity.mCalled = false;
2701 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07002702 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 r.activity.getComponentName().getClassName());
2704 if (!r.activity.mCalled) {
2705 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002706 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002707 + " did not call through to super.onPause()");
2708 }
2709 } catch (SuperNotCalledException e) {
2710 throw e;
2711 } catch (Exception e) {
2712 if (!mInstrumentation.onException(r.activity, e)) {
2713 throw new RuntimeException(
2714 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002715 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 + ": " + e.toString(), e);
2717 }
2718 }
2719 r.paused = true;
2720 }
2721 if (!r.stopped) {
2722 try {
2723 r.activity.performStop();
2724 } catch (SuperNotCalledException e) {
2725 throw e;
2726 } catch (Exception e) {
2727 if (!mInstrumentation.onException(r.activity, e)) {
2728 throw new RuntimeException(
2729 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002730 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 + ": " + e.toString(), e);
2732 }
2733 }
2734 r.stopped = true;
2735 }
2736 if (getNonConfigInstance) {
2737 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002738 r.lastNonConfigurationInstances
2739 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002740 } catch (Exception e) {
2741 if (!mInstrumentation.onException(r.activity, e)) {
2742 throw new RuntimeException(
2743 "Unable to retain activity "
2744 + r.intent.getComponent().toShortString()
2745 + ": " + e.toString(), e);
2746 }
2747 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002748 }
2749 try {
2750 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07002751 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 if (!r.activity.mCalled) {
2753 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002754 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002755 " did not call through to super.onDestroy()");
2756 }
2757 if (r.window != null) {
2758 r.window.closeAllPanels();
2759 }
2760 } catch (SuperNotCalledException e) {
2761 throw e;
2762 } catch (Exception e) {
2763 if (!mInstrumentation.onException(r.activity, e)) {
2764 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002765 "Unable to destroy activity " + safeToComponentShortString(r.intent)
2766 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002767 }
2768 }
2769 }
2770 mActivities.remove(token);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002771 StrictMode.decrementExpectedActivityCount(activityClass);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002772 return r;
2773 }
2774
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002775 private static String safeToComponentShortString(Intent intent) {
2776 ComponentName component = intent.getComponent();
2777 return component == null ? "[Unknown]" : component.toShortString();
2778 }
2779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002780 private final void handleDestroyActivity(IBinder token, boolean finishing,
2781 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002782 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002783 configChanges, getNonConfigInstance);
2784 if (r != null) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002785 cleanUpPendingRemoveWindows(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 WindowManager wm = r.activity.getWindowManager();
2787 View v = r.activity.mDecor;
2788 if (v != null) {
2789 if (r.activity.mVisibleFromServer) {
2790 mNumVisibleActivities--;
2791 }
2792 IBinder wtoken = v.getWindowToken();
2793 if (r.activity.mWindowAdded) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002794 if (r.onlyLocalRequest) {
2795 // Hold off on removing this until the new activity's
2796 // window is being added.
2797 r.mPendingRemoveWindow = v;
2798 r.mPendingRemoveWindowManager = wm;
2799 } else {
2800 wm.removeViewImmediate(v);
2801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002802 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002803 if (wtoken != null && r.mPendingRemoveWindow == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002804 WindowManagerImpl.getDefault().closeAll(wtoken,
2805 r.activity.getClass().getName(), "Activity");
2806 }
2807 r.activity.mDecor = null;
2808 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002809 if (r.mPendingRemoveWindow == null) {
2810 // If we are delaying the removal of the activity window, then
2811 // we can't clean up all windows here. Note that we can't do
2812 // so later either, which means any windows that aren't closed
2813 // by the app will leak. Well we try to warning them a lot
2814 // about leaking windows, because that is a bug, so if they are
2815 // using this recreate facility then they get to live with leaks.
2816 WindowManagerImpl.getDefault().closeAll(token,
2817 r.activity.getClass().getName(), "Activity");
2818 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002819
2820 // Mocked out contexts won't be participating in the normal
2821 // process lifecycle, but if we're running with a proper
2822 // ApplicationContext we need to have it tear down things
2823 // cleanly.
2824 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002825 if (c instanceof ContextImpl) {
2826 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 r.activity.getClass().getName(), "Activity");
2828 }
2829 }
2830 if (finishing) {
2831 try {
2832 ActivityManagerNative.getDefault().activityDestroyed(token);
2833 } catch (RemoteException ex) {
2834 // If the system process has died, it's game over for everyone.
2835 }
2836 }
2837 }
2838
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002839 public final void requestRelaunchActivity(IBinder token,
2840 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
2841 int configChanges, boolean notResumed, Configuration config,
2842 boolean fromServer) {
2843 ActivityClientRecord target = null;
2844
2845 synchronized (mPackages) {
2846 for (int i=0; i<mRelaunchingActivities.size(); i++) {
2847 ActivityClientRecord r = mRelaunchingActivities.get(i);
2848 if (r.token == token) {
2849 target = r;
2850 if (pendingResults != null) {
2851 if (r.pendingResults != null) {
2852 r.pendingResults.addAll(pendingResults);
2853 } else {
2854 r.pendingResults = pendingResults;
2855 }
2856 }
2857 if (pendingNewIntents != null) {
2858 if (r.pendingIntents != null) {
2859 r.pendingIntents.addAll(pendingNewIntents);
2860 } else {
2861 r.pendingIntents = pendingNewIntents;
2862 }
2863 }
2864 break;
2865 }
2866 }
2867
2868 if (target == null) {
2869 target = new ActivityClientRecord();
2870 target.token = token;
2871 target.pendingResults = pendingResults;
2872 target.pendingIntents = pendingNewIntents;
2873 if (!fromServer) {
2874 ActivityClientRecord existing = mActivities.get(token);
2875 if (existing != null) {
2876 target.startsNotResumed = existing.paused;
2877 }
2878 target.onlyLocalRequest = true;
2879 }
2880 mRelaunchingActivities.add(target);
2881 queueOrSendMessage(H.RELAUNCH_ACTIVITY, target);
2882 }
2883
2884 if (fromServer) {
2885 target.startsNotResumed = notResumed;
2886 target.onlyLocalRequest = false;
2887 }
2888 if (config != null) {
2889 target.createdConfig = config;
2890 }
2891 target.pendingConfigChanges |= configChanges;
2892 }
2893 }
2894
2895 private final void handleRelaunchActivity(ActivityClientRecord tmp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002896 // If we are getting ready to gc after going to the background, well
2897 // we are back active so skip it.
2898 unscheduleGcIdler();
2899
2900 Configuration changedConfig = null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002901 int configChanges = 0;
Bob Leee5408332009-09-04 18:31:17 -07002902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002903 // First: make sure we have the most recent configuration and most
2904 // recent version of the activity, or skip it if some previous call
2905 // had taken a more recent version.
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002906 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907 int N = mRelaunchingActivities.size();
2908 IBinder token = tmp.token;
2909 tmp = null;
2910 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002911 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002912 if (r.token == token) {
2913 tmp = r;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002914 configChanges |= tmp.pendingConfigChanges;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 mRelaunchingActivities.remove(i);
2916 i--;
2917 N--;
2918 }
2919 }
Bob Leee5408332009-09-04 18:31:17 -07002920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002921 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002922 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002923 return;
2924 }
Bob Leee5408332009-09-04 18:31:17 -07002925
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002926 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
2927 + tmp.token + " with configChanges=0x"
2928 + Integer.toHexString(configChanges));
2929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002930 if (mPendingConfiguration != null) {
2931 changedConfig = mPendingConfiguration;
2932 mPendingConfiguration = null;
2933 }
2934 }
Bob Leee5408332009-09-04 18:31:17 -07002935
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002936 if (tmp.createdConfig != null) {
2937 // If the activity manager is passing us its current config,
2938 // assume that is really what we want regardless of what we
2939 // may have pending.
2940 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002941 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
2942 && mConfiguration.diff(tmp.createdConfig) != 0)) {
2943 if (changedConfig == null
2944 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
2945 changedConfig = tmp.createdConfig;
2946 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002947 }
2948 }
2949
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002950 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002951 + tmp.token + ": changedConfig=" + changedConfig);
2952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002953 // If there was a pending configuration change, execute it first.
2954 if (changedConfig != null) {
2955 handleConfigurationChanged(changedConfig);
2956 }
Bob Leee5408332009-09-04 18:31:17 -07002957
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002958 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002959 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002960 if (r == null) {
2961 return;
2962 }
Bob Leee5408332009-09-04 18:31:17 -07002963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002964 r.activity.mConfigChangeFlags |= configChanges;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08002965 r.onlyLocalRequest = tmp.onlyLocalRequest;
Christopher Tateb70f3df2009-04-07 16:07:59 -07002966 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07002967
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002968 r.activity.mChangingConfigurations = true;
2969
Dianne Hackborne2b04802010-12-09 09:24:55 -08002970 // Need to ensure state is saved.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 if (!r.paused) {
Dianne Hackborne2b04802010-12-09 09:24:55 -08002972 performPauseActivity(r.token, false, r.isPreHoneycomb());
2973 }
2974 if (r.state == null && !r.stopped && !r.isPreHoneycomb()) {
2975 r.state = new Bundle();
2976 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002977 }
Bob Leee5408332009-09-04 18:31:17 -07002978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002979 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07002980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002981 r.activity = null;
2982 r.window = null;
2983 r.hideForNow = false;
2984 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07002985 // Merge any pending results and pending intents; don't just replace them
2986 if (tmp.pendingResults != null) {
2987 if (r.pendingResults == null) {
2988 r.pendingResults = tmp.pendingResults;
2989 } else {
2990 r.pendingResults.addAll(tmp.pendingResults);
2991 }
2992 }
2993 if (tmp.pendingIntents != null) {
2994 if (r.pendingIntents == null) {
2995 r.pendingIntents = tmp.pendingIntents;
2996 } else {
2997 r.pendingIntents.addAll(tmp.pendingIntents);
2998 }
2999 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003000 r.startsNotResumed = tmp.startsNotResumed;
Bob Leee5408332009-09-04 18:31:17 -07003001
Christopher Tateb70f3df2009-04-07 16:07:59 -07003002 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003003 }
3004
3005 private final void handleRequestThumbnail(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003006 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003007 Bitmap thumbnail = createThumbnailBitmap(r);
3008 CharSequence description = null;
3009 try {
3010 description = r.activity.onCreateDescription();
3011 } catch (Exception e) {
3012 if (!mInstrumentation.onException(r.activity, e)) {
3013 throw new RuntimeException(
3014 "Unable to create description of activity "
3015 + r.intent.getComponent().toShortString()
3016 + ": " + e.toString(), e);
3017 }
3018 }
3019 //System.out.println("Reporting top thumbnail " + thumbnail);
3020 try {
3021 ActivityManagerNative.getDefault().reportThumbnail(
3022 token, thumbnail, description);
3023 } catch (RemoteException ex) {
3024 }
3025 }
3026
3027 ArrayList<ComponentCallbacks> collectComponentCallbacksLocked(
3028 boolean allActivities, Configuration newConfig) {
3029 ArrayList<ComponentCallbacks> callbacks
3030 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07003031
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003032 if (mActivities.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003033 Iterator<ActivityClientRecord> it = mActivities.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003034 while (it.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003035 ActivityClientRecord ar = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003036 Activity a = ar.activity;
3037 if (a != null) {
3038 if (!ar.activity.mFinished && (allActivities ||
3039 (a != null && !ar.paused))) {
3040 // If the activity is currently resumed, its configuration
3041 // needs to change right now.
3042 callbacks.add(a);
3043 } else if (newConfig != null) {
3044 // Otherwise, we will tell it about the change
3045 // the next time it is resumed or shown. Note that
3046 // the activity manager may, before then, decide the
3047 // activity needs to be destroyed to handle its new
3048 // configuration.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003049 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Setting activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003050 + ar.activityInfo.name + " newConfig=" + newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003051 ar.newConfig = newConfig;
3052 }
3053 }
3054 }
3055 }
3056 if (mServices.size() > 0) {
3057 Iterator<Service> it = mServices.values().iterator();
3058 while (it.hasNext()) {
3059 callbacks.add(it.next());
3060 }
3061 }
3062 synchronized (mProviderMap) {
3063 if (mLocalProviders.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003064 Iterator<ProviderClientRecord> it = mLocalProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003065 while (it.hasNext()) {
3066 callbacks.add(it.next().mLocalProvider);
3067 }
3068 }
3069 }
3070 final int N = mAllApplications.size();
3071 for (int i=0; i<N; i++) {
3072 callbacks.add(mAllApplications.get(i));
3073 }
Bob Leee5408332009-09-04 18:31:17 -07003074
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003075 return callbacks;
3076 }
Bob Leee5408332009-09-04 18:31:17 -07003077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003078 private final void performConfigurationChanged(
3079 ComponentCallbacks cb, Configuration config) {
3080 // Only for Activity objects, check that they actually call up to their
3081 // superclass implementation. ComponentCallbacks is an interface, so
3082 // we check the runtime type and act accordingly.
3083 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
3084 if (activity != null) {
3085 activity.mCalled = false;
3086 }
Bob Leee5408332009-09-04 18:31:17 -07003087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003088 boolean shouldChangeConfig = false;
3089 if ((activity == null) || (activity.mCurrentConfig == null)) {
3090 shouldChangeConfig = true;
3091 } else {
Bob Leee5408332009-09-04 18:31:17 -07003092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003093 // If the new config is the same as the config this Activity
3094 // is already running with then don't bother calling
3095 // onConfigurationChanged
3096 int diff = activity.mCurrentConfig.diff(config);
3097 if (diff != 0) {
Bob Leee5408332009-09-04 18:31:17 -07003098
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003099 // If this activity doesn't handle any of the config changes
3100 // then don't bother calling onConfigurationChanged as we're
3101 // going to destroy it.
3102 if ((~activity.mActivityInfo.configChanges & diff) == 0) {
3103 shouldChangeConfig = true;
3104 }
3105 }
3106 }
Bob Leee5408332009-09-04 18:31:17 -07003107
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003108 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003109 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003110 if (shouldChangeConfig) {
3111 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07003112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003113 if (activity != null) {
3114 if (!activity.mCalled) {
3115 throw new SuperNotCalledException(
3116 "Activity " + activity.getLocalClassName() +
3117 " did not call through to super.onConfigurationChanged()");
3118 }
3119 activity.mConfigChangeFlags = 0;
3120 activity.mCurrentConfig = new Configuration(config);
3121 }
3122 }
3123 }
3124
Dianne Hackbornae078162010-03-18 11:29:37 -07003125 final boolean applyConfigurationToResourcesLocked(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003126 if (mResConfiguration == null) {
3127 mResConfiguration = new Configuration();
3128 }
3129 if (!mResConfiguration.isOtherSeqNewer(config)) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003130 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq="
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003131 + mResConfiguration.seq + ", newSeq=" + config.seq);
Dianne Hackbornae078162010-03-18 11:29:37 -07003132 return false;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003133 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003134 int changes = mResConfiguration.updateFrom(config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003135 DisplayMetrics dm = getDisplayMetricsLocked(true);
Bob Leee5408332009-09-04 18:31:17 -07003136
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003137 // set it for java, this also affects newly created Resources
3138 if (config.locale != null) {
3139 Locale.setDefault(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003140 }
Bob Leee5408332009-09-04 18:31:17 -07003141
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003142 Resources.updateSystemConfiguration(config, dm);
Bob Leee5408332009-09-04 18:31:17 -07003143
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003144 ApplicationPackageManager.configurationChanged();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003145 //Slog.i(TAG, "Configuration changed in " + currentPackageName());
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003146
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003147 Iterator<WeakReference<Resources>> it =
3148 mActiveResources.values().iterator();
3149 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
3150 // mActiveResources.entrySet().iterator();
3151 while (it.hasNext()) {
3152 WeakReference<Resources> v = it.next();
3153 Resources r = v.get();
3154 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003155 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources "
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003156 + r + " config to: " + config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003157 r.updateConfiguration(config, dm);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003158 //Slog.i(TAG, "Updated app resources " + v.getKey()
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003159 // + " " + r + ": " + r.getConfiguration());
3160 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003161 //Slog.i(TAG, "Removing old resources " + v.getKey());
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003162 it.remove();
3163 }
3164 }
Dianne Hackbornae078162010-03-18 11:29:37 -07003165
3166 return changes != 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003167 }
3168
3169 final void handleConfigurationChanged(Configuration config) {
3170
3171 ArrayList<ComponentCallbacks> callbacks = null;
3172
3173 synchronized (mPackages) {
3174 if (mPendingConfiguration != null) {
3175 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
3176 config = mPendingConfiguration;
3177 }
3178 mPendingConfiguration = null;
3179 }
3180
3181 if (config == null) {
3182 return;
3183 }
3184
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003185 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003186 + config);
3187
3188 applyConfigurationToResourcesLocked(config);
3189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003190 if (mConfiguration == null) {
3191 mConfiguration = new Configuration();
3192 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003193 if (!mConfiguration.isOtherSeqNewer(config)) {
3194 return;
3195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003196 mConfiguration.updateFrom(config);
Bob Leee5408332009-09-04 18:31:17 -07003197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003198 callbacks = collectComponentCallbacksLocked(false, config);
3199 }
Bob Leee5408332009-09-04 18:31:17 -07003200
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003201 if (callbacks != null) {
3202 final int N = callbacks.size();
3203 for (int i=0; i<N; i++) {
3204 performConfigurationChanged(callbacks.get(i), config);
3205 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003206 }
3207 }
3208
3209 final void handleActivityConfigurationChanged(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003210 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003211 if (r == null || r.activity == null) {
3212 return;
3213 }
Bob Leee5408332009-09-04 18:31:17 -07003214
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003215 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003216 + r.activityInfo.name);
3217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003218 performConfigurationChanged(r.activity, mConfiguration);
3219 }
3220
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003221 final void handleProfilerControl(boolean start, ProfilerControlData pcd) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003222 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003223 try {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003224 Debug.startMethodTracing(pcd.path, pcd.fd.getFileDescriptor(),
3225 8 * 1024 * 1024, 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003226 } catch (RuntimeException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003227 Slog.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003228 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003229 } finally {
3230 try {
3231 pcd.fd.close();
3232 } catch (IOException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003233 Slog.w(TAG, "Failure closing profile fd", e);
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003234 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003235 }
3236 } else {
3237 Debug.stopMethodTracing();
3238 }
3239 }
Bob Leee5408332009-09-04 18:31:17 -07003240
Andy McFadden824c5102010-07-09 16:26:57 -07003241 final void handleDumpHeap(boolean managed, DumpHeapData dhd) {
3242 if (managed) {
3243 try {
3244 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor());
3245 } catch (IOException e) {
3246 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
3247 + " -- can the process access this path?");
3248 } finally {
3249 try {
3250 dhd.fd.close();
3251 } catch (IOException e) {
3252 Slog.w(TAG, "Failure closing profile fd", e);
3253 }
3254 }
3255 } else {
Andy McFadden06a6b552010-07-13 16:28:09 -07003256 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07003257 }
3258 }
3259
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003260 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
3261 boolean hasPkgInfo = false;
3262 if (packages != null) {
3263 for (int i=packages.length-1; i>=0; i--) {
3264 //Slog.i(TAG, "Cleaning old package: " + packages[i]);
3265 if (!hasPkgInfo) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003266 WeakReference<LoadedApk> ref;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003267 ref = mPackages.get(packages[i]);
3268 if (ref != null && ref.get() != null) {
3269 hasPkgInfo = true;
3270 } else {
3271 ref = mResourcePackages.get(packages[i]);
3272 if (ref != null && ref.get() != null) {
3273 hasPkgInfo = true;
3274 }
3275 }
3276 }
3277 mPackages.remove(packages[i]);
3278 mResourcePackages.remove(packages[i]);
3279 }
3280 }
Brad Fitzpatrick390dae12010-11-10 08:27:28 -08003281 ApplicationPackageManager.handlePackageBroadcast(cmd, packages,
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003282 hasPkgInfo);
3283 }
3284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285 final void handleLowMemory() {
3286 ArrayList<ComponentCallbacks> callbacks
3287 = new ArrayList<ComponentCallbacks>();
3288
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003289 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003290 callbacks = collectComponentCallbacksLocked(true, null);
3291 }
Bob Leee5408332009-09-04 18:31:17 -07003292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003293 final int N = callbacks.size();
3294 for (int i=0; i<N; i++) {
3295 callbacks.get(i).onLowMemory();
3296 }
3297
Chris Tatece229052009-03-25 16:44:52 -07003298 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3299 if (Process.myUid() != Process.SYSTEM_UID) {
3300 int sqliteReleased = SQLiteDatabase.releaseMemory();
3301 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3302 }
Bob Leee5408332009-09-04 18:31:17 -07003303
Mike Reedcaf0df12009-04-27 14:32:05 -04003304 // Ask graphics to free up as much as possible (font/image caches)
3305 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306
3307 BinderInternal.forceGc("mem");
3308 }
3309
3310 private final void handleBindApplication(AppBindData data) {
3311 mBoundApplication = data;
3312 mConfiguration = new Configuration(data.config);
3313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003315 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316 android.ddm.DdmHandleAppName.setAppName(data.processName);
3317
3318 /*
3319 * Before spawning a new process, reset the time zone to be the system time zone.
3320 * This needs to be done because the system time zone could have changed after the
3321 * the spawning of this process. Without doing this this process would have the incorrect
3322 * system time zone.
3323 */
3324 TimeZone.setDefault(null);
3325
3326 /*
3327 * Initialize the default locale in this process for the reasons we set the time zone.
3328 */
3329 Locale.setDefault(data.config.locale);
3330
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003331 /*
3332 * Update the system configuration since its preloaded and might not
3333 * reflect configuration changes. The configuration object passed
3334 * in AppBindData can be safely assumed to be up to date
3335 */
3336 Resources.getSystem().updateConfiguration(mConfiguration, null);
3337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 data.info = getPackageInfoNoCheck(data.appInfo);
3339
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003340 /**
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003341 * For system applications on userdebug/eng builds, log stack
3342 * traces of disk and network access to dropbox for analysis.
3343 */
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07003344 if ((data.appInfo.flags &
3345 (ApplicationInfo.FLAG_SYSTEM |
Brad Fitzpatrick50d66f92010-09-13 21:29:05 -07003346 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0) {
3347 StrictMode.conditionallyEnableDebugLogging();
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003348 }
3349
3350 /**
Brad Fitzpatrickb6e18412010-10-28 14:50:05 -07003351 * For apps targetting SDK Honeycomb or later, we don't allow
3352 * network usage on the main event loop / UI thread.
3353 *
3354 * Note to those grepping: this is what ultimately throws
3355 * NetworkOnMainThreadException ...
3356 */
3357 if (data.appInfo.targetSdkVersion > 9) {
3358 StrictMode.enableDeathOnNetwork();
3359 }
3360
3361 /**
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003362 * Switch this process to density compatibility mode if needed.
3363 */
3364 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3365 == 0) {
3366 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3367 }
Bob Leee5408332009-09-04 18:31:17 -07003368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3370 // XXX should have option to change the port.
3371 Debug.changeDebugPort(8100);
3372 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003373 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003374 + " is waiting for the debugger on port 8100...");
3375
3376 IActivityManager mgr = ActivityManagerNative.getDefault();
3377 try {
3378 mgr.showWaitingForDebugger(mAppThread, true);
3379 } catch (RemoteException ex) {
3380 }
3381
3382 Debug.waitForDebugger();
3383
3384 try {
3385 mgr.showWaitingForDebugger(mAppThread, false);
3386 } catch (RemoteException ex) {
3387 }
3388
3389 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003390 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003391 + " can be debugged on port 8100...");
3392 }
3393 }
3394
Robert Greenwalt434203a2010-10-11 16:00:27 -07003395 /**
3396 * Initialize the default http proxy in this process for the reasons we set the time zone.
3397 */
3398 IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
3399 IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
3400 try {
3401 ProxyProperties proxyProperties = service.getProxy();
3402 Proxy.setHttpProxySystemProperty(proxyProperties);
3403 } catch (RemoteException e) {}
3404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003405 if (data.instrumentationName != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08003406 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003407 appContext.init(data.info, null, this);
3408 InstrumentationInfo ii = null;
3409 try {
3410 ii = appContext.getPackageManager().
3411 getInstrumentationInfo(data.instrumentationName, 0);
3412 } catch (PackageManager.NameNotFoundException e) {
3413 }
3414 if (ii == null) {
3415 throw new RuntimeException(
3416 "Unable to find instrumentation info for: "
3417 + data.instrumentationName);
3418 }
3419
3420 mInstrumentationAppDir = ii.sourceDir;
3421 mInstrumentationAppPackage = ii.packageName;
3422 mInstrumentedAppDir = data.info.getAppDir();
3423
3424 ApplicationInfo instrApp = new ApplicationInfo();
3425 instrApp.packageName = ii.packageName;
3426 instrApp.sourceDir = ii.sourceDir;
3427 instrApp.publicSourceDir = ii.publicSourceDir;
3428 instrApp.dataDir = ii.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003429 instrApp.nativeLibraryDir = ii.nativeLibraryDir;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003430 LoadedApk pi = getPackageInfo(instrApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431 appContext.getClassLoader(), false, true);
Dianne Hackborn21556372010-02-04 16:34:40 -08003432 ContextImpl instrContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003433 instrContext.init(pi, null, this);
3434
3435 try {
3436 java.lang.ClassLoader cl = instrContext.getClassLoader();
3437 mInstrumentation = (Instrumentation)
3438 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3439 } catch (Exception e) {
3440 throw new RuntimeException(
3441 "Unable to instantiate instrumentation "
3442 + data.instrumentationName + ": " + e.toString(), e);
3443 }
3444
3445 mInstrumentation.init(this, instrContext, appContext,
3446 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3447
3448 if (data.profileFile != null && !ii.handleProfiling) {
3449 data.handlingProfiling = true;
3450 File file = new File(data.profileFile);
3451 file.getParentFile().mkdirs();
3452 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3453 }
3454
3455 try {
3456 mInstrumentation.onCreate(data.instrumentationArgs);
3457 }
3458 catch (Exception e) {
3459 throw new RuntimeException(
3460 "Exception thrown in onCreate() of "
3461 + data.instrumentationName + ": " + e.toString(), e);
3462 }
3463
3464 } else {
3465 mInstrumentation = new Instrumentation();
3466 }
3467
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08003468 if ((data.appInfo.flags&ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
Dianne Hackbornde398512011-01-18 18:45:21 -08003469 dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08003470 }
3471
Christopher Tate181fafa2009-05-14 11:12:14 -07003472 // If the app is being launched for full backup or restore, bring it up in
3473 // a restricted environment with the base application class.
Dianne Hackborn0be1f782009-11-09 12:30:12 -08003474 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003475 mInitialApplication = app;
3476
3477 List<ProviderInfo> providers = data.providers;
3478 if (providers != null) {
3479 installContentProviders(app, providers);
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08003480 // For process that contains content providers, we want to
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003481 // ensure that the JIT is enabled "at some point".
3482 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003483 }
3484
3485 try {
3486 mInstrumentation.callApplicationOnCreate(app);
3487 } catch (Exception e) {
3488 if (!mInstrumentation.onException(app, e)) {
3489 throw new RuntimeException(
3490 "Unable to create application " + app.getClass().getName()
3491 + ": " + e.toString(), e);
3492 }
3493 }
3494 }
3495
3496 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
3497 IActivityManager am = ActivityManagerNative.getDefault();
3498 if (mBoundApplication.profileFile != null && mBoundApplication.handlingProfiling) {
3499 Debug.stopMethodTracing();
3500 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003501 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003502 // + ", app thr: " + mAppThread);
3503 try {
3504 am.finishInstrumentation(mAppThread, resultCode, results);
3505 } catch (RemoteException ex) {
3506 }
3507 }
3508
3509 private final void installContentProviders(
3510 Context context, List<ProviderInfo> providers) {
3511 final ArrayList<IActivityManager.ContentProviderHolder> results =
3512 new ArrayList<IActivityManager.ContentProviderHolder>();
3513
3514 Iterator<ProviderInfo> i = providers.iterator();
3515 while (i.hasNext()) {
3516 ProviderInfo cpi = i.next();
3517 StringBuilder buf = new StringBuilder(128);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07003518 buf.append("Pub ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003519 buf.append(cpi.authority);
3520 buf.append(": ");
3521 buf.append(cpi.name);
3522 Log.i(TAG, buf.toString());
3523 IContentProvider cp = installProvider(context, null, cpi, false);
3524 if (cp != null) {
3525 IActivityManager.ContentProviderHolder cph =
3526 new IActivityManager.ContentProviderHolder(cpi);
3527 cph.provider = cp;
3528 results.add(cph);
3529 // Don't ever unload this provider from the process.
3530 synchronized(mProviderMap) {
3531 mProviderRefCountMap.put(cp.asBinder(), new ProviderRefCount(10000));
3532 }
3533 }
3534 }
3535
3536 try {
3537 ActivityManagerNative.getDefault().publishContentProviders(
3538 getApplicationThread(), results);
3539 } catch (RemoteException ex) {
3540 }
3541 }
3542
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003543 private final IContentProvider getExistingProvider(Context context, String name) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003544 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003545 final ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003546 if (pr != null) {
3547 return pr.mProvider;
3548 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003549 return null;
3550 }
3551 }
3552
3553 private final IContentProvider getProvider(Context context, String name) {
3554 IContentProvider existing = getExistingProvider(context, name);
3555 if (existing != null) {
3556 return existing;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003557 }
3558
3559 IActivityManager.ContentProviderHolder holder = null;
3560 try {
3561 holder = ActivityManagerNative.getDefault().getContentProvider(
3562 getApplicationThread(), name);
3563 } catch (RemoteException ex) {
3564 }
3565 if (holder == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003566 Slog.e(TAG, "Failed to find provider info for " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003567 return null;
3568 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003569
3570 IContentProvider prov = installProvider(context, holder.provider,
3571 holder.info, true);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003572 //Slog.i(TAG, "noReleaseNeeded=" + holder.noReleaseNeeded);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003573 if (holder.noReleaseNeeded || holder.provider == null) {
3574 // We are not going to release the provider if it is an external
3575 // provider that doesn't care about being released, or if it is
3576 // a local provider running in this process.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003577 //Slog.i(TAG, "*** NO RELEASE NEEDED");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003578 synchronized(mProviderMap) {
3579 mProviderRefCountMap.put(prov.asBinder(), new ProviderRefCount(10000));
3580 }
3581 }
3582 return prov;
3583 }
3584
3585 public final IContentProvider acquireProvider(Context c, String name) {
3586 IContentProvider provider = getProvider(c, name);
3587 if(provider == null)
3588 return null;
3589 IBinder jBinder = provider.asBinder();
3590 synchronized(mProviderMap) {
3591 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3592 if(prc == null) {
3593 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3594 } else {
3595 prc.count++;
3596 } //end else
3597 } //end synchronized
3598 return provider;
3599 }
3600
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003601 public final IContentProvider acquireExistingProvider(Context c, String name) {
3602 IContentProvider provider = getExistingProvider(c, name);
3603 if(provider == null)
3604 return null;
3605 IBinder jBinder = provider.asBinder();
3606 synchronized(mProviderMap) {
3607 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3608 if(prc == null) {
3609 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3610 } else {
3611 prc.count++;
3612 } //end else
3613 } //end synchronized
3614 return provider;
3615 }
3616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003617 public final boolean releaseProvider(IContentProvider provider) {
3618 if(provider == null) {
3619 return false;
3620 }
3621 IBinder jBinder = provider.asBinder();
3622 synchronized(mProviderMap) {
3623 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3624 if(prc == null) {
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07003625 if(localLOGV) Slog.v(TAG, "releaseProvider::Weird shouldn't be here");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626 return false;
3627 } else {
3628 prc.count--;
3629 if(prc.count == 0) {
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003630 // Schedule the actual remove asynchronously, since we
3631 // don't know the context this will be called in.
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003632 // TODO: it would be nice to post a delayed message, so
3633 // if we come back and need the same provider quickly
3634 // we will still have it available.
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003635 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
3636 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003637 } //end if
3638 } //end else
3639 } //end synchronized
3640 return true;
3641 }
3642
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003643 final void completeRemoveProvider(IContentProvider provider) {
3644 IBinder jBinder = provider.asBinder();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003645 String name = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003646 synchronized(mProviderMap) {
3647 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3648 if(prc != null && prc.count == 0) {
3649 mProviderRefCountMap.remove(jBinder);
3650 //invoke removeProvider to dereference provider
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003651 name = removeProviderLocked(provider);
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003652 }
3653 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003654
3655 if (name != null) {
3656 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003657 if(localLOGV) Slog.v(TAG, "removeProvider::Invoking " +
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003658 "ActivityManagerNative.removeContentProvider(" + name);
3659 ActivityManagerNative.getDefault().removeContentProvider(
3660 getApplicationThread(), name);
3661 } catch (RemoteException e) {
3662 //do nothing content provider object is dead any way
3663 } //end catch
3664 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003665 }
3666
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003667 public final String removeProviderLocked(IContentProvider provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003668 if (provider == null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003669 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003670 }
3671 IBinder providerBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003672
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003673 String name = null;
3674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003675 // remove the provider from mProviderMap
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003676 Iterator<ProviderClientRecord> iter = mProviderMap.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003677 while (iter.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003678 ProviderClientRecord pr = iter.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003679 IBinder myBinder = pr.mProvider.asBinder();
3680 if (myBinder == providerBinder) {
3681 //find if its published by this process itself
3682 if(pr.mLocalProvider != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003683 if(localLOGV) Slog.i(TAG, "removeProvider::found local provider returning");
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003684 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003685 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003686 if(localLOGV) Slog.v(TAG, "removeProvider::Not local provider Unlinking " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003687 "death recipient");
3688 //content provider is in another process
3689 myBinder.unlinkToDeath(pr, 0);
3690 iter.remove();
3691 //invoke remove only once for the very first name seen
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003692 if(name == null) {
3693 name = pr.mName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003694 }
3695 } //end if myBinder
3696 } //end while iter
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003697
3698 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003699 }
3700
3701 final void removeDeadProvider(String name, IContentProvider provider) {
3702 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003703 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003704 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003705 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003706 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003707 if (removed != null) {
3708 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003710 }
3711 }
3712 }
3713
3714 final void removeDeadProviderLocked(String name, IContentProvider provider) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003715 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003716 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003717 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003718 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003719 if (removed != null) {
3720 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3721 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003722 }
3723 }
3724
3725 private final IContentProvider installProvider(Context context,
3726 IContentProvider provider, ProviderInfo info, boolean noisy) {
3727 ContentProvider localProvider = null;
3728 if (provider == null) {
3729 if (noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003730 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003731 + info.name);
3732 }
3733 Context c = null;
3734 ApplicationInfo ai = info.applicationInfo;
3735 if (context.getPackageName().equals(ai.packageName)) {
3736 c = context;
3737 } else if (mInitialApplication != null &&
3738 mInitialApplication.getPackageName().equals(ai.packageName)) {
3739 c = mInitialApplication;
3740 } else {
3741 try {
3742 c = context.createPackageContext(ai.packageName,
3743 Context.CONTEXT_INCLUDE_CODE);
3744 } catch (PackageManager.NameNotFoundException e) {
3745 }
3746 }
3747 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003748 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003749 ai.packageName +
3750 " while loading content provider " +
3751 info.name);
3752 return null;
3753 }
3754 try {
3755 final java.lang.ClassLoader cl = c.getClassLoader();
3756 localProvider = (ContentProvider)cl.
3757 loadClass(info.name).newInstance();
3758 provider = localProvider.getIContentProvider();
3759 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003760 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003761 info.name + " from sourceDir " +
3762 info.applicationInfo.sourceDir);
3763 return null;
3764 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003765 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003766 TAG, "Instantiating local provider " + info.name);
3767 // XXX Need to create the correct context for this provider.
3768 localProvider.attachInfo(c, info);
3769 } catch (java.lang.Exception e) {
3770 if (!mInstrumentation.onException(null, e)) {
3771 throw new RuntimeException(
3772 "Unable to get provider " + info.name
3773 + ": " + e.toString(), e);
3774 }
3775 return null;
3776 }
3777 } else if (localLOGV) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003778 Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003779 + info.name);
3780 }
3781
3782 synchronized (mProviderMap) {
3783 // Cache the pointer for the remote provider.
3784 String names[] = PATTERN_SEMICOLON.split(info.authority);
3785 for (int i=0; i<names.length; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003786 ProviderClientRecord pr = new ProviderClientRecord(names[i], provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003787 localProvider);
3788 try {
3789 provider.asBinder().linkToDeath(pr, 0);
3790 mProviderMap.put(names[i], pr);
3791 } catch (RemoteException e) {
3792 return null;
3793 }
3794 }
3795 if (localProvider != null) {
3796 mLocalProviders.put(provider.asBinder(),
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003797 new ProviderClientRecord(null, provider, localProvider));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003798 }
3799 }
3800
3801 return provider;
3802 }
3803
3804 private final void attach(boolean system) {
3805 sThreadLocal.set(this);
3806 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003807 if (!system) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003808 ViewRoot.addFirstDrawHandler(new Runnable() {
3809 public void run() {
3810 ensureJitEnabled();
3811 }
3812 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
3814 RuntimeInit.setApplicationObject(mAppThread.asBinder());
3815 IActivityManager mgr = ActivityManagerNative.getDefault();
3816 try {
3817 mgr.attachApplication(mAppThread);
3818 } catch (RemoteException ex) {
3819 }
3820 } else {
3821 // Don't set application object here -- if the system crashes,
3822 // we can't display an alert, we just want to die die die.
3823 android.ddm.DdmHandleAppName.setAppName("system_process");
3824 try {
3825 mInstrumentation = new Instrumentation();
Dianne Hackborn21556372010-02-04 16:34:40 -08003826 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003827 context.init(getSystemContext().mPackageInfo, null, this);
3828 Application app = Instrumentation.newApplication(Application.class, context);
3829 mAllApplications.add(app);
3830 mInitialApplication = app;
3831 app.onCreate();
3832 } catch (Exception e) {
3833 throw new RuntimeException(
3834 "Unable to instantiate Application():" + e.toString(), e);
3835 }
3836 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003837
3838 ViewRoot.addConfigCallback(new ComponentCallbacks() {
3839 public void onConfigurationChanged(Configuration newConfig) {
3840 synchronized (mPackages) {
Dianne Hackbornae078162010-03-18 11:29:37 -07003841 // We need to apply this change to the resources
3842 // immediately, because upon returning the view
3843 // hierarchy will be informed about it.
3844 if (applyConfigurationToResourcesLocked(newConfig)) {
3845 // This actually changed the resources! Tell
3846 // everyone about it.
3847 if (mPendingConfiguration == null ||
3848 mPendingConfiguration.isOtherSeqNewer(newConfig)) {
3849 mPendingConfiguration = newConfig;
3850
3851 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
3852 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003853 }
3854 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003855 }
3856 public void onLowMemory() {
3857 }
3858 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 }
3860
3861 private final void detach()
3862 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003863 sThreadLocal.set(null);
3864 }
3865
3866 public static final ActivityThread systemMain() {
Romain Guy52339202010-09-03 16:04:46 -07003867 HardwareRenderer.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 ActivityThread thread = new ActivityThread();
3869 thread.attach(true);
3870 return thread;
3871 }
3872
3873 public final void installSystemProviders(List providers) {
3874 if (providers != null) {
3875 installContentProviders(mInitialApplication,
3876 (List<ProviderInfo>)providers);
3877 }
3878 }
3879
3880 public static final void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07003881 SamplingProfilerIntegration.start();
3882
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -08003883 // CloseGuard defaults to true and can be quite spammy. We
3884 // disable it here, but selectively enable it later (via
3885 // StrictMode) on debug builds, but using DropBox, not logs.
3886 CloseGuard.setEnabled(false);
3887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 Process.setArgV0("<pre-initialized>");
3889
3890 Looper.prepareMainLooper();
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07003891 if (sMainThreadHandler == null) {
3892 sMainThreadHandler = new Handler();
3893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003894
3895 ActivityThread thread = new ActivityThread();
3896 thread.attach(false);
3897
Dianne Hackborn287952c2010-09-22 22:34:31 -07003898 if (false) {
3899 Looper.myLooper().setMessageLogging(new
3900 LogPrinter(Log.DEBUG, "ActivityThread"));
3901 }
3902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 Looper.loop();
3904
3905 if (Process.supportsProcesses()) {
3906 throw new RuntimeException("Main thread loop unexpectedly exited");
3907 }
3908
3909 thread.detach();
Bob Leeeec2f412009-09-10 11:01:24 +02003910 String name = (thread.mInitialApplication != null)
3911 ? thread.mInitialApplication.getPackageName()
3912 : "<unknown>";
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003913 Slog.i(TAG, "Main thread of " + name + " is now exiting");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003914 }
3915}