blob: 03bb858376e62f1da2910375154e43cf120ff581 [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;
33import android.content.pm.ProviderInfo;
34import android.content.pm.ServiceInfo;
35import android.content.res.AssetManager;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -070036import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.content.res.Configuration;
38import android.content.res.Resources;
39import android.database.sqlite.SQLiteDatabase;
40import android.database.sqlite.SQLiteDebug;
Vasu Noric3849202010-03-09 10:47:25 -080041import android.database.sqlite.SQLiteDebug.DbStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.graphics.Bitmap;
43import android.graphics.Canvas;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070044import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.os.Bundle;
46import android.os.Debug;
47import android.os.Handler;
48import android.os.IBinder;
49import android.os.Looper;
50import android.os.Message;
51import android.os.MessageQueue;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070052import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.Process;
54import android.os.RemoteException;
55import android.os.ServiceManager;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070056import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.os.SystemClock;
58import android.util.AndroidRuntimeException;
59import android.util.Config;
60import android.util.DisplayMetrics;
61import android.util.EventLog;
62import android.util.Log;
Dianne Hackbornc9421ba2010-03-11 22:23:46 -080063import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.view.Display;
65import android.view.View;
66import android.view.ViewDebug;
67import android.view.ViewManager;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -080068import android.view.ViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.view.Window;
70import android.view.WindowManager;
71import android.view.WindowManagerImpl;
72
73import com.android.internal.os.BinderInternal;
74import com.android.internal.os.RuntimeInit;
Bob Leee5408332009-09-04 18:31:17 -070075import com.android.internal.os.SamplingProfilerIntegration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076
77import org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl;
78
79import java.io.File;
80import java.io.FileDescriptor;
81import java.io.FileOutputStream;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070082import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import java.io.PrintWriter;
84import java.lang.ref.WeakReference;
85import java.util.ArrayList;
86import java.util.HashMap;
87import java.util.Iterator;
88import java.util.List;
89import java.util.Locale;
90import java.util.Map;
91import java.util.TimeZone;
92import java.util.regex.Pattern;
93
Bob Leee5408332009-09-04 18:31:17 -070094import dalvik.system.SamplingProfiler;
95
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096final class SuperNotCalledException extends AndroidRuntimeException {
97 public SuperNotCalledException(String msg) {
98 super(msg);
99 }
100}
101
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700102final class RemoteServiceException extends AndroidRuntimeException {
103 public RemoteServiceException(String msg) {
104 super(msg);
105 }
106}
107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108/**
109 * This manages the execution of the main thread in an
110 * application process, scheduling and executing activities,
111 * broadcasts, and other operations on it as the activity
112 * manager requests.
113 *
114 * {@hide}
115 */
116public final class ActivityThread {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700117 static final String TAG = "ActivityThread";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 private static final boolean DEBUG = false;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700119 static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
120 static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700121 private static final boolean DEBUG_RESULTS = false;
Christopher Tate436344a2009-09-30 16:17:37 -0700122 private static final boolean DEBUG_BACKUP = false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700123 private static final boolean DEBUG_CONFIGURATION = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
125 private static final Pattern PATTERN_SEMICOLON = Pattern.compile(";");
126 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
127 private static final int LOG_ON_PAUSE_CALLED = 30021;
128 private static final int LOG_ON_RESUME_CALLED = 30022;
129
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700130 static ContextImpl mSystemContext = null;
Bob Leee5408332009-09-04 18:31:17 -0700131
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700132 static IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700134 final ApplicationThread mAppThread = new ApplicationThread();
135 final Looper mLooper = Looper.myLooper();
136 final H mH = new H();
137 final HashMap<IBinder, ActivityClientRecord> mActivities
138 = new HashMap<IBinder, ActivityClientRecord>();
139 // List of new activities (via ActivityRecord.nextIdle) that should
140 // be reported when next we idle.
141 ActivityClientRecord mNewActivities = null;
142 // Number of activities that are currently visible on-screen.
143 int mNumVisibleActivities = 0;
144 final HashMap<IBinder, Service> mServices
145 = new HashMap<IBinder, Service>();
146 AppBindData mBoundApplication;
147 Configuration mConfiguration;
148 Configuration mResConfiguration;
149 Application mInitialApplication;
150 final ArrayList<Application> mAllApplications
151 = new ArrayList<Application>();
152 // set of instantiated backup agents, keyed by package name
153 final HashMap<String, BackupAgent> mBackupAgents = new HashMap<String, BackupAgent>();
154 static final ThreadLocal sThreadLocal = new ThreadLocal();
155 Instrumentation mInstrumentation;
156 String mInstrumentationAppDir = null;
157 String mInstrumentationAppPackage = null;
158 String mInstrumentedAppDir = null;
159 boolean mSystemThread = false;
160 boolean mJitEnabled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700162 // These can be accessed by multiple threads; mPackages is the lock.
163 // XXX For now we keep around information about all packages we have
164 // seen, not removing entries from this map.
165 final HashMap<String, WeakReference<LoadedApk>> mPackages
166 = new HashMap<String, WeakReference<LoadedApk>>();
167 final HashMap<String, WeakReference<LoadedApk>> mResourcePackages
168 = new HashMap<String, WeakReference<LoadedApk>>();
169 Display mDisplay = null;
170 DisplayMetrics mDisplayMetrics = null;
171 final HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources
172 = new HashMap<ResourcesKey, WeakReference<Resources> >();
173 final ArrayList<ActivityClientRecord> mRelaunchingActivities
174 = new ArrayList<ActivityClientRecord>();
175 Configuration mPendingConfiguration = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700177 // The lock of mProviderMap protects the following variables.
178 final HashMap<String, ProviderClientRecord> mProviderMap
179 = new HashMap<String, ProviderClientRecord>();
180 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap
181 = new HashMap<IBinder, ProviderRefCount>();
182 final HashMap<IBinder, ProviderClientRecord> mLocalProviders
183 = new HashMap<IBinder, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700185 final GcIdler mGcIdler = new GcIdler();
186 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700188 private static final class ActivityClientRecord {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700190 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 Intent intent;
192 Bundle state;
193 Activity activity;
194 Window window;
195 Activity parent;
196 String embeddedID;
197 Object lastNonConfigurationInstance;
198 HashMap<String,Object> lastNonConfigurationChildInstances;
199 boolean paused;
200 boolean stopped;
201 boolean hideForNow;
202 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700203 Configuration createdConfig;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700204 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205
206 ActivityInfo activityInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700207 LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208
209 List<ResultInfo> pendingResults;
210 List<Intent> pendingIntents;
211
212 boolean startsNotResumed;
213 boolean isForward;
214
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700215 ActivityClientRecord() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216 parent = null;
217 embeddedID = null;
218 paused = false;
219 stopped = false;
220 hideForNow = false;
221 nextIdle = null;
222 }
223
224 public String toString() {
225 ComponentName componentName = intent.getComponent();
226 return "ActivityRecord{"
227 + Integer.toHexString(System.identityHashCode(this))
228 + " token=" + token + " " + (componentName == null
229 ? "no component name" : componentName.toShortString())
230 + "}";
231 }
232 }
233
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700234 private final class ProviderClientRecord implements IBinder.DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 final String mName;
236 final IContentProvider mProvider;
237 final ContentProvider mLocalProvider;
238
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700239 ProviderClientRecord(String name, IContentProvider provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 ContentProvider localProvider) {
241 mName = name;
242 mProvider = provider;
243 mLocalProvider = localProvider;
244 }
245
246 public void binderDied() {
247 removeDeadProvider(mName, mProvider);
248 }
249 }
250
251 private static final class NewIntentData {
252 List<Intent> intents;
253 IBinder token;
254 public String toString() {
255 return "NewIntentData{intents=" + intents + " token=" + token + "}";
256 }
257 }
258
259 private static final class ReceiverData {
260 Intent intent;
261 ActivityInfo info;
262 int resultCode;
263 String resultData;
264 Bundle resultExtras;
265 boolean sync;
266 boolean resultAbort;
267 public String toString() {
268 return "ReceiverData{intent=" + intent + " packageName=" +
269 info.packageName + " resultCode=" + resultCode
270 + " resultData=" + resultData + " resultExtras=" + resultExtras + "}";
271 }
272 }
273
Christopher Tate181fafa2009-05-14 11:12:14 -0700274 private static final class CreateBackupAgentData {
275 ApplicationInfo appInfo;
276 int backupMode;
277 public String toString() {
278 return "CreateBackupAgentData{appInfo=" + appInfo
279 + " backupAgent=" + appInfo.backupAgentName
280 + " mode=" + backupMode + "}";
281 }
282 }
Bob Leee5408332009-09-04 18:31:17 -0700283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284 private static final class CreateServiceData {
285 IBinder token;
286 ServiceInfo info;
287 Intent intent;
288 public String toString() {
289 return "CreateServiceData{token=" + token + " className="
290 + info.name + " packageName=" + info.packageName
291 + " intent=" + intent + "}";
292 }
293 }
294
295 private static final class BindServiceData {
296 IBinder token;
297 Intent intent;
298 boolean rebind;
299 public String toString() {
300 return "BindServiceData{token=" + token + " intent=" + intent + "}";
301 }
302 }
303
304 private static final class ServiceArgsData {
305 IBinder token;
306 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700307 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 Intent args;
309 public String toString() {
310 return "ServiceArgsData{token=" + token + " startId=" + startId
311 + " args=" + args + "}";
312 }
313 }
314
315 private static final class AppBindData {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700316 LoadedApk info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317 String processName;
318 ApplicationInfo appInfo;
319 List<ProviderInfo> providers;
320 ComponentName instrumentationName;
321 String profileFile;
322 Bundle instrumentationArgs;
323 IInstrumentationWatcher instrumentationWatcher;
324 int debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700325 boolean restrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326 Configuration config;
327 boolean handlingProfiling;
328 public String toString() {
329 return "AppBindData{appInfo=" + appInfo + "}";
330 }
331 }
332
333 private static final class DumpServiceInfo {
334 FileDescriptor fd;
335 IBinder service;
336 String[] args;
337 boolean dumped;
338 }
339
340 private static final class ResultData {
341 IBinder token;
342 List<ResultInfo> results;
343 public String toString() {
344 return "ResultData{token=" + token + " results" + results + "}";
345 }
346 }
347
348 private static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800349 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800350 String what;
351 String who;
352 }
353
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700354 private static final class ProfilerControlData {
355 String path;
356 ParcelFileDescriptor fd;
357 }
358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800359 private final class ApplicationThread extends ApplicationThreadNative {
360 private static final String HEAP_COLUMN = "%17s %8s %8s %8s %8s";
361 private static final String ONE_COUNT_COLUMN = "%17s %8d";
362 private static final String TWO_COUNT_COLUMNS = "%17s %8d %17s %8d";
Vasu Noric3849202010-03-09 10:47:25 -0800363 private static final String DB_INFO_FORMAT = " %8d %8d %10d %s";
Bob Leee5408332009-09-04 18:31:17 -0700364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365 // Formatting for checkin service - update version if row format changes
366 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;
Bob Leee5408332009-09-04 18:31:17 -0700367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800368 public final void schedulePauseActivity(IBinder token, boolean finished,
369 boolean userLeaving, int configChanges) {
370 queueOrSendMessage(
371 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
372 token,
373 (userLeaving ? 1 : 0),
374 configChanges);
375 }
376
377 public final void scheduleStopActivity(IBinder token, boolean showWindow,
378 int configChanges) {
379 queueOrSendMessage(
380 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
381 token, 0, configChanges);
382 }
383
384 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
385 queueOrSendMessage(
386 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
387 token);
388 }
389
390 public final void scheduleResumeActivity(IBinder token, boolean isForward) {
391 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
392 }
393
394 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
395 ResultData res = new ResultData();
396 res.token = token;
397 res.results = results;
398 queueOrSendMessage(H.SEND_RESULT, res);
399 }
400
401 // we use token to identify this activity without having to send the
402 // activity itself back to the activity manager. (matters more with ipc)
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700403 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404 ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
405 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700406 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407
408 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700409 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800410 r.intent = intent;
411 r.activityInfo = info;
412 r.state = state;
413
414 r.pendingResults = pendingResults;
415 r.pendingIntents = pendingNewIntents;
416
417 r.startsNotResumed = notResumed;
418 r.isForward = isForward;
419
420 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
421 }
422
423 public final void scheduleRelaunchActivity(IBinder token,
424 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800425 int configChanges, boolean notResumed, Configuration config) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700426 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427
428 r.token = token;
429 r.pendingResults = pendingResults;
430 r.pendingIntents = pendingNewIntents;
431 r.startsNotResumed = notResumed;
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800432 r.createdConfig = config;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800434 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435 mRelaunchingActivities.add(r);
436 }
Bob Leee5408332009-09-04 18:31:17 -0700437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800438 queueOrSendMessage(H.RELAUNCH_ACTIVITY, r, configChanges);
439 }
440
441 public final void scheduleNewIntent(List<Intent> intents, IBinder token) {
442 NewIntentData data = new NewIntentData();
443 data.intents = intents;
444 data.token = token;
445
446 queueOrSendMessage(H.NEW_INTENT, data);
447 }
448
449 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
450 int configChanges) {
451 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
452 configChanges);
453 }
454
455 public final void scheduleReceiver(Intent intent, ActivityInfo info,
456 int resultCode, String data, Bundle extras, boolean sync) {
457 ReceiverData r = new ReceiverData();
458
459 r.intent = intent;
460 r.info = info;
461 r.resultCode = resultCode;
462 r.resultData = data;
463 r.resultExtras = extras;
464 r.sync = sync;
465
466 queueOrSendMessage(H.RECEIVER, r);
467 }
468
Christopher Tate181fafa2009-05-14 11:12:14 -0700469 public final void scheduleCreateBackupAgent(ApplicationInfo app, int backupMode) {
470 CreateBackupAgentData d = new CreateBackupAgentData();
471 d.appInfo = app;
472 d.backupMode = backupMode;
473
474 queueOrSendMessage(H.CREATE_BACKUP_AGENT, d);
475 }
476
477 public final void scheduleDestroyBackupAgent(ApplicationInfo app) {
478 CreateBackupAgentData d = new CreateBackupAgentData();
479 d.appInfo = app;
480
481 queueOrSendMessage(H.DESTROY_BACKUP_AGENT, d);
482 }
483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 public final void scheduleCreateService(IBinder token,
485 ServiceInfo info) {
486 CreateServiceData s = new CreateServiceData();
487 s.token = token;
488 s.info = info;
489
490 queueOrSendMessage(H.CREATE_SERVICE, s);
491 }
492
493 public final void scheduleBindService(IBinder token, Intent intent,
494 boolean rebind) {
495 BindServiceData s = new BindServiceData();
496 s.token = token;
497 s.intent = intent;
498 s.rebind = rebind;
499
500 queueOrSendMessage(H.BIND_SERVICE, s);
501 }
502
503 public final void scheduleUnbindService(IBinder token, Intent intent) {
504 BindServiceData s = new BindServiceData();
505 s.token = token;
506 s.intent = intent;
507
508 queueOrSendMessage(H.UNBIND_SERVICE, s);
509 }
510
511 public final void scheduleServiceArgs(IBinder token, int startId,
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700512 int flags ,Intent args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 ServiceArgsData s = new ServiceArgsData();
514 s.token = token;
515 s.startId = startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700516 s.flags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 s.args = args;
518
519 queueOrSendMessage(H.SERVICE_ARGS, s);
520 }
521
522 public final void scheduleStopService(IBinder token) {
523 queueOrSendMessage(H.STOP_SERVICE, token);
524 }
525
526 public final void bindApplication(String processName,
527 ApplicationInfo appInfo, List<ProviderInfo> providers,
528 ComponentName instrumentationName, String profileFile,
529 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
Christopher Tate181fafa2009-05-14 11:12:14 -0700530 int debugMode, boolean isRestrictedBackupMode, Configuration config,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800531 Map<String, IBinder> services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532
533 if (services != null) {
534 // Setup the service cache in the ServiceManager
535 ServiceManager.initServiceCache(services);
536 }
537
538 AppBindData data = new AppBindData();
539 data.processName = processName;
540 data.appInfo = appInfo;
541 data.providers = providers;
542 data.instrumentationName = instrumentationName;
543 data.profileFile = profileFile;
544 data.instrumentationArgs = instrumentationArgs;
545 data.instrumentationWatcher = instrumentationWatcher;
546 data.debugMode = debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700547 data.restrictedBackupMode = isRestrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800548 data.config = config;
549 queueOrSendMessage(H.BIND_APPLICATION, data);
550 }
551
552 public final void scheduleExit() {
553 queueOrSendMessage(H.EXIT_APPLICATION, null);
554 }
555
Christopher Tate5e1ab332009-09-01 20:32:49 -0700556 public final void scheduleSuicide() {
557 queueOrSendMessage(H.SUICIDE, null);
558 }
559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 public void requestThumbnail(IBinder token) {
561 queueOrSendMessage(H.REQUEST_THUMBNAIL, token);
562 }
563
564 public void scheduleConfigurationChanged(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800565 synchronized (mPackages) {
566 if (mPendingConfiguration == null ||
567 mPendingConfiguration.isOtherSeqNewer(config)) {
568 mPendingConfiguration = config;
569 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570 }
571 queueOrSendMessage(H.CONFIGURATION_CHANGED, config);
572 }
573
574 public void updateTimeZone() {
575 TimeZone.setDefault(null);
576 }
577
578 public void processInBackground() {
579 mH.removeMessages(H.GC_WHEN_IDLE);
580 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
581 }
582
583 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) {
584 DumpServiceInfo data = new DumpServiceInfo();
585 data.fd = fd;
586 data.service = servicetoken;
587 data.args = args;
588 data.dumped = false;
589 queueOrSendMessage(H.DUMP_SERVICE, data);
590 synchronized (data) {
591 while (!data.dumped) {
592 try {
593 data.wait();
594 } catch (InterruptedException e) {
595 // no need to do anything here, we will keep waiting until
596 // dumped is set
597 }
598 }
599 }
600 }
601
602 // This function exists to make sure all receiver dispatching is
603 // correctly ordered, since these are one-way calls and the binder driver
604 // applies transaction ordering per object for such calls.
605 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700606 int resultCode, String dataStr, Bundle extras, boolean ordered,
607 boolean sticky) throws RemoteException {
608 receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609 }
Bob Leee5408332009-09-04 18:31:17 -0700610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 public void scheduleLowMemory() {
612 queueOrSendMessage(H.LOW_MEMORY, null);
613 }
614
615 public void scheduleActivityConfigurationChanged(IBinder token) {
616 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token);
617 }
618
619 public void requestPss() {
620 try {
621 ActivityManagerNative.getDefault().reportPss(this,
622 (int)Process.getPss(Process.myPid()));
623 } catch (RemoteException e) {
624 }
625 }
Bob Leee5408332009-09-04 18:31:17 -0700626
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700627 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd) {
628 ProfilerControlData pcd = new ProfilerControlData();
629 pcd.path = path;
630 pcd.fd = fd;
631 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800632 }
633
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700634 public void setSchedulingGroup(int group) {
635 // Note: do this immediately, since going into the foreground
636 // should happen regardless of what pending work we have to do
637 // and the activity manager will wait for us to report back that
638 // we are done before sending us to the background.
639 try {
640 Process.setProcessGroup(Process.myPid(), group);
641 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800642 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700643 }
644 }
Bob Leee5408332009-09-04 18:31:17 -0700645
Dianne Hackborn3025ef32009-08-31 21:31:47 -0700646 public void getMemoryInfo(Debug.MemoryInfo outInfo) {
647 Debug.getMemoryInfo(outInfo);
648 }
Bob Leee5408332009-09-04 18:31:17 -0700649
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700650 public void dispatchPackageBroadcast(int cmd, String[] packages) {
651 queueOrSendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
652 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700653
654 public void scheduleCrash(String msg) {
655 queueOrSendMessage(H.SCHEDULE_CRASH, msg);
656 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 @Override
659 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
660 long nativeMax = Debug.getNativeHeapSize() / 1024;
661 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
662 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
663
664 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
665 Debug.getMemoryInfo(memInfo);
666
667 final int nativeShared = memInfo.nativeSharedDirty;
668 final int dalvikShared = memInfo.dalvikSharedDirty;
669 final int otherShared = memInfo.otherSharedDirty;
670
671 final int nativePrivate = memInfo.nativePrivateDirty;
672 final int dalvikPrivate = memInfo.dalvikPrivateDirty;
673 final int otherPrivate = memInfo.otherPrivateDirty;
674
675 Runtime runtime = Runtime.getRuntime();
676
677 long dalvikMax = runtime.totalMemory() / 1024;
678 long dalvikFree = runtime.freeMemory() / 1024;
679 long dalvikAllocated = dalvikMax - dalvikFree;
680 long viewInstanceCount = ViewDebug.getViewInstanceCount();
681 long viewRootInstanceCount = ViewDebug.getViewRootInstanceCount();
Dianne Hackborn21556372010-02-04 16:34:40 -0800682 long appContextInstanceCount = ContextImpl.getInstanceCount();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 long activityInstanceCount = Activity.getInstanceCount();
684 int globalAssetCount = AssetManager.getGlobalAssetCount();
685 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
686 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
687 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
688 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
689 int openSslSocketCount = OpenSSLSocketImpl.getInstanceCount();
690 long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024;
Vasu Noric3849202010-03-09 10:47:25 -0800691 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -0700692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 // Check to see if we were called by checkin server. If so, print terse format.
694 boolean doCheckinFormat = false;
695 if (args != null) {
696 for (String arg : args) {
697 if ("-c".equals(arg)) doCheckinFormat = true;
698 }
699 }
Bob Leee5408332009-09-04 18:31:17 -0700700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 // For checkin, we print one long comma-separated list of values
702 if (doCheckinFormat) {
703 // NOTE: if you change anything significant below, also consider changing
704 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -0700705 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -0700707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 // Header
709 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
710 pw.print(Process.myPid()); pw.print(',');
711 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 // Heap info - max
714 pw.print(nativeMax); pw.print(',');
715 pw.print(dalvikMax); pw.print(',');
716 pw.print("N/A,");
717 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 // Heap info - allocated
720 pw.print(nativeAllocated); pw.print(',');
721 pw.print(dalvikAllocated); pw.print(',');
722 pw.print("N/A,");
723 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 // Heap info - free
726 pw.print(nativeFree); pw.print(',');
727 pw.print(dalvikFree); pw.print(',');
728 pw.print("N/A,");
729 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 // Heap info - proportional set size
732 pw.print(memInfo.nativePss); pw.print(',');
733 pw.print(memInfo.dalvikPss); pw.print(',');
734 pw.print(memInfo.otherPss); pw.print(',');
735 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 // Heap info - shared
Bob Leee5408332009-09-04 18:31:17 -0700738 pw.print(nativeShared); pw.print(',');
739 pw.print(dalvikShared); pw.print(',');
740 pw.print(otherShared); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 pw.print(nativeShared + dalvikShared + otherShared); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 // Heap info - private
Bob Leee5408332009-09-04 18:31:17 -0700744 pw.print(nativePrivate); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 pw.print(dalvikPrivate); pw.print(',');
746 pw.print(otherPrivate); pw.print(',');
747 pw.print(nativePrivate + dalvikPrivate + otherPrivate); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749 // Object counts
750 pw.print(viewInstanceCount); pw.print(',');
751 pw.print(viewRootInstanceCount); pw.print(',');
752 pw.print(appContextInstanceCount); pw.print(',');
753 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 pw.print(globalAssetCount); pw.print(',');
756 pw.print(globalAssetManagerCount); pw.print(',');
757 pw.print(binderLocalObjectCount); pw.print(',');
758 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 pw.print(binderDeathObjectCount); pw.print(',');
761 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763 // SQL
764 pw.print(sqliteAllocated); pw.print(',');
Vasu Noric3849202010-03-09 10:47:25 -0800765 pw.print(stats.memoryUsed / 1024); pw.print(',');
766 pw.print(stats.pageCacheOverflo / 1024); pw.print(',');
767 pw.print(stats.largestMemAlloc / 1024); pw.print(',');
768 for (int i = 0; i < stats.dbStats.size(); i++) {
769 DbStats dbStats = stats.dbStats.get(i);
770 printRow(pw, DB_INFO_FORMAT, dbStats.pageSize, dbStats.dbSize,
771 dbStats.lookaside, dbStats.dbName);
772 pw.print(',');
773 }
Bob Leee5408332009-09-04 18:31:17 -0700774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 return;
776 }
Bob Leee5408332009-09-04 18:31:17 -0700777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 // otherwise, show human-readable format
779 printRow(pw, HEAP_COLUMN, "", "native", "dalvik", "other", "total");
780 printRow(pw, HEAP_COLUMN, "size:", nativeMax, dalvikMax, "N/A", nativeMax + dalvikMax);
781 printRow(pw, HEAP_COLUMN, "allocated:", nativeAllocated, dalvikAllocated, "N/A",
782 nativeAllocated + dalvikAllocated);
783 printRow(pw, HEAP_COLUMN, "free:", nativeFree, dalvikFree, "N/A",
784 nativeFree + dalvikFree);
785
786 printRow(pw, HEAP_COLUMN, "(Pss):", memInfo.nativePss, memInfo.dalvikPss,
787 memInfo.otherPss, memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss);
788
789 printRow(pw, HEAP_COLUMN, "(shared dirty):", nativeShared, dalvikShared, otherShared,
790 nativeShared + dalvikShared + otherShared);
791 printRow(pw, HEAP_COLUMN, "(priv dirty):", nativePrivate, dalvikPrivate, otherPrivate,
792 nativePrivate + dalvikPrivate + otherPrivate);
793
794 pw.println(" ");
795 pw.println(" Objects");
796 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRoots:",
797 viewRootInstanceCount);
798
799 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
800 "Activities:", activityInstanceCount);
801
802 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
803 "AssetManagers:", globalAssetManagerCount);
804
805 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
806 "Proxy Binders:", binderProxyObjectCount);
807 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
808
809 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -0700810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 // SQLite mem info
812 pw.println(" ");
813 pw.println(" SQL");
Vasu Noric3849202010-03-09 10:47:25 -0800814 printRow(pw, TWO_COUNT_COLUMNS, "heap:", sqliteAllocated, "memoryUsed:",
815 stats.memoryUsed / 1024);
816 printRow(pw, TWO_COUNT_COLUMNS, "pageCacheOverflo:", stats.pageCacheOverflo / 1024,
817 "largestMemAlloc:", stats.largestMemAlloc / 1024);
818 pw.println(" ");
819 int N = stats.dbStats.size();
820 if (N > 0) {
821 pw.println(" DATABASES");
822 printRow(pw, " %8s %8s %10s %s", "Pagesize", "Dbsize", "Lookaside", "Dbname");
823 for (int i = 0; i < N; i++) {
824 DbStats dbStats = stats.dbStats.get(i);
825 printRow(pw, DB_INFO_FORMAT, dbStats.pageSize, dbStats.dbSize,
826 dbStats.lookaside, dbStats.dbName);
827 }
828 }
Bob Leee5408332009-09-04 18:31:17 -0700829
Dianne Hackborn82e1ee92009-08-11 18:56:41 -0700830 // Asset details.
831 String assetAlloc = AssetManager.getAssetAllocations();
832 if (assetAlloc != null) {
833 pw.println(" ");
834 pw.println(" Asset Allocations");
835 pw.print(assetAlloc);
836 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 }
838
839 private void printRow(PrintWriter pw, String format, Object...objs) {
840 pw.println(String.format(format, objs));
841 }
842 }
843
844 private final class H extends Handler {
Bob Leee5408332009-09-04 18:31:17 -0700845 private H() {
846 SamplingProfiler.getInstance().setEventThread(mLooper.getThread());
847 }
848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 public static final int LAUNCH_ACTIVITY = 100;
850 public static final int PAUSE_ACTIVITY = 101;
851 public static final int PAUSE_ACTIVITY_FINISHING= 102;
852 public static final int STOP_ACTIVITY_SHOW = 103;
853 public static final int STOP_ACTIVITY_HIDE = 104;
854 public static final int SHOW_WINDOW = 105;
855 public static final int HIDE_WINDOW = 106;
856 public static final int RESUME_ACTIVITY = 107;
857 public static final int SEND_RESULT = 108;
858 public static final int DESTROY_ACTIVITY = 109;
859 public static final int BIND_APPLICATION = 110;
860 public static final int EXIT_APPLICATION = 111;
861 public static final int NEW_INTENT = 112;
862 public static final int RECEIVER = 113;
863 public static final int CREATE_SERVICE = 114;
864 public static final int SERVICE_ARGS = 115;
865 public static final int STOP_SERVICE = 116;
866 public static final int REQUEST_THUMBNAIL = 117;
867 public static final int CONFIGURATION_CHANGED = 118;
868 public static final int CLEAN_UP_CONTEXT = 119;
869 public static final int GC_WHEN_IDLE = 120;
870 public static final int BIND_SERVICE = 121;
871 public static final int UNBIND_SERVICE = 122;
872 public static final int DUMP_SERVICE = 123;
873 public static final int LOW_MEMORY = 124;
874 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
875 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800876 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -0700877 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -0700878 public static final int DESTROY_BACKUP_AGENT = 129;
879 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700880 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800881 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700882 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700883 public static final int SCHEDULE_CRASH = 134;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 String codeToString(int code) {
885 if (localLOGV) {
886 switch (code) {
887 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
888 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
889 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
890 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
891 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
892 case SHOW_WINDOW: return "SHOW_WINDOW";
893 case HIDE_WINDOW: return "HIDE_WINDOW";
894 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
895 case SEND_RESULT: return "SEND_RESULT";
896 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
897 case BIND_APPLICATION: return "BIND_APPLICATION";
898 case EXIT_APPLICATION: return "EXIT_APPLICATION";
899 case NEW_INTENT: return "NEW_INTENT";
900 case RECEIVER: return "RECEIVER";
901 case CREATE_SERVICE: return "CREATE_SERVICE";
902 case SERVICE_ARGS: return "SERVICE_ARGS";
903 case STOP_SERVICE: return "STOP_SERVICE";
904 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
905 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
906 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
907 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
908 case BIND_SERVICE: return "BIND_SERVICE";
909 case UNBIND_SERVICE: return "UNBIND_SERVICE";
910 case DUMP_SERVICE: return "DUMP_SERVICE";
911 case LOW_MEMORY: return "LOW_MEMORY";
912 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
913 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800914 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -0700915 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
916 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -0700917 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700918 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800919 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700920 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700921 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 }
923 }
924 return "(unknown)";
925 }
926 public void handleMessage(Message msg) {
927 switch (msg.what) {
928 case LAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700929 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930
931 r.packageInfo = getPackageInfoNoCheck(
932 r.activityInfo.applicationInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -0700933 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 } break;
935 case RELAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700936 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 handleRelaunchActivity(r, msg.arg1);
938 } break;
939 case PAUSE_ACTIVITY:
940 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -0700941 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 break;
943 case PAUSE_ACTIVITY_FINISHING:
944 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
945 break;
946 case STOP_ACTIVITY_SHOW:
947 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
948 break;
949 case STOP_ACTIVITY_HIDE:
950 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
951 break;
952 case SHOW_WINDOW:
953 handleWindowVisibility((IBinder)msg.obj, true);
954 break;
955 case HIDE_WINDOW:
956 handleWindowVisibility((IBinder)msg.obj, false);
957 break;
958 case RESUME_ACTIVITY:
959 handleResumeActivity((IBinder)msg.obj, true,
960 msg.arg1 != 0);
961 break;
962 case SEND_RESULT:
963 handleSendResult((ResultData)msg.obj);
964 break;
965 case DESTROY_ACTIVITY:
966 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
967 msg.arg2, false);
968 break;
969 case BIND_APPLICATION:
970 AppBindData data = (AppBindData)msg.obj;
971 handleBindApplication(data);
972 break;
973 case EXIT_APPLICATION:
974 if (mInitialApplication != null) {
975 mInitialApplication.onTerminate();
976 }
977 Looper.myLooper().quit();
978 break;
979 case NEW_INTENT:
980 handleNewIntent((NewIntentData)msg.obj);
981 break;
982 case RECEIVER:
983 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -0700984 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 break;
986 case CREATE_SERVICE:
987 handleCreateService((CreateServiceData)msg.obj);
988 break;
989 case BIND_SERVICE:
990 handleBindService((BindServiceData)msg.obj);
991 break;
992 case UNBIND_SERVICE:
993 handleUnbindService((BindServiceData)msg.obj);
994 break;
995 case SERVICE_ARGS:
996 handleServiceArgs((ServiceArgsData)msg.obj);
997 break;
998 case STOP_SERVICE:
999 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -07001000 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 break;
1002 case REQUEST_THUMBNAIL:
1003 handleRequestThumbnail((IBinder)msg.obj);
1004 break;
1005 case CONFIGURATION_CHANGED:
1006 handleConfigurationChanged((Configuration)msg.obj);
1007 break;
1008 case CLEAN_UP_CONTEXT:
1009 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1010 cci.context.performFinalCleanup(cci.who, cci.what);
1011 break;
1012 case GC_WHEN_IDLE:
1013 scheduleGcIdler();
1014 break;
1015 case DUMP_SERVICE:
1016 handleDumpService((DumpServiceInfo)msg.obj);
1017 break;
1018 case LOW_MEMORY:
1019 handleLowMemory();
1020 break;
1021 case ACTIVITY_CONFIGURATION_CHANGED:
1022 handleActivityConfigurationChanged((IBinder)msg.obj);
1023 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001024 case PROFILER_CONTROL:
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001025 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001026 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001027 case CREATE_BACKUP_AGENT:
1028 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1029 break;
1030 case DESTROY_BACKUP_AGENT:
1031 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1032 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001033 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001034 Process.killProcess(Process.myPid());
1035 break;
1036 case REMOVE_PROVIDER:
1037 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001038 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001039 case ENABLE_JIT:
1040 ensureJitEnabled();
1041 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001042 case DISPATCH_PACKAGE_BROADCAST:
1043 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
1044 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001045 case SCHEDULE_CRASH:
1046 throw new RemoteServiceException((String)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 }
1048 }
Bob Leee5408332009-09-04 18:31:17 -07001049
1050 void maybeSnapshot() {
1051 if (mBoundApplication != null) {
1052 SamplingProfilerIntegration.writeSnapshot(
1053 mBoundApplication.processName);
1054 }
1055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 }
1057
1058 private final class Idler implements MessageQueue.IdleHandler {
1059 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001060 ActivityClientRecord a = mNewActivities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 if (a != null) {
1062 mNewActivities = null;
1063 IActivityManager am = ActivityManagerNative.getDefault();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001064 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001066 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 TAG, "Reporting idle of " + a +
1068 " finished=" +
1069 (a.activity != null ? a.activity.mFinished : false));
1070 if (a.activity != null && !a.activity.mFinished) {
1071 try {
Dianne Hackborne88846e2009-09-30 21:34:25 -07001072 am.activityIdle(a.token, a.createdConfig);
1073 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 } catch (RemoteException ex) {
1075 }
1076 }
1077 prev = a;
1078 a = a.nextIdle;
1079 prev.nextIdle = null;
1080 } while (a != null);
1081 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001082 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 return false;
1084 }
1085 }
1086
1087 final class GcIdler implements MessageQueue.IdleHandler {
1088 public final boolean queueIdle() {
1089 doGcIfNeeded();
1090 return false;
1091 }
1092 }
1093
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001094 private final static class ResourcesKey {
1095 final private String mResDir;
1096 final private float mScale;
1097 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07001098
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001099 ResourcesKey(String resDir, float scale) {
1100 mResDir = resDir;
1101 mScale = scale;
1102 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
1103 }
Bob Leee5408332009-09-04 18:31:17 -07001104
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001105 @Override
1106 public int hashCode() {
1107 return mHash;
1108 }
1109
1110 @Override
1111 public boolean equals(Object obj) {
1112 if (!(obj instanceof ResourcesKey)) {
1113 return false;
1114 }
1115 ResourcesKey peer = (ResourcesKey) obj;
1116 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
1117 }
1118 }
1119
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001120 public static final ActivityThread currentActivityThread() {
1121 return (ActivityThread)sThreadLocal.get();
1122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001124 public static final String currentPackageName() {
1125 ActivityThread am = currentActivityThread();
1126 return (am != null && am.mBoundApplication != null)
1127 ? am.mBoundApplication.processName : null;
1128 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001130 public static final Application currentApplication() {
1131 ActivityThread am = currentActivityThread();
1132 return am != null ? am.mInitialApplication : null;
1133 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001135 public static IPackageManager getPackageManager() {
1136 if (sPackageManager != null) {
1137 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1138 return sPackageManager;
1139 }
1140 IBinder b = ServiceManager.getService("package");
1141 //Slog.v("PackageManager", "default service binder = " + b);
1142 sPackageManager = IPackageManager.Stub.asInterface(b);
1143 //Slog.v("PackageManager", "default service = " + sPackageManager);
1144 return sPackageManager;
1145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001147 DisplayMetrics getDisplayMetricsLocked(boolean forceUpdate) {
1148 if (mDisplayMetrics != null && !forceUpdate) {
1149 return mDisplayMetrics;
1150 }
1151 if (mDisplay == null) {
1152 WindowManager wm = WindowManagerImpl.getDefault();
1153 mDisplay = wm.getDefaultDisplay();
1154 }
1155 DisplayMetrics metrics = mDisplayMetrics = new DisplayMetrics();
1156 mDisplay.getMetrics(metrics);
1157 //Slog.i("foo", "New metrics: w=" + metrics.widthPixels + " h="
1158 // + metrics.heightPixels + " den=" + metrics.density
1159 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi);
1160 return metrics;
1161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001163 /**
1164 * Creates the top level Resources for applications with the given compatibility info.
1165 *
1166 * @param resDir the resource directory.
1167 * @param compInfo the compability info. It will use the default compatibility info when it's
1168 * null.
1169 */
1170 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
1171 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
1172 Resources r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001174 // Resources is app scale dependent.
1175 if (false) {
1176 Slog.w(TAG, "getTopLevelResources: " + resDir + " / "
1177 + compInfo.applicationScale);
1178 }
1179 WeakReference<Resources> wr = mActiveResources.get(key);
1180 r = wr != null ? wr.get() : null;
1181 //if (r != null) Slog.i(TAG, "isUpToDate " + resDir + ": " + r.getAssets().isUpToDate());
1182 if (r != null && r.getAssets().isUpToDate()) {
1183 if (false) {
1184 Slog.w(TAG, "Returning cached resources " + r + " " + resDir
1185 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
1186 }
1187 return r;
1188 }
1189 }
1190
1191 //if (r != null) {
1192 // Slog.w(TAG, "Throwing away out-of-date resources!!!! "
1193 // + r + " " + resDir);
1194 //}
1195
1196 AssetManager assets = new AssetManager();
1197 if (assets.addAssetPath(resDir) == 0) {
1198 return null;
1199 }
1200
1201 //Slog.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
1202 DisplayMetrics metrics = getDisplayMetricsLocked(false);
1203 r = new Resources(assets, metrics, getConfiguration(), compInfo);
1204 if (false) {
1205 Slog.i(TAG, "Created app resources " + resDir + " " + r + ": "
1206 + r.getConfiguration() + " appScale="
1207 + r.getCompatibilityInfo().applicationScale);
1208 }
1209
1210 synchronized (mPackages) {
1211 WeakReference<Resources> wr = mActiveResources.get(key);
1212 Resources existing = wr != null ? wr.get() : null;
1213 if (existing != null && existing.getAssets().isUpToDate()) {
1214 // Someone else already created the resources while we were
1215 // unlocked; go ahead and use theirs.
1216 r.getAssets().close();
1217 return existing;
1218 }
1219
1220 // XXX need to remove entries when weak references go away
1221 mActiveResources.put(key, new WeakReference<Resources>(r));
1222 return r;
1223 }
1224 }
1225
1226 /**
1227 * Creates the top level resources for the given package.
1228 */
1229 Resources getTopLevelResources(String resDir, LoadedApk pkgInfo) {
1230 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo);
1231 }
1232
1233 final Handler getHandler() {
1234 return mH;
1235 }
1236
1237 public final LoadedApk getPackageInfo(String packageName, int flags) {
1238 synchronized (mPackages) {
1239 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
1241 ref = mPackages.get(packageName);
1242 } else {
1243 ref = mResourcePackages.get(packageName);
1244 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001245 LoadedApk packageInfo = ref != null ? ref.get() : null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001246 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001247 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
1248 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 if (packageInfo != null && (packageInfo.mResources == null
1250 || packageInfo.mResources.getAssets().isUpToDate())) {
1251 if (packageInfo.isSecurityViolation()
1252 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
1253 throw new SecurityException(
1254 "Requesting code from " + packageName
1255 + " to be run in process "
1256 + mBoundApplication.processName
1257 + "/" + mBoundApplication.appInfo.uid);
1258 }
1259 return packageInfo;
1260 }
1261 }
1262
1263 ApplicationInfo ai = null;
1264 try {
1265 ai = getPackageManager().getApplicationInfo(packageName,
1266 PackageManager.GET_SHARED_LIBRARY_FILES);
1267 } catch (RemoteException e) {
1268 }
1269
1270 if (ai != null) {
1271 return getPackageInfo(ai, flags);
1272 }
1273
1274 return null;
1275 }
1276
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001277 public final LoadedApk getPackageInfo(ApplicationInfo ai, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
1279 boolean securityViolation = includeCode && ai.uid != 0
1280 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
1281 ? ai.uid != mBoundApplication.appInfo.uid : true);
1282 if ((flags&(Context.CONTEXT_INCLUDE_CODE
1283 |Context.CONTEXT_IGNORE_SECURITY))
1284 == Context.CONTEXT_INCLUDE_CODE) {
1285 if (securityViolation) {
1286 String msg = "Requesting code from " + ai.packageName
1287 + " (with uid " + ai.uid + ")";
1288 if (mBoundApplication != null) {
1289 msg = msg + " to be run in process "
1290 + mBoundApplication.processName + " (with uid "
1291 + mBoundApplication.appInfo.uid + ")";
1292 }
1293 throw new SecurityException(msg);
1294 }
1295 }
1296 return getPackageInfo(ai, null, securityViolation, includeCode);
1297 }
1298
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001299 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 return getPackageInfo(ai, null, false, true);
1301 }
1302
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001303 private final LoadedApk getPackageInfo(ApplicationInfo aInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
1305 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001306 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 if (includeCode) {
1308 ref = mPackages.get(aInfo.packageName);
1309 } else {
1310 ref = mResourcePackages.get(aInfo.packageName);
1311 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001312 LoadedApk packageInfo = ref != null ? ref.get() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 if (packageInfo == null || (packageInfo.mResources != null
1314 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001315 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 : "Loading resource-only package ") + aInfo.packageName
1317 + " (in " + (mBoundApplication != null
1318 ? mBoundApplication.processName : null)
1319 + ")");
1320 packageInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001321 new LoadedApk(this, aInfo, this, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 securityViolation, includeCode &&
1323 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
1324 if (includeCode) {
1325 mPackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001326 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 } else {
1328 mResourcePackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001329 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 }
1331 }
1332 return packageInfo;
1333 }
1334 }
1335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 ActivityThread() {
1337 }
1338
1339 public ApplicationThread getApplicationThread()
1340 {
1341 return mAppThread;
1342 }
1343
1344 public Instrumentation getInstrumentation()
1345 {
1346 return mInstrumentation;
1347 }
1348
1349 public Configuration getConfiguration() {
1350 return mConfiguration;
1351 }
1352
1353 public boolean isProfiling() {
1354 return mBoundApplication != null && mBoundApplication.profileFile != null;
1355 }
1356
1357 public String getProfileFilePath() {
1358 return mBoundApplication.profileFile;
1359 }
1360
1361 public Looper getLooper() {
1362 return mLooper;
1363 }
1364
1365 public Application getApplication() {
1366 return mInitialApplication;
1367 }
Bob Leee5408332009-09-04 18:31:17 -07001368
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07001369 public String getProcessName() {
1370 return mBoundApplication.processName;
1371 }
Bob Leee5408332009-09-04 18:31:17 -07001372
Dianne Hackborn21556372010-02-04 16:34:40 -08001373 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 synchronized (this) {
1375 if (mSystemContext == null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001376 ContextImpl context =
1377 ContextImpl.createSystemContext(this);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001378 LoadedApk info = new LoadedApk(this, "android", context, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 context.init(info, null, this);
1380 context.getResources().updateConfiguration(
1381 getConfiguration(), getDisplayMetricsLocked(false));
1382 mSystemContext = context;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001383 //Slog.i(TAG, "Created system resources " + context.getResources()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 // + ": " + context.getResources().getConfiguration());
1385 }
1386 }
1387 return mSystemContext;
1388 }
1389
Mike Cleron432b7132009-09-24 15:28:29 -07001390 public void installSystemApplicationInfo(ApplicationInfo info) {
1391 synchronized (this) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001392 ContextImpl context = getSystemContext();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001393 context.init(new LoadedApk(this, "android", context, info), null, this);
Mike Cleron432b7132009-09-24 15:28:29 -07001394 }
1395 }
1396
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001397 void ensureJitEnabled() {
1398 if (!mJitEnabled) {
1399 mJitEnabled = true;
1400 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
1401 }
1402 }
1403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 void scheduleGcIdler() {
1405 if (!mGcIdlerScheduled) {
1406 mGcIdlerScheduled = true;
1407 Looper.myQueue().addIdleHandler(mGcIdler);
1408 }
1409 mH.removeMessages(H.GC_WHEN_IDLE);
1410 }
1411
1412 void unscheduleGcIdler() {
1413 if (mGcIdlerScheduled) {
1414 mGcIdlerScheduled = false;
1415 Looper.myQueue().removeIdleHandler(mGcIdler);
1416 }
1417 mH.removeMessages(H.GC_WHEN_IDLE);
1418 }
1419
1420 void doGcIfNeeded() {
1421 mGcIdlerScheduled = false;
1422 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001423 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 // + "m now=" + now);
1425 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001426 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 BinderInternal.forceGc("bg");
1428 }
1429 }
1430
1431 public final ActivityInfo resolveActivityInfo(Intent intent) {
1432 ActivityInfo aInfo = intent.resolveActivityInfo(
1433 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
1434 if (aInfo == null) {
1435 // Throw an exception.
1436 Instrumentation.checkStartActivityResult(
1437 IActivityManager.START_CLASS_NOT_FOUND, intent);
1438 }
1439 return aInfo;
1440 }
Bob Leee5408332009-09-04 18:31:17 -07001441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
1444 Object lastNonConfigurationInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001445 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001447 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 r.intent = intent;
1449 r.state = state;
1450 r.parent = parent;
1451 r.embeddedID = id;
1452 r.activityInfo = activityInfo;
1453 r.lastNonConfigurationInstance = lastNonConfigurationInstance;
1454 if (localLOGV) {
1455 ComponentName compname = intent.getComponent();
1456 String name;
1457 if (compname != null) {
1458 name = compname.toShortString();
1459 } else {
1460 name = "(Intent " + intent + ").getComponent() returned null";
1461 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001462 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 + ", comp=" + name
1464 + ", token=" + token);
1465 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07001466 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 }
1468
1469 public final Activity getActivity(IBinder token) {
1470 return mActivities.get(token).activity;
1471 }
1472
1473 public final void sendActivityResult(
1474 IBinder token, String id, int requestCode,
1475 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001476 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07001477 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
1479 list.add(new ResultInfo(id, requestCode, resultCode, data));
1480 mAppThread.scheduleSendResult(token, list);
1481 }
1482
1483 // if the thread hasn't started yet, we don't have the handler, so just
1484 // save the messages until we're ready.
1485 private final void queueOrSendMessage(int what, Object obj) {
1486 queueOrSendMessage(what, obj, 0, 0);
1487 }
1488
1489 private final void queueOrSendMessage(int what, Object obj, int arg1) {
1490 queueOrSendMessage(what, obj, arg1, 0);
1491 }
1492
1493 private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
1494 synchronized (this) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001495 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
1497 + ": " + arg1 + " / " + obj);
1498 Message msg = Message.obtain();
1499 msg.what = what;
1500 msg.obj = obj;
1501 msg.arg1 = arg1;
1502 msg.arg2 = arg2;
1503 mH.sendMessage(msg);
1504 }
1505 }
1506
Dianne Hackborn21556372010-02-04 16:34:40 -08001507 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 String what) {
1509 ContextCleanupInfo cci = new ContextCleanupInfo();
1510 cci.context = context;
1511 cci.who = who;
1512 cci.what = what;
1513 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
1514 }
1515
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001516 private final Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
1518
1519 ActivityInfo aInfo = r.activityInfo;
1520 if (r.packageInfo == null) {
1521 r.packageInfo = getPackageInfo(aInfo.applicationInfo,
1522 Context.CONTEXT_INCLUDE_CODE);
1523 }
Bob Leee5408332009-09-04 18:31:17 -07001524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 ComponentName component = r.intent.getComponent();
1526 if (component == null) {
1527 component = r.intent.resolveActivity(
1528 mInitialApplication.getPackageManager());
1529 r.intent.setComponent(component);
1530 }
1531
1532 if (r.activityInfo.targetActivity != null) {
1533 component = new ComponentName(r.activityInfo.packageName,
1534 r.activityInfo.targetActivity);
1535 }
1536
1537 Activity activity = null;
1538 try {
1539 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
1540 activity = mInstrumentation.newActivity(
1541 cl, component.getClassName(), r.intent);
1542 r.intent.setExtrasClassLoader(cl);
1543 if (r.state != null) {
1544 r.state.setClassLoader(cl);
1545 }
1546 } catch (Exception e) {
1547 if (!mInstrumentation.onException(activity, e)) {
1548 throw new RuntimeException(
1549 "Unable to instantiate activity " + component
1550 + ": " + e.toString(), e);
1551 }
1552 }
1553
1554 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001555 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001556
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001557 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
1558 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559 TAG, r + ": app=" + app
1560 + ", appName=" + app.getPackageName()
1561 + ", pkg=" + r.packageInfo.getPackageName()
1562 + ", comp=" + r.intent.getComponent().toShortString()
1563 + ", dir=" + r.packageInfo.getAppDir());
1564
1565 if (activity != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001566 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 appContext.init(r.packageInfo, r.token, this);
1568 appContext.setOuterContext(activity);
1569 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
1570 Configuration config = new Configuration(mConfiguration);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001571 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07001572 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001573 activity.attach(appContext, this, getInstrumentation(), r.token,
1574 r.ident, app, r.intent, r.activityInfo, title, r.parent,
1575 r.embeddedID, r.lastNonConfigurationInstance,
1576 r.lastNonConfigurationChildInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07001577
Christopher Tateb70f3df2009-04-07 16:07:59 -07001578 if (customIntent != null) {
1579 activity.mIntent = customIntent;
1580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 r.lastNonConfigurationInstance = null;
1582 r.lastNonConfigurationChildInstances = null;
1583 activity.mStartedActivity = false;
1584 int theme = r.activityInfo.getThemeResource();
1585 if (theme != 0) {
1586 activity.setTheme(theme);
1587 }
1588
1589 activity.mCalled = false;
1590 mInstrumentation.callActivityOnCreate(activity, r.state);
1591 if (!activity.mCalled) {
1592 throw new SuperNotCalledException(
1593 "Activity " + r.intent.getComponent().toShortString() +
1594 " did not call through to super.onCreate()");
1595 }
1596 r.activity = activity;
1597 r.stopped = true;
1598 if (!r.activity.mFinished) {
1599 activity.performStart();
1600 r.stopped = false;
1601 }
1602 if (!r.activity.mFinished) {
1603 if (r.state != null) {
1604 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
1605 }
1606 }
1607 if (!r.activity.mFinished) {
1608 activity.mCalled = false;
1609 mInstrumentation.callActivityOnPostCreate(activity, r.state);
1610 if (!activity.mCalled) {
1611 throw new SuperNotCalledException(
1612 "Activity " + r.intent.getComponent().toShortString() +
1613 " did not call through to super.onPostCreate()");
1614 }
1615 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616 }
1617 r.paused = true;
1618
1619 mActivities.put(r.token, r);
1620
1621 } catch (SuperNotCalledException e) {
1622 throw e;
1623
1624 } catch (Exception e) {
1625 if (!mInstrumentation.onException(activity, e)) {
1626 throw new RuntimeException(
1627 "Unable to start activity " + component
1628 + ": " + e.toString(), e);
1629 }
1630 }
1631
1632 return activity;
1633 }
1634
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001635 private final void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 // If we are getting ready to gc after going to the background, well
1637 // we are back active so skip it.
1638 unscheduleGcIdler();
1639
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001640 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001642 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643
1644 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08001645 r.createdConfig = new Configuration(mConfiguration);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001646 Bundle oldState = r.state;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 handleResumeActivity(r.token, false, r.isForward);
1648
1649 if (!r.activity.mFinished && r.startsNotResumed) {
1650 // The activity manager actually wants this one to start out
1651 // paused, because it needs to be visible but isn't in the
1652 // foreground. We accomplish this by going through the
1653 // normal startup (because activities expect to go through
1654 // onResume() the first time they run, before their window
1655 // is displayed), and then pausing it. However, in this case
1656 // we do -not- need to do the full pause cycle (of freezing
1657 // and such) because the activity manager assumes it can just
1658 // retain the current state it has.
1659 try {
1660 r.activity.mCalled = false;
1661 mInstrumentation.callActivityOnPause(r.activity);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001662 // We need to keep around the original state, in case
1663 // we need to be created again.
1664 r.state = oldState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 if (!r.activity.mCalled) {
1666 throw new SuperNotCalledException(
1667 "Activity " + r.intent.getComponent().toShortString() +
1668 " did not call through to super.onPause()");
1669 }
1670
1671 } catch (SuperNotCalledException e) {
1672 throw e;
1673
1674 } catch (Exception e) {
1675 if (!mInstrumentation.onException(r.activity, e)) {
1676 throw new RuntimeException(
1677 "Unable to pause activity "
1678 + r.intent.getComponent().toShortString()
1679 + ": " + e.toString(), e);
1680 }
1681 }
1682 r.paused = true;
1683 }
1684 } else {
1685 // If there was an error, for any reason, tell the activity
1686 // manager to stop us.
1687 try {
1688 ActivityManagerNative.getDefault()
1689 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
1690 } catch (RemoteException ex) {
1691 }
1692 }
1693 }
1694
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001695 private final void deliverNewIntents(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 List<Intent> intents) {
1697 final int N = intents.size();
1698 for (int i=0; i<N; i++) {
1699 Intent intent = intents.get(i);
1700 intent.setExtrasClassLoader(r.activity.getClassLoader());
1701 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
1702 }
1703 }
1704
1705 public final void performNewIntents(IBinder token,
1706 List<Intent> intents) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001707 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 if (r != null) {
1709 final boolean resumed = !r.paused;
1710 if (resumed) {
1711 mInstrumentation.callActivityOnPause(r.activity);
1712 }
1713 deliverNewIntents(r, intents);
1714 if (resumed) {
1715 mInstrumentation.callActivityOnResume(r.activity);
1716 }
1717 }
1718 }
Bob Leee5408332009-09-04 18:31:17 -07001719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 private final void handleNewIntent(NewIntentData data) {
1721 performNewIntents(data.token, data.intents);
1722 }
1723
1724 private final void handleReceiver(ReceiverData data) {
1725 // If we are getting ready to gc after going to the background, well
1726 // we are back active so skip it.
1727 unscheduleGcIdler();
1728
1729 String component = data.intent.getComponent().getClassName();
1730
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001731 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 data.info.applicationInfo);
1733
1734 IActivityManager mgr = ActivityManagerNative.getDefault();
1735
1736 BroadcastReceiver receiver = null;
1737 try {
1738 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1739 data.intent.setExtrasClassLoader(cl);
1740 if (data.resultExtras != null) {
1741 data.resultExtras.setClassLoader(cl);
1742 }
1743 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
1744 } catch (Exception e) {
1745 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001746 if (DEBUG_BROADCAST) Slog.i(TAG,
1747 "Finishing failed broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
1749 data.resultData, data.resultExtras, data.resultAbort);
1750 } catch (RemoteException ex) {
1751 }
1752 throw new RuntimeException(
1753 "Unable to instantiate receiver " + component
1754 + ": " + e.toString(), e);
1755 }
1756
1757 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001758 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001759
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001760 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 TAG, "Performing receive of " + data.intent
1762 + ": app=" + app
1763 + ", appName=" + app.getPackageName()
1764 + ", pkg=" + packageInfo.getPackageName()
1765 + ", comp=" + data.intent.getComponent().toShortString()
1766 + ", dir=" + packageInfo.getAppDir());
1767
Dianne Hackborn21556372010-02-04 16:34:40 -08001768 ContextImpl context = (ContextImpl)app.getBaseContext();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 receiver.setOrderedHint(true);
1770 receiver.setResult(data.resultCode, data.resultData,
1771 data.resultExtras);
1772 receiver.setOrderedHint(data.sync);
1773 receiver.onReceive(context.getReceiverRestrictedContext(),
1774 data.intent);
1775 } catch (Exception e) {
1776 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001777 if (DEBUG_BROADCAST) Slog.i(TAG,
1778 "Finishing failed broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
1780 data.resultData, data.resultExtras, data.resultAbort);
1781 } catch (RemoteException ex) {
1782 }
1783 if (!mInstrumentation.onException(receiver, e)) {
1784 throw new RuntimeException(
1785 "Unable to start receiver " + component
1786 + ": " + e.toString(), e);
1787 }
1788 }
1789
1790 try {
1791 if (data.sync) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001792 if (DEBUG_BROADCAST) Slog.i(TAG,
1793 "Finishing ordered broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 mgr.finishReceiver(
1795 mAppThread.asBinder(), receiver.getResultCode(),
1796 receiver.getResultData(), receiver.getResultExtras(false),
1797 receiver.getAbortBroadcast());
1798 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001799 if (DEBUG_BROADCAST) Slog.i(TAG,
1800 "Finishing broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 mgr.finishReceiver(mAppThread.asBinder(), 0, null, null, false);
1802 }
1803 } catch (RemoteException ex) {
1804 }
1805 }
1806
Christopher Tate181fafa2009-05-14 11:12:14 -07001807 // Instantiate a BackupAgent and tell it that it's alive
1808 private final void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001809 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001810
1811 // no longer idle; we have backup work to do
1812 unscheduleGcIdler();
1813
1814 // instantiate the BackupAgent class named in the manifest
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001815 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001816 String packageName = packageInfo.mPackageName;
1817 if (mBackupAgents.get(packageName) != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001818 Slog.d(TAG, "BackupAgent " + " for " + packageName
Christopher Tate181fafa2009-05-14 11:12:14 -07001819 + " already exists");
1820 return;
1821 }
Bob Leee5408332009-09-04 18:31:17 -07001822
Christopher Tate181fafa2009-05-14 11:12:14 -07001823 BackupAgent agent = null;
1824 String classname = data.appInfo.backupAgentName;
1825 if (classname == null) {
1826 if (data.backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001827 Slog.e(TAG, "Attempted incremental backup but no defined agent for "
Christopher Tate181fafa2009-05-14 11:12:14 -07001828 + packageName);
1829 return;
1830 }
1831 classname = "android.app.FullBackupAgent";
1832 }
1833 try {
Christopher Tated1475e02009-07-09 15:36:17 -07001834 IBinder binder = null;
1835 try {
1836 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1837 agent = (BackupAgent) cl.loadClass(data.appInfo.backupAgentName).newInstance();
1838
1839 // set up the agent's context
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001840 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing BackupAgent "
Christopher Tated1475e02009-07-09 15:36:17 -07001841 + data.appInfo.backupAgentName);
1842
Dianne Hackborn21556372010-02-04 16:34:40 -08001843 ContextImpl context = new ContextImpl();
Christopher Tated1475e02009-07-09 15:36:17 -07001844 context.init(packageInfo, null, this);
1845 context.setOuterContext(agent);
1846 agent.attach(context);
1847
1848 agent.onCreate();
1849 binder = agent.onBind();
1850 mBackupAgents.put(packageName, agent);
1851 } catch (Exception e) {
1852 // If this is during restore, fail silently; otherwise go
1853 // ahead and let the user see the crash.
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001854 Slog.e(TAG, "Agent threw during creation: " + e);
Christopher Tated1475e02009-07-09 15:36:17 -07001855 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE) {
1856 throw e;
1857 }
1858 // falling through with 'binder' still null
1859 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001860
1861 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07001862 try {
1863 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
1864 } catch (RemoteException e) {
1865 // nothing to do.
1866 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001867 } catch (Exception e) {
1868 throw new RuntimeException("Unable to create BackupAgent "
1869 + data.appInfo.backupAgentName + ": " + e.toString(), e);
1870 }
1871 }
1872
1873 // Tear down a BackupAgent
1874 private final void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001875 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07001876
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001877 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001878 String packageName = packageInfo.mPackageName;
1879 BackupAgent agent = mBackupAgents.get(packageName);
1880 if (agent != null) {
1881 try {
1882 agent.onDestroy();
1883 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001884 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001885 e.printStackTrace();
1886 }
1887 mBackupAgents.remove(packageName);
1888 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001889 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001890 }
1891 }
1892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 private final void handleCreateService(CreateServiceData data) {
1894 // If we are getting ready to gc after going to the background, well
1895 // we are back active so skip it.
1896 unscheduleGcIdler();
1897
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001898 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 data.info.applicationInfo);
1900 Service service = null;
1901 try {
1902 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1903 service = (Service) cl.loadClass(data.info.name).newInstance();
1904 } catch (Exception e) {
1905 if (!mInstrumentation.onException(service, e)) {
1906 throw new RuntimeException(
1907 "Unable to instantiate service " + data.info.name
1908 + ": " + e.toString(), e);
1909 }
1910 }
1911
1912 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001913 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001914
Dianne Hackborn21556372010-02-04 16:34:40 -08001915 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916 context.init(packageInfo, null, this);
1917
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001918 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 context.setOuterContext(service);
1920 service.attach(context, this, data.info.name, data.token, app,
1921 ActivityManagerNative.getDefault());
1922 service.onCreate();
1923 mServices.put(data.token, service);
1924 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001925 ActivityManagerNative.getDefault().serviceDoneExecuting(
1926 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 } catch (RemoteException e) {
1928 // nothing to do.
1929 }
1930 } catch (Exception e) {
1931 if (!mInstrumentation.onException(service, e)) {
1932 throw new RuntimeException(
1933 "Unable to create service " + data.info.name
1934 + ": " + e.toString(), e);
1935 }
1936 }
1937 }
1938
1939 private final void handleBindService(BindServiceData data) {
1940 Service s = mServices.get(data.token);
1941 if (s != null) {
1942 try {
1943 data.intent.setExtrasClassLoader(s.getClassLoader());
1944 try {
1945 if (!data.rebind) {
1946 IBinder binder = s.onBind(data.intent);
1947 ActivityManagerNative.getDefault().publishService(
1948 data.token, data.intent, binder);
1949 } else {
1950 s.onRebind(data.intent);
1951 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001952 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001954 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 } catch (RemoteException ex) {
1956 }
1957 } catch (Exception e) {
1958 if (!mInstrumentation.onException(s, e)) {
1959 throw new RuntimeException(
1960 "Unable to bind to service " + s
1961 + " with " + data.intent + ": " + e.toString(), e);
1962 }
1963 }
1964 }
1965 }
1966
1967 private final void handleUnbindService(BindServiceData data) {
1968 Service s = mServices.get(data.token);
1969 if (s != null) {
1970 try {
1971 data.intent.setExtrasClassLoader(s.getClassLoader());
1972 boolean doRebind = s.onUnbind(data.intent);
1973 try {
1974 if (doRebind) {
1975 ActivityManagerNative.getDefault().unbindFinished(
1976 data.token, data.intent, doRebind);
1977 } else {
1978 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001979 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 }
1981 } catch (RemoteException ex) {
1982 }
1983 } catch (Exception e) {
1984 if (!mInstrumentation.onException(s, e)) {
1985 throw new RuntimeException(
1986 "Unable to unbind to service " + s
1987 + " with " + data.intent + ": " + e.toString(), e);
1988 }
1989 }
1990 }
1991 }
1992
1993 private void handleDumpService(DumpServiceInfo info) {
1994 try {
1995 Service s = mServices.get(info.service);
1996 if (s != null) {
1997 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
1998 s.dump(info.fd, pw, info.args);
1999 pw.close();
2000 }
2001 } finally {
2002 synchronized (info) {
2003 info.dumped = true;
2004 info.notifyAll();
2005 }
2006 }
2007 }
2008
2009 private final void handleServiceArgs(ServiceArgsData data) {
2010 Service s = mServices.get(data.token);
2011 if (s != null) {
2012 try {
2013 if (data.args != null) {
2014 data.args.setExtrasClassLoader(s.getClassLoader());
2015 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002016 int res = s.onStartCommand(data.args, data.flags, data.startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002018 ActivityManagerNative.getDefault().serviceDoneExecuting(
2019 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 } catch (RemoteException e) {
2021 // nothing to do.
2022 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002023 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 } catch (Exception e) {
2025 if (!mInstrumentation.onException(s, e)) {
2026 throw new RuntimeException(
2027 "Unable to start service " + s
2028 + " with " + data.args + ": " + e.toString(), e);
2029 }
2030 }
2031 }
2032 }
2033
2034 private final void handleStopService(IBinder token) {
2035 Service s = mServices.remove(token);
2036 if (s != null) {
2037 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002038 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 s.onDestroy();
2040 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002041 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08002043 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 }
2045 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002046 ActivityManagerNative.getDefault().serviceDoneExecuting(
2047 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 } catch (RemoteException e) {
2049 // nothing to do.
2050 }
2051 } catch (Exception e) {
2052 if (!mInstrumentation.onException(s, e)) {
2053 throw new RuntimeException(
2054 "Unable to stop service " + s
2055 + ": " + e.toString(), e);
2056 }
2057 }
2058 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002059 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 }
2061
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002062 public final ActivityClientRecord performResumeActivity(IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 boolean clearHide) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002064 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002065 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 + " finished=" + r.activity.mFinished);
2067 if (r != null && !r.activity.mFinished) {
2068 if (clearHide) {
2069 r.hideForNow = false;
2070 r.activity.mStartedActivity = false;
2071 }
2072 try {
2073 if (r.pendingIntents != null) {
2074 deliverNewIntents(r, r.pendingIntents);
2075 r.pendingIntents = null;
2076 }
2077 if (r.pendingResults != null) {
2078 deliverResults(r, r.pendingResults);
2079 r.pendingResults = null;
2080 }
2081 r.activity.performResume();
2082
Bob Leee5408332009-09-04 18:31:17 -07002083 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086 r.paused = false;
2087 r.stopped = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 r.state = null;
2089 } catch (Exception e) {
2090 if (!mInstrumentation.onException(r.activity, e)) {
2091 throw new RuntimeException(
2092 "Unable to resume activity "
2093 + r.intent.getComponent().toShortString()
2094 + ": " + e.toString(), e);
2095 }
2096 }
2097 }
2098 return r;
2099 }
2100
2101 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2102 // If we are getting ready to gc after going to the background, well
2103 // we are back active so skip it.
2104 unscheduleGcIdler();
2105
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002106 ActivityClientRecord r = performResumeActivity(token, clearHide);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107
2108 if (r != null) {
2109 final Activity a = r.activity;
2110
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002111 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002112 TAG, "Resume " + r + " started activity: " +
2113 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2114 + ", finished: " + a.mFinished);
2115
2116 final int forwardBit = isForward ?
2117 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002119 // If the window hasn't yet been added to the window manager,
2120 // and this guy didn't finish itself or start another activity,
2121 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002122 boolean willBeVisible = !a.mStartedActivity;
2123 if (!willBeVisible) {
2124 try {
2125 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
2126 a.getActivityToken());
2127 } catch (RemoteException e) {
2128 }
2129 }
2130 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002131 r.window = r.activity.getWindow();
2132 View decor = r.window.getDecorView();
2133 decor.setVisibility(View.INVISIBLE);
2134 ViewManager wm = a.getWindowManager();
2135 WindowManager.LayoutParams l = r.window.getAttributes();
2136 a.mDecor = decor;
2137 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2138 l.softInputMode |= forwardBit;
2139 if (a.mVisibleFromClient) {
2140 a.mWindowAdded = true;
2141 wm.addView(decor, l);
2142 }
2143
2144 // If the window has already been added, but during resume
2145 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002146 // window visible.
2147 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002148 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149 TAG, "Launch " + r + " mStartedActivity set");
2150 r.hideForNow = true;
2151 }
2152
2153 // The window is now visible if it has been added, we are not
2154 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002155 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002156 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002158 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002159 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002160 performConfigurationChanged(r.activity, r.newConfig);
2161 r.newConfig = null;
2162 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002163 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164 + isForward);
2165 WindowManager.LayoutParams l = r.window.getAttributes();
2166 if ((l.softInputMode
2167 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2168 != forwardBit) {
2169 l.softInputMode = (l.softInputMode
2170 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2171 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002172 if (r.activity.mVisibleFromClient) {
2173 ViewManager wm = a.getWindowManager();
2174 View decor = r.window.getDecorView();
2175 wm.updateViewLayout(decor, l);
2176 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002177 }
2178 r.activity.mVisibleFromServer = true;
2179 mNumVisibleActivities++;
2180 if (r.activity.mVisibleFromClient) {
2181 r.activity.makeVisible();
2182 }
2183 }
2184
2185 r.nextIdle = mNewActivities;
2186 mNewActivities = r;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002187 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002188 TAG, "Scheduling idle handler for " + r);
2189 Looper.myQueue().addIdleHandler(new Idler());
2190
2191 } else {
2192 // If an exception was thrown when trying to resume, then
2193 // just end this activity.
2194 try {
2195 ActivityManagerNative.getDefault()
2196 .finishActivity(token, Activity.RESULT_CANCELED, null);
2197 } catch (RemoteException ex) {
2198 }
2199 }
2200 }
2201
2202 private int mThumbnailWidth = -1;
2203 private int mThumbnailHeight = -1;
2204
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002205 private final Bitmap createThumbnailBitmap(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002206 Bitmap thumbnail = null;
2207 try {
2208 int w = mThumbnailWidth;
2209 int h;
2210 if (w < 0) {
2211 Resources res = r.activity.getResources();
2212 mThumbnailHeight = h =
2213 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
2214
2215 mThumbnailWidth = w =
2216 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
2217 } else {
2218 h = mThumbnailHeight;
2219 }
2220
2221 // XXX Only set hasAlpha if needed?
2222 thumbnail = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
2223 thumbnail.eraseColor(0);
2224 Canvas cv = new Canvas(thumbnail);
2225 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
2226 thumbnail = null;
2227 }
2228 } catch (Exception e) {
2229 if (!mInstrumentation.onException(r.activity, e)) {
2230 throw new RuntimeException(
2231 "Unable to create thumbnail of "
2232 + r.intent.getComponent().toShortString()
2233 + ": " + e.toString(), e);
2234 }
2235 thumbnail = null;
2236 }
2237
2238 return thumbnail;
2239 }
2240
2241 private final void handlePauseActivity(IBinder token, boolean finished,
2242 boolean userLeaving, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002243 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002245 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002246 if (userLeaving) {
2247 performUserLeavingActivity(r);
2248 }
Bob Leee5408332009-09-04 18:31:17 -07002249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 r.activity.mConfigChangeFlags |= configChanges;
2251 Bundle state = performPauseActivity(token, finished, true);
2252
2253 // Tell the activity manager we have paused.
2254 try {
2255 ActivityManagerNative.getDefault().activityPaused(token, state);
2256 } catch (RemoteException ex) {
2257 }
2258 }
2259 }
2260
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002261 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002262 mInstrumentation.callActivityOnUserLeaving(r.activity);
2263 }
2264
2265 final Bundle performPauseActivity(IBinder token, boolean finished,
2266 boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002267 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002268 return r != null ? performPauseActivity(r, finished, saveState) : null;
2269 }
2270
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002271 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002272 boolean saveState) {
2273 if (r.paused) {
2274 if (r.activity.mFinished) {
2275 // If we are finishing, we won't call onResume() in certain cases.
2276 // So here we likewise don't want to call onPause() if the activity
2277 // isn't resumed.
2278 return null;
2279 }
2280 RuntimeException e = new RuntimeException(
2281 "Performing pause of activity that is not resumed: "
2282 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002283 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002284 }
2285 Bundle state = null;
2286 if (finished) {
2287 r.activity.mFinished = true;
2288 }
2289 try {
2290 // Next have the activity save its current state and managed dialogs...
2291 if (!r.activity.mFinished && saveState) {
2292 state = new Bundle();
2293 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2294 r.state = state;
2295 }
2296 // Now we are idle.
2297 r.activity.mCalled = false;
2298 mInstrumentation.callActivityOnPause(r.activity);
2299 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
2300 if (!r.activity.mCalled) {
2301 throw new SuperNotCalledException(
2302 "Activity " + r.intent.getComponent().toShortString() +
2303 " did not call through to super.onPause()");
2304 }
2305
2306 } catch (SuperNotCalledException e) {
2307 throw e;
2308
2309 } catch (Exception e) {
2310 if (!mInstrumentation.onException(r.activity, e)) {
2311 throw new RuntimeException(
2312 "Unable to pause activity "
2313 + r.intent.getComponent().toShortString()
2314 + ": " + e.toString(), e);
2315 }
2316 }
2317 r.paused = true;
2318 return state;
2319 }
2320
2321 final void performStopActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002322 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002323 performStopActivityInner(r, null, false);
2324 }
2325
2326 private static class StopInfo {
2327 Bitmap thumbnail;
2328 CharSequence description;
2329 }
2330
2331 private final class ProviderRefCount {
2332 public int count;
2333 ProviderRefCount(int pCount) {
2334 count = pCount;
2335 }
2336 }
2337
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002338 private final void performStopActivityInner(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002339 StopInfo info, boolean keepShown) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002340 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002341 if (r != null) {
2342 if (!keepShown && r.stopped) {
2343 if (r.activity.mFinished) {
2344 // If we are finishing, we won't call onResume() in certain
2345 // cases. So here we likewise don't want to call onStop()
2346 // if the activity isn't resumed.
2347 return;
2348 }
2349 RuntimeException e = new RuntimeException(
2350 "Performing stop of activity that is not resumed: "
2351 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002352 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 }
2354
2355 if (info != null) {
2356 try {
2357 // First create a thumbnail for the activity...
2358 //info.thumbnail = createThumbnailBitmap(r);
2359 info.description = r.activity.onCreateDescription();
2360 } catch (Exception e) {
2361 if (!mInstrumentation.onException(r.activity, e)) {
2362 throw new RuntimeException(
2363 "Unable to save state of activity "
2364 + r.intent.getComponent().toShortString()
2365 + ": " + e.toString(), e);
2366 }
2367 }
2368 }
2369
2370 if (!keepShown) {
2371 try {
2372 // Now we are idle.
2373 r.activity.performStop();
2374 } catch (Exception e) {
2375 if (!mInstrumentation.onException(r.activity, e)) {
2376 throw new RuntimeException(
2377 "Unable to stop activity "
2378 + r.intent.getComponent().toShortString()
2379 + ": " + e.toString(), e);
2380 }
2381 }
2382 r.stopped = true;
2383 }
2384
2385 r.paused = true;
2386 }
2387 }
2388
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002389 private final void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 View v = r.activity.mDecor;
2391 if (v != null) {
2392 if (show) {
2393 if (!r.activity.mVisibleFromServer) {
2394 r.activity.mVisibleFromServer = true;
2395 mNumVisibleActivities++;
2396 if (r.activity.mVisibleFromClient) {
2397 r.activity.makeVisible();
2398 }
2399 }
2400 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002401 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002402 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002403 performConfigurationChanged(r.activity, r.newConfig);
2404 r.newConfig = null;
2405 }
2406 } else {
2407 if (r.activity.mVisibleFromServer) {
2408 r.activity.mVisibleFromServer = false;
2409 mNumVisibleActivities--;
2410 v.setVisibility(View.INVISIBLE);
2411 }
2412 }
2413 }
2414 }
2415
2416 private final void handleStopActivity(IBinder token, boolean show, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002417 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 r.activity.mConfigChangeFlags |= configChanges;
2419
2420 StopInfo info = new StopInfo();
2421 performStopActivityInner(r, info, show);
2422
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002423 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002424 TAG, "Finishing stop of " + r + ": show=" + show
2425 + " win=" + r.window);
2426
2427 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07002428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002429 // Tell activity manager we have been stopped.
2430 try {
2431 ActivityManagerNative.getDefault().activityStopped(
2432 r.token, info.thumbnail, info.description);
2433 } catch (RemoteException ex) {
2434 }
2435 }
2436
2437 final void performRestartActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002438 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 if (r.stopped) {
2440 r.activity.performRestart();
2441 r.stopped = false;
2442 }
2443 }
2444
2445 private final void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002446 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002447 if (!show && !r.stopped) {
2448 performStopActivityInner(r, null, show);
2449 } else if (show && r.stopped) {
2450 // If we are getting ready to gc after going to the background, well
2451 // we are back active so skip it.
2452 unscheduleGcIdler();
2453
2454 r.activity.performRestart();
2455 r.stopped = false;
2456 }
2457 if (r.activity.mDecor != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002458 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002459 TAG, "Handle window " + r + " visibility: " + show);
2460 updateVisibility(r, show);
2461 }
2462 }
2463
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002464 private final void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002465 final int N = results.size();
2466 for (int i=0; i<N; i++) {
2467 ResultInfo ri = results.get(i);
2468 try {
2469 if (ri.mData != null) {
2470 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
2471 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002472 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07002473 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002474 r.activity.dispatchActivityResult(ri.mResultWho,
2475 ri.mRequestCode, ri.mResultCode, ri.mData);
2476 } catch (Exception e) {
2477 if (!mInstrumentation.onException(r.activity, e)) {
2478 throw new RuntimeException(
2479 "Failure delivering result " + ri + " to activity "
2480 + r.intent.getComponent().toShortString()
2481 + ": " + e.toString(), e);
2482 }
2483 }
2484 }
2485 }
2486
2487 private final void handleSendResult(ResultData res) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002488 ActivityClientRecord r = mActivities.get(res.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002489 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490 if (r != null) {
2491 final boolean resumed = !r.paused;
2492 if (!r.activity.mFinished && r.activity.mDecor != null
2493 && r.hideForNow && resumed) {
2494 // We had hidden the activity because it started another
2495 // one... we have gotten a result back and we are not
2496 // paused, so make sure our window is visible.
2497 updateVisibility(r, true);
2498 }
2499 if (resumed) {
2500 try {
2501 // Now we are idle.
2502 r.activity.mCalled = false;
2503 mInstrumentation.callActivityOnPause(r.activity);
2504 if (!r.activity.mCalled) {
2505 throw new SuperNotCalledException(
2506 "Activity " + r.intent.getComponent().toShortString()
2507 + " did not call through to super.onPause()");
2508 }
2509 } catch (SuperNotCalledException e) {
2510 throw e;
2511 } catch (Exception e) {
2512 if (!mInstrumentation.onException(r.activity, e)) {
2513 throw new RuntimeException(
2514 "Unable to pause activity "
2515 + r.intent.getComponent().toShortString()
2516 + ": " + e.toString(), e);
2517 }
2518 }
2519 }
2520 deliverResults(r, res.results);
2521 if (resumed) {
2522 mInstrumentation.callActivityOnResume(r.activity);
2523 }
2524 }
2525 }
2526
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002527 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002528 return performDestroyActivity(token, finishing, 0, false);
2529 }
2530
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002531 private final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002533 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002534 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535 if (r != null) {
2536 r.activity.mConfigChangeFlags |= configChanges;
2537 if (finishing) {
2538 r.activity.mFinished = true;
2539 }
2540 if (!r.paused) {
2541 try {
2542 r.activity.mCalled = false;
2543 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07002544 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 r.activity.getComponentName().getClassName());
2546 if (!r.activity.mCalled) {
2547 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002548 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 + " did not call through to super.onPause()");
2550 }
2551 } catch (SuperNotCalledException e) {
2552 throw e;
2553 } catch (Exception e) {
2554 if (!mInstrumentation.onException(r.activity, e)) {
2555 throw new RuntimeException(
2556 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002557 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 + ": " + e.toString(), e);
2559 }
2560 }
2561 r.paused = true;
2562 }
2563 if (!r.stopped) {
2564 try {
2565 r.activity.performStop();
2566 } catch (SuperNotCalledException e) {
2567 throw e;
2568 } catch (Exception e) {
2569 if (!mInstrumentation.onException(r.activity, e)) {
2570 throw new RuntimeException(
2571 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002572 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 + ": " + e.toString(), e);
2574 }
2575 }
2576 r.stopped = true;
2577 }
2578 if (getNonConfigInstance) {
2579 try {
2580 r.lastNonConfigurationInstance
2581 = r.activity.onRetainNonConfigurationInstance();
2582 } catch (Exception e) {
2583 if (!mInstrumentation.onException(r.activity, e)) {
2584 throw new RuntimeException(
2585 "Unable to retain activity "
2586 + r.intent.getComponent().toShortString()
2587 + ": " + e.toString(), e);
2588 }
2589 }
2590 try {
2591 r.lastNonConfigurationChildInstances
2592 = r.activity.onRetainNonConfigurationChildInstances();
2593 } catch (Exception e) {
2594 if (!mInstrumentation.onException(r.activity, e)) {
2595 throw new RuntimeException(
2596 "Unable to retain child activities "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002597 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002598 + ": " + e.toString(), e);
2599 }
2600 }
Bob Leee5408332009-09-04 18:31:17 -07002601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 }
2603 try {
2604 r.activity.mCalled = false;
2605 r.activity.onDestroy();
2606 if (!r.activity.mCalled) {
2607 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002608 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609 " did not call through to super.onDestroy()");
2610 }
2611 if (r.window != null) {
2612 r.window.closeAllPanels();
2613 }
2614 } catch (SuperNotCalledException e) {
2615 throw e;
2616 } catch (Exception e) {
2617 if (!mInstrumentation.onException(r.activity, e)) {
2618 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002619 "Unable to destroy activity " + safeToComponentShortString(r.intent)
2620 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 }
2622 }
2623 }
2624 mActivities.remove(token);
2625
2626 return r;
2627 }
2628
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002629 private static String safeToComponentShortString(Intent intent) {
2630 ComponentName component = intent.getComponent();
2631 return component == null ? "[Unknown]" : component.toShortString();
2632 }
2633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002634 private final void handleDestroyActivity(IBinder token, boolean finishing,
2635 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002636 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 configChanges, getNonConfigInstance);
2638 if (r != null) {
2639 WindowManager wm = r.activity.getWindowManager();
2640 View v = r.activity.mDecor;
2641 if (v != null) {
2642 if (r.activity.mVisibleFromServer) {
2643 mNumVisibleActivities--;
2644 }
2645 IBinder wtoken = v.getWindowToken();
2646 if (r.activity.mWindowAdded) {
2647 wm.removeViewImmediate(v);
2648 }
2649 if (wtoken != null) {
2650 WindowManagerImpl.getDefault().closeAll(wtoken,
2651 r.activity.getClass().getName(), "Activity");
2652 }
2653 r.activity.mDecor = null;
2654 }
2655 WindowManagerImpl.getDefault().closeAll(token,
2656 r.activity.getClass().getName(), "Activity");
2657
2658 // Mocked out contexts won't be participating in the normal
2659 // process lifecycle, but if we're running with a proper
2660 // ApplicationContext we need to have it tear down things
2661 // cleanly.
2662 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002663 if (c instanceof ContextImpl) {
2664 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002665 r.activity.getClass().getName(), "Activity");
2666 }
2667 }
2668 if (finishing) {
2669 try {
2670 ActivityManagerNative.getDefault().activityDestroyed(token);
2671 } catch (RemoteException ex) {
2672 // If the system process has died, it's game over for everyone.
2673 }
2674 }
2675 }
2676
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002677 private final void handleRelaunchActivity(ActivityClientRecord tmp, int configChanges) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678 // If we are getting ready to gc after going to the background, well
2679 // we are back active so skip it.
2680 unscheduleGcIdler();
2681
2682 Configuration changedConfig = null;
Bob Leee5408332009-09-04 18:31:17 -07002683
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002684 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002685 + tmp.token + " with configChanges=0x"
2686 + Integer.toHexString(configChanges));
2687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 // First: make sure we have the most recent configuration and most
2689 // recent version of the activity, or skip it if some previous call
2690 // had taken a more recent version.
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002691 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 int N = mRelaunchingActivities.size();
2693 IBinder token = tmp.token;
2694 tmp = null;
2695 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002696 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002697 if (r.token == token) {
2698 tmp = r;
2699 mRelaunchingActivities.remove(i);
2700 i--;
2701 N--;
2702 }
2703 }
Bob Leee5408332009-09-04 18:31:17 -07002704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002705 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002706 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002707 return;
2708 }
Bob Leee5408332009-09-04 18:31:17 -07002709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002710 if (mPendingConfiguration != null) {
2711 changedConfig = mPendingConfiguration;
2712 mPendingConfiguration = null;
2713 }
2714 }
Bob Leee5408332009-09-04 18:31:17 -07002715
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002716 if (tmp.createdConfig != null) {
2717 // If the activity manager is passing us its current config,
2718 // assume that is really what we want regardless of what we
2719 // may have pending.
2720 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002721 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
2722 && mConfiguration.diff(tmp.createdConfig) != 0)) {
2723 if (changedConfig == null
2724 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
2725 changedConfig = tmp.createdConfig;
2726 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002727 }
2728 }
2729
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002730 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002731 + tmp.token + ": changedConfig=" + changedConfig);
2732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002733 // If there was a pending configuration change, execute it first.
2734 if (changedConfig != null) {
2735 handleConfigurationChanged(changedConfig);
2736 }
Bob Leee5408332009-09-04 18:31:17 -07002737
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002738 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002739 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002740 if (r == null) {
2741 return;
2742 }
Bob Leee5408332009-09-04 18:31:17 -07002743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744 r.activity.mConfigChangeFlags |= configChanges;
Christopher Tateb70f3df2009-04-07 16:07:59 -07002745 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07002746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002747 Bundle savedState = null;
2748 if (!r.paused) {
2749 savedState = performPauseActivity(r.token, false, true);
2750 }
Bob Leee5408332009-09-04 18:31:17 -07002751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07002753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002754 r.activity = null;
2755 r.window = null;
2756 r.hideForNow = false;
2757 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07002758 // Merge any pending results and pending intents; don't just replace them
2759 if (tmp.pendingResults != null) {
2760 if (r.pendingResults == null) {
2761 r.pendingResults = tmp.pendingResults;
2762 } else {
2763 r.pendingResults.addAll(tmp.pendingResults);
2764 }
2765 }
2766 if (tmp.pendingIntents != null) {
2767 if (r.pendingIntents == null) {
2768 r.pendingIntents = tmp.pendingIntents;
2769 } else {
2770 r.pendingIntents.addAll(tmp.pendingIntents);
2771 }
2772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002773 r.startsNotResumed = tmp.startsNotResumed;
2774 if (savedState != null) {
2775 r.state = savedState;
2776 }
Bob Leee5408332009-09-04 18:31:17 -07002777
Christopher Tateb70f3df2009-04-07 16:07:59 -07002778 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002779 }
2780
2781 private final void handleRequestThumbnail(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002782 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002783 Bitmap thumbnail = createThumbnailBitmap(r);
2784 CharSequence description = null;
2785 try {
2786 description = r.activity.onCreateDescription();
2787 } catch (Exception e) {
2788 if (!mInstrumentation.onException(r.activity, e)) {
2789 throw new RuntimeException(
2790 "Unable to create description of activity "
2791 + r.intent.getComponent().toShortString()
2792 + ": " + e.toString(), e);
2793 }
2794 }
2795 //System.out.println("Reporting top thumbnail " + thumbnail);
2796 try {
2797 ActivityManagerNative.getDefault().reportThumbnail(
2798 token, thumbnail, description);
2799 } catch (RemoteException ex) {
2800 }
2801 }
2802
2803 ArrayList<ComponentCallbacks> collectComponentCallbacksLocked(
2804 boolean allActivities, Configuration newConfig) {
2805 ArrayList<ComponentCallbacks> callbacks
2806 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07002807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 if (mActivities.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002809 Iterator<ActivityClientRecord> it = mActivities.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002810 while (it.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002811 ActivityClientRecord ar = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 Activity a = ar.activity;
2813 if (a != null) {
2814 if (!ar.activity.mFinished && (allActivities ||
2815 (a != null && !ar.paused))) {
2816 // If the activity is currently resumed, its configuration
2817 // needs to change right now.
2818 callbacks.add(a);
2819 } else if (newConfig != null) {
2820 // Otherwise, we will tell it about the change
2821 // the next time it is resumed or shown. Note that
2822 // the activity manager may, before then, decide the
2823 // activity needs to be destroyed to handle its new
2824 // configuration.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002825 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Setting activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002826 + ar.activityInfo.name + " newConfig=" + newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 ar.newConfig = newConfig;
2828 }
2829 }
2830 }
2831 }
2832 if (mServices.size() > 0) {
2833 Iterator<Service> it = mServices.values().iterator();
2834 while (it.hasNext()) {
2835 callbacks.add(it.next());
2836 }
2837 }
2838 synchronized (mProviderMap) {
2839 if (mLocalProviders.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002840 Iterator<ProviderClientRecord> it = mLocalProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 while (it.hasNext()) {
2842 callbacks.add(it.next().mLocalProvider);
2843 }
2844 }
2845 }
2846 final int N = mAllApplications.size();
2847 for (int i=0; i<N; i++) {
2848 callbacks.add(mAllApplications.get(i));
2849 }
Bob Leee5408332009-09-04 18:31:17 -07002850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 return callbacks;
2852 }
Bob Leee5408332009-09-04 18:31:17 -07002853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002854 private final void performConfigurationChanged(
2855 ComponentCallbacks cb, Configuration config) {
2856 // Only for Activity objects, check that they actually call up to their
2857 // superclass implementation. ComponentCallbacks is an interface, so
2858 // we check the runtime type and act accordingly.
2859 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
2860 if (activity != null) {
2861 activity.mCalled = false;
2862 }
Bob Leee5408332009-09-04 18:31:17 -07002863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002864 boolean shouldChangeConfig = false;
2865 if ((activity == null) || (activity.mCurrentConfig == null)) {
2866 shouldChangeConfig = true;
2867 } else {
Bob Leee5408332009-09-04 18:31:17 -07002868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002869 // If the new config is the same as the config this Activity
2870 // is already running with then don't bother calling
2871 // onConfigurationChanged
2872 int diff = activity.mCurrentConfig.diff(config);
2873 if (diff != 0) {
Bob Leee5408332009-09-04 18:31:17 -07002874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002875 // If this activity doesn't handle any of the config changes
2876 // then don't bother calling onConfigurationChanged as we're
2877 // going to destroy it.
2878 if ((~activity.mActivityInfo.configChanges & diff) == 0) {
2879 shouldChangeConfig = true;
2880 }
2881 }
2882 }
Bob Leee5408332009-09-04 18:31:17 -07002883
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002884 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002885 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 if (shouldChangeConfig) {
2887 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07002888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002889 if (activity != null) {
2890 if (!activity.mCalled) {
2891 throw new SuperNotCalledException(
2892 "Activity " + activity.getLocalClassName() +
2893 " did not call through to super.onConfigurationChanged()");
2894 }
2895 activity.mConfigChangeFlags = 0;
2896 activity.mCurrentConfig = new Configuration(config);
2897 }
2898 }
2899 }
2900
Dianne Hackbornae078162010-03-18 11:29:37 -07002901 final boolean applyConfigurationToResourcesLocked(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002902 if (mResConfiguration == null) {
2903 mResConfiguration = new Configuration();
2904 }
2905 if (!mResConfiguration.isOtherSeqNewer(config)) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002906 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq="
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002907 + mResConfiguration.seq + ", newSeq=" + config.seq);
Dianne Hackbornae078162010-03-18 11:29:37 -07002908 return false;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002909 }
Dianne Hackbornae078162010-03-18 11:29:37 -07002910 int changes = mResConfiguration.updateFrom(config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002911 DisplayMetrics dm = getDisplayMetricsLocked(true);
Bob Leee5408332009-09-04 18:31:17 -07002912
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002913 // set it for java, this also affects newly created Resources
2914 if (config.locale != null) {
2915 Locale.setDefault(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002916 }
Bob Leee5408332009-09-04 18:31:17 -07002917
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002918 Resources.updateSystemConfiguration(config, dm);
Bob Leee5408332009-09-04 18:31:17 -07002919
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002920 ContextImpl.ApplicationPackageManager.configurationChanged();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002921 //Slog.i(TAG, "Configuration changed in " + currentPackageName());
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002922
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002923 Iterator<WeakReference<Resources>> it =
2924 mActiveResources.values().iterator();
2925 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
2926 // mActiveResources.entrySet().iterator();
2927 while (it.hasNext()) {
2928 WeakReference<Resources> v = it.next();
2929 Resources r = v.get();
2930 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002931 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources "
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002932 + r + " config to: " + config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002933 r.updateConfiguration(config, dm);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002934 //Slog.i(TAG, "Updated app resources " + v.getKey()
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002935 // + " " + r + ": " + r.getConfiguration());
2936 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002937 //Slog.i(TAG, "Removing old resources " + v.getKey());
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002938 it.remove();
2939 }
2940 }
Dianne Hackbornae078162010-03-18 11:29:37 -07002941
2942 return changes != 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002943 }
2944
2945 final void handleConfigurationChanged(Configuration config) {
2946
2947 ArrayList<ComponentCallbacks> callbacks = null;
2948
2949 synchronized (mPackages) {
2950 if (mPendingConfiguration != null) {
2951 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
2952 config = mPendingConfiguration;
2953 }
2954 mPendingConfiguration = null;
2955 }
2956
2957 if (config == null) {
2958 return;
2959 }
2960
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002961 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002962 + config);
2963
2964 applyConfigurationToResourcesLocked(config);
2965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002966 if (mConfiguration == null) {
2967 mConfiguration = new Configuration();
2968 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002969 if (!mConfiguration.isOtherSeqNewer(config)) {
2970 return;
2971 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002972 mConfiguration.updateFrom(config);
Bob Leee5408332009-09-04 18:31:17 -07002973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974 callbacks = collectComponentCallbacksLocked(false, config);
2975 }
Bob Leee5408332009-09-04 18:31:17 -07002976
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002977 if (callbacks != null) {
2978 final int N = callbacks.size();
2979 for (int i=0; i<N; i++) {
2980 performConfigurationChanged(callbacks.get(i), config);
2981 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002982 }
2983 }
2984
2985 final void handleActivityConfigurationChanged(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002986 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002987 if (r == null || r.activity == null) {
2988 return;
2989 }
Bob Leee5408332009-09-04 18:31:17 -07002990
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002991 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002992 + r.activityInfo.name);
2993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002994 performConfigurationChanged(r.activity, mConfiguration);
2995 }
2996
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07002997 final void handleProfilerControl(boolean start, ProfilerControlData pcd) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08002998 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08002999 try {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003000 Debug.startMethodTracing(pcd.path, pcd.fd.getFileDescriptor(),
3001 8 * 1024 * 1024, 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003002 } catch (RuntimeException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003003 Slog.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003004 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003005 } finally {
3006 try {
3007 pcd.fd.close();
3008 } catch (IOException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003009 Slog.w(TAG, "Failure closing profile fd", e);
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003010 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003011 }
3012 } else {
3013 Debug.stopMethodTracing();
3014 }
3015 }
Bob Leee5408332009-09-04 18:31:17 -07003016
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003017 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
3018 boolean hasPkgInfo = false;
3019 if (packages != null) {
3020 for (int i=packages.length-1; i>=0; i--) {
3021 //Slog.i(TAG, "Cleaning old package: " + packages[i]);
3022 if (!hasPkgInfo) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003023 WeakReference<LoadedApk> ref;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003024 ref = mPackages.get(packages[i]);
3025 if (ref != null && ref.get() != null) {
3026 hasPkgInfo = true;
3027 } else {
3028 ref = mResourcePackages.get(packages[i]);
3029 if (ref != null && ref.get() != null) {
3030 hasPkgInfo = true;
3031 }
3032 }
3033 }
3034 mPackages.remove(packages[i]);
3035 mResourcePackages.remove(packages[i]);
3036 }
3037 }
3038 ContextImpl.ApplicationPackageManager.handlePackageBroadcast(cmd, packages,
3039 hasPkgInfo);
3040 }
3041
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003042 final void handleLowMemory() {
3043 ArrayList<ComponentCallbacks> callbacks
3044 = new ArrayList<ComponentCallbacks>();
3045
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003046 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003047 callbacks = collectComponentCallbacksLocked(true, null);
3048 }
Bob Leee5408332009-09-04 18:31:17 -07003049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003050 final int N = callbacks.size();
3051 for (int i=0; i<N; i++) {
3052 callbacks.get(i).onLowMemory();
3053 }
3054
Chris Tatece229052009-03-25 16:44:52 -07003055 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3056 if (Process.myUid() != Process.SYSTEM_UID) {
3057 int sqliteReleased = SQLiteDatabase.releaseMemory();
3058 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3059 }
Bob Leee5408332009-09-04 18:31:17 -07003060
Mike Reedcaf0df12009-04-27 14:32:05 -04003061 // Ask graphics to free up as much as possible (font/image caches)
3062 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003063
3064 BinderInternal.forceGc("mem");
3065 }
3066
3067 private final void handleBindApplication(AppBindData data) {
3068 mBoundApplication = data;
3069 mConfiguration = new Configuration(data.config);
3070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003071 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003072 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003073 android.ddm.DdmHandleAppName.setAppName(data.processName);
3074
3075 /*
3076 * Before spawning a new process, reset the time zone to be the system time zone.
3077 * This needs to be done because the system time zone could have changed after the
3078 * the spawning of this process. Without doing this this process would have the incorrect
3079 * system time zone.
3080 */
3081 TimeZone.setDefault(null);
3082
3083 /*
3084 * Initialize the default locale in this process for the reasons we set the time zone.
3085 */
3086 Locale.setDefault(data.config.locale);
3087
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003088 /*
3089 * Update the system configuration since its preloaded and might not
3090 * reflect configuration changes. The configuration object passed
3091 * in AppBindData can be safely assumed to be up to date
3092 */
3093 Resources.getSystem().updateConfiguration(mConfiguration, null);
3094
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003095 data.info = getPackageInfoNoCheck(data.appInfo);
3096
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003097 /**
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003098 * For system applications on userdebug/eng builds, log stack
3099 * traces of disk and network access to dropbox for analysis.
3100 */
3101 if ((data.appInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0 &&
3102 !"user".equals(Build.TYPE)) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003103 StrictMode.setThreadBlockingPolicy(
3104 StrictMode.DISALLOW_DISK_WRITE |
3105 StrictMode.DISALLOW_DISK_READ |
3106 StrictMode.DISALLOW_NETWORK |
3107 StrictMode.PENALTY_DROPBOX);
3108 }
3109
3110 /**
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003111 * Switch this process to density compatibility mode if needed.
3112 */
3113 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3114 == 0) {
3115 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3116 }
Bob Leee5408332009-09-04 18:31:17 -07003117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003118 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3119 // XXX should have option to change the port.
3120 Debug.changeDebugPort(8100);
3121 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003122 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003123 + " is waiting for the debugger on port 8100...");
3124
3125 IActivityManager mgr = ActivityManagerNative.getDefault();
3126 try {
3127 mgr.showWaitingForDebugger(mAppThread, true);
3128 } catch (RemoteException ex) {
3129 }
3130
3131 Debug.waitForDebugger();
3132
3133 try {
3134 mgr.showWaitingForDebugger(mAppThread, false);
3135 } catch (RemoteException ex) {
3136 }
3137
3138 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003139 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003140 + " can be debugged on port 8100...");
3141 }
3142 }
3143
3144 if (data.instrumentationName != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08003145 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003146 appContext.init(data.info, null, this);
3147 InstrumentationInfo ii = null;
3148 try {
3149 ii = appContext.getPackageManager().
3150 getInstrumentationInfo(data.instrumentationName, 0);
3151 } catch (PackageManager.NameNotFoundException e) {
3152 }
3153 if (ii == null) {
3154 throw new RuntimeException(
3155 "Unable to find instrumentation info for: "
3156 + data.instrumentationName);
3157 }
3158
3159 mInstrumentationAppDir = ii.sourceDir;
3160 mInstrumentationAppPackage = ii.packageName;
3161 mInstrumentedAppDir = data.info.getAppDir();
3162
3163 ApplicationInfo instrApp = new ApplicationInfo();
3164 instrApp.packageName = ii.packageName;
3165 instrApp.sourceDir = ii.sourceDir;
3166 instrApp.publicSourceDir = ii.publicSourceDir;
3167 instrApp.dataDir = ii.dataDir;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003168 LoadedApk pi = getPackageInfo(instrApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003169 appContext.getClassLoader(), false, true);
Dianne Hackborn21556372010-02-04 16:34:40 -08003170 ContextImpl instrContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003171 instrContext.init(pi, null, this);
3172
3173 try {
3174 java.lang.ClassLoader cl = instrContext.getClassLoader();
3175 mInstrumentation = (Instrumentation)
3176 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3177 } catch (Exception e) {
3178 throw new RuntimeException(
3179 "Unable to instantiate instrumentation "
3180 + data.instrumentationName + ": " + e.toString(), e);
3181 }
3182
3183 mInstrumentation.init(this, instrContext, appContext,
3184 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3185
3186 if (data.profileFile != null && !ii.handleProfiling) {
3187 data.handlingProfiling = true;
3188 File file = new File(data.profileFile);
3189 file.getParentFile().mkdirs();
3190 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3191 }
3192
3193 try {
3194 mInstrumentation.onCreate(data.instrumentationArgs);
3195 }
3196 catch (Exception e) {
3197 throw new RuntimeException(
3198 "Exception thrown in onCreate() of "
3199 + data.instrumentationName + ": " + e.toString(), e);
3200 }
3201
3202 } else {
3203 mInstrumentation = new Instrumentation();
3204 }
3205
Christopher Tate181fafa2009-05-14 11:12:14 -07003206 // If the app is being launched for full backup or restore, bring it up in
3207 // a restricted environment with the base application class.
Dianne Hackborn0be1f782009-11-09 12:30:12 -08003208 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209 mInitialApplication = app;
3210
3211 List<ProviderInfo> providers = data.providers;
3212 if (providers != null) {
3213 installContentProviders(app, providers);
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003214 // For process that contain content providers, we want to
3215 // ensure that the JIT is enabled "at some point".
3216 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003217 }
3218
3219 try {
3220 mInstrumentation.callApplicationOnCreate(app);
3221 } catch (Exception e) {
3222 if (!mInstrumentation.onException(app, e)) {
3223 throw new RuntimeException(
3224 "Unable to create application " + app.getClass().getName()
3225 + ": " + e.toString(), e);
3226 }
3227 }
3228 }
3229
3230 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
3231 IActivityManager am = ActivityManagerNative.getDefault();
3232 if (mBoundApplication.profileFile != null && mBoundApplication.handlingProfiling) {
3233 Debug.stopMethodTracing();
3234 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003235 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003236 // + ", app thr: " + mAppThread);
3237 try {
3238 am.finishInstrumentation(mAppThread, resultCode, results);
3239 } catch (RemoteException ex) {
3240 }
3241 }
3242
3243 private final void installContentProviders(
3244 Context context, List<ProviderInfo> providers) {
3245 final ArrayList<IActivityManager.ContentProviderHolder> results =
3246 new ArrayList<IActivityManager.ContentProviderHolder>();
3247
3248 Iterator<ProviderInfo> i = providers.iterator();
3249 while (i.hasNext()) {
3250 ProviderInfo cpi = i.next();
3251 StringBuilder buf = new StringBuilder(128);
3252 buf.append("Publishing provider ");
3253 buf.append(cpi.authority);
3254 buf.append(": ");
3255 buf.append(cpi.name);
3256 Log.i(TAG, buf.toString());
3257 IContentProvider cp = installProvider(context, null, cpi, false);
3258 if (cp != null) {
3259 IActivityManager.ContentProviderHolder cph =
3260 new IActivityManager.ContentProviderHolder(cpi);
3261 cph.provider = cp;
3262 results.add(cph);
3263 // Don't ever unload this provider from the process.
3264 synchronized(mProviderMap) {
3265 mProviderRefCountMap.put(cp.asBinder(), new ProviderRefCount(10000));
3266 }
3267 }
3268 }
3269
3270 try {
3271 ActivityManagerNative.getDefault().publishContentProviders(
3272 getApplicationThread(), results);
3273 } catch (RemoteException ex) {
3274 }
3275 }
3276
3277 private final IContentProvider getProvider(Context context, String name) {
3278 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003279 final ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003280 if (pr != null) {
3281 return pr.mProvider;
3282 }
3283 }
3284
3285 IActivityManager.ContentProviderHolder holder = null;
3286 try {
3287 holder = ActivityManagerNative.getDefault().getContentProvider(
3288 getApplicationThread(), name);
3289 } catch (RemoteException ex) {
3290 }
3291 if (holder == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003292 Slog.e(TAG, "Failed to find provider info for " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003293 return null;
3294 }
3295 if (holder.permissionFailure != null) {
3296 throw new SecurityException("Permission " + holder.permissionFailure
3297 + " required for provider " + name);
3298 }
3299
3300 IContentProvider prov = installProvider(context, holder.provider,
3301 holder.info, true);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003302 //Slog.i(TAG, "noReleaseNeeded=" + holder.noReleaseNeeded);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303 if (holder.noReleaseNeeded || holder.provider == null) {
3304 // We are not going to release the provider if it is an external
3305 // provider that doesn't care about being released, or if it is
3306 // a local provider running in this process.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003307 //Slog.i(TAG, "*** NO RELEASE NEEDED");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003308 synchronized(mProviderMap) {
3309 mProviderRefCountMap.put(prov.asBinder(), new ProviderRefCount(10000));
3310 }
3311 }
3312 return prov;
3313 }
3314
3315 public final IContentProvider acquireProvider(Context c, String name) {
3316 IContentProvider provider = getProvider(c, name);
3317 if(provider == null)
3318 return null;
3319 IBinder jBinder = provider.asBinder();
3320 synchronized(mProviderMap) {
3321 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3322 if(prc == null) {
3323 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3324 } else {
3325 prc.count++;
3326 } //end else
3327 } //end synchronized
3328 return provider;
3329 }
3330
3331 public final boolean releaseProvider(IContentProvider provider) {
3332 if(provider == null) {
3333 return false;
3334 }
3335 IBinder jBinder = provider.asBinder();
3336 synchronized(mProviderMap) {
3337 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3338 if(prc == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003339 if(localLOGV) Slog.v(TAG, "releaseProvider::Weird shouldnt be here");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003340 return false;
3341 } else {
3342 prc.count--;
3343 if(prc.count == 0) {
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003344 // Schedule the actual remove asynchronously, since we
3345 // don't know the context this will be called in.
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003346 // TODO: it would be nice to post a delayed message, so
3347 // if we come back and need the same provider quickly
3348 // we will still have it available.
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003349 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
3350 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351 } //end if
3352 } //end else
3353 } //end synchronized
3354 return true;
3355 }
3356
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003357 final void completeRemoveProvider(IContentProvider provider) {
3358 IBinder jBinder = provider.asBinder();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003359 String name = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003360 synchronized(mProviderMap) {
3361 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3362 if(prc != null && prc.count == 0) {
3363 mProviderRefCountMap.remove(jBinder);
3364 //invoke removeProvider to dereference provider
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003365 name = removeProviderLocked(provider);
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003366 }
3367 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003368
3369 if (name != null) {
3370 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003371 if(localLOGV) Slog.v(TAG, "removeProvider::Invoking " +
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003372 "ActivityManagerNative.removeContentProvider(" + name);
3373 ActivityManagerNative.getDefault().removeContentProvider(
3374 getApplicationThread(), name);
3375 } catch (RemoteException e) {
3376 //do nothing content provider object is dead any way
3377 } //end catch
3378 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003379 }
3380
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003381 public final String removeProviderLocked(IContentProvider provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003382 if (provider == null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003383 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003384 }
3385 IBinder providerBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003386
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003387 String name = null;
3388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 // remove the provider from mProviderMap
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003390 Iterator<ProviderClientRecord> iter = mProviderMap.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003391 while (iter.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003392 ProviderClientRecord pr = iter.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 IBinder myBinder = pr.mProvider.asBinder();
3394 if (myBinder == providerBinder) {
3395 //find if its published by this process itself
3396 if(pr.mLocalProvider != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003397 if(localLOGV) Slog.i(TAG, "removeProvider::found local provider returning");
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003398 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003399 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003400 if(localLOGV) Slog.v(TAG, "removeProvider::Not local provider Unlinking " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003401 "death recipient");
3402 //content provider is in another process
3403 myBinder.unlinkToDeath(pr, 0);
3404 iter.remove();
3405 //invoke remove only once for the very first name seen
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003406 if(name == null) {
3407 name = pr.mName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003408 }
3409 } //end if myBinder
3410 } //end while iter
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003411
3412 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003413 }
3414
3415 final void removeDeadProvider(String name, IContentProvider provider) {
3416 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003417 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003418 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003419 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003420 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003421 if (removed != null) {
3422 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003424 }
3425 }
3426 }
3427
3428 final void removeDeadProviderLocked(String name, IContentProvider provider) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003429 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003430 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003431 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003432 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003433 if (removed != null) {
3434 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3435 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003436 }
3437 }
3438
3439 private final IContentProvider installProvider(Context context,
3440 IContentProvider provider, ProviderInfo info, boolean noisy) {
3441 ContentProvider localProvider = null;
3442 if (provider == null) {
3443 if (noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003444 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003445 + info.name);
3446 }
3447 Context c = null;
3448 ApplicationInfo ai = info.applicationInfo;
3449 if (context.getPackageName().equals(ai.packageName)) {
3450 c = context;
3451 } else if (mInitialApplication != null &&
3452 mInitialApplication.getPackageName().equals(ai.packageName)) {
3453 c = mInitialApplication;
3454 } else {
3455 try {
3456 c = context.createPackageContext(ai.packageName,
3457 Context.CONTEXT_INCLUDE_CODE);
3458 } catch (PackageManager.NameNotFoundException e) {
3459 }
3460 }
3461 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003462 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003463 ai.packageName +
3464 " while loading content provider " +
3465 info.name);
3466 return null;
3467 }
3468 try {
3469 final java.lang.ClassLoader cl = c.getClassLoader();
3470 localProvider = (ContentProvider)cl.
3471 loadClass(info.name).newInstance();
3472 provider = localProvider.getIContentProvider();
3473 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003474 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003475 info.name + " from sourceDir " +
3476 info.applicationInfo.sourceDir);
3477 return null;
3478 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003479 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003480 TAG, "Instantiating local provider " + info.name);
3481 // XXX Need to create the correct context for this provider.
3482 localProvider.attachInfo(c, info);
3483 } catch (java.lang.Exception e) {
3484 if (!mInstrumentation.onException(null, e)) {
3485 throw new RuntimeException(
3486 "Unable to get provider " + info.name
3487 + ": " + e.toString(), e);
3488 }
3489 return null;
3490 }
3491 } else if (localLOGV) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003492 Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003493 + info.name);
3494 }
3495
3496 synchronized (mProviderMap) {
3497 // Cache the pointer for the remote provider.
3498 String names[] = PATTERN_SEMICOLON.split(info.authority);
3499 for (int i=0; i<names.length; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003500 ProviderClientRecord pr = new ProviderClientRecord(names[i], provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003501 localProvider);
3502 try {
3503 provider.asBinder().linkToDeath(pr, 0);
3504 mProviderMap.put(names[i], pr);
3505 } catch (RemoteException e) {
3506 return null;
3507 }
3508 }
3509 if (localProvider != null) {
3510 mLocalProviders.put(provider.asBinder(),
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003511 new ProviderClientRecord(null, provider, localProvider));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003512 }
3513 }
3514
3515 return provider;
3516 }
3517
3518 private final void attach(boolean system) {
3519 sThreadLocal.set(this);
3520 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003521 if (!system) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003522 ViewRoot.addFirstDrawHandler(new Runnable() {
3523 public void run() {
3524 ensureJitEnabled();
3525 }
3526 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003527 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
3528 RuntimeInit.setApplicationObject(mAppThread.asBinder());
3529 IActivityManager mgr = ActivityManagerNative.getDefault();
3530 try {
3531 mgr.attachApplication(mAppThread);
3532 } catch (RemoteException ex) {
3533 }
3534 } else {
3535 // Don't set application object here -- if the system crashes,
3536 // we can't display an alert, we just want to die die die.
3537 android.ddm.DdmHandleAppName.setAppName("system_process");
3538 try {
3539 mInstrumentation = new Instrumentation();
Dianne Hackborn21556372010-02-04 16:34:40 -08003540 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003541 context.init(getSystemContext().mPackageInfo, null, this);
3542 Application app = Instrumentation.newApplication(Application.class, context);
3543 mAllApplications.add(app);
3544 mInitialApplication = app;
3545 app.onCreate();
3546 } catch (Exception e) {
3547 throw new RuntimeException(
3548 "Unable to instantiate Application():" + e.toString(), e);
3549 }
3550 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003551
3552 ViewRoot.addConfigCallback(new ComponentCallbacks() {
3553 public void onConfigurationChanged(Configuration newConfig) {
3554 synchronized (mPackages) {
Dianne Hackbornae078162010-03-18 11:29:37 -07003555 // We need to apply this change to the resources
3556 // immediately, because upon returning the view
3557 // hierarchy will be informed about it.
3558 if (applyConfigurationToResourcesLocked(newConfig)) {
3559 // This actually changed the resources! Tell
3560 // everyone about it.
3561 if (mPendingConfiguration == null ||
3562 mPendingConfiguration.isOtherSeqNewer(newConfig)) {
3563 mPendingConfiguration = newConfig;
3564
3565 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
3566 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003567 }
3568 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003569 }
3570 public void onLowMemory() {
3571 }
3572 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003573 }
3574
3575 private final void detach()
3576 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003577 sThreadLocal.set(null);
3578 }
3579
3580 public static final ActivityThread systemMain() {
3581 ActivityThread thread = new ActivityThread();
3582 thread.attach(true);
3583 return thread;
3584 }
3585
3586 public final void installSystemProviders(List providers) {
3587 if (providers != null) {
3588 installContentProviders(mInitialApplication,
3589 (List<ProviderInfo>)providers);
3590 }
3591 }
3592
3593 public static final void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07003594 SamplingProfilerIntegration.start();
3595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003596 Process.setArgV0("<pre-initialized>");
3597
3598 Looper.prepareMainLooper();
3599
3600 ActivityThread thread = new ActivityThread();
3601 thread.attach(false);
3602
3603 Looper.loop();
3604
3605 if (Process.supportsProcesses()) {
3606 throw new RuntimeException("Main thread loop unexpectedly exited");
3607 }
3608
3609 thread.detach();
Bob Leeeec2f412009-09-10 11:01:24 +02003610 String name = (thread.mInitialApplication != null)
3611 ? thread.mInitialApplication.getPackageName()
3612 : "<unknown>";
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003613 Slog.i(TAG, "Main thread of " + name + " is now exiting");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003614 }
3615}