blob: 0fb2b492616515af217b70cdcc678bd88faa81b5 [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";
Jim Miller0b2a6d02010-07-13 18:01:29 -0700118 private static final android.graphics.Bitmap.Config THUMBNAIL_FORMAT = Bitmap.Config.RGB_565;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 private static final boolean DEBUG = false;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700120 static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
121 static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700122 private static final boolean DEBUG_RESULTS = false;
Christopher Tate436344a2009-09-30 16:17:37 -0700123 private static final boolean DEBUG_BACKUP = false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700124 private static final boolean DEBUG_CONFIGURATION = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
126 private static final Pattern PATTERN_SEMICOLON = Pattern.compile(";");
127 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
128 private static final int LOG_ON_PAUSE_CALLED = 30021;
129 private static final int LOG_ON_RESUME_CALLED = 30022;
130
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700131 static ContextImpl mSystemContext = null;
Bob Leee5408332009-09-04 18:31:17 -0700132
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700133 static IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700135 final ApplicationThread mAppThread = new ApplicationThread();
136 final Looper mLooper = Looper.myLooper();
137 final H mH = new H();
138 final HashMap<IBinder, ActivityClientRecord> mActivities
139 = new HashMap<IBinder, ActivityClientRecord>();
140 // List of new activities (via ActivityRecord.nextIdle) that should
141 // be reported when next we idle.
142 ActivityClientRecord mNewActivities = null;
143 // Number of activities that are currently visible on-screen.
144 int mNumVisibleActivities = 0;
145 final HashMap<IBinder, Service> mServices
146 = new HashMap<IBinder, Service>();
147 AppBindData mBoundApplication;
148 Configuration mConfiguration;
149 Configuration mResConfiguration;
150 Application mInitialApplication;
151 final ArrayList<Application> mAllApplications
152 = new ArrayList<Application>();
153 // set of instantiated backup agents, keyed by package name
154 final HashMap<String, BackupAgent> mBackupAgents = new HashMap<String, BackupAgent>();
155 static final ThreadLocal sThreadLocal = new ThreadLocal();
156 Instrumentation mInstrumentation;
157 String mInstrumentationAppDir = null;
158 String mInstrumentationAppPackage = null;
159 String mInstrumentedAppDir = null;
160 boolean mSystemThread = false;
161 boolean mJitEnabled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700163 // These can be accessed by multiple threads; mPackages is the lock.
164 // XXX For now we keep around information about all packages we have
165 // seen, not removing entries from this map.
166 final HashMap<String, WeakReference<LoadedApk>> mPackages
167 = new HashMap<String, WeakReference<LoadedApk>>();
168 final HashMap<String, WeakReference<LoadedApk>> mResourcePackages
169 = new HashMap<String, WeakReference<LoadedApk>>();
170 Display mDisplay = null;
171 DisplayMetrics mDisplayMetrics = null;
172 final HashMap<ResourcesKey, WeakReference<Resources> > mActiveResources
173 = new HashMap<ResourcesKey, WeakReference<Resources> >();
174 final ArrayList<ActivityClientRecord> mRelaunchingActivities
175 = new ArrayList<ActivityClientRecord>();
176 Configuration mPendingConfiguration = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700178 // The lock of mProviderMap protects the following variables.
179 final HashMap<String, ProviderClientRecord> mProviderMap
180 = new HashMap<String, ProviderClientRecord>();
181 final HashMap<IBinder, ProviderRefCount> mProviderRefCountMap
182 = new HashMap<IBinder, ProviderRefCount>();
183 final HashMap<IBinder, ProviderClientRecord> mLocalProviders
184 = new HashMap<IBinder, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700186 final GcIdler mGcIdler = new GcIdler();
187 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700189 private static final class ActivityClientRecord {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700191 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 Intent intent;
193 Bundle state;
194 Activity activity;
195 Window window;
196 Activity parent;
197 String embeddedID;
198 Object lastNonConfigurationInstance;
199 HashMap<String,Object> lastNonConfigurationChildInstances;
200 boolean paused;
201 boolean stopped;
202 boolean hideForNow;
203 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700204 Configuration createdConfig;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700205 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206
207 ActivityInfo activityInfo;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700208 LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209
210 List<ResultInfo> pendingResults;
211 List<Intent> pendingIntents;
212
213 boolean startsNotResumed;
214 boolean isForward;
215
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700216 ActivityClientRecord() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 parent = null;
218 embeddedID = null;
219 paused = false;
220 stopped = false;
221 hideForNow = false;
222 nextIdle = null;
223 }
224
225 public String toString() {
226 ComponentName componentName = intent.getComponent();
227 return "ActivityRecord{"
228 + Integer.toHexString(System.identityHashCode(this))
229 + " token=" + token + " " + (componentName == null
230 ? "no component name" : componentName.toShortString())
231 + "}";
232 }
233 }
234
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700235 private final class ProviderClientRecord implements IBinder.DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236 final String mName;
237 final IContentProvider mProvider;
238 final ContentProvider mLocalProvider;
239
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700240 ProviderClientRecord(String name, IContentProvider provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 ContentProvider localProvider) {
242 mName = name;
243 mProvider = provider;
244 mLocalProvider = localProvider;
245 }
246
247 public void binderDied() {
248 removeDeadProvider(mName, mProvider);
249 }
250 }
251
252 private static final class NewIntentData {
253 List<Intent> intents;
254 IBinder token;
255 public String toString() {
256 return "NewIntentData{intents=" + intents + " token=" + token + "}";
257 }
258 }
259
260 private static final class ReceiverData {
261 Intent intent;
262 ActivityInfo info;
263 int resultCode;
264 String resultData;
265 Bundle resultExtras;
266 boolean sync;
267 boolean resultAbort;
268 public String toString() {
269 return "ReceiverData{intent=" + intent + " packageName=" +
270 info.packageName + " resultCode=" + resultCode
271 + " resultData=" + resultData + " resultExtras=" + resultExtras + "}";
272 }
273 }
274
Christopher Tate181fafa2009-05-14 11:12:14 -0700275 private static final class CreateBackupAgentData {
276 ApplicationInfo appInfo;
277 int backupMode;
278 public String toString() {
279 return "CreateBackupAgentData{appInfo=" + appInfo
280 + " backupAgent=" + appInfo.backupAgentName
281 + " mode=" + backupMode + "}";
282 }
283 }
Bob Leee5408332009-09-04 18:31:17 -0700284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800285 private static final class CreateServiceData {
286 IBinder token;
287 ServiceInfo info;
288 Intent intent;
289 public String toString() {
290 return "CreateServiceData{token=" + token + " className="
291 + info.name + " packageName=" + info.packageName
292 + " intent=" + intent + "}";
293 }
294 }
295
296 private static final class BindServiceData {
297 IBinder token;
298 Intent intent;
299 boolean rebind;
300 public String toString() {
301 return "BindServiceData{token=" + token + " intent=" + intent + "}";
302 }
303 }
304
305 private static final class ServiceArgsData {
306 IBinder token;
307 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700308 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800309 Intent args;
310 public String toString() {
311 return "ServiceArgsData{token=" + token + " startId=" + startId
312 + " args=" + args + "}";
313 }
314 }
315
316 private static final class AppBindData {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700317 LoadedApk info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 String processName;
319 ApplicationInfo appInfo;
320 List<ProviderInfo> providers;
321 ComponentName instrumentationName;
322 String profileFile;
323 Bundle instrumentationArgs;
324 IInstrumentationWatcher instrumentationWatcher;
325 int debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700326 boolean restrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 Configuration config;
328 boolean handlingProfiling;
329 public String toString() {
330 return "AppBindData{appInfo=" + appInfo + "}";
331 }
332 }
333
334 private static final class DumpServiceInfo {
335 FileDescriptor fd;
336 IBinder service;
337 String[] args;
338 boolean dumped;
339 }
340
341 private static final class ResultData {
342 IBinder token;
343 List<ResultInfo> results;
344 public String toString() {
345 return "ResultData{token=" + token + " results" + results + "}";
346 }
347 }
348
349 private static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800350 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800351 String what;
352 String who;
353 }
354
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700355 private static final class ProfilerControlData {
356 String path;
357 ParcelFileDescriptor fd;
358 }
359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360 private final class ApplicationThread extends ApplicationThreadNative {
361 private static final String HEAP_COLUMN = "%17s %8s %8s %8s %8s";
362 private static final String ONE_COUNT_COLUMN = "%17s %8d";
363 private static final String TWO_COUNT_COLUMNS = "%17s %8d %17s %8d";
Vasu Noric3849202010-03-09 10:47:25 -0800364 private static final String DB_INFO_FORMAT = " %8d %8d %10d %s";
Bob Leee5408332009-09-04 18:31:17 -0700365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366 // Formatting for checkin service - update version if row format changes
367 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;
Bob Leee5408332009-09-04 18:31:17 -0700368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 public final void schedulePauseActivity(IBinder token, boolean finished,
370 boolean userLeaving, int configChanges) {
371 queueOrSendMessage(
372 finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
373 token,
374 (userLeaving ? 1 : 0),
375 configChanges);
376 }
377
378 public final void scheduleStopActivity(IBinder token, boolean showWindow,
379 int configChanges) {
380 queueOrSendMessage(
381 showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
382 token, 0, configChanges);
383 }
384
385 public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
386 queueOrSendMessage(
387 showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
388 token);
389 }
390
391 public final void scheduleResumeActivity(IBinder token, boolean isForward) {
392 queueOrSendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
393 }
394
395 public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
396 ResultData res = new ResultData();
397 res.token = token;
398 res.results = results;
399 queueOrSendMessage(H.SEND_RESULT, res);
400 }
401
402 // we use token to identify this activity without having to send the
403 // activity itself back to the activity manager. (matters more with ipc)
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700404 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
406 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700407 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408
409 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700410 r.ident = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 r.intent = intent;
412 r.activityInfo = info;
413 r.state = state;
414
415 r.pendingResults = pendingResults;
416 r.pendingIntents = pendingNewIntents;
417
418 r.startsNotResumed = notResumed;
419 r.isForward = isForward;
420
421 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
422 }
423
424 public final void scheduleRelaunchActivity(IBinder token,
425 List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800426 int configChanges, boolean notResumed, Configuration config) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700427 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428
429 r.token = token;
430 r.pendingResults = pendingResults;
431 r.pendingIntents = pendingNewIntents;
432 r.startsNotResumed = notResumed;
Dianne Hackborn871ecdc2009-12-11 15:24:33 -0800433 r.createdConfig = config;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800435 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 mRelaunchingActivities.add(r);
437 }
Bob Leee5408332009-09-04 18:31:17 -0700438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439 queueOrSendMessage(H.RELAUNCH_ACTIVITY, r, configChanges);
440 }
441
442 public final void scheduleNewIntent(List<Intent> intents, IBinder token) {
443 NewIntentData data = new NewIntentData();
444 data.intents = intents;
445 data.token = token;
446
447 queueOrSendMessage(H.NEW_INTENT, data);
448 }
449
450 public final void scheduleDestroyActivity(IBinder token, boolean finishing,
451 int configChanges) {
452 queueOrSendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
453 configChanges);
454 }
455
456 public final void scheduleReceiver(Intent intent, ActivityInfo info,
457 int resultCode, String data, Bundle extras, boolean sync) {
458 ReceiverData r = new ReceiverData();
459
460 r.intent = intent;
461 r.info = info;
462 r.resultCode = resultCode;
463 r.resultData = data;
464 r.resultExtras = extras;
465 r.sync = sync;
466
467 queueOrSendMessage(H.RECEIVER, r);
468 }
469
Christopher Tate181fafa2009-05-14 11:12:14 -0700470 public final void scheduleCreateBackupAgent(ApplicationInfo app, int backupMode) {
471 CreateBackupAgentData d = new CreateBackupAgentData();
472 d.appInfo = app;
473 d.backupMode = backupMode;
474
475 queueOrSendMessage(H.CREATE_BACKUP_AGENT, d);
476 }
477
478 public final void scheduleDestroyBackupAgent(ApplicationInfo app) {
479 CreateBackupAgentData d = new CreateBackupAgentData();
480 d.appInfo = app;
481
482 queueOrSendMessage(H.DESTROY_BACKUP_AGENT, d);
483 }
484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800485 public final void scheduleCreateService(IBinder token,
486 ServiceInfo info) {
487 CreateServiceData s = new CreateServiceData();
488 s.token = token;
489 s.info = info;
490
491 queueOrSendMessage(H.CREATE_SERVICE, s);
492 }
493
494 public final void scheduleBindService(IBinder token, Intent intent,
495 boolean rebind) {
496 BindServiceData s = new BindServiceData();
497 s.token = token;
498 s.intent = intent;
499 s.rebind = rebind;
500
501 queueOrSendMessage(H.BIND_SERVICE, s);
502 }
503
504 public final void scheduleUnbindService(IBinder token, Intent intent) {
505 BindServiceData s = new BindServiceData();
506 s.token = token;
507 s.intent = intent;
508
509 queueOrSendMessage(H.UNBIND_SERVICE, s);
510 }
511
512 public final void scheduleServiceArgs(IBinder token, int startId,
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700513 int flags ,Intent args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514 ServiceArgsData s = new ServiceArgsData();
515 s.token = token;
516 s.startId = startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700517 s.flags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518 s.args = args;
519
520 queueOrSendMessage(H.SERVICE_ARGS, s);
521 }
522
523 public final void scheduleStopService(IBinder token) {
524 queueOrSendMessage(H.STOP_SERVICE, token);
525 }
526
527 public final void bindApplication(String processName,
528 ApplicationInfo appInfo, List<ProviderInfo> providers,
529 ComponentName instrumentationName, String profileFile,
530 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
Christopher Tate181fafa2009-05-14 11:12:14 -0700531 int debugMode, boolean isRestrictedBackupMode, Configuration config,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532 Map<String, IBinder> services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533
534 if (services != null) {
535 // Setup the service cache in the ServiceManager
536 ServiceManager.initServiceCache(services);
537 }
538
539 AppBindData data = new AppBindData();
540 data.processName = processName;
541 data.appInfo = appInfo;
542 data.providers = providers;
543 data.instrumentationName = instrumentationName;
544 data.profileFile = profileFile;
545 data.instrumentationArgs = instrumentationArgs;
546 data.instrumentationWatcher = instrumentationWatcher;
547 data.debugMode = debugMode;
Christopher Tate181fafa2009-05-14 11:12:14 -0700548 data.restrictedBackupMode = isRestrictedBackupMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549 data.config = config;
550 queueOrSendMessage(H.BIND_APPLICATION, data);
551 }
552
553 public final void scheduleExit() {
554 queueOrSendMessage(H.EXIT_APPLICATION, null);
555 }
556
Christopher Tate5e1ab332009-09-01 20:32:49 -0700557 public final void scheduleSuicide() {
558 queueOrSendMessage(H.SUICIDE, null);
559 }
560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561 public void requestThumbnail(IBinder token) {
562 queueOrSendMessage(H.REQUEST_THUMBNAIL, token);
563 }
564
565 public void scheduleConfigurationChanged(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800566 synchronized (mPackages) {
567 if (mPendingConfiguration == null ||
568 mPendingConfiguration.isOtherSeqNewer(config)) {
569 mPendingConfiguration = config;
570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571 }
572 queueOrSendMessage(H.CONFIGURATION_CHANGED, config);
573 }
574
575 public void updateTimeZone() {
576 TimeZone.setDefault(null);
577 }
578
579 public void processInBackground() {
580 mH.removeMessages(H.GC_WHEN_IDLE);
581 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
582 }
583
584 public void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args) {
585 DumpServiceInfo data = new DumpServiceInfo();
586 data.fd = fd;
587 data.service = servicetoken;
588 data.args = args;
589 data.dumped = false;
590 queueOrSendMessage(H.DUMP_SERVICE, data);
591 synchronized (data) {
592 while (!data.dumped) {
593 try {
594 data.wait();
595 } catch (InterruptedException e) {
596 // no need to do anything here, we will keep waiting until
597 // dumped is set
598 }
599 }
600 }
601 }
602
603 // This function exists to make sure all receiver dispatching is
604 // correctly ordered, since these are one-way calls and the binder driver
605 // applies transaction ordering per object for such calls.
606 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700607 int resultCode, String dataStr, Bundle extras, boolean ordered,
608 boolean sticky) throws RemoteException {
609 receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 }
Bob Leee5408332009-09-04 18:31:17 -0700611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612 public void scheduleLowMemory() {
613 queueOrSendMessage(H.LOW_MEMORY, null);
614 }
615
616 public void scheduleActivityConfigurationChanged(IBinder token) {
617 queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token);
618 }
619
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700620 public void profilerControl(boolean start, String path, ParcelFileDescriptor fd) {
621 ProfilerControlData pcd = new ProfilerControlData();
622 pcd.path = path;
623 pcd.fd = fd;
624 queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800625 }
626
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700627 public void setSchedulingGroup(int group) {
628 // Note: do this immediately, since going into the foreground
629 // should happen regardless of what pending work we have to do
630 // and the activity manager will wait for us to report back that
631 // we are done before sending us to the background.
632 try {
633 Process.setProcessGroup(Process.myPid(), group);
634 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800635 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -0700636 }
637 }
Bob Leee5408332009-09-04 18:31:17 -0700638
Dianne Hackborn3025ef32009-08-31 21:31:47 -0700639 public void getMemoryInfo(Debug.MemoryInfo outInfo) {
640 Debug.getMemoryInfo(outInfo);
641 }
Bob Leee5408332009-09-04 18:31:17 -0700642
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700643 public void dispatchPackageBroadcast(int cmd, String[] packages) {
644 queueOrSendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
645 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700646
647 public void scheduleCrash(String msg) {
648 queueOrSendMessage(H.SCHEDULE_CRASH, msg);
649 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 @Override
652 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
653 long nativeMax = Debug.getNativeHeapSize() / 1024;
654 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
655 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
656
657 Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
658 Debug.getMemoryInfo(memInfo);
659
660 final int nativeShared = memInfo.nativeSharedDirty;
661 final int dalvikShared = memInfo.dalvikSharedDirty;
662 final int otherShared = memInfo.otherSharedDirty;
663
664 final int nativePrivate = memInfo.nativePrivateDirty;
665 final int dalvikPrivate = memInfo.dalvikPrivateDirty;
666 final int otherPrivate = memInfo.otherPrivateDirty;
667
668 Runtime runtime = Runtime.getRuntime();
669
670 long dalvikMax = runtime.totalMemory() / 1024;
671 long dalvikFree = runtime.freeMemory() / 1024;
672 long dalvikAllocated = dalvikMax - dalvikFree;
673 long viewInstanceCount = ViewDebug.getViewInstanceCount();
674 long viewRootInstanceCount = ViewDebug.getViewRootInstanceCount();
Dianne Hackborn21556372010-02-04 16:34:40 -0800675 long appContextInstanceCount = ContextImpl.getInstanceCount();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 long activityInstanceCount = Activity.getInstanceCount();
677 int globalAssetCount = AssetManager.getGlobalAssetCount();
678 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
679 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
680 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
681 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
682 int openSslSocketCount = OpenSSLSocketImpl.getInstanceCount();
683 long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024;
Vasu Noric3849202010-03-09 10:47:25 -0800684 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -0700685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 // Check to see if we were called by checkin server. If so, print terse format.
687 boolean doCheckinFormat = false;
688 if (args != null) {
689 for (String arg : args) {
690 if ("-c".equals(arg)) doCheckinFormat = true;
691 }
692 }
Bob Leee5408332009-09-04 18:31:17 -0700693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 // For checkin, we print one long comma-separated list of values
695 if (doCheckinFormat) {
696 // NOTE: if you change anything significant below, also consider changing
697 // ACTIVITY_THREAD_CHECKIN_VERSION.
Bob Leee5408332009-09-04 18:31:17 -0700698 String processName = (mBoundApplication != null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 ? mBoundApplication.processName : "unknown";
Bob Leee5408332009-09-04 18:31:17 -0700700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 // Header
702 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
703 pw.print(Process.myPid()); pw.print(',');
704 pw.print(processName); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 // Heap info - max
707 pw.print(nativeMax); pw.print(',');
708 pw.print(dalvikMax); pw.print(',');
709 pw.print("N/A,");
710 pw.print(nativeMax + dalvikMax); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 // Heap info - allocated
713 pw.print(nativeAllocated); pw.print(',');
714 pw.print(dalvikAllocated); pw.print(',');
715 pw.print("N/A,");
716 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 // Heap info - free
719 pw.print(nativeFree); pw.print(',');
720 pw.print(dalvikFree); pw.print(',');
721 pw.print("N/A,");
722 pw.print(nativeFree + dalvikFree); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 // Heap info - proportional set size
725 pw.print(memInfo.nativePss); pw.print(',');
726 pw.print(memInfo.dalvikPss); pw.print(',');
727 pw.print(memInfo.otherPss); pw.print(',');
728 pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 // Heap info - shared
Bob Leee5408332009-09-04 18:31:17 -0700731 pw.print(nativeShared); pw.print(',');
732 pw.print(dalvikShared); pw.print(',');
733 pw.print(otherShared); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 pw.print(nativeShared + dalvikShared + otherShared); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 // Heap info - private
Bob Leee5408332009-09-04 18:31:17 -0700737 pw.print(nativePrivate); pw.print(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 pw.print(dalvikPrivate); pw.print(',');
739 pw.print(otherPrivate); pw.print(',');
740 pw.print(nativePrivate + dalvikPrivate + otherPrivate); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800742 // Object counts
743 pw.print(viewInstanceCount); pw.print(',');
744 pw.print(viewRootInstanceCount); pw.print(',');
745 pw.print(appContextInstanceCount); pw.print(',');
746 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 pw.print(globalAssetCount); pw.print(',');
749 pw.print(globalAssetManagerCount); pw.print(',');
750 pw.print(binderLocalObjectCount); pw.print(',');
751 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 pw.print(binderDeathObjectCount); pw.print(',');
754 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -0700755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 // SQL
757 pw.print(sqliteAllocated); pw.print(',');
Vasu Noric3849202010-03-09 10:47:25 -0800758 pw.print(stats.memoryUsed / 1024); pw.print(',');
759 pw.print(stats.pageCacheOverflo / 1024); pw.print(',');
760 pw.print(stats.largestMemAlloc / 1024); pw.print(',');
761 for (int i = 0; i < stats.dbStats.size(); i++) {
762 DbStats dbStats = stats.dbStats.get(i);
763 printRow(pw, DB_INFO_FORMAT, dbStats.pageSize, dbStats.dbSize,
764 dbStats.lookaside, dbStats.dbName);
765 pw.print(',');
766 }
Bob Leee5408332009-09-04 18:31:17 -0700767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 return;
769 }
Bob Leee5408332009-09-04 18:31:17 -0700770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 // otherwise, show human-readable format
772 printRow(pw, HEAP_COLUMN, "", "native", "dalvik", "other", "total");
773 printRow(pw, HEAP_COLUMN, "size:", nativeMax, dalvikMax, "N/A", nativeMax + dalvikMax);
774 printRow(pw, HEAP_COLUMN, "allocated:", nativeAllocated, dalvikAllocated, "N/A",
775 nativeAllocated + dalvikAllocated);
776 printRow(pw, HEAP_COLUMN, "free:", nativeFree, dalvikFree, "N/A",
777 nativeFree + dalvikFree);
778
779 printRow(pw, HEAP_COLUMN, "(Pss):", memInfo.nativePss, memInfo.dalvikPss,
780 memInfo.otherPss, memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss);
781
782 printRow(pw, HEAP_COLUMN, "(shared dirty):", nativeShared, dalvikShared, otherShared,
783 nativeShared + dalvikShared + otherShared);
784 printRow(pw, HEAP_COLUMN, "(priv dirty):", nativePrivate, dalvikPrivate, otherPrivate,
785 nativePrivate + dalvikPrivate + otherPrivate);
786
787 pw.println(" ");
788 pw.println(" Objects");
789 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRoots:",
790 viewRootInstanceCount);
791
792 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
793 "Activities:", activityInstanceCount);
794
795 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
796 "AssetManagers:", globalAssetManagerCount);
797
798 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
799 "Proxy Binders:", binderProxyObjectCount);
800 printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount);
801
802 printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount);
Bob Leee5408332009-09-04 18:31:17 -0700803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 // SQLite mem info
805 pw.println(" ");
806 pw.println(" SQL");
Vasu Noric3849202010-03-09 10:47:25 -0800807 printRow(pw, TWO_COUNT_COLUMNS, "heap:", sqliteAllocated, "memoryUsed:",
808 stats.memoryUsed / 1024);
809 printRow(pw, TWO_COUNT_COLUMNS, "pageCacheOverflo:", stats.pageCacheOverflo / 1024,
810 "largestMemAlloc:", stats.largestMemAlloc / 1024);
811 pw.println(" ");
812 int N = stats.dbStats.size();
813 if (N > 0) {
814 pw.println(" DATABASES");
815 printRow(pw, " %8s %8s %10s %s", "Pagesize", "Dbsize", "Lookaside", "Dbname");
816 for (int i = 0; i < N; i++) {
817 DbStats dbStats = stats.dbStats.get(i);
818 printRow(pw, DB_INFO_FORMAT, dbStats.pageSize, dbStats.dbSize,
819 dbStats.lookaside, dbStats.dbName);
820 }
821 }
Bob Leee5408332009-09-04 18:31:17 -0700822
Dianne Hackborn82e1ee92009-08-11 18:56:41 -0700823 // Asset details.
824 String assetAlloc = AssetManager.getAssetAllocations();
825 if (assetAlloc != null) {
826 pw.println(" ");
827 pw.println(" Asset Allocations");
828 pw.print(assetAlloc);
829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 }
831
832 private void printRow(PrintWriter pw, String format, Object...objs) {
833 pw.println(String.format(format, objs));
834 }
835 }
836
837 private final class H extends Handler {
Bob Leee5408332009-09-04 18:31:17 -0700838 private H() {
839 SamplingProfiler.getInstance().setEventThread(mLooper.getThread());
840 }
841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 public static final int LAUNCH_ACTIVITY = 100;
843 public static final int PAUSE_ACTIVITY = 101;
844 public static final int PAUSE_ACTIVITY_FINISHING= 102;
845 public static final int STOP_ACTIVITY_SHOW = 103;
846 public static final int STOP_ACTIVITY_HIDE = 104;
847 public static final int SHOW_WINDOW = 105;
848 public static final int HIDE_WINDOW = 106;
849 public static final int RESUME_ACTIVITY = 107;
850 public static final int SEND_RESULT = 108;
851 public static final int DESTROY_ACTIVITY = 109;
852 public static final int BIND_APPLICATION = 110;
853 public static final int EXIT_APPLICATION = 111;
854 public static final int NEW_INTENT = 112;
855 public static final int RECEIVER = 113;
856 public static final int CREATE_SERVICE = 114;
857 public static final int SERVICE_ARGS = 115;
858 public static final int STOP_SERVICE = 116;
859 public static final int REQUEST_THUMBNAIL = 117;
860 public static final int CONFIGURATION_CHANGED = 118;
861 public static final int CLEAN_UP_CONTEXT = 119;
862 public static final int GC_WHEN_IDLE = 120;
863 public static final int BIND_SERVICE = 121;
864 public static final int UNBIND_SERVICE = 122;
865 public static final int DUMP_SERVICE = 123;
866 public static final int LOW_MEMORY = 124;
867 public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
868 public static final int RELAUNCH_ACTIVITY = 126;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800869 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -0700870 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -0700871 public static final int DESTROY_BACKUP_AGENT = 129;
872 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700873 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800874 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700875 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700876 public static final int SCHEDULE_CRASH = 134;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 String codeToString(int code) {
878 if (localLOGV) {
879 switch (code) {
880 case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
881 case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
882 case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
883 case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
884 case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
885 case SHOW_WINDOW: return "SHOW_WINDOW";
886 case HIDE_WINDOW: return "HIDE_WINDOW";
887 case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
888 case SEND_RESULT: return "SEND_RESULT";
889 case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
890 case BIND_APPLICATION: return "BIND_APPLICATION";
891 case EXIT_APPLICATION: return "EXIT_APPLICATION";
892 case NEW_INTENT: return "NEW_INTENT";
893 case RECEIVER: return "RECEIVER";
894 case CREATE_SERVICE: return "CREATE_SERVICE";
895 case SERVICE_ARGS: return "SERVICE_ARGS";
896 case STOP_SERVICE: return "STOP_SERVICE";
897 case REQUEST_THUMBNAIL: return "REQUEST_THUMBNAIL";
898 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
899 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
900 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
901 case BIND_SERVICE: return "BIND_SERVICE";
902 case UNBIND_SERVICE: return "UNBIND_SERVICE";
903 case DUMP_SERVICE: return "DUMP_SERVICE";
904 case LOW_MEMORY: return "LOW_MEMORY";
905 case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
906 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800907 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -0700908 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
909 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -0700910 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -0700911 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800912 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -0700913 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700914 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 }
916 }
917 return "(unknown)";
918 }
919 public void handleMessage(Message msg) {
920 switch (msg.what) {
921 case LAUNCH_ACTIVITY: {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700922 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923
924 r.packageInfo = getPackageInfoNoCheck(
925 r.activityInfo.applicationInfo);
Christopher Tateb70f3df2009-04-07 16:07:59 -0700926 handleLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 } break;
928 case RELAUNCH_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 handleRelaunchActivity(r, msg.arg1);
931 } break;
932 case PAUSE_ACTIVITY:
933 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
Bob Leee5408332009-09-04 18:31:17 -0700934 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 break;
936 case PAUSE_ACTIVITY_FINISHING:
937 handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);
938 break;
939 case STOP_ACTIVITY_SHOW:
940 handleStopActivity((IBinder)msg.obj, true, msg.arg2);
941 break;
942 case STOP_ACTIVITY_HIDE:
943 handleStopActivity((IBinder)msg.obj, false, msg.arg2);
944 break;
945 case SHOW_WINDOW:
946 handleWindowVisibility((IBinder)msg.obj, true);
947 break;
948 case HIDE_WINDOW:
949 handleWindowVisibility((IBinder)msg.obj, false);
950 break;
951 case RESUME_ACTIVITY:
952 handleResumeActivity((IBinder)msg.obj, true,
953 msg.arg1 != 0);
954 break;
955 case SEND_RESULT:
956 handleSendResult((ResultData)msg.obj);
957 break;
958 case DESTROY_ACTIVITY:
959 handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
960 msg.arg2, false);
961 break;
962 case BIND_APPLICATION:
963 AppBindData data = (AppBindData)msg.obj;
964 handleBindApplication(data);
965 break;
966 case EXIT_APPLICATION:
967 if (mInitialApplication != null) {
968 mInitialApplication.onTerminate();
969 }
970 Looper.myLooper().quit();
971 break;
972 case NEW_INTENT:
973 handleNewIntent((NewIntentData)msg.obj);
974 break;
975 case RECEIVER:
976 handleReceiver((ReceiverData)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -0700977 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 break;
979 case CREATE_SERVICE:
980 handleCreateService((CreateServiceData)msg.obj);
981 break;
982 case BIND_SERVICE:
983 handleBindService((BindServiceData)msg.obj);
984 break;
985 case UNBIND_SERVICE:
986 handleUnbindService((BindServiceData)msg.obj);
987 break;
988 case SERVICE_ARGS:
989 handleServiceArgs((ServiceArgsData)msg.obj);
990 break;
991 case STOP_SERVICE:
992 handleStopService((IBinder)msg.obj);
Bob Leee5408332009-09-04 18:31:17 -0700993 maybeSnapshot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 break;
995 case REQUEST_THUMBNAIL:
996 handleRequestThumbnail((IBinder)msg.obj);
997 break;
998 case CONFIGURATION_CHANGED:
999 handleConfigurationChanged((Configuration)msg.obj);
1000 break;
1001 case CLEAN_UP_CONTEXT:
1002 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1003 cci.context.performFinalCleanup(cci.who, cci.what);
1004 break;
1005 case GC_WHEN_IDLE:
1006 scheduleGcIdler();
1007 break;
1008 case DUMP_SERVICE:
1009 handleDumpService((DumpServiceInfo)msg.obj);
1010 break;
1011 case LOW_MEMORY:
1012 handleLowMemory();
1013 break;
1014 case ACTIVITY_CONFIGURATION_CHANGED:
1015 handleActivityConfigurationChanged((IBinder)msg.obj);
1016 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001017 case PROFILER_CONTROL:
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07001018 handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001019 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001020 case CREATE_BACKUP_AGENT:
1021 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
1022 break;
1023 case DESTROY_BACKUP_AGENT:
1024 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
1025 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001026 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001027 Process.killProcess(Process.myPid());
1028 break;
1029 case REMOVE_PROVIDER:
1030 completeRemoveProvider((IContentProvider)msg.obj);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001031 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001032 case ENABLE_JIT:
1033 ensureJitEnabled();
1034 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001035 case DISPATCH_PACKAGE_BROADCAST:
1036 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
1037 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001038 case SCHEDULE_CRASH:
1039 throw new RemoteServiceException((String)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 }
1041 }
Bob Leee5408332009-09-04 18:31:17 -07001042
1043 void maybeSnapshot() {
1044 if (mBoundApplication != null) {
1045 SamplingProfilerIntegration.writeSnapshot(
1046 mBoundApplication.processName);
1047 }
1048 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 }
1050
1051 private final class Idler implements MessageQueue.IdleHandler {
1052 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001053 ActivityClientRecord a = mNewActivities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 if (a != null) {
1055 mNewActivities = null;
1056 IActivityManager am = ActivityManagerNative.getDefault();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001057 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001059 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 TAG, "Reporting idle of " + a +
1061 " finished=" +
1062 (a.activity != null ? a.activity.mFinished : false));
1063 if (a.activity != null && !a.activity.mFinished) {
1064 try {
Dianne Hackborne88846e2009-09-30 21:34:25 -07001065 am.activityIdle(a.token, a.createdConfig);
1066 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 } catch (RemoteException ex) {
1068 }
1069 }
1070 prev = a;
1071 a = a.nextIdle;
1072 prev.nextIdle = null;
1073 } while (a != null);
1074 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001075 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 return false;
1077 }
1078 }
1079
1080 final class GcIdler implements MessageQueue.IdleHandler {
1081 public final boolean queueIdle() {
1082 doGcIfNeeded();
1083 return false;
1084 }
1085 }
1086
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001087 private final static class ResourcesKey {
1088 final private String mResDir;
1089 final private float mScale;
1090 final private int mHash;
Bob Leee5408332009-09-04 18:31:17 -07001091
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001092 ResourcesKey(String resDir, float scale) {
1093 mResDir = resDir;
1094 mScale = scale;
1095 mHash = mResDir.hashCode() << 2 + (int) (mScale * 2);
1096 }
Bob Leee5408332009-09-04 18:31:17 -07001097
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07001098 @Override
1099 public int hashCode() {
1100 return mHash;
1101 }
1102
1103 @Override
1104 public boolean equals(Object obj) {
1105 if (!(obj instanceof ResourcesKey)) {
1106 return false;
1107 }
1108 ResourcesKey peer = (ResourcesKey) obj;
1109 return mResDir.equals(peer.mResDir) && mScale == peer.mScale;
1110 }
1111 }
1112
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001113 public static final ActivityThread currentActivityThread() {
1114 return (ActivityThread)sThreadLocal.get();
1115 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001117 public static final String currentPackageName() {
1118 ActivityThread am = currentActivityThread();
1119 return (am != null && am.mBoundApplication != null)
1120 ? am.mBoundApplication.processName : null;
1121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001123 public static final Application currentApplication() {
1124 ActivityThread am = currentActivityThread();
1125 return am != null ? am.mInitialApplication : null;
1126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001128 public static IPackageManager getPackageManager() {
1129 if (sPackageManager != null) {
1130 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1131 return sPackageManager;
1132 }
1133 IBinder b = ServiceManager.getService("package");
1134 //Slog.v("PackageManager", "default service binder = " + b);
1135 sPackageManager = IPackageManager.Stub.asInterface(b);
1136 //Slog.v("PackageManager", "default service = " + sPackageManager);
1137 return sPackageManager;
1138 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001140 DisplayMetrics getDisplayMetricsLocked(boolean forceUpdate) {
1141 if (mDisplayMetrics != null && !forceUpdate) {
1142 return mDisplayMetrics;
1143 }
1144 if (mDisplay == null) {
1145 WindowManager wm = WindowManagerImpl.getDefault();
1146 mDisplay = wm.getDefaultDisplay();
1147 }
1148 DisplayMetrics metrics = mDisplayMetrics = new DisplayMetrics();
1149 mDisplay.getMetrics(metrics);
1150 //Slog.i("foo", "New metrics: w=" + metrics.widthPixels + " h="
1151 // + metrics.heightPixels + " den=" + metrics.density
1152 // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi);
1153 return metrics;
1154 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001156 /**
1157 * Creates the top level Resources for applications with the given compatibility info.
1158 *
1159 * @param resDir the resource directory.
1160 * @param compInfo the compability info. It will use the default compatibility info when it's
1161 * null.
1162 */
1163 Resources getTopLevelResources(String resDir, CompatibilityInfo compInfo) {
1164 ResourcesKey key = new ResourcesKey(resDir, compInfo.applicationScale);
1165 Resources r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001167 // Resources is app scale dependent.
1168 if (false) {
1169 Slog.w(TAG, "getTopLevelResources: " + resDir + " / "
1170 + compInfo.applicationScale);
1171 }
1172 WeakReference<Resources> wr = mActiveResources.get(key);
1173 r = wr != null ? wr.get() : null;
1174 //if (r != null) Slog.i(TAG, "isUpToDate " + resDir + ": " + r.getAssets().isUpToDate());
1175 if (r != null && r.getAssets().isUpToDate()) {
1176 if (false) {
1177 Slog.w(TAG, "Returning cached resources " + r + " " + resDir
1178 + ": appScale=" + r.getCompatibilityInfo().applicationScale);
1179 }
1180 return r;
1181 }
1182 }
1183
1184 //if (r != null) {
1185 // Slog.w(TAG, "Throwing away out-of-date resources!!!! "
1186 // + r + " " + resDir);
1187 //}
1188
1189 AssetManager assets = new AssetManager();
1190 if (assets.addAssetPath(resDir) == 0) {
1191 return null;
1192 }
1193
1194 //Slog.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
1195 DisplayMetrics metrics = getDisplayMetricsLocked(false);
1196 r = new Resources(assets, metrics, getConfiguration(), compInfo);
1197 if (false) {
1198 Slog.i(TAG, "Created app resources " + resDir + " " + r + ": "
1199 + r.getConfiguration() + " appScale="
1200 + r.getCompatibilityInfo().applicationScale);
1201 }
1202
1203 synchronized (mPackages) {
1204 WeakReference<Resources> wr = mActiveResources.get(key);
1205 Resources existing = wr != null ? wr.get() : null;
1206 if (existing != null && existing.getAssets().isUpToDate()) {
1207 // Someone else already created the resources while we were
1208 // unlocked; go ahead and use theirs.
1209 r.getAssets().close();
1210 return existing;
1211 }
1212
1213 // XXX need to remove entries when weak references go away
1214 mActiveResources.put(key, new WeakReference<Resources>(r));
1215 return r;
1216 }
1217 }
1218
1219 /**
1220 * Creates the top level resources for the given package.
1221 */
1222 Resources getTopLevelResources(String resDir, LoadedApk pkgInfo) {
1223 return getTopLevelResources(resDir, pkgInfo.mCompatibilityInfo);
1224 }
1225
1226 final Handler getHandler() {
1227 return mH;
1228 }
1229
1230 public final LoadedApk getPackageInfo(String packageName, int flags) {
1231 synchronized (mPackages) {
1232 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
1234 ref = mPackages.get(packageName);
1235 } else {
1236 ref = mResourcePackages.get(packageName);
1237 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001238 LoadedApk packageInfo = ref != null ? ref.get() : null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001239 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001240 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
1241 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242 if (packageInfo != null && (packageInfo.mResources == null
1243 || packageInfo.mResources.getAssets().isUpToDate())) {
1244 if (packageInfo.isSecurityViolation()
1245 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
1246 throw new SecurityException(
1247 "Requesting code from " + packageName
1248 + " to be run in process "
1249 + mBoundApplication.processName
1250 + "/" + mBoundApplication.appInfo.uid);
1251 }
1252 return packageInfo;
1253 }
1254 }
1255
1256 ApplicationInfo ai = null;
1257 try {
1258 ai = getPackageManager().getApplicationInfo(packageName,
1259 PackageManager.GET_SHARED_LIBRARY_FILES);
1260 } catch (RemoteException e) {
1261 }
1262
1263 if (ai != null) {
1264 return getPackageInfo(ai, flags);
1265 }
1266
1267 return null;
1268 }
1269
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001270 public final LoadedApk getPackageInfo(ApplicationInfo ai, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
1272 boolean securityViolation = includeCode && ai.uid != 0
1273 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
1274 ? ai.uid != mBoundApplication.appInfo.uid : true);
1275 if ((flags&(Context.CONTEXT_INCLUDE_CODE
1276 |Context.CONTEXT_IGNORE_SECURITY))
1277 == Context.CONTEXT_INCLUDE_CODE) {
1278 if (securityViolation) {
1279 String msg = "Requesting code from " + ai.packageName
1280 + " (with uid " + ai.uid + ")";
1281 if (mBoundApplication != null) {
1282 msg = msg + " to be run in process "
1283 + mBoundApplication.processName + " (with uid "
1284 + mBoundApplication.appInfo.uid + ")";
1285 }
1286 throw new SecurityException(msg);
1287 }
1288 }
1289 return getPackageInfo(ai, null, securityViolation, includeCode);
1290 }
1291
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001292 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 return getPackageInfo(ai, null, false, true);
1294 }
1295
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001296 private final LoadedApk getPackageInfo(ApplicationInfo aInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 ClassLoader baseLoader, boolean securityViolation, boolean includeCode) {
1298 synchronized (mPackages) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001299 WeakReference<LoadedApk> ref;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 if (includeCode) {
1301 ref = mPackages.get(aInfo.packageName);
1302 } else {
1303 ref = mResourcePackages.get(aInfo.packageName);
1304 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001305 LoadedApk packageInfo = ref != null ? ref.get() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 if (packageInfo == null || (packageInfo.mResources != null
1307 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001308 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309 : "Loading resource-only package ") + aInfo.packageName
1310 + " (in " + (mBoundApplication != null
1311 ? mBoundApplication.processName : null)
1312 + ")");
1313 packageInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001314 new LoadedApk(this, aInfo, this, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 securityViolation, includeCode &&
1316 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0);
1317 if (includeCode) {
1318 mPackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001319 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 } else {
1321 mResourcePackages.put(aInfo.packageName,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001322 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 }
1324 }
1325 return packageInfo;
1326 }
1327 }
1328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 ActivityThread() {
1330 }
1331
1332 public ApplicationThread getApplicationThread()
1333 {
1334 return mAppThread;
1335 }
1336
1337 public Instrumentation getInstrumentation()
1338 {
1339 return mInstrumentation;
1340 }
1341
1342 public Configuration getConfiguration() {
1343 return mConfiguration;
1344 }
1345
1346 public boolean isProfiling() {
1347 return mBoundApplication != null && mBoundApplication.profileFile != null;
1348 }
1349
1350 public String getProfileFilePath() {
1351 return mBoundApplication.profileFile;
1352 }
1353
1354 public Looper getLooper() {
1355 return mLooper;
1356 }
1357
1358 public Application getApplication() {
1359 return mInitialApplication;
1360 }
Bob Leee5408332009-09-04 18:31:17 -07001361
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07001362 public String getProcessName() {
1363 return mBoundApplication.processName;
1364 }
Bob Leee5408332009-09-04 18:31:17 -07001365
Dianne Hackborn21556372010-02-04 16:34:40 -08001366 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 synchronized (this) {
1368 if (mSystemContext == null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001369 ContextImpl context =
1370 ContextImpl.createSystemContext(this);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001371 LoadedApk info = new LoadedApk(this, "android", context, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 context.init(info, null, this);
1373 context.getResources().updateConfiguration(
1374 getConfiguration(), getDisplayMetricsLocked(false));
1375 mSystemContext = context;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001376 //Slog.i(TAG, "Created system resources " + context.getResources()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 // + ": " + context.getResources().getConfiguration());
1378 }
1379 }
1380 return mSystemContext;
1381 }
1382
Mike Cleron432b7132009-09-24 15:28:29 -07001383 public void installSystemApplicationInfo(ApplicationInfo info) {
1384 synchronized (this) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001385 ContextImpl context = getSystemContext();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001386 context.init(new LoadedApk(this, "android", context, info), null, this);
Mike Cleron432b7132009-09-24 15:28:29 -07001387 }
1388 }
1389
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001390 void ensureJitEnabled() {
1391 if (!mJitEnabled) {
1392 mJitEnabled = true;
1393 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
1394 }
1395 }
1396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 void scheduleGcIdler() {
1398 if (!mGcIdlerScheduled) {
1399 mGcIdlerScheduled = true;
1400 Looper.myQueue().addIdleHandler(mGcIdler);
1401 }
1402 mH.removeMessages(H.GC_WHEN_IDLE);
1403 }
1404
1405 void unscheduleGcIdler() {
1406 if (mGcIdlerScheduled) {
1407 mGcIdlerScheduled = false;
1408 Looper.myQueue().removeIdleHandler(mGcIdler);
1409 }
1410 mH.removeMessages(H.GC_WHEN_IDLE);
1411 }
1412
1413 void doGcIfNeeded() {
1414 mGcIdlerScheduled = false;
1415 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001416 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 // + "m now=" + now);
1418 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001419 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 BinderInternal.forceGc("bg");
1421 }
1422 }
1423
1424 public final ActivityInfo resolveActivityInfo(Intent intent) {
1425 ActivityInfo aInfo = intent.resolveActivityInfo(
1426 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
1427 if (aInfo == null) {
1428 // Throw an exception.
1429 Instrumentation.checkStartActivityResult(
1430 IActivityManager.START_CLASS_NOT_FOUND, intent);
1431 }
1432 return aInfo;
1433 }
Bob Leee5408332009-09-04 18:31:17 -07001434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
1437 Object lastNonConfigurationInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001438 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001440 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 r.intent = intent;
1442 r.state = state;
1443 r.parent = parent;
1444 r.embeddedID = id;
1445 r.activityInfo = activityInfo;
1446 r.lastNonConfigurationInstance = lastNonConfigurationInstance;
1447 if (localLOGV) {
1448 ComponentName compname = intent.getComponent();
1449 String name;
1450 if (compname != null) {
1451 name = compname.toShortString();
1452 } else {
1453 name = "(Intent " + intent + ").getComponent() returned null";
1454 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001455 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 + ", comp=" + name
1457 + ", token=" + token);
1458 }
Christopher Tateb70f3df2009-04-07 16:07:59 -07001459 return performLaunchActivity(r, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 }
1461
1462 public final Activity getActivity(IBinder token) {
1463 return mActivities.get(token).activity;
1464 }
1465
1466 public final void sendActivityResult(
1467 IBinder token, String id, int requestCode,
1468 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001469 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07001470 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
1472 list.add(new ResultInfo(id, requestCode, resultCode, data));
1473 mAppThread.scheduleSendResult(token, list);
1474 }
1475
1476 // if the thread hasn't started yet, we don't have the handler, so just
1477 // save the messages until we're ready.
1478 private final void queueOrSendMessage(int what, Object obj) {
1479 queueOrSendMessage(what, obj, 0, 0);
1480 }
1481
1482 private final void queueOrSendMessage(int what, Object obj, int arg1) {
1483 queueOrSendMessage(what, obj, arg1, 0);
1484 }
1485
1486 private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
1487 synchronized (this) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001488 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
1490 + ": " + arg1 + " / " + obj);
1491 Message msg = Message.obtain();
1492 msg.what = what;
1493 msg.obj = obj;
1494 msg.arg1 = arg1;
1495 msg.arg2 = arg2;
1496 mH.sendMessage(msg);
1497 }
1498 }
1499
Dianne Hackborn21556372010-02-04 16:34:40 -08001500 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 String what) {
1502 ContextCleanupInfo cci = new ContextCleanupInfo();
1503 cci.context = context;
1504 cci.who = who;
1505 cci.what = what;
1506 queueOrSendMessage(H.CLEAN_UP_CONTEXT, cci);
1507 }
1508
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001509 private final Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
1511
1512 ActivityInfo aInfo = r.activityInfo;
1513 if (r.packageInfo == null) {
1514 r.packageInfo = getPackageInfo(aInfo.applicationInfo,
1515 Context.CONTEXT_INCLUDE_CODE);
1516 }
Bob Leee5408332009-09-04 18:31:17 -07001517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 ComponentName component = r.intent.getComponent();
1519 if (component == null) {
1520 component = r.intent.resolveActivity(
1521 mInitialApplication.getPackageManager());
1522 r.intent.setComponent(component);
1523 }
1524
1525 if (r.activityInfo.targetActivity != null) {
1526 component = new ComponentName(r.activityInfo.packageName,
1527 r.activityInfo.targetActivity);
1528 }
1529
1530 Activity activity = null;
1531 try {
1532 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
1533 activity = mInstrumentation.newActivity(
1534 cl, component.getClassName(), r.intent);
1535 r.intent.setExtrasClassLoader(cl);
1536 if (r.state != null) {
1537 r.state.setClassLoader(cl);
1538 }
1539 } catch (Exception e) {
1540 if (!mInstrumentation.onException(activity, e)) {
1541 throw new RuntimeException(
1542 "Unable to instantiate activity " + component
1543 + ": " + e.toString(), e);
1544 }
1545 }
1546
1547 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001548 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001549
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001550 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
1551 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 TAG, r + ": app=" + app
1553 + ", appName=" + app.getPackageName()
1554 + ", pkg=" + r.packageInfo.getPackageName()
1555 + ", comp=" + r.intent.getComponent().toShortString()
1556 + ", dir=" + r.packageInfo.getAppDir());
1557
1558 if (activity != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08001559 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 appContext.init(r.packageInfo, r.token, this);
1561 appContext.setOuterContext(activity);
1562 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
1563 Configuration config = new Configuration(mConfiguration);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001564 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07001565 + r.activityInfo.name + " with config " + config);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07001566 activity.attach(appContext, this, getInstrumentation(), r.token,
1567 r.ident, app, r.intent, r.activityInfo, title, r.parent,
1568 r.embeddedID, r.lastNonConfigurationInstance,
1569 r.lastNonConfigurationChildInstances, config);
Bob Leee5408332009-09-04 18:31:17 -07001570
Christopher Tateb70f3df2009-04-07 16:07:59 -07001571 if (customIntent != null) {
1572 activity.mIntent = customIntent;
1573 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 r.lastNonConfigurationInstance = null;
1575 r.lastNonConfigurationChildInstances = null;
1576 activity.mStartedActivity = false;
1577 int theme = r.activityInfo.getThemeResource();
1578 if (theme != 0) {
1579 activity.setTheme(theme);
1580 }
1581
1582 activity.mCalled = false;
1583 mInstrumentation.callActivityOnCreate(activity, r.state);
1584 if (!activity.mCalled) {
1585 throw new SuperNotCalledException(
1586 "Activity " + r.intent.getComponent().toShortString() +
1587 " did not call through to super.onCreate()");
1588 }
1589 r.activity = activity;
1590 r.stopped = true;
1591 if (!r.activity.mFinished) {
1592 activity.performStart();
1593 r.stopped = false;
1594 }
1595 if (!r.activity.mFinished) {
1596 if (r.state != null) {
1597 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
1598 }
1599 }
1600 if (!r.activity.mFinished) {
1601 activity.mCalled = false;
1602 mInstrumentation.callActivityOnPostCreate(activity, r.state);
1603 if (!activity.mCalled) {
1604 throw new SuperNotCalledException(
1605 "Activity " + r.intent.getComponent().toShortString() +
1606 " did not call through to super.onPostCreate()");
1607 }
1608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 }
1610 r.paused = true;
1611
1612 mActivities.put(r.token, r);
1613
1614 } catch (SuperNotCalledException e) {
1615 throw e;
1616
1617 } catch (Exception e) {
1618 if (!mInstrumentation.onException(activity, e)) {
1619 throw new RuntimeException(
1620 "Unable to start activity " + component
1621 + ": " + e.toString(), e);
1622 }
1623 }
1624
1625 return activity;
1626 }
1627
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001628 private final void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 // If we are getting ready to gc after going to the background, well
1630 // we are back active so skip it.
1631 unscheduleGcIdler();
1632
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001633 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 TAG, "Handling launch of " + r);
Christopher Tateb70f3df2009-04-07 16:07:59 -07001635 Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636
1637 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08001638 r.createdConfig = new Configuration(mConfiguration);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001639 Bundle oldState = r.state;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 handleResumeActivity(r.token, false, r.isForward);
1641
1642 if (!r.activity.mFinished && r.startsNotResumed) {
1643 // The activity manager actually wants this one to start out
1644 // paused, because it needs to be visible but isn't in the
1645 // foreground. We accomplish this by going through the
1646 // normal startup (because activities expect to go through
1647 // onResume() the first time they run, before their window
1648 // is displayed), and then pausing it. However, in this case
1649 // we do -not- need to do the full pause cycle (of freezing
1650 // and such) because the activity manager assumes it can just
1651 // retain the current state it has.
1652 try {
1653 r.activity.mCalled = false;
1654 mInstrumentation.callActivityOnPause(r.activity);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001655 // We need to keep around the original state, in case
1656 // we need to be created again.
1657 r.state = oldState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 if (!r.activity.mCalled) {
1659 throw new SuperNotCalledException(
1660 "Activity " + r.intent.getComponent().toShortString() +
1661 " did not call through to super.onPause()");
1662 }
1663
1664 } catch (SuperNotCalledException e) {
1665 throw e;
1666
1667 } catch (Exception e) {
1668 if (!mInstrumentation.onException(r.activity, e)) {
1669 throw new RuntimeException(
1670 "Unable to pause activity "
1671 + r.intent.getComponent().toShortString()
1672 + ": " + e.toString(), e);
1673 }
1674 }
1675 r.paused = true;
1676 }
1677 } else {
1678 // If there was an error, for any reason, tell the activity
1679 // manager to stop us.
1680 try {
1681 ActivityManagerNative.getDefault()
1682 .finishActivity(r.token, Activity.RESULT_CANCELED, null);
1683 } catch (RemoteException ex) {
1684 }
1685 }
1686 }
1687
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001688 private final void deliverNewIntents(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 List<Intent> intents) {
1690 final int N = intents.size();
1691 for (int i=0; i<N; i++) {
1692 Intent intent = intents.get(i);
1693 intent.setExtrasClassLoader(r.activity.getClassLoader());
1694 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
1695 }
1696 }
1697
1698 public final void performNewIntents(IBinder token,
1699 List<Intent> intents) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001700 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 if (r != null) {
1702 final boolean resumed = !r.paused;
1703 if (resumed) {
1704 mInstrumentation.callActivityOnPause(r.activity);
1705 }
1706 deliverNewIntents(r, intents);
1707 if (resumed) {
1708 mInstrumentation.callActivityOnResume(r.activity);
1709 }
1710 }
1711 }
Bob Leee5408332009-09-04 18:31:17 -07001712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 private final void handleNewIntent(NewIntentData data) {
1714 performNewIntents(data.token, data.intents);
1715 }
1716
1717 private final void handleReceiver(ReceiverData data) {
1718 // If we are getting ready to gc after going to the background, well
1719 // we are back active so skip it.
1720 unscheduleGcIdler();
1721
1722 String component = data.intent.getComponent().getClassName();
1723
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001724 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 data.info.applicationInfo);
1726
1727 IActivityManager mgr = ActivityManagerNative.getDefault();
1728
1729 BroadcastReceiver receiver = null;
1730 try {
1731 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1732 data.intent.setExtrasClassLoader(cl);
1733 if (data.resultExtras != null) {
1734 data.resultExtras.setClassLoader(cl);
1735 }
1736 receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
1737 } catch (Exception e) {
1738 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001739 if (DEBUG_BROADCAST) Slog.i(TAG,
1740 "Finishing failed broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
1742 data.resultData, data.resultExtras, data.resultAbort);
1743 } catch (RemoteException ex) {
1744 }
1745 throw new RuntimeException(
1746 "Unable to instantiate receiver " + component
1747 + ": " + e.toString(), e);
1748 }
1749
1750 try {
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001751 Application app = packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07001752
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001753 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 TAG, "Performing receive of " + data.intent
1755 + ": app=" + app
1756 + ", appName=" + app.getPackageName()
1757 + ", pkg=" + packageInfo.getPackageName()
1758 + ", comp=" + data.intent.getComponent().toShortString()
1759 + ", dir=" + packageInfo.getAppDir());
1760
Dianne Hackborn21556372010-02-04 16:34:40 -08001761 ContextImpl context = (ContextImpl)app.getBaseContext();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 receiver.setOrderedHint(true);
1763 receiver.setResult(data.resultCode, data.resultData,
1764 data.resultExtras);
1765 receiver.setOrderedHint(data.sync);
1766 receiver.onReceive(context.getReceiverRestrictedContext(),
1767 data.intent);
1768 } catch (Exception e) {
1769 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001770 if (DEBUG_BROADCAST) Slog.i(TAG,
1771 "Finishing failed broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 mgr.finishReceiver(mAppThread.asBinder(), data.resultCode,
1773 data.resultData, data.resultExtras, data.resultAbort);
1774 } catch (RemoteException ex) {
1775 }
1776 if (!mInstrumentation.onException(receiver, e)) {
1777 throw new RuntimeException(
1778 "Unable to start receiver " + component
1779 + ": " + e.toString(), e);
1780 }
1781 }
1782
1783 try {
1784 if (data.sync) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001785 if (DEBUG_BROADCAST) Slog.i(TAG,
1786 "Finishing ordered broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 mgr.finishReceiver(
1788 mAppThread.asBinder(), receiver.getResultCode(),
1789 receiver.getResultData(), receiver.getResultExtras(false),
1790 receiver.getAbortBroadcast());
1791 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001792 if (DEBUG_BROADCAST) Slog.i(TAG,
1793 "Finishing broadcast to " + data.intent.getComponent());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 mgr.finishReceiver(mAppThread.asBinder(), 0, null, null, false);
1795 }
1796 } catch (RemoteException ex) {
1797 }
1798 }
1799
Christopher Tate181fafa2009-05-14 11:12:14 -07001800 // Instantiate a BackupAgent and tell it that it's alive
1801 private final void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001802 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001803
1804 // no longer idle; we have backup work to do
1805 unscheduleGcIdler();
1806
1807 // instantiate the BackupAgent class named in the manifest
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001808 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001809 String packageName = packageInfo.mPackageName;
1810 if (mBackupAgents.get(packageName) != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001811 Slog.d(TAG, "BackupAgent " + " for " + packageName
Christopher Tate181fafa2009-05-14 11:12:14 -07001812 + " already exists");
1813 return;
1814 }
Bob Leee5408332009-09-04 18:31:17 -07001815
Christopher Tate181fafa2009-05-14 11:12:14 -07001816 BackupAgent agent = null;
1817 String classname = data.appInfo.backupAgentName;
1818 if (classname == null) {
1819 if (data.backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001820 Slog.e(TAG, "Attempted incremental backup but no defined agent for "
Christopher Tate181fafa2009-05-14 11:12:14 -07001821 + packageName);
1822 return;
1823 }
1824 classname = "android.app.FullBackupAgent";
1825 }
1826 try {
Christopher Tated1475e02009-07-09 15:36:17 -07001827 IBinder binder = null;
1828 try {
1829 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1830 agent = (BackupAgent) cl.loadClass(data.appInfo.backupAgentName).newInstance();
1831
1832 // set up the agent's context
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001833 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing BackupAgent "
Christopher Tated1475e02009-07-09 15:36:17 -07001834 + data.appInfo.backupAgentName);
1835
Dianne Hackborn21556372010-02-04 16:34:40 -08001836 ContextImpl context = new ContextImpl();
Christopher Tated1475e02009-07-09 15:36:17 -07001837 context.init(packageInfo, null, this);
1838 context.setOuterContext(agent);
1839 agent.attach(context);
1840
1841 agent.onCreate();
1842 binder = agent.onBind();
1843 mBackupAgents.put(packageName, agent);
1844 } catch (Exception e) {
1845 // If this is during restore, fail silently; otherwise go
1846 // ahead and let the user see the crash.
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001847 Slog.e(TAG, "Agent threw during creation: " + e);
Christopher Tated1475e02009-07-09 15:36:17 -07001848 if (data.backupMode != IApplicationThread.BACKUP_MODE_RESTORE) {
1849 throw e;
1850 }
1851 // falling through with 'binder' still null
1852 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001853
1854 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07001855 try {
1856 ActivityManagerNative.getDefault().backupAgentCreated(packageName, binder);
1857 } catch (RemoteException e) {
1858 // nothing to do.
1859 }
Christopher Tate181fafa2009-05-14 11:12:14 -07001860 } catch (Exception e) {
1861 throw new RuntimeException("Unable to create BackupAgent "
1862 + data.appInfo.backupAgentName + ": " + e.toString(), e);
1863 }
1864 }
1865
1866 // Tear down a BackupAgent
1867 private final void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001868 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07001869
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001870 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001871 String packageName = packageInfo.mPackageName;
1872 BackupAgent agent = mBackupAgents.get(packageName);
1873 if (agent != null) {
1874 try {
1875 agent.onDestroy();
1876 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001877 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07001878 e.printStackTrace();
1879 }
1880 mBackupAgents.remove(packageName);
1881 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001882 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07001883 }
1884 }
1885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 private final void handleCreateService(CreateServiceData data) {
1887 // If we are getting ready to gc after going to the background, well
1888 // we are back active so skip it.
1889 unscheduleGcIdler();
1890
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001891 LoadedApk packageInfo = getPackageInfoNoCheck(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 data.info.applicationInfo);
1893 Service service = null;
1894 try {
1895 java.lang.ClassLoader cl = packageInfo.getClassLoader();
1896 service = (Service) cl.loadClass(data.info.name).newInstance();
1897 } catch (Exception e) {
1898 if (!mInstrumentation.onException(service, e)) {
1899 throw new RuntimeException(
1900 "Unable to instantiate service " + data.info.name
1901 + ": " + e.toString(), e);
1902 }
1903 }
1904
1905 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001906 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907
Dianne Hackborn21556372010-02-04 16:34:40 -08001908 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 context.init(packageInfo, null, this);
1910
Dianne Hackborn0be1f782009-11-09 12:30:12 -08001911 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912 context.setOuterContext(service);
1913 service.attach(context, this, data.info.name, data.token, app,
1914 ActivityManagerNative.getDefault());
1915 service.onCreate();
1916 mServices.put(data.token, service);
1917 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001918 ActivityManagerNative.getDefault().serviceDoneExecuting(
1919 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 } catch (RemoteException e) {
1921 // nothing to do.
1922 }
1923 } catch (Exception e) {
1924 if (!mInstrumentation.onException(service, e)) {
1925 throw new RuntimeException(
1926 "Unable to create service " + data.info.name
1927 + ": " + e.toString(), e);
1928 }
1929 }
1930 }
1931
1932 private final void handleBindService(BindServiceData data) {
1933 Service s = mServices.get(data.token);
1934 if (s != null) {
1935 try {
1936 data.intent.setExtrasClassLoader(s.getClassLoader());
1937 try {
1938 if (!data.rebind) {
1939 IBinder binder = s.onBind(data.intent);
1940 ActivityManagerNative.getDefault().publishService(
1941 data.token, data.intent, binder);
1942 } else {
1943 s.onRebind(data.intent);
1944 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001945 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001947 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 } catch (RemoteException ex) {
1949 }
1950 } catch (Exception e) {
1951 if (!mInstrumentation.onException(s, e)) {
1952 throw new RuntimeException(
1953 "Unable to bind to service " + s
1954 + " with " + data.intent + ": " + e.toString(), e);
1955 }
1956 }
1957 }
1958 }
1959
1960 private final void handleUnbindService(BindServiceData data) {
1961 Service s = mServices.get(data.token);
1962 if (s != null) {
1963 try {
1964 data.intent.setExtrasClassLoader(s.getClassLoader());
1965 boolean doRebind = s.onUnbind(data.intent);
1966 try {
1967 if (doRebind) {
1968 ActivityManagerNative.getDefault().unbindFinished(
1969 data.token, data.intent, doRebind);
1970 } else {
1971 ActivityManagerNative.getDefault().serviceDoneExecuting(
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07001972 data.token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 }
1974 } catch (RemoteException ex) {
1975 }
1976 } catch (Exception e) {
1977 if (!mInstrumentation.onException(s, e)) {
1978 throw new RuntimeException(
1979 "Unable to unbind to service " + s
1980 + " with " + data.intent + ": " + e.toString(), e);
1981 }
1982 }
1983 }
1984 }
1985
1986 private void handleDumpService(DumpServiceInfo info) {
1987 try {
1988 Service s = mServices.get(info.service);
1989 if (s != null) {
1990 PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd));
1991 s.dump(info.fd, pw, info.args);
1992 pw.close();
1993 }
1994 } finally {
1995 synchronized (info) {
1996 info.dumped = true;
1997 info.notifyAll();
1998 }
1999 }
2000 }
2001
2002 private final void handleServiceArgs(ServiceArgsData data) {
2003 Service s = mServices.get(data.token);
2004 if (s != null) {
2005 try {
2006 if (data.args != null) {
2007 data.args.setExtrasClassLoader(s.getClassLoader());
2008 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002009 int res = s.onStartCommand(data.args, data.flags, data.startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002011 ActivityManagerNative.getDefault().serviceDoneExecuting(
2012 data.token, 1, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 } catch (RemoteException e) {
2014 // nothing to do.
2015 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002016 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 } catch (Exception e) {
2018 if (!mInstrumentation.onException(s, e)) {
2019 throw new RuntimeException(
2020 "Unable to start service " + s
2021 + " with " + data.args + ": " + e.toString(), e);
2022 }
2023 }
2024 }
2025 }
2026
2027 private final void handleStopService(IBinder token) {
2028 Service s = mServices.remove(token);
2029 if (s != null) {
2030 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002031 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 s.onDestroy();
2033 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002034 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08002036 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002037 }
2038 try {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -07002039 ActivityManagerNative.getDefault().serviceDoneExecuting(
2040 token, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 } catch (RemoteException e) {
2042 // nothing to do.
2043 }
2044 } catch (Exception e) {
2045 if (!mInstrumentation.onException(s, e)) {
2046 throw new RuntimeException(
2047 "Unable to stop service " + s
2048 + ": " + e.toString(), e);
2049 }
2050 }
2051 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002052 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 }
2054
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002055 public final ActivityClientRecord performResumeActivity(IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 boolean clearHide) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002057 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002058 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 + " finished=" + r.activity.mFinished);
2060 if (r != null && !r.activity.mFinished) {
2061 if (clearHide) {
2062 r.hideForNow = false;
2063 r.activity.mStartedActivity = false;
2064 }
2065 try {
2066 if (r.pendingIntents != null) {
2067 deliverNewIntents(r, r.pendingIntents);
2068 r.pendingIntents = null;
2069 }
2070 if (r.pendingResults != null) {
2071 deliverResults(r, r.pendingResults);
2072 r.pendingResults = null;
2073 }
2074 r.activity.performResume();
2075
Bob Leee5408332009-09-04 18:31:17 -07002076 EventLog.writeEvent(LOG_ON_RESUME_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 r.activity.getComponentName().getClassName());
Bob Leee5408332009-09-04 18:31:17 -07002078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 r.paused = false;
2080 r.stopped = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 r.state = null;
2082 } catch (Exception e) {
2083 if (!mInstrumentation.onException(r.activity, e)) {
2084 throw new RuntimeException(
2085 "Unable to resume activity "
2086 + r.intent.getComponent().toShortString()
2087 + ": " + e.toString(), e);
2088 }
2089 }
2090 }
2091 return r;
2092 }
2093
2094 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
2095 // If we are getting ready to gc after going to the background, well
2096 // we are back active so skip it.
2097 unscheduleGcIdler();
2098
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002099 ActivityClientRecord r = performResumeActivity(token, clearHide);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002100
2101 if (r != null) {
2102 final Activity a = r.activity;
2103
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002104 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 TAG, "Resume " + r + " started activity: " +
2106 a.mStartedActivity + ", hideForNow: " + r.hideForNow
2107 + ", finished: " + a.mFinished);
2108
2109 final int forwardBit = isForward ?
2110 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07002111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002112 // If the window hasn't yet been added to the window manager,
2113 // and this guy didn't finish itself or start another activity,
2114 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002115 boolean willBeVisible = !a.mStartedActivity;
2116 if (!willBeVisible) {
2117 try {
2118 willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
2119 a.getActivityToken());
2120 } catch (RemoteException e) {
2121 }
2122 }
2123 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 r.window = r.activity.getWindow();
2125 View decor = r.window.getDecorView();
2126 decor.setVisibility(View.INVISIBLE);
2127 ViewManager wm = a.getWindowManager();
2128 WindowManager.LayoutParams l = r.window.getAttributes();
2129 a.mDecor = decor;
2130 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
2131 l.softInputMode |= forwardBit;
2132 if (a.mVisibleFromClient) {
2133 a.mWindowAdded = true;
2134 wm.addView(decor, l);
2135 }
2136
2137 // If the window has already been added, but during resume
2138 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002139 // window visible.
2140 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002141 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002142 TAG, "Launch " + r + " mStartedActivity set");
2143 r.hideForNow = true;
2144 }
2145
2146 // The window is now visible if it has been added, we are not
2147 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002148 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002149 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002150 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002151 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002152 + r.activityInfo.name + " with newConfig " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002153 performConfigurationChanged(r.activity, r.newConfig);
2154 r.newConfig = null;
2155 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002156 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157 + isForward);
2158 WindowManager.LayoutParams l = r.window.getAttributes();
2159 if ((l.softInputMode
2160 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
2161 != forwardBit) {
2162 l.softInputMode = (l.softInputMode
2163 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
2164 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07002165 if (r.activity.mVisibleFromClient) {
2166 ViewManager wm = a.getWindowManager();
2167 View decor = r.window.getDecorView();
2168 wm.updateViewLayout(decor, l);
2169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002170 }
2171 r.activity.mVisibleFromServer = true;
2172 mNumVisibleActivities++;
2173 if (r.activity.mVisibleFromClient) {
2174 r.activity.makeVisible();
2175 }
2176 }
2177
2178 r.nextIdle = mNewActivities;
2179 mNewActivities = r;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002180 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002181 TAG, "Scheduling idle handler for " + r);
2182 Looper.myQueue().addIdleHandler(new Idler());
2183
2184 } else {
2185 // If an exception was thrown when trying to resume, then
2186 // just end this activity.
2187 try {
2188 ActivityManagerNative.getDefault()
2189 .finishActivity(token, Activity.RESULT_CANCELED, null);
2190 } catch (RemoteException ex) {
2191 }
2192 }
2193 }
2194
2195 private int mThumbnailWidth = -1;
2196 private int mThumbnailHeight = -1;
2197
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002198 private final Bitmap createThumbnailBitmap(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002199 Bitmap thumbnail = null;
2200 try {
2201 int w = mThumbnailWidth;
2202 int h;
2203 if (w < 0) {
2204 Resources res = r.activity.getResources();
2205 mThumbnailHeight = h =
2206 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
2207
2208 mThumbnailWidth = w =
2209 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
2210 } else {
2211 h = mThumbnailHeight;
2212 }
2213
Jim Miller0b2a6d02010-07-13 18:01:29 -07002214 // On platforms where we don't want thumbnails, set dims to (0,0)
2215 if ((w > 0) && (h > 0)) {
2216 View topView = r.activity.getWindow().getDecorView();
2217
2218 // Maximize bitmap by capturing in native aspect.
2219 if (topView.getWidth() >= topView.getHeight()) {
2220 thumbnail = Bitmap.createBitmap(w, h, THUMBNAIL_FORMAT);
2221 } else {
2222 thumbnail = Bitmap.createBitmap(h, w, THUMBNAIL_FORMAT);
2223 }
2224
2225 thumbnail.eraseColor(0);
2226 Canvas cv = new Canvas(thumbnail);
2227 if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
2228 thumbnail = null;
2229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002230 }
Jim Miller0b2a6d02010-07-13 18:01:29 -07002231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002232 } catch (Exception e) {
2233 if (!mInstrumentation.onException(r.activity, e)) {
2234 throw new RuntimeException(
2235 "Unable to create thumbnail of "
2236 + r.intent.getComponent().toShortString()
2237 + ": " + e.toString(), e);
2238 }
2239 thumbnail = null;
2240 }
2241
2242 return thumbnail;
2243 }
2244
2245 private final void handlePauseActivity(IBinder token, boolean finished,
2246 boolean userLeaving, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002247 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002248 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002249 //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 if (userLeaving) {
2251 performUserLeavingActivity(r);
2252 }
Bob Leee5408332009-09-04 18:31:17 -07002253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002254 r.activity.mConfigChangeFlags |= configChanges;
2255 Bundle state = performPauseActivity(token, finished, true);
2256
2257 // Tell the activity manager we have paused.
2258 try {
2259 ActivityManagerNative.getDefault().activityPaused(token, state);
2260 } catch (RemoteException ex) {
2261 }
2262 }
2263 }
2264
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002265 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002266 mInstrumentation.callActivityOnUserLeaving(r.activity);
2267 }
2268
2269 final Bundle performPauseActivity(IBinder token, boolean finished,
2270 boolean saveState) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002271 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002272 return r != null ? performPauseActivity(r, finished, saveState) : null;
2273 }
2274
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002275 final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002276 boolean saveState) {
2277 if (r.paused) {
2278 if (r.activity.mFinished) {
2279 // If we are finishing, we won't call onResume() in certain cases.
2280 // So here we likewise don't want to call onPause() if the activity
2281 // isn't resumed.
2282 return null;
2283 }
2284 RuntimeException e = new RuntimeException(
2285 "Performing pause of activity that is not resumed: "
2286 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002287 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002288 }
2289 Bundle state = null;
2290 if (finished) {
2291 r.activity.mFinished = true;
2292 }
2293 try {
2294 // Next have the activity save its current state and managed dialogs...
2295 if (!r.activity.mFinished && saveState) {
2296 state = new Bundle();
2297 mInstrumentation.callActivityOnSaveInstanceState(r.activity, state);
2298 r.state = state;
2299 }
2300 // Now we are idle.
2301 r.activity.mCalled = false;
2302 mInstrumentation.callActivityOnPause(r.activity);
2303 EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
2304 if (!r.activity.mCalled) {
2305 throw new SuperNotCalledException(
2306 "Activity " + r.intent.getComponent().toShortString() +
2307 " did not call through to super.onPause()");
2308 }
2309
2310 } catch (SuperNotCalledException e) {
2311 throw e;
2312
2313 } catch (Exception e) {
2314 if (!mInstrumentation.onException(r.activity, e)) {
2315 throw new RuntimeException(
2316 "Unable to pause activity "
2317 + r.intent.getComponent().toShortString()
2318 + ": " + e.toString(), e);
2319 }
2320 }
2321 r.paused = true;
2322 return state;
2323 }
2324
2325 final void performStopActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002326 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002327 performStopActivityInner(r, null, false);
2328 }
2329
2330 private static class StopInfo {
2331 Bitmap thumbnail;
2332 CharSequence description;
2333 }
2334
2335 private final class ProviderRefCount {
2336 public int count;
2337 ProviderRefCount(int pCount) {
2338 count = pCount;
2339 }
2340 }
2341
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002342 private final void performStopActivityInner(ActivityClientRecord r,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002343 StopInfo info, boolean keepShown) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002344 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002345 if (r != null) {
2346 if (!keepShown && r.stopped) {
2347 if (r.activity.mFinished) {
2348 // If we are finishing, we won't call onResume() in certain
2349 // cases. So here we likewise don't want to call onStop()
2350 // if the activity isn't resumed.
2351 return;
2352 }
2353 RuntimeException e = new RuntimeException(
2354 "Performing stop of activity that is not resumed: "
2355 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08002356 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002357 }
2358
2359 if (info != null) {
2360 try {
2361 // First create a thumbnail for the activity...
Jim Miller0b2a6d02010-07-13 18:01:29 -07002362 info.thumbnail = createThumbnailBitmap(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 info.description = r.activity.onCreateDescription();
2364 } catch (Exception e) {
2365 if (!mInstrumentation.onException(r.activity, e)) {
2366 throw new RuntimeException(
2367 "Unable to save state of activity "
2368 + r.intent.getComponent().toShortString()
2369 + ": " + e.toString(), e);
2370 }
2371 }
2372 }
2373
2374 if (!keepShown) {
2375 try {
2376 // Now we are idle.
2377 r.activity.performStop();
2378 } catch (Exception e) {
2379 if (!mInstrumentation.onException(r.activity, e)) {
2380 throw new RuntimeException(
2381 "Unable to stop activity "
2382 + r.intent.getComponent().toShortString()
2383 + ": " + e.toString(), e);
2384 }
2385 }
2386 r.stopped = true;
2387 }
2388
2389 r.paused = true;
2390 }
2391 }
2392
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002393 private final void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394 View v = r.activity.mDecor;
2395 if (v != null) {
2396 if (show) {
2397 if (!r.activity.mVisibleFromServer) {
2398 r.activity.mVisibleFromServer = true;
2399 mNumVisibleActivities++;
2400 if (r.activity.mVisibleFromClient) {
2401 r.activity.makeVisible();
2402 }
2403 }
2404 if (r.newConfig != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002405 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002406 + r.activityInfo.name + " with new config " + r.newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002407 performConfigurationChanged(r.activity, r.newConfig);
2408 r.newConfig = null;
2409 }
2410 } else {
2411 if (r.activity.mVisibleFromServer) {
2412 r.activity.mVisibleFromServer = false;
2413 mNumVisibleActivities--;
2414 v.setVisibility(View.INVISIBLE);
2415 }
2416 }
2417 }
2418 }
2419
2420 private final void handleStopActivity(IBinder token, boolean show, int configChanges) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002421 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002422 r.activity.mConfigChangeFlags |= configChanges;
2423
2424 StopInfo info = new StopInfo();
2425 performStopActivityInner(r, info, show);
2426
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002427 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002428 TAG, "Finishing stop of " + r + ": show=" + show
2429 + " win=" + r.window);
2430
2431 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07002432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002433 // Tell activity manager we have been stopped.
2434 try {
2435 ActivityManagerNative.getDefault().activityStopped(
2436 r.token, info.thumbnail, info.description);
2437 } catch (RemoteException ex) {
2438 }
2439 }
2440
2441 final void performRestartActivity(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002442 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 if (r.stopped) {
2444 r.activity.performRestart();
2445 r.stopped = false;
2446 }
2447 }
2448
2449 private final void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002450 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451 if (!show && !r.stopped) {
2452 performStopActivityInner(r, null, show);
2453 } else if (show && r.stopped) {
2454 // If we are getting ready to gc after going to the background, well
2455 // we are back active so skip it.
2456 unscheduleGcIdler();
2457
2458 r.activity.performRestart();
2459 r.stopped = false;
2460 }
2461 if (r.activity.mDecor != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002462 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002463 TAG, "Handle window " + r + " visibility: " + show);
2464 updateVisibility(r, show);
2465 }
2466 }
2467
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002468 private final void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002469 final int N = results.size();
2470 for (int i=0; i<N; i++) {
2471 ResultInfo ri = results.get(i);
2472 try {
2473 if (ri.mData != null) {
2474 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
2475 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002476 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07002477 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 r.activity.dispatchActivityResult(ri.mResultWho,
2479 ri.mRequestCode, ri.mResultCode, ri.mData);
2480 } catch (Exception e) {
2481 if (!mInstrumentation.onException(r.activity, e)) {
2482 throw new RuntimeException(
2483 "Failure delivering result " + ri + " to activity "
2484 + r.intent.getComponent().toShortString()
2485 + ": " + e.toString(), e);
2486 }
2487 }
2488 }
2489 }
2490
2491 private final void handleSendResult(ResultData res) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002492 ActivityClientRecord r = mActivities.get(res.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002493 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494 if (r != null) {
2495 final boolean resumed = !r.paused;
2496 if (!r.activity.mFinished && r.activity.mDecor != null
2497 && r.hideForNow && resumed) {
2498 // We had hidden the activity because it started another
2499 // one... we have gotten a result back and we are not
2500 // paused, so make sure our window is visible.
2501 updateVisibility(r, true);
2502 }
2503 if (resumed) {
2504 try {
2505 // Now we are idle.
2506 r.activity.mCalled = false;
2507 mInstrumentation.callActivityOnPause(r.activity);
2508 if (!r.activity.mCalled) {
2509 throw new SuperNotCalledException(
2510 "Activity " + r.intent.getComponent().toShortString()
2511 + " did not call through to super.onPause()");
2512 }
2513 } catch (SuperNotCalledException e) {
2514 throw e;
2515 } catch (Exception e) {
2516 if (!mInstrumentation.onException(r.activity, e)) {
2517 throw new RuntimeException(
2518 "Unable to pause activity "
2519 + r.intent.getComponent().toShortString()
2520 + ": " + e.toString(), e);
2521 }
2522 }
2523 }
2524 deliverResults(r, res.results);
2525 if (resumed) {
2526 mInstrumentation.callActivityOnResume(r.activity);
2527 }
2528 }
2529 }
2530
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002531 public final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532 return performDestroyActivity(token, finishing, 0, false);
2533 }
2534
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002535 private final ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002537 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002538 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 if (r != null) {
2540 r.activity.mConfigChangeFlags |= configChanges;
2541 if (finishing) {
2542 r.activity.mFinished = true;
2543 }
2544 if (!r.paused) {
2545 try {
2546 r.activity.mCalled = false;
2547 mInstrumentation.callActivityOnPause(r.activity);
Bob Leee5408332009-09-04 18:31:17 -07002548 EventLog.writeEvent(LOG_ON_PAUSE_CALLED,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 r.activity.getComponentName().getClassName());
2550 if (!r.activity.mCalled) {
2551 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002552 "Activity " + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002553 + " did not call through to super.onPause()");
2554 }
2555 } catch (SuperNotCalledException e) {
2556 throw e;
2557 } catch (Exception e) {
2558 if (!mInstrumentation.onException(r.activity, e)) {
2559 throw new RuntimeException(
2560 "Unable to pause activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002561 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 + ": " + e.toString(), e);
2563 }
2564 }
2565 r.paused = true;
2566 }
2567 if (!r.stopped) {
2568 try {
2569 r.activity.performStop();
2570 } catch (SuperNotCalledException e) {
2571 throw e;
2572 } catch (Exception e) {
2573 if (!mInstrumentation.onException(r.activity, e)) {
2574 throw new RuntimeException(
2575 "Unable to stop activity "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002576 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577 + ": " + e.toString(), e);
2578 }
2579 }
2580 r.stopped = true;
2581 }
2582 if (getNonConfigInstance) {
2583 try {
2584 r.lastNonConfigurationInstance
2585 = r.activity.onRetainNonConfigurationInstance();
2586 } catch (Exception e) {
2587 if (!mInstrumentation.onException(r.activity, e)) {
2588 throw new RuntimeException(
2589 "Unable to retain activity "
2590 + r.intent.getComponent().toShortString()
2591 + ": " + e.toString(), e);
2592 }
2593 }
2594 try {
2595 r.lastNonConfigurationChildInstances
2596 = r.activity.onRetainNonConfigurationChildInstances();
2597 } catch (Exception e) {
2598 if (!mInstrumentation.onException(r.activity, e)) {
2599 throw new RuntimeException(
2600 "Unable to retain child activities "
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002601 + safeToComponentShortString(r.intent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 + ": " + e.toString(), e);
2603 }
2604 }
Bob Leee5408332009-09-04 18:31:17 -07002605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002606 }
2607 try {
2608 r.activity.mCalled = false;
2609 r.activity.onDestroy();
2610 if (!r.activity.mCalled) {
2611 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002612 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002613 " did not call through to super.onDestroy()");
2614 }
2615 if (r.window != null) {
2616 r.window.closeAllPanels();
2617 }
2618 } catch (SuperNotCalledException e) {
2619 throw e;
2620 } catch (Exception e) {
2621 if (!mInstrumentation.onException(r.activity, e)) {
2622 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002623 "Unable to destroy activity " + safeToComponentShortString(r.intent)
2624 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625 }
2626 }
2627 }
2628 mActivities.remove(token);
2629
2630 return r;
2631 }
2632
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07002633 private static String safeToComponentShortString(Intent intent) {
2634 ComponentName component = intent.getComponent();
2635 return component == null ? "[Unknown]" : component.toShortString();
2636 }
2637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002638 private final void handleDestroyActivity(IBinder token, boolean finishing,
2639 int configChanges, boolean getNonConfigInstance) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002640 ActivityClientRecord r = performDestroyActivity(token, finishing,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641 configChanges, getNonConfigInstance);
2642 if (r != null) {
2643 WindowManager wm = r.activity.getWindowManager();
2644 View v = r.activity.mDecor;
2645 if (v != null) {
2646 if (r.activity.mVisibleFromServer) {
2647 mNumVisibleActivities--;
2648 }
2649 IBinder wtoken = v.getWindowToken();
2650 if (r.activity.mWindowAdded) {
2651 wm.removeViewImmediate(v);
2652 }
2653 if (wtoken != null) {
2654 WindowManagerImpl.getDefault().closeAll(wtoken,
2655 r.activity.getClass().getName(), "Activity");
2656 }
2657 r.activity.mDecor = null;
2658 }
2659 WindowManagerImpl.getDefault().closeAll(token,
2660 r.activity.getClass().getName(), "Activity");
2661
2662 // Mocked out contexts won't be participating in the normal
2663 // process lifecycle, but if we're running with a proper
2664 // ApplicationContext we need to have it tear down things
2665 // cleanly.
2666 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08002667 if (c instanceof ContextImpl) {
2668 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002669 r.activity.getClass().getName(), "Activity");
2670 }
2671 }
2672 if (finishing) {
2673 try {
2674 ActivityManagerNative.getDefault().activityDestroyed(token);
2675 } catch (RemoteException ex) {
2676 // If the system process has died, it's game over for everyone.
2677 }
2678 }
2679 }
2680
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002681 private final void handleRelaunchActivity(ActivityClientRecord tmp, int configChanges) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 // If we are getting ready to gc after going to the background, well
2683 // we are back active so skip it.
2684 unscheduleGcIdler();
2685
2686 Configuration changedConfig = null;
Bob Leee5408332009-09-04 18:31:17 -07002687
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002688 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002689 + tmp.token + " with configChanges=0x"
2690 + Integer.toHexString(configChanges));
2691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 // First: make sure we have the most recent configuration and most
2693 // recent version of the activity, or skip it if some previous call
2694 // had taken a more recent version.
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002695 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002696 int N = mRelaunchingActivities.size();
2697 IBinder token = tmp.token;
2698 tmp = null;
2699 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002700 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002701 if (r.token == token) {
2702 tmp = r;
2703 mRelaunchingActivities.remove(i);
2704 i--;
2705 N--;
2706 }
2707 }
Bob Leee5408332009-09-04 18:31:17 -07002708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002709 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002710 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 return;
2712 }
Bob Leee5408332009-09-04 18:31:17 -07002713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002714 if (mPendingConfiguration != null) {
2715 changedConfig = mPendingConfiguration;
2716 mPendingConfiguration = null;
2717 }
2718 }
Bob Leee5408332009-09-04 18:31:17 -07002719
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002720 if (tmp.createdConfig != null) {
2721 // If the activity manager is passing us its current config,
2722 // assume that is really what we want regardless of what we
2723 // may have pending.
2724 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002725 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
2726 && mConfiguration.diff(tmp.createdConfig) != 0)) {
2727 if (changedConfig == null
2728 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
2729 changedConfig = tmp.createdConfig;
2730 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08002731 }
2732 }
2733
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002734 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002735 + tmp.token + ": changedConfig=" + changedConfig);
2736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002737 // If there was a pending configuration change, execute it first.
2738 if (changedConfig != null) {
2739 handleConfigurationChanged(changedConfig);
2740 }
Bob Leee5408332009-09-04 18:31:17 -07002741
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002742 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002743 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744 if (r == null) {
2745 return;
2746 }
Bob Leee5408332009-09-04 18:31:17 -07002747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002748 r.activity.mConfigChangeFlags |= configChanges;
Christopher Tateb70f3df2009-04-07 16:07:59 -07002749 Intent currentIntent = r.activity.mIntent;
Bob Leee5408332009-09-04 18:31:17 -07002750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002751 Bundle savedState = null;
2752 if (!r.paused) {
2753 savedState = performPauseActivity(r.token, false, true);
2754 }
Bob Leee5408332009-09-04 18:31:17 -07002755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002756 handleDestroyActivity(r.token, false, configChanges, true);
Bob Leee5408332009-09-04 18:31:17 -07002757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758 r.activity = null;
2759 r.window = null;
2760 r.hideForNow = false;
2761 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07002762 // Merge any pending results and pending intents; don't just replace them
2763 if (tmp.pendingResults != null) {
2764 if (r.pendingResults == null) {
2765 r.pendingResults = tmp.pendingResults;
2766 } else {
2767 r.pendingResults.addAll(tmp.pendingResults);
2768 }
2769 }
2770 if (tmp.pendingIntents != null) {
2771 if (r.pendingIntents == null) {
2772 r.pendingIntents = tmp.pendingIntents;
2773 } else {
2774 r.pendingIntents.addAll(tmp.pendingIntents);
2775 }
2776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002777 r.startsNotResumed = tmp.startsNotResumed;
2778 if (savedState != null) {
2779 r.state = savedState;
2780 }
Bob Leee5408332009-09-04 18:31:17 -07002781
Christopher Tateb70f3df2009-04-07 16:07:59 -07002782 handleLaunchActivity(r, currentIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002783 }
2784
2785 private final void handleRequestThumbnail(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002786 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002787 Bitmap thumbnail = createThumbnailBitmap(r);
2788 CharSequence description = null;
2789 try {
2790 description = r.activity.onCreateDescription();
2791 } catch (Exception e) {
2792 if (!mInstrumentation.onException(r.activity, e)) {
2793 throw new RuntimeException(
2794 "Unable to create description of activity "
2795 + r.intent.getComponent().toShortString()
2796 + ": " + e.toString(), e);
2797 }
2798 }
2799 //System.out.println("Reporting top thumbnail " + thumbnail);
2800 try {
2801 ActivityManagerNative.getDefault().reportThumbnail(
2802 token, thumbnail, description);
2803 } catch (RemoteException ex) {
2804 }
2805 }
2806
2807 ArrayList<ComponentCallbacks> collectComponentCallbacksLocked(
2808 boolean allActivities, Configuration newConfig) {
2809 ArrayList<ComponentCallbacks> callbacks
2810 = new ArrayList<ComponentCallbacks>();
Bob Leee5408332009-09-04 18:31:17 -07002811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 if (mActivities.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002813 Iterator<ActivityClientRecord> it = mActivities.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 while (it.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002815 ActivityClientRecord ar = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 Activity a = ar.activity;
2817 if (a != null) {
2818 if (!ar.activity.mFinished && (allActivities ||
2819 (a != null && !ar.paused))) {
2820 // If the activity is currently resumed, its configuration
2821 // needs to change right now.
2822 callbacks.add(a);
2823 } else if (newConfig != null) {
2824 // Otherwise, we will tell it about the change
2825 // the next time it is resumed or shown. Note that
2826 // the activity manager may, before then, decide the
2827 // activity needs to be destroyed to handle its new
2828 // configuration.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002829 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Setting activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002830 + ar.activityInfo.name + " newConfig=" + newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 ar.newConfig = newConfig;
2832 }
2833 }
2834 }
2835 }
2836 if (mServices.size() > 0) {
2837 Iterator<Service> it = mServices.values().iterator();
2838 while (it.hasNext()) {
2839 callbacks.add(it.next());
2840 }
2841 }
2842 synchronized (mProviderMap) {
2843 if (mLocalProviders.size() > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002844 Iterator<ProviderClientRecord> it = mLocalProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845 while (it.hasNext()) {
2846 callbacks.add(it.next().mLocalProvider);
2847 }
2848 }
2849 }
2850 final int N = mAllApplications.size();
2851 for (int i=0; i<N; i++) {
2852 callbacks.add(mAllApplications.get(i));
2853 }
Bob Leee5408332009-09-04 18:31:17 -07002854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002855 return callbacks;
2856 }
Bob Leee5408332009-09-04 18:31:17 -07002857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002858 private final void performConfigurationChanged(
2859 ComponentCallbacks cb, Configuration config) {
2860 // Only for Activity objects, check that they actually call up to their
2861 // superclass implementation. ComponentCallbacks is an interface, so
2862 // we check the runtime type and act accordingly.
2863 Activity activity = (cb instanceof Activity) ? (Activity) cb : null;
2864 if (activity != null) {
2865 activity.mCalled = false;
2866 }
Bob Leee5408332009-09-04 18:31:17 -07002867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002868 boolean shouldChangeConfig = false;
2869 if ((activity == null) || (activity.mCurrentConfig == null)) {
2870 shouldChangeConfig = true;
2871 } else {
Bob Leee5408332009-09-04 18:31:17 -07002872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 // If the new config is the same as the config this Activity
2874 // is already running with then don't bother calling
2875 // onConfigurationChanged
2876 int diff = activity.mCurrentConfig.diff(config);
2877 if (diff != 0) {
Bob Leee5408332009-09-04 18:31:17 -07002878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002879 // If this activity doesn't handle any of the config changes
2880 // then don't bother calling onConfigurationChanged as we're
2881 // going to destroy it.
2882 if ((~activity.mActivityInfo.configChanges & diff) == 0) {
2883 shouldChangeConfig = true;
2884 }
2885 }
2886 }
Bob Leee5408332009-09-04 18:31:17 -07002887
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002888 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Config callback " + cb
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002889 + ": shouldChangeConfig=" + shouldChangeConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002890 if (shouldChangeConfig) {
2891 cb.onConfigurationChanged(config);
Bob Leee5408332009-09-04 18:31:17 -07002892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 if (activity != null) {
2894 if (!activity.mCalled) {
2895 throw new SuperNotCalledException(
2896 "Activity " + activity.getLocalClassName() +
2897 " did not call through to super.onConfigurationChanged()");
2898 }
2899 activity.mConfigChangeFlags = 0;
2900 activity.mCurrentConfig = new Configuration(config);
2901 }
2902 }
2903 }
2904
Dianne Hackbornae078162010-03-18 11:29:37 -07002905 final boolean applyConfigurationToResourcesLocked(Configuration config) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002906 if (mResConfiguration == null) {
2907 mResConfiguration = new Configuration();
2908 }
2909 if (!mResConfiguration.isOtherSeqNewer(config)) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002910 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Skipping new config: curSeq="
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002911 + mResConfiguration.seq + ", newSeq=" + config.seq);
Dianne Hackbornae078162010-03-18 11:29:37 -07002912 return false;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002913 }
Dianne Hackbornae078162010-03-18 11:29:37 -07002914 int changes = mResConfiguration.updateFrom(config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002915 DisplayMetrics dm = getDisplayMetricsLocked(true);
Bob Leee5408332009-09-04 18:31:17 -07002916
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002917 // set it for java, this also affects newly created Resources
2918 if (config.locale != null) {
2919 Locale.setDefault(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002920 }
Bob Leee5408332009-09-04 18:31:17 -07002921
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002922 Resources.updateSystemConfiguration(config, dm);
Bob Leee5408332009-09-04 18:31:17 -07002923
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002924 ContextImpl.ApplicationPackageManager.configurationChanged();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002925 //Slog.i(TAG, "Configuration changed in " + currentPackageName());
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002926
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002927 Iterator<WeakReference<Resources>> it =
2928 mActiveResources.values().iterator();
2929 //Iterator<Map.Entry<String, WeakReference<Resources>>> it =
2930 // mActiveResources.entrySet().iterator();
2931 while (it.hasNext()) {
2932 WeakReference<Resources> v = it.next();
2933 Resources r = v.get();
2934 if (r != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002935 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Changing resources "
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002936 + r + " config to: " + config);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002937 r.updateConfiguration(config, dm);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002938 //Slog.i(TAG, "Updated app resources " + v.getKey()
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002939 // + " " + r + ": " + r.getConfiguration());
2940 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002941 //Slog.i(TAG, "Removing old resources " + v.getKey());
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002942 it.remove();
2943 }
2944 }
Dianne Hackbornae078162010-03-18 11:29:37 -07002945
2946 return changes != 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002947 }
2948
2949 final void handleConfigurationChanged(Configuration config) {
2950
2951 ArrayList<ComponentCallbacks> callbacks = null;
2952
2953 synchronized (mPackages) {
2954 if (mPendingConfiguration != null) {
2955 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
2956 config = mPendingConfiguration;
2957 }
2958 mPendingConfiguration = null;
2959 }
2960
2961 if (config == null) {
2962 return;
2963 }
2964
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002965 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002966 + config);
2967
2968 applyConfigurationToResourcesLocked(config);
2969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002970 if (mConfiguration == null) {
2971 mConfiguration = new Configuration();
2972 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002973 if (!mConfiguration.isOtherSeqNewer(config)) {
2974 return;
2975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976 mConfiguration.updateFrom(config);
Bob Leee5408332009-09-04 18:31:17 -07002977
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002978 callbacks = collectComponentCallbacksLocked(false, config);
2979 }
Bob Leee5408332009-09-04 18:31:17 -07002980
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002981 if (callbacks != null) {
2982 final int N = callbacks.size();
2983 for (int i=0; i<N; i++) {
2984 performConfigurationChanged(callbacks.get(i), config);
2985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002986 }
2987 }
2988
2989 final void handleActivityConfigurationChanged(IBinder token) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002990 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002991 if (r == null || r.activity == null) {
2992 return;
2993 }
Bob Leee5408332009-09-04 18:31:17 -07002994
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002995 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002996 + r.activityInfo.name);
2997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002998 performConfigurationChanged(r.activity, mConfiguration);
2999 }
3000
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003001 final void handleProfilerControl(boolean start, ProfilerControlData pcd) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003002 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003003 try {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003004 Debug.startMethodTracing(pcd.path, pcd.fd.getFileDescriptor(),
3005 8 * 1024 * 1024, 0);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003006 } catch (RuntimeException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003007 Slog.w(TAG, "Profiling failed on path " + pcd.path
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003008 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003009 } finally {
3010 try {
3011 pcd.fd.close();
3012 } catch (IOException e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003013 Slog.w(TAG, "Failure closing profile fd", e);
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07003014 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08003015 }
3016 } else {
3017 Debug.stopMethodTracing();
3018 }
3019 }
Bob Leee5408332009-09-04 18:31:17 -07003020
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003021 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
3022 boolean hasPkgInfo = false;
3023 if (packages != null) {
3024 for (int i=packages.length-1; i>=0; i--) {
3025 //Slog.i(TAG, "Cleaning old package: " + packages[i]);
3026 if (!hasPkgInfo) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003027 WeakReference<LoadedApk> ref;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07003028 ref = mPackages.get(packages[i]);
3029 if (ref != null && ref.get() != null) {
3030 hasPkgInfo = true;
3031 } else {
3032 ref = mResourcePackages.get(packages[i]);
3033 if (ref != null && ref.get() != null) {
3034 hasPkgInfo = true;
3035 }
3036 }
3037 }
3038 mPackages.remove(packages[i]);
3039 mResourcePackages.remove(packages[i]);
3040 }
3041 }
3042 ContextImpl.ApplicationPackageManager.handlePackageBroadcast(cmd, packages,
3043 hasPkgInfo);
3044 }
3045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003046 final void handleLowMemory() {
3047 ArrayList<ComponentCallbacks> callbacks
3048 = new ArrayList<ComponentCallbacks>();
3049
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003050 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003051 callbacks = collectComponentCallbacksLocked(true, null);
3052 }
Bob Leee5408332009-09-04 18:31:17 -07003053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003054 final int N = callbacks.size();
3055 for (int i=0; i<N; i++) {
3056 callbacks.get(i).onLowMemory();
3057 }
3058
Chris Tatece229052009-03-25 16:44:52 -07003059 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
3060 if (Process.myUid() != Process.SYSTEM_UID) {
3061 int sqliteReleased = SQLiteDatabase.releaseMemory();
3062 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
3063 }
Bob Leee5408332009-09-04 18:31:17 -07003064
Mike Reedcaf0df12009-04-27 14:32:05 -04003065 // Ask graphics to free up as much as possible (font/image caches)
3066 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003067
3068 BinderInternal.forceGc("mem");
3069 }
3070
3071 private final void handleBindApplication(AppBindData data) {
3072 mBoundApplication = data;
3073 mConfiguration = new Configuration(data.config);
3074
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003075 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08003076 Process.setArgV0(data.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003077 android.ddm.DdmHandleAppName.setAppName(data.processName);
3078
3079 /*
3080 * Before spawning a new process, reset the time zone to be the system time zone.
3081 * This needs to be done because the system time zone could have changed after the
3082 * the spawning of this process. Without doing this this process would have the incorrect
3083 * system time zone.
3084 */
3085 TimeZone.setDefault(null);
3086
3087 /*
3088 * Initialize the default locale in this process for the reasons we set the time zone.
3089 */
3090 Locale.setDefault(data.config.locale);
3091
Suchi Amalapurapuc9843292009-06-24 17:02:25 -07003092 /*
3093 * Update the system configuration since its preloaded and might not
3094 * reflect configuration changes. The configuration object passed
3095 * in AppBindData can be safely assumed to be up to date
3096 */
3097 Resources.getSystem().updateConfiguration(mConfiguration, null);
3098
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003099 data.info = getPackageInfoNoCheck(data.appInfo);
3100
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003101 /**
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003102 * For system applications on userdebug/eng builds, log stack
3103 * traces of disk and network access to dropbox for analysis.
3104 */
3105 if ((data.appInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0 &&
3106 !"user".equals(Build.TYPE)) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07003107 StrictMode.setThreadBlockingPolicy(
3108 StrictMode.DISALLOW_DISK_WRITE |
3109 StrictMode.DISALLOW_DISK_READ |
3110 StrictMode.DISALLOW_NETWORK |
3111 StrictMode.PENALTY_DROPBOX);
3112 }
3113
3114 /**
Dianne Hackborn96e240f2009-07-26 17:42:30 -07003115 * Switch this process to density compatibility mode if needed.
3116 */
3117 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
3118 == 0) {
3119 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
3120 }
Bob Leee5408332009-09-04 18:31:17 -07003121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003122 if (data.debugMode != IApplicationThread.DEBUG_OFF) {
3123 // XXX should have option to change the port.
3124 Debug.changeDebugPort(8100);
3125 if (data.debugMode == IApplicationThread.DEBUG_WAIT) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003126 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003127 + " is waiting for the debugger on port 8100...");
3128
3129 IActivityManager mgr = ActivityManagerNative.getDefault();
3130 try {
3131 mgr.showWaitingForDebugger(mAppThread, true);
3132 } catch (RemoteException ex) {
3133 }
3134
3135 Debug.waitForDebugger();
3136
3137 try {
3138 mgr.showWaitingForDebugger(mAppThread, false);
3139 } catch (RemoteException ex) {
3140 }
3141
3142 } else {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003143 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003144 + " can be debugged on port 8100...");
3145 }
3146 }
3147
3148 if (data.instrumentationName != null) {
Dianne Hackborn21556372010-02-04 16:34:40 -08003149 ContextImpl appContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003150 appContext.init(data.info, null, this);
3151 InstrumentationInfo ii = null;
3152 try {
3153 ii = appContext.getPackageManager().
3154 getInstrumentationInfo(data.instrumentationName, 0);
3155 } catch (PackageManager.NameNotFoundException e) {
3156 }
3157 if (ii == null) {
3158 throw new RuntimeException(
3159 "Unable to find instrumentation info for: "
3160 + data.instrumentationName);
3161 }
3162
3163 mInstrumentationAppDir = ii.sourceDir;
3164 mInstrumentationAppPackage = ii.packageName;
3165 mInstrumentedAppDir = data.info.getAppDir();
3166
3167 ApplicationInfo instrApp = new ApplicationInfo();
3168 instrApp.packageName = ii.packageName;
3169 instrApp.sourceDir = ii.sourceDir;
3170 instrApp.publicSourceDir = ii.publicSourceDir;
3171 instrApp.dataDir = ii.dataDir;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003172 LoadedApk pi = getPackageInfo(instrApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003173 appContext.getClassLoader(), false, true);
Dianne Hackborn21556372010-02-04 16:34:40 -08003174 ContextImpl instrContext = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003175 instrContext.init(pi, null, this);
3176
3177 try {
3178 java.lang.ClassLoader cl = instrContext.getClassLoader();
3179 mInstrumentation = (Instrumentation)
3180 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
3181 } catch (Exception e) {
3182 throw new RuntimeException(
3183 "Unable to instantiate instrumentation "
3184 + data.instrumentationName + ": " + e.toString(), e);
3185 }
3186
3187 mInstrumentation.init(this, instrContext, appContext,
3188 new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher);
3189
3190 if (data.profileFile != null && !ii.handleProfiling) {
3191 data.handlingProfiling = true;
3192 File file = new File(data.profileFile);
3193 file.getParentFile().mkdirs();
3194 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
3195 }
3196
3197 try {
3198 mInstrumentation.onCreate(data.instrumentationArgs);
3199 }
3200 catch (Exception e) {
3201 throw new RuntimeException(
3202 "Exception thrown in onCreate() of "
3203 + data.instrumentationName + ": " + e.toString(), e);
3204 }
3205
3206 } else {
3207 mInstrumentation = new Instrumentation();
3208 }
3209
Christopher Tate181fafa2009-05-14 11:12:14 -07003210 // If the app is being launched for full backup or restore, bring it up in
3211 // a restricted environment with the base application class.
Dianne Hackborn0be1f782009-11-09 12:30:12 -08003212 Application app = data.info.makeApplication(data.restrictedBackupMode, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003213 mInitialApplication = app;
3214
3215 List<ProviderInfo> providers = data.providers;
3216 if (providers != null) {
3217 installContentProviders(app, providers);
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003218 // For process that contain content providers, we want to
3219 // ensure that the JIT is enabled "at some point".
3220 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003221 }
3222
3223 try {
3224 mInstrumentation.callApplicationOnCreate(app);
3225 } catch (Exception e) {
3226 if (!mInstrumentation.onException(app, e)) {
3227 throw new RuntimeException(
3228 "Unable to create application " + app.getClass().getName()
3229 + ": " + e.toString(), e);
3230 }
3231 }
3232 }
3233
3234 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
3235 IActivityManager am = ActivityManagerNative.getDefault();
3236 if (mBoundApplication.profileFile != null && mBoundApplication.handlingProfiling) {
3237 Debug.stopMethodTracing();
3238 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003239 //Slog.i(TAG, "am: " + ActivityManagerNative.getDefault()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003240 // + ", app thr: " + mAppThread);
3241 try {
3242 am.finishInstrumentation(mAppThread, resultCode, results);
3243 } catch (RemoteException ex) {
3244 }
3245 }
3246
3247 private final void installContentProviders(
3248 Context context, List<ProviderInfo> providers) {
3249 final ArrayList<IActivityManager.ContentProviderHolder> results =
3250 new ArrayList<IActivityManager.ContentProviderHolder>();
3251
3252 Iterator<ProviderInfo> i = providers.iterator();
3253 while (i.hasNext()) {
3254 ProviderInfo cpi = i.next();
3255 StringBuilder buf = new StringBuilder(128);
3256 buf.append("Publishing provider ");
3257 buf.append(cpi.authority);
3258 buf.append(": ");
3259 buf.append(cpi.name);
3260 Log.i(TAG, buf.toString());
3261 IContentProvider cp = installProvider(context, null, cpi, false);
3262 if (cp != null) {
3263 IActivityManager.ContentProviderHolder cph =
3264 new IActivityManager.ContentProviderHolder(cpi);
3265 cph.provider = cp;
3266 results.add(cph);
3267 // Don't ever unload this provider from the process.
3268 synchronized(mProviderMap) {
3269 mProviderRefCountMap.put(cp.asBinder(), new ProviderRefCount(10000));
3270 }
3271 }
3272 }
3273
3274 try {
3275 ActivityManagerNative.getDefault().publishContentProviders(
3276 getApplicationThread(), results);
3277 } catch (RemoteException ex) {
3278 }
3279 }
3280
3281 private final IContentProvider getProvider(Context context, String name) {
3282 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003283 final ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003284 if (pr != null) {
3285 return pr.mProvider;
3286 }
3287 }
3288
3289 IActivityManager.ContentProviderHolder holder = null;
3290 try {
3291 holder = ActivityManagerNative.getDefault().getContentProvider(
3292 getApplicationThread(), name);
3293 } catch (RemoteException ex) {
3294 }
3295 if (holder == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003296 Slog.e(TAG, "Failed to find provider info for " + name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003297 return null;
3298 }
3299 if (holder.permissionFailure != null) {
3300 throw new SecurityException("Permission " + holder.permissionFailure
3301 + " required for provider " + name);
3302 }
3303
3304 IContentProvider prov = installProvider(context, holder.provider,
3305 holder.info, true);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003306 //Slog.i(TAG, "noReleaseNeeded=" + holder.noReleaseNeeded);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 if (holder.noReleaseNeeded || holder.provider == null) {
3308 // We are not going to release the provider if it is an external
3309 // provider that doesn't care about being released, or if it is
3310 // a local provider running in this process.
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003311 //Slog.i(TAG, "*** NO RELEASE NEEDED");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 synchronized(mProviderMap) {
3313 mProviderRefCountMap.put(prov.asBinder(), new ProviderRefCount(10000));
3314 }
3315 }
3316 return prov;
3317 }
3318
3319 public final IContentProvider acquireProvider(Context c, String name) {
3320 IContentProvider provider = getProvider(c, name);
3321 if(provider == null)
3322 return null;
3323 IBinder jBinder = provider.asBinder();
3324 synchronized(mProviderMap) {
3325 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3326 if(prc == null) {
3327 mProviderRefCountMap.put(jBinder, new ProviderRefCount(1));
3328 } else {
3329 prc.count++;
3330 } //end else
3331 } //end synchronized
3332 return provider;
3333 }
3334
3335 public final boolean releaseProvider(IContentProvider provider) {
3336 if(provider == null) {
3337 return false;
3338 }
3339 IBinder jBinder = provider.asBinder();
3340 synchronized(mProviderMap) {
3341 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3342 if(prc == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003343 if(localLOGV) Slog.v(TAG, "releaseProvider::Weird shouldnt be here");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003344 return false;
3345 } else {
3346 prc.count--;
3347 if(prc.count == 0) {
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003348 // Schedule the actual remove asynchronously, since we
3349 // don't know the context this will be called in.
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003350 // TODO: it would be nice to post a delayed message, so
3351 // if we come back and need the same provider quickly
3352 // we will still have it available.
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003353 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, provider);
3354 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003355 } //end if
3356 } //end else
3357 } //end synchronized
3358 return true;
3359 }
3360
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003361 final void completeRemoveProvider(IContentProvider provider) {
3362 IBinder jBinder = provider.asBinder();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003363 String name = null;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003364 synchronized(mProviderMap) {
3365 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
3366 if(prc != null && prc.count == 0) {
3367 mProviderRefCountMap.remove(jBinder);
3368 //invoke removeProvider to dereference provider
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003369 name = removeProviderLocked(provider);
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003370 }
3371 }
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003372
3373 if (name != null) {
3374 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003375 if(localLOGV) Slog.v(TAG, "removeProvider::Invoking " +
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003376 "ActivityManagerNative.removeContentProvider(" + name);
3377 ActivityManagerNative.getDefault().removeContentProvider(
3378 getApplicationThread(), name);
3379 } catch (RemoteException e) {
3380 //do nothing content provider object is dead any way
3381 } //end catch
3382 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07003383 }
3384
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003385 public final String removeProviderLocked(IContentProvider provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003386 if (provider == null) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003387 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003388 }
3389 IBinder providerBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003390
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003391 String name = null;
3392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 // remove the provider from mProviderMap
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003394 Iterator<ProviderClientRecord> iter = mProviderMap.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003395 while (iter.hasNext()) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003396 ProviderClientRecord pr = iter.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 IBinder myBinder = pr.mProvider.asBinder();
3398 if (myBinder == providerBinder) {
3399 //find if its published by this process itself
3400 if(pr.mLocalProvider != null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003401 if(localLOGV) Slog.i(TAG, "removeProvider::found local provider returning");
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003402 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003403 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003404 if(localLOGV) Slog.v(TAG, "removeProvider::Not local provider Unlinking " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003405 "death recipient");
3406 //content provider is in another process
3407 myBinder.unlinkToDeath(pr, 0);
3408 iter.remove();
3409 //invoke remove only once for the very first name seen
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003410 if(name == null) {
3411 name = pr.mName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003412 }
3413 } //end if myBinder
3414 } //end while iter
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07003415
3416 return name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003417 }
3418
3419 final void removeDeadProvider(String name, IContentProvider provider) {
3420 synchronized(mProviderMap) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003421 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003422 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003423 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003424 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003425 if (removed != null) {
3426 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428 }
3429 }
3430 }
3431
3432 final void removeDeadProviderLocked(String name, IContentProvider provider) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003433 ProviderClientRecord pr = mProviderMap.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003434 if (pr.mProvider.asBinder() == provider.asBinder()) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003435 Slog.i(TAG, "Removing dead content provider: " + name);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003436 ProviderClientRecord removed = mProviderMap.remove(name);
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07003437 if (removed != null) {
3438 removed.mProvider.asBinder().unlinkToDeath(removed, 0);
3439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003440 }
3441 }
3442
3443 private final IContentProvider installProvider(Context context,
3444 IContentProvider provider, ProviderInfo info, boolean noisy) {
3445 ContentProvider localProvider = null;
3446 if (provider == null) {
3447 if (noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003448 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003449 + info.name);
3450 }
3451 Context c = null;
3452 ApplicationInfo ai = info.applicationInfo;
3453 if (context.getPackageName().equals(ai.packageName)) {
3454 c = context;
3455 } else if (mInitialApplication != null &&
3456 mInitialApplication.getPackageName().equals(ai.packageName)) {
3457 c = mInitialApplication;
3458 } else {
3459 try {
3460 c = context.createPackageContext(ai.packageName,
3461 Context.CONTEXT_INCLUDE_CODE);
3462 } catch (PackageManager.NameNotFoundException e) {
3463 }
3464 }
3465 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003466 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003467 ai.packageName +
3468 " while loading content provider " +
3469 info.name);
3470 return null;
3471 }
3472 try {
3473 final java.lang.ClassLoader cl = c.getClassLoader();
3474 localProvider = (ContentProvider)cl.
3475 loadClass(info.name).newInstance();
3476 provider = localProvider.getIContentProvider();
3477 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003478 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003479 info.name + " from sourceDir " +
3480 info.applicationInfo.sourceDir);
3481 return null;
3482 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003483 if (Config.LOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484 TAG, "Instantiating local provider " + info.name);
3485 // XXX Need to create the correct context for this provider.
3486 localProvider.attachInfo(c, info);
3487 } catch (java.lang.Exception e) {
3488 if (!mInstrumentation.onException(null, e)) {
3489 throw new RuntimeException(
3490 "Unable to get provider " + info.name
3491 + ": " + e.toString(), e);
3492 }
3493 return null;
3494 }
3495 } else if (localLOGV) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003496 Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003497 + info.name);
3498 }
3499
3500 synchronized (mProviderMap) {
3501 // Cache the pointer for the remote provider.
3502 String names[] = PATTERN_SEMICOLON.split(info.authority);
3503 for (int i=0; i<names.length; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003504 ProviderClientRecord pr = new ProviderClientRecord(names[i], provider,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003505 localProvider);
3506 try {
3507 provider.asBinder().linkToDeath(pr, 0);
3508 mProviderMap.put(names[i], pr);
3509 } catch (RemoteException e) {
3510 return null;
3511 }
3512 }
3513 if (localProvider != null) {
3514 mLocalProviders.put(provider.asBinder(),
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003515 new ProviderClientRecord(null, provider, localProvider));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003516 }
3517 }
3518
3519 return provider;
3520 }
3521
3522 private final void attach(boolean system) {
3523 sThreadLocal.set(this);
3524 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003525 if (!system) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003526 ViewRoot.addFirstDrawHandler(new Runnable() {
3527 public void run() {
3528 ensureJitEnabled();
3529 }
3530 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003531 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
3532 RuntimeInit.setApplicationObject(mAppThread.asBinder());
3533 IActivityManager mgr = ActivityManagerNative.getDefault();
3534 try {
3535 mgr.attachApplication(mAppThread);
3536 } catch (RemoteException ex) {
3537 }
3538 } else {
3539 // Don't set application object here -- if the system crashes,
3540 // we can't display an alert, we just want to die die die.
3541 android.ddm.DdmHandleAppName.setAppName("system_process");
3542 try {
3543 mInstrumentation = new Instrumentation();
Dianne Hackborn21556372010-02-04 16:34:40 -08003544 ContextImpl context = new ContextImpl();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003545 context.init(getSystemContext().mPackageInfo, null, this);
3546 Application app = Instrumentation.newApplication(Application.class, context);
3547 mAllApplications.add(app);
3548 mInitialApplication = app;
3549 app.onCreate();
3550 } catch (Exception e) {
3551 throw new RuntimeException(
3552 "Unable to instantiate Application():" + e.toString(), e);
3553 }
3554 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003555
3556 ViewRoot.addConfigCallback(new ComponentCallbacks() {
3557 public void onConfigurationChanged(Configuration newConfig) {
3558 synchronized (mPackages) {
Dianne Hackbornae078162010-03-18 11:29:37 -07003559 // We need to apply this change to the resources
3560 // immediately, because upon returning the view
3561 // hierarchy will be informed about it.
3562 if (applyConfigurationToResourcesLocked(newConfig)) {
3563 // This actually changed the resources! Tell
3564 // everyone about it.
3565 if (mPendingConfiguration == null ||
3566 mPendingConfiguration.isOtherSeqNewer(newConfig)) {
3567 mPendingConfiguration = newConfig;
3568
3569 queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
3570 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003571 }
3572 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003573 }
3574 public void onLowMemory() {
3575 }
3576 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003577 }
3578
3579 private final void detach()
3580 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003581 sThreadLocal.set(null);
3582 }
3583
3584 public static final ActivityThread systemMain() {
3585 ActivityThread thread = new ActivityThread();
3586 thread.attach(true);
3587 return thread;
3588 }
3589
3590 public final void installSystemProviders(List providers) {
3591 if (providers != null) {
3592 installContentProviders(mInitialApplication,
3593 (List<ProviderInfo>)providers);
3594 }
3595 }
3596
3597 public static final void main(String[] args) {
Bob Leee5408332009-09-04 18:31:17 -07003598 SamplingProfilerIntegration.start();
3599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003600 Process.setArgV0("<pre-initialized>");
3601
3602 Looper.prepareMainLooper();
3603
3604 ActivityThread thread = new ActivityThread();
3605 thread.attach(false);
3606
3607 Looper.loop();
3608
3609 if (Process.supportsProcesses()) {
3610 throw new RuntimeException("Main thread loop unexpectedly exited");
3611 }
3612
3613 thread.detach();
Bob Leeeec2f412009-09-10 11:01:24 +02003614 String name = (thread.mInitialApplication != null)
3615 ? thread.mInitialApplication.getPackageName()
3616 : "<unknown>";
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003617 Slog.i(TAG, "Main thread of " + name + " is now exiting");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003618 }
3619}