[picopc] Added ethernet patch based on Yi Sun <beyounn@gmail.com> from android-x86.org
[picopc-android-gingerbread:frameworks-base.git] / core / java / android / app / ContextImpl.java
1 /*
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
17 package android.app;
18
19 import com.android.internal.policy.PolicyManager;
20 import com.android.internal.util.XmlUtils;
21 import com.google.android.collect.Maps;
22
23 import org.xmlpull.v1.XmlPullParserException;
24
25 import android.content.BroadcastReceiver;
26 import android.content.ComponentName;
27 import android.content.ContentResolver;
28 import android.content.Context;
29 import android.content.ContextWrapper;
30 import android.content.IContentProvider;
31 import android.content.Intent;
32 import android.content.IntentFilter;
33 import android.content.IIntentReceiver;
34 import android.content.IntentSender;
35 import android.content.ReceiverCallNotAllowedException;
36 import android.content.ServiceConnection;
37 import android.content.SharedPreferences;
38 import android.content.pm.ActivityInfo;
39 import android.content.pm.ApplicationInfo;
40 import android.content.pm.ComponentInfo;
41 import android.content.pm.FeatureInfo;
42 import android.content.pm.IPackageDataObserver;
43 import android.content.pm.IPackageDeleteObserver;
44 import android.content.pm.IPackageInstallObserver;
45 import android.content.pm.IPackageMoveObserver;
46 import android.content.pm.IPackageManager;
47 import android.content.pm.IPackageStatsObserver;
48 import android.content.pm.InstrumentationInfo;
49 import android.content.pm.PackageInfo;
50 import android.content.pm.PackageManager;
51 import android.content.pm.PermissionGroupInfo;
52 import android.content.pm.PermissionInfo;
53 import android.content.pm.ProviderInfo;
54 import android.content.pm.ResolveInfo;
55 import android.content.pm.ServiceInfo;
56 import android.content.res.AssetManager;
57 import android.content.res.Resources;
58 import android.content.res.XmlResourceParser;
59 import android.database.sqlite.SQLiteDatabase;
60 import android.database.sqlite.SQLiteDatabase.CursorFactory;
61 import android.graphics.Bitmap;
62 import android.graphics.drawable.Drawable;
63 import android.hardware.SensorManager;
64 import android.hardware.usb.IUsbManager;
65 import android.hardware.usb.UsbManager;
66 import android.location.ILocationManager;
67 import android.location.LocationManager;
68 import android.media.AudioManager;
69 import android.net.ConnectivityManager;
70 import android.net.IConnectivityManager;
71 import android.net.ThrottleManager;
72 import android.net.IThrottleManager;
73 import android.net.Uri;
74 import android.net.wifi.IWifiManager;
75 import android.net.wifi.WifiManager;
76 import android.net.ethernet.IEthernetManager;
77 import android.net.ethernet.EthernetManager;
78 import android.nfc.NfcManager;
79 import android.os.Binder;
80 import android.os.Bundle;
81 import android.os.DropBoxManager;
82 import android.os.Environment;
83 import android.os.FileUtils;
84 import android.os.Handler;
85 import android.os.IBinder;
86 import android.os.IPowerManager;
87 import android.os.Looper;
88 import android.os.PowerManager;
89 import android.os.Process;
90 import android.os.RemoteException;
91 import android.os.ServiceManager;
92 import android.os.Vibrator;
93 import android.os.FileUtils.FileStatus;
94 import android.os.storage.StorageManager;
95 import android.telephony.TelephonyManager;
96 import android.text.ClipboardManager;
97 import android.util.AndroidRuntimeException;
98 import android.util.Log;
99 import android.view.ContextThemeWrapper;
100 import android.view.LayoutInflater;
101 import android.view.WindowManagerImpl;
102 import android.view.accessibility.AccessibilityManager;
103 import android.view.inputmethod.InputMethodManager;
104 import android.accounts.AccountManager;
105 import android.accounts.IAccountManager;
106 import android.app.admin.DevicePolicyManager;
107 import com.android.internal.os.IDropBoxManagerService;
108
109 import java.io.File;
110 import java.io.FileInputStream;
111 import java.io.FileNotFoundException;
112 import java.io.FileOutputStream;
113 import java.io.IOException;
114 import java.io.InputStream;
115 import java.lang.ref.WeakReference;
116 import java.util.ArrayList;
117 import java.util.HashMap;
118 import java.util.HashSet;
119 import java.util.Iterator;
120 import java.util.List;
121 import java.util.Map;
122 import java.util.Map.Entry;
123 import java.util.Set;
124 import java.util.WeakHashMap;
125 import java.util.concurrent.CountDownLatch;
126 import java.util.concurrent.ExecutorService;
127
128 class ReceiverRestrictedContext extends ContextWrapper {
129     ReceiverRestrictedContext(Context base) {
130         super(base);
131     }
132
133     @Override
134     public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
135         return registerReceiver(receiver, filter, null, null);
136     }
137
138     @Override
139     public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
140             String broadcastPermission, Handler scheduler) {
141         throw new ReceiverCallNotAllowedException(
142                 "IntentReceiver components are not allowed to register to receive intents");
143         //ex.fillInStackTrace();
144         //Log.e("IntentReceiver", ex.getMessage(), ex);
145         //return mContext.registerReceiver(receiver, filter, broadcastPermission,
146         //        scheduler);
147     }
148
149     @Override
150     public boolean bindService(Intent service, ServiceConnection conn, int flags) {
151         throw new ReceiverCallNotAllowedException(
152                 "IntentReceiver components are not allowed to bind to services");
153         //ex.fillInStackTrace();
154         //Log.e("IntentReceiver", ex.getMessage(), ex);
155         //return mContext.bindService(service, interfaceName, conn, flags);
156     }
157 }
158
159 /**
160  * Common implementation of Context API, which provides the base
161  * context object for Activity and other application components.
162  */
163 class ContextImpl extends Context {
164     private final static String TAG = "ApplicationContext";
165     private final static boolean DEBUG = false;
166     private final static boolean DEBUG_ICONS = false;
167
168     private static final Object sSync = new Object();
169     private static AlarmManager sAlarmManager;
170     private static PowerManager sPowerManager;
171     private static ConnectivityManager sConnectivityManager;
172     private static ThrottleManager sThrottleManager;
173     private static WifiManager sWifiManager;
174     private static EthernetManager sEthernetManager;
175     private static LocationManager sLocationManager;
176     private static final HashMap<String, SharedPreferencesImpl> sSharedPrefs =
177             new HashMap<String, SharedPreferencesImpl>();
178
179     private AudioManager mAudioManager;
180     /*package*/ LoadedApk mPackageInfo;
181     private Resources mResources;
182     /*package*/ ActivityThread mMainThread;
183     private Context mOuterContext;
184     private IBinder mActivityToken = null;
185     private ApplicationContentResolver mContentResolver;
186     private int mThemeResource = 0;
187     private Resources.Theme mTheme = null;
188     private PackageManager mPackageManager;
189     private NotificationManager mNotificationManager = null;
190     private ActivityManager mActivityManager = null;
191     private WallpaperManager mWallpaperManager = null;
192     private Context mReceiverRestrictedContext = null;
193     private SearchManager mSearchManager = null;
194     private SensorManager mSensorManager = null;
195     private StorageManager mStorageManager = null;
196     private UsbManager mUsbManager = null;
197     private Vibrator mVibrator = null;
198     private LayoutInflater mLayoutInflater = null;
199     private StatusBarManager mStatusBarManager = null;
200     private TelephonyManager mTelephonyManager = null;
201     private ClipboardManager mClipboardManager = null;
202     private boolean mRestricted;
203     private AccountManager mAccountManager; // protected by mSync
204     private DropBoxManager mDropBoxManager = null;
205     private DevicePolicyManager mDevicePolicyManager = null;
206     private UiModeManager mUiModeManager = null;
207     private DownloadManager mDownloadManager = null;
208     private NfcManager mNfcManager = null;
209
210     private final Object mSync = new Object();
211
212     private File mDatabasesDir;
213     private File mPreferencesDir;
214     private File mFilesDir;
215     private File mCacheDir;
216     private File mExternalFilesDir;
217     private File mExternalCacheDir;
218
219     private static long sInstanceCount = 0;
220
221     private static final String[] EMPTY_FILE_LIST = {};
222
223     // For debug only
224     /*
225     @Override
226     protected void finalize() throws Throwable {
227         super.finalize();
228         --sInstanceCount;
229     }
230     */
231
232     public static long getInstanceCount() {
233         return sInstanceCount;
234     }
235
236     @Override
237     public AssetManager getAssets() {
238         return mResources.getAssets();
239     }
240
241     @Override
242     public Resources getResources() {
243         return mResources;
244     }
245
246     @Override
247     public PackageManager getPackageManager() {
248         if (mPackageManager != null) {
249             return mPackageManager;
250         }
251
252         IPackageManager pm = ActivityThread.getPackageManager();
253         if (pm != null) {
254             // Doesn't matter if we make more than one instance.
255             return (mPackageManager = new ApplicationPackageManager(this, pm));
256         }
257
258         return null;
259     }
260
261     @Override
262     public ContentResolver getContentResolver() {
263         return mContentResolver;
264     }
265
266     @Override
267     public Looper getMainLooper() {
268         return mMainThread.getLooper();
269     }
270
271     @Override
272     public Context getApplicationContext() {
273         return (mPackageInfo != null) ?
274                 mPackageInfo.getApplication() : mMainThread.getApplication();
275     }
276
277     @Override
278     public void setTheme(int resid) {
279         mThemeResource = resid;
280     }
281
282     @Override
283     public Resources.Theme getTheme() {
284         if (mTheme == null) {
285             if (mThemeResource == 0) {
286                 mThemeResource = com.android.internal.R.style.Theme;
287             }
288             mTheme = mResources.newTheme();
289             mTheme.applyStyle(mThemeResource, true);
290         }
291         return mTheme;
292     }
293
294     @Override
295     public ClassLoader getClassLoader() {
296         return mPackageInfo != null ?
297                 mPackageInfo.getClassLoader() : ClassLoader.getSystemClassLoader();
298     }
299
300     @Override
301     public String getPackageName() {
302         if (mPackageInfo != null) {
303             return mPackageInfo.getPackageName();
304         }
305         throw new RuntimeException("Not supported in system context");
306     }
307
308     @Override
309     public ApplicationInfo getApplicationInfo() {
310         if (mPackageInfo != null) {
311             return mPackageInfo.getApplicationInfo();
312         }
313         throw new RuntimeException("Not supported in system context");
314     }
315
316     @Override
317     public String getPackageResourcePath() {
318         if (mPackageInfo != null) {
319             return mPackageInfo.getResDir();
320         }
321         throw new RuntimeException("Not supported in system context");
322     }
323
324     @Override
325     public String getPackageCodePath() {
326         if (mPackageInfo != null) {
327             return mPackageInfo.getAppDir();
328         }
329         throw new RuntimeException("Not supported in system context");
330     }
331
332     private static File makeBackupFile(File prefsFile) {
333         return new File(prefsFile.getPath() + ".bak");
334     }
335
336     public File getSharedPrefsFile(String name) {
337         return makeFilename(getPreferencesDir(), name + ".xml");
338     }
339
340     @Override
341     public SharedPreferences getSharedPreferences(String name, int mode) {
342         SharedPreferencesImpl sp;
343         File prefsFile;
344         boolean needInitialLoad = false;
345         synchronized (sSharedPrefs) {
346             sp = sSharedPrefs.get(name);
347             if (sp != null && !sp.hasFileChangedUnexpectedly()) {
348                 return sp;
349             }
350             prefsFile = getSharedPrefsFile(name);
351             if (sp == null) {
352                 sp = new SharedPreferencesImpl(prefsFile, mode, null);
353                 sSharedPrefs.put(name, sp);
354                 needInitialLoad = true;
355             }
356         }
357
358         synchronized (sp) {
359             if (needInitialLoad && sp.isLoaded()) {
360                 // lost the race to load; another thread handled it
361                 return sp;
362             }
363             File backup = makeBackupFile(prefsFile);
364             if (backup.exists()) {
365                 prefsFile.delete();
366                 backup.renameTo(prefsFile);
367             }
368
369             // Debugging
370             if (prefsFile.exists() && !prefsFile.canRead()) {
371                 Log.w(TAG, "Attempt to read preferences file " + prefsFile + " without permission");
372             }
373
374             Map map = null;
375             FileStatus stat = new FileStatus();
376             if (FileUtils.getFileStatus(prefsFile.getPath(), stat) && prefsFile.canRead()) {
377                 try {
378                     FileInputStream str = new FileInputStream(prefsFile);
379                     map = XmlUtils.readMapXml(str);
380                     str.close();
381                 } catch (org.xmlpull.v1.XmlPullParserException e) {
382                     Log.w(TAG, "getSharedPreferences", e);
383                 } catch (FileNotFoundException e) {
384                     Log.w(TAG, "getSharedPreferences", e);
385                 } catch (IOException e) {
386                     Log.w(TAG, "getSharedPreferences", e);
387                 }
388             }
389             sp.replace(map, stat);
390         }
391         return sp;
392     }
393
394     private File getPreferencesDir() {
395         synchronized (mSync) {
396             if (mPreferencesDir == null) {
397                 mPreferencesDir = new File(getDataDirFile(), "shared_prefs");
398             }
399             return mPreferencesDir;
400         }
401     }
402
403     @Override
404     public FileInputStream openFileInput(String name)
405         throws FileNotFoundException {
406         File f = makeFilename(getFilesDir(), name);
407         return new FileInputStream(f);
408     }
409
410     @Override
411     public FileOutputStream openFileOutput(String name, int mode)
412         throws FileNotFoundException {
413         final boolean append = (mode&MODE_APPEND) != 0;
414         File f = makeFilename(getFilesDir(), name);
415         try {
416             FileOutputStream fos = new FileOutputStream(f, append);
417             setFilePermissionsFromMode(f.getPath(), mode, 0);
418             return fos;
419         } catch (FileNotFoundException e) {
420         }
421
422         File parent = f.getParentFile();
423         parent.mkdir();
424         FileUtils.setPermissions(
425             parent.getPath(),
426             FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
427             -1, -1);
428         FileOutputStream fos = new FileOutputStream(f, append);
429         setFilePermissionsFromMode(f.getPath(), mode, 0);
430         return fos;
431     }
432
433     @Override
434     public boolean deleteFile(String name) {
435         File f = makeFilename(getFilesDir(), name);
436         return f.delete();
437     }
438
439     @Override
440     public File getFilesDir() {
441         synchronized (mSync) {
442             if (mFilesDir == null) {
443                 mFilesDir = new File(getDataDirFile(), "files");
444             }
445             if (!mFilesDir.exists()) {
446                 if(!mFilesDir.mkdirs()) {
447                     Log.w(TAG, "Unable to create files directory " + mFilesDir.getPath());
448                     return null;
449                 }
450                 FileUtils.setPermissions(
451                         mFilesDir.getPath(),
452                         FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
453                         -1, -1);
454             }
455             return mFilesDir;
456         }
457     }
458
459     @Override
460     public File getExternalFilesDir(String type) {
461         synchronized (mSync) {
462             if (mExternalFilesDir == null) {
463                 mExternalFilesDir = Environment.getExternalStorageAppFilesDirectory(
464                         getPackageName());
465             }
466             if (!mExternalFilesDir.exists()) {
467                 try {
468                     (new File(Environment.getExternalStorageAndroidDataDir(),
469                             ".nomedia")).createNewFile();
470                 } catch (IOException e) {
471                 }
472                 if (!mExternalFilesDir.mkdirs()) {
473                     Log.w(TAG, "Unable to create external files directory");
474                     return null;
475                 }
476             }
477             if (type == null) {
478                 return mExternalFilesDir;
479             }
480             File dir = new File(mExternalFilesDir, type);
481             if (!dir.exists()) {
482                 if (!dir.mkdirs()) {
483                     Log.w(TAG, "Unable to create external media directory " + dir);
484                     return null;
485                 }
486             }
487             return dir;
488         }
489     }
490
491     @Override
492     public File getCacheDir() {
493         synchronized (mSync) {
494             if (mCacheDir == null) {
495                 mCacheDir = new File(getDataDirFile(), "cache");
496             }
497             if (!mCacheDir.exists()) {
498                 if(!mCacheDir.mkdirs()) {
499                     Log.w(TAG, "Unable to create cache directory");
500                     return null;
501                 }
502                 FileUtils.setPermissions(
503                         mCacheDir.getPath(),
504                         FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
505                         -1, -1);
506             }
507         }
508         return mCacheDir;
509     }
510
511     @Override
512     public File getExternalCacheDir() {
513         synchronized (mSync) {
514             if (mExternalCacheDir == null) {
515                 mExternalCacheDir = Environment.getExternalStorageAppCacheDirectory(
516                         getPackageName());
517             }
518             if (!mExternalCacheDir.exists()) {
519                 try {
520                     (new File(Environment.getExternalStorageAndroidDataDir(),
521                             ".nomedia")).createNewFile();
522                 } catch (IOException e) {
523                 }
524                 if (!mExternalCacheDir.mkdirs()) {
525                     Log.w(TAG, "Unable to create external cache directory");
526                     return null;
527                 }
528             }
529             return mExternalCacheDir;
530         }
531     }
532
533     @Override
534     public File getFileStreamPath(String name) {
535         return makeFilename(getFilesDir(), name);
536     }
537
538     @Override
539     public String[] fileList() {
540         final String[] list = getFilesDir().list();
541         return (list != null) ? list : EMPTY_FILE_LIST;
542     }
543
544     @Override
545     public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory) {
546         File f = validateFilePath(name, true);
547         SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(f, factory);
548         setFilePermissionsFromMode(f.getPath(), mode, 0);
549         return db;
550     }
551
552     @Override
553     public boolean deleteDatabase(String name) {
554         try {
555             File f = validateFilePath(name, false);
556             return f.delete();
557         } catch (Exception e) {
558         }
559         return false;
560     }
561
562     @Override
563     public File getDatabasePath(String name) {
564         return validateFilePath(name, false);
565     }
566
567     @Override
568     public String[] databaseList() {
569         final String[] list = getDatabasesDir().list();
570         return (list != null) ? list : EMPTY_FILE_LIST;
571     }
572
573
574     private File getDatabasesDir() {
575         synchronized (mSync) {
576             if (mDatabasesDir == null) {
577                 mDatabasesDir = new File(getDataDirFile(), "databases");
578             }
579             if (mDatabasesDir.getPath().equals("databases")) {
580                 mDatabasesDir = new File("/data/system");
581             }
582             return mDatabasesDir;
583         }
584     }
585
586     @Override
587     public Drawable getWallpaper() {
588         return getWallpaperManager().getDrawable();
589     }
590
591     @Override
592     public Drawable peekWallpaper() {
593         return getWallpaperManager().peekDrawable();
594     }
595
596     @Override
597     public int getWallpaperDesiredMinimumWidth() {
598         return getWallpaperManager().getDesiredMinimumWidth();
599     }
600
601     @Override
602     public int getWallpaperDesiredMinimumHeight() {
603         return getWallpaperManager().getDesiredMinimumHeight();
604     }
605
606     @Override
607     public void setWallpaper(Bitmap bitmap) throws IOException  {
608         getWallpaperManager().setBitmap(bitmap);
609     }
610
611     @Override
612     public void setWallpaper(InputStream data) throws IOException {
613         getWallpaperManager().setStream(data);
614     }
615
616     @Override
617     public void clearWallpaper() throws IOException {
618         getWallpaperManager().clear();
619     }
620
621     @Override
622     public void startActivity(Intent intent) {
623         if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
624             throw new AndroidRuntimeException(
625                     "Calling startActivity() from outside of an Activity "
626                     + " context requires the FLAG_ACTIVITY_NEW_TASK flag."
627                     + " Is this really what you want?");
628         }
629         mMainThread.getInstrumentation().execStartActivity(
630             getOuterContext(), mMainThread.getApplicationThread(), null, null, intent, -1);
631     }
632
633     @Override
634     public void startIntentSender(IntentSender intent,
635             Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
636             throws IntentSender.SendIntentException {
637         try {
638             String resolvedType = null;
639             if (fillInIntent != null) {
640                 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
641             }
642             int result = ActivityManagerNative.getDefault()
643                 .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
644                         fillInIntent, resolvedType, null, null,
645                         0, flagsMask, flagsValues);
646             if (result == IActivityManager.START_CANCELED) {
647                 throw new IntentSender.SendIntentException();
648             }
649             Instrumentation.checkStartActivityResult(result, null);
650         } catch (RemoteException e) {
651         }
652     }
653
654     @Override
655     public void sendBroadcast(Intent intent) {
656         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
657         try {
658             ActivityManagerNative.getDefault().broadcastIntent(
659                 mMainThread.getApplicationThread(), intent, resolvedType, null,
660                 Activity.RESULT_OK, null, null, null, false, false);
661         } catch (RemoteException e) {
662         }
663     }
664
665     @Override
666     public void sendBroadcast(Intent intent, String receiverPermission) {
667         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
668         try {
669             ActivityManagerNative.getDefault().broadcastIntent(
670                 mMainThread.getApplicationThread(), intent, resolvedType, null,
671                 Activity.RESULT_OK, null, null, receiverPermission, false, false);
672         } catch (RemoteException e) {
673         }
674     }
675
676     @Override
677     public void sendOrderedBroadcast(Intent intent,
678             String receiverPermission) {
679         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
680         try {
681             ActivityManagerNative.getDefault().broadcastIntent(
682                 mMainThread.getApplicationThread(), intent, resolvedType, null,
683                 Activity.RESULT_OK, null, null, receiverPermission, true, false);
684         } catch (RemoteException e) {
685         }
686     }
687
688     @Override
689     public void sendOrderedBroadcast(Intent intent,
690             String receiverPermission, BroadcastReceiver resultReceiver,
691             Handler scheduler, int initialCode, String initialData,
692             Bundle initialExtras) {
693         IIntentReceiver rd = null;
694         if (resultReceiver != null) {
695             if (mPackageInfo != null) {
696                 if (scheduler == null) {
697                     scheduler = mMainThread.getHandler();
698                 }
699                 rd = mPackageInfo.getReceiverDispatcher(
700                     resultReceiver, getOuterContext(), scheduler,
701                     mMainThread.getInstrumentation(), false);
702             } else {
703                 if (scheduler == null) {
704                     scheduler = mMainThread.getHandler();
705                 }
706                 rd = new LoadedApk.ReceiverDispatcher(
707                         resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
708             }
709         }
710         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
711         try {
712             ActivityManagerNative.getDefault().broadcastIntent(
713                 mMainThread.getApplicationThread(), intent, resolvedType, rd,
714                 initialCode, initialData, initialExtras, receiverPermission,
715                 true, false);
716         } catch (RemoteException e) {
717         }
718     }
719
720     @Override
721     public void sendStickyBroadcast(Intent intent) {
722         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
723         try {
724             ActivityManagerNative.getDefault().broadcastIntent(
725                 mMainThread.getApplicationThread(), intent, resolvedType, null,
726                 Activity.RESULT_OK, null, null, null, false, true);
727         } catch (RemoteException e) {
728         }
729     }
730
731     @Override
732     public void sendStickyOrderedBroadcast(Intent intent,
733             BroadcastReceiver resultReceiver,
734             Handler scheduler, int initialCode, String initialData,
735             Bundle initialExtras) {
736         IIntentReceiver rd = null;
737         if (resultReceiver != null) {
738             if (mPackageInfo != null) {
739                 if (scheduler == null) {
740                     scheduler = mMainThread.getHandler();
741                 }
742                 rd = mPackageInfo.getReceiverDispatcher(
743                     resultReceiver, getOuterContext(), scheduler,
744                     mMainThread.getInstrumentation(), false);
745             } else {
746                 if (scheduler == null) {
747                     scheduler = mMainThread.getHandler();
748                 }
749                 rd = new LoadedApk.ReceiverDispatcher(
750                         resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
751             }
752         }
753         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
754         try {
755             ActivityManagerNative.getDefault().broadcastIntent(
756                 mMainThread.getApplicationThread(), intent, resolvedType, rd,
757                 initialCode, initialData, initialExtras, null,
758                 true, true);
759         } catch (RemoteException e) {
760         }
761     }
762
763     @Override
764     public void removeStickyBroadcast(Intent intent) {
765         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
766         if (resolvedType != null) {
767             intent = new Intent(intent);
768             intent.setDataAndType(intent.getData(), resolvedType);
769         }
770         try {
771             ActivityManagerNative.getDefault().unbroadcastIntent(
772                 mMainThread.getApplicationThread(), intent);
773         } catch (RemoteException e) {
774         }
775     }
776
777     @Override
778     public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
779         return registerReceiver(receiver, filter, null, null);
780     }
781
782     @Override
783     public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
784             String broadcastPermission, Handler scheduler) {
785         return registerReceiverInternal(receiver, filter, broadcastPermission,
786                 scheduler, getOuterContext());
787     }
788
789     private Intent registerReceiverInternal(BroadcastReceiver receiver,
790             IntentFilter filter, String broadcastPermission,
791             Handler scheduler, Context context) {
792         IIntentReceiver rd = null;
793         if (receiver != null) {
794             if (mPackageInfo != null && context != null) {
795                 if (scheduler == null) {
796                     scheduler = mMainThread.getHandler();
797                 }
798                 rd = mPackageInfo.getReceiverDispatcher(
799                     receiver, context, scheduler,
800                     mMainThread.getInstrumentation(), true);
801             } else {
802                 if (scheduler == null) {
803                     scheduler = mMainThread.getHandler();
804                 }
805                 rd = new LoadedApk.ReceiverDispatcher(
806                         receiver, context, scheduler, null, true).getIIntentReceiver();
807             }
808         }
809         try {
810             return ActivityManagerNative.getDefault().registerReceiver(
811                     mMainThread.getApplicationThread(),
812                     rd, filter, broadcastPermission);
813         } catch (RemoteException e) {
814             return null;
815         }
816     }
817
818     @Override
819     public void unregisterReceiver(BroadcastReceiver receiver) {
820         if (mPackageInfo != null) {
821             IIntentReceiver rd = mPackageInfo.forgetReceiverDispatcher(
822                     getOuterContext(), receiver);
823             try {
824                 ActivityManagerNative.getDefault().unregisterReceiver(rd);
825             } catch (RemoteException e) {
826             }
827         } else {
828             throw new RuntimeException("Not supported in system context");
829         }
830     }
831
832     @Override
833     public ComponentName startService(Intent service) {
834         try {
835             ComponentName cn = ActivityManagerNative.getDefault().startService(
836                 mMainThread.getApplicationThread(), service,
837                 service.resolveTypeIfNeeded(getContentResolver()));
838             if (cn != null && cn.getPackageName().equals("!")) {
839                 throw new SecurityException(
840                         "Not allowed to start service " + service
841                         + " without permission " + cn.getClassName());
842             }
843             return cn;
844         } catch (RemoteException e) {
845             return null;
846         }
847     }
848
849     @Override
850     public boolean stopService(Intent service) {
851         try {
852             int res = ActivityManagerNative.getDefault().stopService(
853                 mMainThread.getApplicationThread(), service,
854                 service.resolveTypeIfNeeded(getContentResolver()));
855             if (res < 0) {
856                 throw new SecurityException(
857                         "Not allowed to stop service " + service);
858             }
859             return res != 0;
860         } catch (RemoteException e) {
861             return false;
862         }
863     }
864
865     @Override
866     public boolean bindService(Intent service, ServiceConnection conn,
867             int flags) {
868         IServiceConnection sd;
869         if (mPackageInfo != null) {
870             sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(),
871                     mMainThread.getHandler(), flags);
872         } else {
873             throw new RuntimeException("Not supported in system context");
874         }
875         try {
876             int res = ActivityManagerNative.getDefault().bindService(
877                 mMainThread.getApplicationThread(), getActivityToken(),
878                 service, service.resolveTypeIfNeeded(getContentResolver()),
879                 sd, flags);
880             if (res < 0) {
881                 throw new SecurityException(
882                         "Not allowed to bind to service " + service);
883             }
884             return res != 0;
885         } catch (RemoteException e) {
886             return false;
887         }
888     }
889
890     @Override
891     public void unbindService(ServiceConnection conn) {
892         if (mPackageInfo != null) {
893             IServiceConnection sd = mPackageInfo.forgetServiceDispatcher(
894                     getOuterContext(), conn);
895             try {
896                 ActivityManagerNative.getDefault().unbindService(sd);
897             } catch (RemoteException e) {
898             }
899         } else {
900             throw new RuntimeException("Not supported in system context");
901         }
902     }
903
904     @Override
905     public boolean startInstrumentation(ComponentName className,
906             String profileFile, Bundle arguments) {
907         try {
908             return ActivityManagerNative.getDefault().startInstrumentation(
909                     className, profileFile, 0, arguments, null);
910         } catch (RemoteException e) {
911             // System has crashed, nothing we can do.
912         }
913         return false;
914     }
915
916     @Override
917     public Object getSystemService(String name) {
918         if (WINDOW_SERVICE.equals(name)) {
919             return WindowManagerImpl.getDefault();
920         } else if (LAYOUT_INFLATER_SERVICE.equals(name)) {
921             synchronized (mSync) {
922                 LayoutInflater inflater = mLayoutInflater;
923                 if (inflater != null) {
924                     return inflater;
925                 }
926                 mLayoutInflater = inflater =
927                     PolicyManager.makeNewLayoutInflater(getOuterContext());
928                 return inflater;
929             }
930         } else if (ACTIVITY_SERVICE.equals(name)) {
931             return getActivityManager();
932         } else if (INPUT_METHOD_SERVICE.equals(name)) {
933             return InputMethodManager.getInstance(this);
934         } else if (ALARM_SERVICE.equals(name)) {
935             return getAlarmManager();
936         } else if (ACCOUNT_SERVICE.equals(name)) {
937             return getAccountManager();
938         } else if (POWER_SERVICE.equals(name)) {
939             return getPowerManager();
940         } else if (CONNECTIVITY_SERVICE.equals(name)) {
941             return getConnectivityManager();
942         } else if (THROTTLE_SERVICE.equals(name)) {
943             return getThrottleManager();
944         } else if (WIFI_SERVICE.equals(name)) {
945             return getWifiManager();
946         } else if (ETHERNET_SERVICE.equals(name)) {
947             return getEthernetManager();
948         } else if (NOTIFICATION_SERVICE.equals(name)) {
949             return getNotificationManager();
950         } else if (KEYGUARD_SERVICE.equals(name)) {
951             return new KeyguardManager();
952         } else if (ACCESSIBILITY_SERVICE.equals(name)) {
953             return AccessibilityManager.getInstance(this);
954         } else if (LOCATION_SERVICE.equals(name)) {
955             return getLocationManager();
956         } else if (SEARCH_SERVICE.equals(name)) {
957             return getSearchManager();
958         } else if (SENSOR_SERVICE.equals(name)) {
959             return getSensorManager();
960         } else if (STORAGE_SERVICE.equals(name)) {
961             return getStorageManager();
962         } else if (USB_SERVICE.equals(name)) {
963             return getUsbManager();
964         } else if (VIBRATOR_SERVICE.equals(name)) {
965             return getVibrator();
966         } else if (STATUS_BAR_SERVICE.equals(name)) {
967             synchronized (mSync) {
968                 if (mStatusBarManager == null) {
969                     mStatusBarManager = new StatusBarManager(getOuterContext());
970                 }
971                 return mStatusBarManager;
972             }
973         } else if (AUDIO_SERVICE.equals(name)) {
974             return getAudioManager();
975         } else if (TELEPHONY_SERVICE.equals(name)) {
976             return getTelephonyManager();
977         } else if (CLIPBOARD_SERVICE.equals(name)) {
978             return getClipboardManager();
979         } else if (WALLPAPER_SERVICE.equals(name)) {
980             return getWallpaperManager();
981         } else if (DROPBOX_SERVICE.equals(name)) {
982             return getDropBoxManager();
983         } else if (DEVICE_POLICY_SERVICE.equals(name)) {
984             return getDevicePolicyManager();
985         } else if (UI_MODE_SERVICE.equals(name)) {
986             return getUiModeManager();
987         } else if (DOWNLOAD_SERVICE.equals(name)) {
988             return getDownloadManager();
989         } else if (NFC_SERVICE.equals(name)) {
990             return getNfcManager();
991         }
992
993         return null;
994     }
995
996     private AccountManager getAccountManager() {
997         synchronized (mSync) {
998             if (mAccountManager == null) {
999                 IBinder b = ServiceManager.getService(ACCOUNT_SERVICE);
1000                 IAccountManager service = IAccountManager.Stub.asInterface(b);
1001                 mAccountManager = new AccountManager(this, service);
1002             }
1003             return mAccountManager;
1004         }
1005     }
1006
1007     private ActivityManager getActivityManager() {
1008         synchronized (mSync) {
1009             if (mActivityManager == null) {
1010                 mActivityManager = new ActivityManager(getOuterContext(),
1011                         mMainThread.getHandler());
1012             }
1013         }
1014         return mActivityManager;
1015     }
1016
1017     private AlarmManager getAlarmManager() {
1018         synchronized (sSync) {
1019             if (sAlarmManager == null) {
1020                 IBinder b = ServiceManager.getService(ALARM_SERVICE);
1021                 IAlarmManager service = IAlarmManager.Stub.asInterface(b);
1022                 sAlarmManager = new AlarmManager(service);
1023             }
1024         }
1025         return sAlarmManager;
1026     }
1027
1028     private PowerManager getPowerManager() {
1029         synchronized (sSync) {
1030             if (sPowerManager == null) {
1031                 IBinder b = ServiceManager.getService(POWER_SERVICE);
1032                 IPowerManager service = IPowerManager.Stub.asInterface(b);
1033                 sPowerManager = new PowerManager(service, mMainThread.getHandler());
1034             }
1035         }
1036         return sPowerManager;
1037     }
1038
1039     private ConnectivityManager getConnectivityManager()
1040     {
1041         synchronized (sSync) {
1042             if (sConnectivityManager == null) {
1043                 IBinder b = ServiceManager.getService(CONNECTIVITY_SERVICE);
1044                 IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
1045                 sConnectivityManager = new ConnectivityManager(service);
1046             }
1047         }
1048         return sConnectivityManager;
1049     }
1050
1051     private ThrottleManager getThrottleManager()
1052     {
1053         synchronized (sSync) {
1054             if (sThrottleManager == null) {
1055                 IBinder b = ServiceManager.getService(THROTTLE_SERVICE);
1056                 IThrottleManager service = IThrottleManager.Stub.asInterface(b);
1057                 sThrottleManager = new ThrottleManager(service);
1058             }
1059         }
1060         return sThrottleManager;
1061     }
1062
1063     private WifiManager getWifiManager()
1064     {
1065         synchronized (sSync) {
1066             if (sWifiManager == null) {
1067                 IBinder b = ServiceManager.getService(WIFI_SERVICE);
1068                 IWifiManager service = IWifiManager.Stub.asInterface(b);
1069                 sWifiManager = new WifiManager(service, mMainThread.getHandler());
1070             }
1071         }
1072         return sWifiManager;
1073     }
1074
1075     private EthernetManager getEthernetManager()
1076     {
1077         synchronized (sSync) {
1078             if (sEthernetManager == null) {
1079                 IBinder b = ServiceManager.getService(ETHERNET_SERVICE);
1080                 if (b == null) 
1081                 {
1082                         Log.w(TAG, "Error getting service name:" + ETHERNET_SERVICE);
1083                 }
1084                 IEthernetManager service = IEthernetManager.Stub.asInterface(b);
1085                 sEthernetManager = new EthernetManager(service, mMainThread.getHandler());
1086             }
1087         }
1088         return sEthernetManager;
1089     }
1090
1091     private NotificationManager getNotificationManager() {
1092         synchronized (mSync) {
1093             if (mNotificationManager == null) {
1094                 mNotificationManager = new NotificationManager(
1095                         new ContextThemeWrapper(getOuterContext(), com.android.internal.R.style.Theme_Dialog),
1096                         mMainThread.getHandler());
1097             }
1098         }
1099         return mNotificationManager;
1100     }
1101
1102     private WallpaperManager getWallpaperManager() {
1103         synchronized (mSync) {
1104             if (mWallpaperManager == null) {
1105                 mWallpaperManager = new WallpaperManager(getOuterContext(),
1106                         mMainThread.getHandler());
1107             }
1108         }
1109         return mWallpaperManager;
1110     }
1111
1112     private TelephonyManager getTelephonyManager() {
1113         synchronized (mSync) {
1114             if (mTelephonyManager == null) {
1115                 mTelephonyManager = new TelephonyManager(getOuterContext());
1116             }
1117         }
1118         return mTelephonyManager;
1119     }
1120
1121     private ClipboardManager getClipboardManager() {
1122         synchronized (mSync) {
1123             if (mClipboardManager == null) {
1124                 mClipboardManager = new ClipboardManager(getOuterContext(),
1125                         mMainThread.getHandler());
1126             }
1127         }
1128         return mClipboardManager;
1129     }
1130
1131     private LocationManager getLocationManager() {
1132         synchronized (sSync) {
1133             if (sLocationManager == null) {
1134                 IBinder b = ServiceManager.getService(LOCATION_SERVICE);
1135                 ILocationManager service = ILocationManager.Stub.asInterface(b);
1136                 sLocationManager = new LocationManager(service);
1137             }
1138         }
1139         return sLocationManager;
1140     }
1141
1142     private SearchManager getSearchManager() {
1143         synchronized (mSync) {
1144             if (mSearchManager == null) {
1145                 mSearchManager = new SearchManager(getOuterContext(), mMainThread.getHandler());
1146             }
1147         }
1148         return mSearchManager;
1149     }
1150
1151     private SensorManager getSensorManager() {
1152         synchronized (mSync) {
1153             if (mSensorManager == null) {
1154                 mSensorManager = new SensorManager(mMainThread.getHandler().getLooper());
1155             }
1156         }
1157         return mSensorManager;
1158     }
1159
1160     private StorageManager getStorageManager() {
1161         synchronized (mSync) {
1162             if (mStorageManager == null) {
1163                 try {
1164                     mStorageManager = new StorageManager(mMainThread.getHandler().getLooper());
1165                 } catch (RemoteException rex) {
1166                     Log.e(TAG, "Failed to create StorageManager", rex);
1167                     mStorageManager = null;
1168                 }
1169             }
1170         }
1171         return mStorageManager;
1172     }
1173
1174     private UsbManager getUsbManager() {
1175         synchronized (mSync) {
1176             if (mUsbManager == null) {
1177                 IBinder b = ServiceManager.getService(USB_SERVICE);
1178                 IUsbManager service = IUsbManager.Stub.asInterface(b);
1179                 mUsbManager = new UsbManager(this, service);
1180             }
1181         }
1182         return mUsbManager;
1183     }
1184
1185     private Vibrator getVibrator() {
1186         synchronized (mSync) {
1187             if (mVibrator == null) {
1188                 mVibrator = new Vibrator();
1189             }
1190         }
1191         return mVibrator;
1192     }
1193
1194     private AudioManager getAudioManager()
1195     {
1196         if (mAudioManager == null) {
1197             mAudioManager = new AudioManager(this);
1198         }
1199         return mAudioManager;
1200     }
1201
1202     /* package */ static DropBoxManager createDropBoxManager() {
1203         IBinder b = ServiceManager.getService(DROPBOX_SERVICE);
1204         IDropBoxManagerService service = IDropBoxManagerService.Stub.asInterface(b);
1205         return new DropBoxManager(service);
1206     }
1207
1208     private DropBoxManager getDropBoxManager() {
1209         synchronized (mSync) {
1210             if (mDropBoxManager == null) {
1211                 mDropBoxManager = createDropBoxManager();
1212             }
1213         }
1214         return mDropBoxManager;
1215     }
1216
1217     private DevicePolicyManager getDevicePolicyManager() {
1218         synchronized (mSync) {
1219             if (mDevicePolicyManager == null) {
1220                 mDevicePolicyManager = DevicePolicyManager.create(this,
1221                         mMainThread.getHandler());
1222             }
1223         }
1224         return mDevicePolicyManager;
1225     }
1226
1227     private UiModeManager getUiModeManager() {
1228         synchronized (mSync) {
1229             if (mUiModeManager == null) {
1230                 mUiModeManager = new UiModeManager();
1231             }
1232         }
1233         return mUiModeManager;
1234     }
1235
1236     private DownloadManager getDownloadManager() {
1237         synchronized (mSync) {
1238             if (mDownloadManager == null) {
1239                 mDownloadManager = new DownloadManager(getContentResolver(), getPackageName());
1240             }
1241         }
1242         return mDownloadManager;
1243     }
1244
1245     private NfcManager getNfcManager() {
1246         synchronized (mSync) {
1247             if (mNfcManager == null) {
1248                 mNfcManager = new NfcManager(this);
1249             }
1250         }
1251         return mNfcManager;
1252     }
1253
1254     @Override
1255     public int checkPermission(String permission, int pid, int uid) {
1256         if (permission == null) {
1257             throw new IllegalArgumentException("permission is null");
1258         }
1259
1260         if (!Process.supportsProcesses()) {
1261             return PackageManager.PERMISSION_GRANTED;
1262         }
1263         try {
1264             return ActivityManagerNative.getDefault().checkPermission(
1265                     permission, pid, uid);
1266         } catch (RemoteException e) {
1267             return PackageManager.PERMISSION_DENIED;
1268         }
1269     }
1270
1271     @Override
1272     public int checkCallingPermission(String permission) {
1273         if (permission == null) {
1274             throw new IllegalArgumentException("permission is null");
1275         }
1276
1277         if (!Process.supportsProcesses()) {
1278             return PackageManager.PERMISSION_GRANTED;
1279         }
1280         int pid = Binder.getCallingPid();
1281         if (pid != Process.myPid()) {
1282             return checkPermission(permission, pid,
1283                     Binder.getCallingUid());
1284         }
1285         return PackageManager.PERMISSION_DENIED;
1286     }
1287
1288     @Override
1289     public int checkCallingOrSelfPermission(String permission) {
1290         if (permission == null) {
1291             throw new IllegalArgumentException("permission is null");
1292         }
1293
1294         return checkPermission(permission, Binder.getCallingPid(),
1295                 Binder.getCallingUid());
1296     }
1297
1298     private void enforce(
1299             String permission, int resultOfCheck,
1300             boolean selfToo, int uid, String message) {
1301         if (resultOfCheck != PackageManager.PERMISSION_GRANTED) {
1302             throw new SecurityException(
1303                     (message != null ? (message + ": ") : "") +
1304                     (selfToo
1305                      ? "Neither user " + uid + " nor current process has "
1306                      : "User " + uid + " does not have ") +
1307                     permission +
1308                     ".");
1309         }
1310     }
1311
1312     public void enforcePermission(
1313             String permission, int pid, int uid, String message) {
1314         enforce(permission,
1315                 checkPermission(permission, pid, uid),
1316                 false,
1317                 uid,
1318                 message);
1319     }
1320
1321     public void enforceCallingPermission(String permission, String message) {
1322         enforce(permission,
1323                 checkCallingPermission(permission),
1324                 false,
1325                 Binder.getCallingUid(),
1326                 message);
1327     }
1328
1329     public void enforceCallingOrSelfPermission(
1330             String permission, String message) {
1331         enforce(permission,
1332                 checkCallingOrSelfPermission(permission),
1333                 true,
1334                 Binder.getCallingUid(),
1335                 message);
1336     }
1337
1338     @Override
1339     public void grantUriPermission(String toPackage, Uri uri, int modeFlags) {
1340          try {
1341             ActivityManagerNative.getDefault().grantUriPermission(
1342                     mMainThread.getApplicationThread(), toPackage, uri,
1343                     modeFlags);
1344         } catch (RemoteException e) {
1345         }
1346     }
1347
1348     @Override
1349     public void revokeUriPermission(Uri uri, int modeFlags) {
1350          try {
1351             ActivityManagerNative.getDefault().revokeUriPermission(
1352                     mMainThread.getApplicationThread(), uri,
1353                     modeFlags);
1354         } catch (RemoteException e) {
1355         }
1356     }
1357
1358     @Override
1359     public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
1360         if (!Process.supportsProcesses()) {
1361             return PackageManager.PERMISSION_GRANTED;
1362         }
1363         try {
1364             return ActivityManagerNative.getDefault().checkUriPermission(
1365                     uri, pid, uid, modeFlags);
1366         } catch (RemoteException e) {
1367             return PackageManager.PERMISSION_DENIED;
1368         }
1369     }
1370
1371     @Override
1372     public int checkCallingUriPermission(Uri uri, int modeFlags) {
1373         if (!Process.supportsProcesses()) {
1374             return PackageManager.PERMISSION_GRANTED;
1375         }
1376         int pid = Binder.getCallingPid();
1377         if (pid != Process.myPid()) {
1378             return checkUriPermission(uri, pid,
1379                     Binder.getCallingUid(), modeFlags);
1380         }
1381         return PackageManager.PERMISSION_DENIED;
1382     }
1383
1384     @Override
1385     public int checkCallingOrSelfUriPermission(Uri uri, int modeFlags) {
1386         return checkUriPermission(uri, Binder.getCallingPid(),
1387                 Binder.getCallingUid(), modeFlags);
1388     }
1389
1390     @Override
1391     public int checkUriPermission(Uri uri, String readPermission,
1392             String writePermission, int pid, int uid, int modeFlags) {
1393         if (DEBUG) {
1394             Log.i("foo", "checkUriPermission: uri=" + uri + "readPermission="
1395                     + readPermission + " writePermission=" + writePermission
1396                     + " pid=" + pid + " uid=" + uid + " mode" + modeFlags);
1397         }
1398         if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
1399             if (readPermission == null
1400                     || checkPermission(readPermission, pid, uid)
1401                     == PackageManager.PERMISSION_GRANTED) {
1402                 return PackageManager.PERMISSION_GRANTED;
1403             }
1404         }
1405         if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
1406             if (writePermission == null
1407                     || checkPermission(writePermission, pid, uid)
1408                     == PackageManager.PERMISSION_GRANTED) {
1409                 return PackageManager.PERMISSION_GRANTED;
1410             }
1411         }
1412         return uri != null ? checkUriPermission(uri, pid, uid, modeFlags)
1413                 : PackageManager.PERMISSION_DENIED;
1414     }
1415
1416     private String uriModeFlagToString(int uriModeFlags) {
1417         switch (uriModeFlags) {
1418             case Intent.FLAG_GRANT_READ_URI_PERMISSION |
1419                     Intent.FLAG_GRANT_WRITE_URI_PERMISSION:
1420                 return "read and write";
1421             case Intent.FLAG_GRANT_READ_URI_PERMISSION:
1422                 return "read";
1423             case Intent.FLAG_GRANT_WRITE_URI_PERMISSION:
1424                 return "write";
1425         }
1426         throw new IllegalArgumentException(
1427                 "Unknown permission mode flags: " + uriModeFlags);
1428     }
1429
1430     private void enforceForUri(
1431             int modeFlags, int resultOfCheck, boolean selfToo,
1432             int uid, Uri uri, String message) {
1433         if (resultOfCheck != PackageManager.PERMISSION_GRANTED) {
1434             throw new SecurityException(
1435                     (message != null ? (message + ": ") : "") +
1436                     (selfToo
1437                      ? "Neither user " + uid + " nor current process has "
1438                      : "User " + uid + " does not have ") +
1439                     uriModeFlagToString(modeFlags) +
1440                     " permission on " +
1441                     uri +
1442                     ".");
1443         }
1444     }
1445
1446     public void enforceUriPermission(
1447             Uri uri, int pid, int uid, int modeFlags, String message) {
1448         enforceForUri(
1449                 modeFlags, checkUriPermission(uri, pid, uid, modeFlags),
1450                 false, uid, uri, message);
1451     }
1452
1453     public void enforceCallingUriPermission(
1454             Uri uri, int modeFlags, String message) {
1455         enforceForUri(
1456                 modeFlags, checkCallingUriPermission(uri, modeFlags),
1457                 false, Binder.getCallingUid(), uri, message);
1458     }
1459
1460     public void enforceCallingOrSelfUriPermission(
1461             Uri uri, int modeFlags, String message) {
1462         enforceForUri(
1463                 modeFlags,
1464                 checkCallingOrSelfUriPermission(uri, modeFlags), true,
1465                 Binder.getCallingUid(), uri, message);
1466     }
1467
1468     public void enforceUriPermission(
1469             Uri uri, String readPermission, String writePermission,
1470             int pid, int uid, int modeFlags, String message) {
1471         enforceForUri(modeFlags,
1472                       checkUriPermission(
1473                               uri, readPermission, writePermission, pid, uid,
1474                               modeFlags),
1475                       false,
1476                       uid,
1477                       uri,
1478                       message);
1479     }
1480
1481     @Override
1482     public Context createPackageContext(String packageName, int flags)
1483         throws PackageManager.NameNotFoundException {
1484         if (packageName.equals("system") || packageName.equals("android")) {
1485             return new ContextImpl(mMainThread.getSystemContext());
1486         }
1487
1488         LoadedApk pi =
1489             mMainThread.getPackageInfo(packageName, flags);
1490         if (pi != null) {
1491             ContextImpl c = new ContextImpl();
1492             c.mRestricted = (flags & CONTEXT_RESTRICTED) == CONTEXT_RESTRICTED;
1493             c.init(pi, null, mMainThread, mResources);
1494             if (c.mResources != null) {
1495                 return c;
1496             }
1497         }
1498
1499         // Should be a better exception.
1500         throw new PackageManager.NameNotFoundException(
1501             "Application package " + packageName + " not found");
1502     }
1503
1504     @Override
1505     public boolean isRestricted() {
1506         return mRestricted;
1507     }
1508
1509     private File getDataDirFile() {
1510         if (mPackageInfo != null) {
1511             return mPackageInfo.getDataDirFile();
1512         }
1513         throw new RuntimeException("Not supported in system context");
1514     }
1515
1516     @Override
1517     public File getDir(String name, int mode) {
1518         name = "app_" + name;
1519         File file = makeFilename(getDataDirFile(), name);
1520         if (!file.exists()) {
1521             file.mkdir();
1522             setFilePermissionsFromMode(file.getPath(), mode,
1523                     FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH);
1524         }
1525         return file;
1526     }
1527
1528     static ContextImpl createSystemContext(ActivityThread mainThread) {
1529         ContextImpl context = new ContextImpl();
1530         context.init(Resources.getSystem(), mainThread);
1531         return context;
1532     }
1533
1534     ContextImpl() {
1535         // For debug only
1536         //++sInstanceCount;
1537         mOuterContext = this;
1538     }
1539
1540     /**
1541      * Create a new ApplicationContext from an existing one.  The new one
1542      * works and operates the same as the one it is copying.
1543      *
1544      * @param context Existing application context.
1545      */
1546     public ContextImpl(ContextImpl context) {
1547         ++sInstanceCount;
1548         mPackageInfo = context.mPackageInfo;
1549         mResources = context.mResources;
1550         mMainThread = context.mMainThread;
1551         mContentResolver = context.mContentResolver;
1552         mOuterContext = this;
1553     }
1554
1555     final void init(LoadedApk packageInfo,
1556             IBinder activityToken, ActivityThread mainThread) {
1557         init(packageInfo, activityToken, mainThread, null);
1558     }
1559
1560     final void init(LoadedApk packageInfo,
1561                 IBinder activityToken, ActivityThread mainThread,
1562                 Resources container) {
1563         mPackageInfo = packageInfo;
1564         mResources = mPackageInfo.getResources(mainThread);
1565
1566         if (mResources != null && container != null
1567                 && container.getCompatibilityInfo().applicationScale !=
1568                         mResources.getCompatibilityInfo().applicationScale) {
1569             if (DEBUG) {
1570                 Log.d(TAG, "loaded context has different scaling. Using container's" +
1571                         " compatiblity info:" + container.getDisplayMetrics());
1572             }
1573             mResources = mainThread.getTopLevelResources(
1574                     mPackageInfo.getResDir(), container.getCompatibilityInfo().copy());
1575         }
1576         mMainThread = mainThread;
1577         mContentResolver = new ApplicationContentResolver(this, mainThread);
1578
1579         setActivityToken(activityToken);
1580     }
1581
1582     final void init(Resources resources, ActivityThread mainThread) {
1583         mPackageInfo = null;
1584         mResources = resources;
1585         mMainThread = mainThread;
1586         mContentResolver = new ApplicationContentResolver(this, mainThread);
1587     }
1588
1589     final void scheduleFinalCleanup(String who, String what) {
1590         mMainThread.scheduleContextCleanup(this, who, what);
1591     }
1592
1593     final void performFinalCleanup(String who, String what) {
1594         //Log.i(TAG, "Cleanup up context: " + this);
1595         mPackageInfo.removeContextRegistrations(getOuterContext(), who, what);
1596     }
1597
1598     final Context getReceiverRestrictedContext() {
1599         if (mReceiverRestrictedContext != null) {
1600             return mReceiverRestrictedContext;
1601         }
1602         return mReceiverRestrictedContext = new ReceiverRestrictedContext(getOuterContext());
1603     }
1604
1605     final void setActivityToken(IBinder token) {
1606         mActivityToken = token;
1607     }
1608
1609     final void setOuterContext(Context context) {
1610         mOuterContext = context;
1611     }
1612
1613     final Context getOuterContext() {
1614         return mOuterContext;
1615     }
1616
1617     final IBinder getActivityToken() {
1618         return mActivityToken;
1619     }
1620
1621     private static void setFilePermissionsFromMode(String name, int mode,
1622             int extraPermissions) {
1623         int perms = FileUtils.S_IRUSR|FileUtils.S_IWUSR
1624             |FileUtils.S_IRGRP|FileUtils.S_IWGRP
1625             |extraPermissions;
1626         if ((mode&MODE_WORLD_READABLE) != 0) {
1627             perms |= FileUtils.S_IROTH;
1628         }
1629         if ((mode&MODE_WORLD_WRITEABLE) != 0) {
1630             perms |= FileUtils.S_IWOTH;
1631         }
1632         if (DEBUG) {
1633             Log.i(TAG, "File " + name + ": mode=0x" + Integer.toHexString(mode)
1634                   + ", perms=0x" + Integer.toHexString(perms));
1635         }
1636         FileUtils.setPermissions(name, perms, -1, -1);
1637     }
1638
1639     private File validateFilePath(String name, boolean createDirectory) {
1640         File dir;
1641         File f;
1642
1643         if (name.charAt(0) == File.separatorChar) {
1644             String dirPath = name.substring(0, name.lastIndexOf(File.separatorChar));
1645             dir = new File(dirPath);
1646             name = name.substring(name.lastIndexOf(File.separatorChar));
1647             f = new File(dir, name);
1648         } else {
1649             dir = getDatabasesDir();
1650             f = makeFilename(dir, name);
1651         }
1652
1653         if (createDirectory && !dir.isDirectory() && dir.mkdir()) {
1654             FileUtils.setPermissions(dir.getPath(),
1655                 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1656                 -1, -1);
1657         }
1658
1659         return f;
1660     }
1661
1662     private File makeFilename(File base, String name) {
1663         if (name.indexOf(File.separatorChar) < 0) {
1664             return new File(base, name);
1665         }
1666         throw new IllegalArgumentException(
1667                 "File " + name + " contains a path separator");
1668     }
1669
1670     // ----------------------------------------------------------------------
1671     // ----------------------------------------------------------------------
1672     // ----------------------------------------------------------------------
1673
1674     private static final class ApplicationContentResolver extends ContentResolver {
1675         public ApplicationContentResolver(Context context, ActivityThread mainThread) {
1676             super(context);
1677             mMainThread = mainThread;
1678         }
1679
1680         @Override
1681         protected IContentProvider acquireProvider(Context context, String name) {
1682             return mMainThread.acquireProvider(context, name);
1683         }
1684
1685         @Override
1686         protected IContentProvider acquireExistingProvider(Context context, String name) {
1687             return mMainThread.acquireExistingProvider(context, name);
1688         }
1689
1690         @Override
1691         public boolean releaseProvider(IContentProvider provider) {
1692             return mMainThread.releaseProvider(provider);
1693         }
1694
1695         private final ActivityThread mMainThread;
1696     }
1697
1698     // ----------------------------------------------------------------------
1699     // ----------------------------------------------------------------------
1700     // ----------------------------------------------------------------------
1701
1702     /*package*/
1703     static final class ApplicationPackageManager extends PackageManager {
1704         @Override
1705         public PackageInfo getPackageInfo(String packageName, int flags)
1706                 throws NameNotFoundException {
1707             try {
1708                 PackageInfo pi = mPM.getPackageInfo(packageName, flags);
1709                 if (pi != null) {
1710                     return pi;
1711                 }
1712             } catch (RemoteException e) {
1713                 throw new RuntimeException("Package manager has died", e);
1714             }
1715
1716             throw new NameNotFoundException(packageName);
1717         }
1718
1719         @Override
1720         public String[] currentToCanonicalPackageNames(String[] names) {
1721             try {
1722                 return mPM.currentToCanonicalPackageNames(names);
1723             } catch (RemoteException e) {
1724                 throw new RuntimeException("Package manager has died", e);
1725             }
1726         }
1727
1728         @Override
1729         public String[] canonicalToCurrentPackageNames(String[] names) {
1730             try {
1731                 return mPM.canonicalToCurrentPackageNames(names);
1732             } catch (RemoteException e) {
1733                 throw new RuntimeException("Package manager has died", e);
1734             }
1735         }
1736
1737         @Override
1738         public Intent getLaunchIntentForPackage(String packageName) {
1739             // First see if the package has an INFO activity; the existence of
1740             // such an activity is implied to be the desired front-door for the
1741             // overall package (such as if it has multiple launcher entries).
1742             Intent intentToResolve = new Intent(Intent.ACTION_MAIN);
1743             intentToResolve.addCategory(Intent.CATEGORY_INFO);
1744             intentToResolve.setPackage(packageName);
1745             ResolveInfo resolveInfo = resolveActivity(intentToResolve, 0);
1746
1747             // Otherwise, try to find a main launcher activity.
1748             if (resolveInfo == null) {
1749                 // reuse the intent instance
1750                 intentToResolve.removeCategory(Intent.CATEGORY_INFO);
1751                 intentToResolve.addCategory(Intent.CATEGORY_LAUNCHER);
1752                 intentToResolve.setPackage(packageName);
1753                 resolveInfo = resolveActivity(intentToResolve, 0);
1754             }
1755             if (resolveInfo == null) {
1756                 return null;
1757             }
1758             Intent intent = new Intent(intentToResolve);
1759             intent.setClassName(resolveInfo.activityInfo.applicationInfo.packageName,
1760                                 resolveInfo.activityInfo.name);
1761             intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1762             return intent;
1763         }
1764
1765         @Override
1766         public int[] getPackageGids(String packageName)
1767             throws NameNotFoundException {
1768             try {
1769                 int[] gids = mPM.getPackageGids(packageName);
1770                 if (gids == null || gids.length > 0) {
1771                     return gids;
1772                 }
1773             } catch (RemoteException e) {
1774                 throw new RuntimeException("Package manager has died", e);
1775             }
1776
1777             throw new NameNotFoundException(packageName);
1778         }
1779
1780         @Override
1781         public PermissionInfo getPermissionInfo(String name, int flags)
1782             throws NameNotFoundException {
1783             try {
1784                 PermissionInfo pi = mPM.getPermissionInfo(name, flags);
1785                 if (pi != null) {
1786                     return pi;
1787                 }
1788             } catch (RemoteException e) {
1789                 throw new RuntimeException("Package manager has died", e);
1790             }
1791
1792             throw new NameNotFoundException(name);
1793         }
1794
1795         @Override
1796         public List<PermissionInfo> queryPermissionsByGroup(String group, int flags)
1797                 throws NameNotFoundException {
1798             try {
1799                 List<PermissionInfo> pi = mPM.queryPermissionsByGroup(group, flags);
1800                 if (pi != null) {
1801                     return pi;
1802                 }
1803             } catch (RemoteException e) {
1804                 throw new RuntimeException("Package manager has died", e);
1805             }
1806
1807             throw new NameNotFoundException(group);
1808         }
1809
1810         @Override
1811         public PermissionGroupInfo getPermissionGroupInfo(String name,
1812                 int flags) throws NameNotFoundException {
1813             try {
1814                 PermissionGroupInfo pgi = mPM.getPermissionGroupInfo(name, flags);
1815                 if (pgi != null) {
1816                     return pgi;
1817                 }
1818             } catch (RemoteException e) {
1819                 throw new RuntimeException("Package manager has died", e);
1820             }
1821
1822             throw new NameNotFoundException(name);
1823         }
1824
1825         @Override
1826         public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1827             try {
1828                 return mPM.getAllPermissionGroups(flags);
1829             } catch (RemoteException e) {
1830                 throw new RuntimeException("Package manager has died", e);
1831             }
1832         }
1833
1834         @Override
1835         public ApplicationInfo getApplicationInfo(String packageName, int flags)
1836             throws NameNotFoundException {
1837             try {
1838                 ApplicationInfo ai = mPM.getApplicationInfo(packageName, flags);
1839                 if (ai != null) {
1840                     return ai;
1841                 }
1842             } catch (RemoteException e) {
1843                 throw new RuntimeException("Package manager has died", e);
1844             }
1845
1846             throw new NameNotFoundException(packageName);
1847         }
1848
1849         @Override
1850         public ActivityInfo getActivityInfo(ComponentName className, int flags)
1851             throws NameNotFoundException {
1852             try {
1853                 ActivityInfo ai = mPM.getActivityInfo(className, flags);
1854                 if (ai != null) {
1855                     return ai;
1856                 }
1857             } catch (RemoteException e) {
1858                 throw new RuntimeException("Package manager has died", e);
1859             }
1860
1861             throw new NameNotFoundException(className.toString());
1862         }
1863
1864         @Override
1865         public ActivityInfo getReceiverInfo(ComponentName className, int flags)
1866             throws NameNotFoundException {
1867             try {
1868                 ActivityInfo ai = mPM.getReceiverInfo(className, flags);
1869                 if (ai != null) {
1870                     return ai;
1871                 }
1872             } catch (RemoteException e) {
1873                 throw new RuntimeException("Package manager has died", e);
1874             }
1875
1876             throw new NameNotFoundException(className.toString());
1877         }
1878
1879         @Override
1880         public ServiceInfo getServiceInfo(ComponentName className, int flags)
1881             throws NameNotFoundException {
1882             try {
1883                 ServiceInfo si = mPM.getServiceInfo(className, flags);
1884                 if (si != null) {
1885                     return si;
1886                 }
1887             } catch (RemoteException e) {
1888                 throw new RuntimeException("Package manager has died", e);
1889             }
1890
1891             throw new NameNotFoundException(className.toString());
1892         }
1893
1894         @Override
1895         public ProviderInfo getProviderInfo(ComponentName className, int flags)
1896             throws NameNotFoundException {
1897             try {
1898                 ProviderInfo pi = mPM.getProviderInfo(className, flags);
1899                 if (pi != null) {
1900                     return pi;
1901                 }
1902             } catch (RemoteException e) {
1903                 throw new RuntimeException("Package manager has died", e);
1904             }
1905
1906             throw new NameNotFoundException(className.toString());
1907         }
1908
1909         @Override
1910         public String[] getSystemSharedLibraryNames() {
1911              try {
1912                  return mPM.getSystemSharedLibraryNames();
1913              } catch (RemoteException e) {
1914                  throw new RuntimeException("Package manager has died", e);
1915              }
1916         }
1917
1918         @Override
1919         public FeatureInfo[] getSystemAvailableFeatures() {
1920             try {
1921                 return mPM.getSystemAvailableFeatures();
1922             } catch (RemoteException e) {
1923                 throw new RuntimeException("Package manager has died", e);
1924             }
1925         }
1926
1927         @Override
1928         public boolean hasSystemFeature(String name) {
1929             try {
1930                 return mPM.hasSystemFeature(name);
1931             } catch (RemoteException e) {
1932                 throw new RuntimeException("Package manager has died", e);
1933             }
1934         }
1935
1936         @Override
1937         public int checkPermission(String permName, String pkgName) {
1938             try {
1939                 return mPM.checkPermission(permName, pkgName);
1940             } catch (RemoteException e) {
1941                 throw new RuntimeException("Package manager has died", e);
1942             }
1943         }
1944
1945         @Override
1946         public boolean addPermission(PermissionInfo info) {
1947             try {
1948                 return mPM.addPermission(info);
1949             } catch (RemoteException e) {
1950                 throw new RuntimeException("Package manager has died", e);
1951             }
1952         }
1953
1954         @Override
1955         public boolean addPermissionAsync(PermissionInfo info) {
1956             try {
1957                 return mPM.addPermissionAsync(info);
1958             } catch (RemoteException e) {
1959                 throw new RuntimeException("Package manager has died", e);
1960             }
1961         }
1962
1963         @Override
1964         public void removePermission(String name) {
1965             try {
1966                 mPM.removePermission(name);
1967             } catch (RemoteException e) {
1968                 throw new RuntimeException("Package manager has died", e);
1969             }
1970         }
1971
1972         @Override
1973         public int checkSignatures(String pkg1, String pkg2) {
1974             try {
1975                 return mPM.checkSignatures(pkg1, pkg2);
1976             } catch (RemoteException e) {
1977                 throw new RuntimeException("Package manager has died", e);
1978             }
1979         }
1980
1981         @Override
1982         public int checkSignatures(int uid1, int uid2) {
1983             try {
1984                 return mPM.checkUidSignatures(uid1, uid2);
1985             } catch (RemoteException e) {
1986                 throw new RuntimeException("Package manager has died", e);
1987             }
1988         }
1989
1990         @Override
1991         public String[] getPackagesForUid(int uid) {
1992             try {
1993                 return mPM.getPackagesForUid(uid);
1994             } catch (RemoteException e) {
1995                 throw new RuntimeException("Package manager has died", e);
1996             }
1997         }
1998
1999         @Override
2000         public String getNameForUid(int uid) {
2001             try {
2002                 return mPM.getNameForUid(uid);
2003             } catch (RemoteException e) {
2004                 throw new RuntimeException("Package manager has died", e);
2005             }
2006         }
2007
2008         @Override
2009         public int getUidForSharedUser(String sharedUserName)
2010                 throws NameNotFoundException {
2011             try {
2012                 int uid = mPM.getUidForSharedUser(sharedUserName);
2013                 if(uid != -1) {
2014                     return uid;
2015                 }
2016             } catch (RemoteException e) {
2017                 throw new RuntimeException("Package manager has died", e);
2018             }
2019             throw new NameNotFoundException("No shared userid for user:"+sharedUserName);
2020         }
2021
2022         @Override
2023         public List<PackageInfo> getInstalledPackages(int flags) {
2024             try {
2025                 return mPM.getInstalledPackages(flags);
2026             } catch (RemoteException e) {
2027                 throw new RuntimeException("Package manager has died", e);
2028             }
2029         }
2030
2031         @Override
2032         public List<ApplicationInfo> getInstalledApplications(int flags) {
2033             try {
2034                 return mPM.getInstalledApplications(flags);
2035             } catch (RemoteException e) {
2036                 throw new RuntimeException("Package manager has died", e);
2037             }
2038         }
2039
2040         @Override
2041         public ResolveInfo resolveActivity(Intent intent, int flags) {
2042             try {
2043                 return mPM.resolveIntent(
2044                     intent,
2045                     intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2046                     flags);
2047             } catch (RemoteException e) {
2048                 throw new RuntimeException("Package manager has died", e);
2049             }
2050         }
2051
2052         @Override
2053         public List<ResolveInfo> queryIntentActivities(Intent intent,
2054                 int flags) {
2055             try {
2056                 return mPM.queryIntentActivities(
2057                     intent,
2058                     intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2059                     flags);
2060             } catch (RemoteException e) {
2061                 throw new RuntimeException("Package manager has died", e);
2062             }
2063         }
2064
2065         @Override
2066         public List<ResolveInfo> queryIntentActivityOptions(
2067                 ComponentName caller, Intent[] specifics, Intent intent,
2068                 int flags) {
2069             final ContentResolver resolver = mContext.getContentResolver();
2070
2071             String[] specificTypes = null;
2072             if (specifics != null) {
2073                 final int N = specifics.length;
2074                 for (int i=0; i<N; i++) {
2075                     Intent sp = specifics[i];
2076                     if (sp != null) {
2077                         String t = sp.resolveTypeIfNeeded(resolver);
2078                         if (t != null) {
2079                             if (specificTypes == null) {
2080                                 specificTypes = new String[N];
2081                             }
2082                             specificTypes[i] = t;
2083                         }
2084                     }
2085                 }
2086             }
2087
2088             try {
2089                 return mPM.queryIntentActivityOptions(caller, specifics,
2090                     specificTypes, intent, intent.resolveTypeIfNeeded(resolver),
2091                     flags);
2092             } catch (RemoteException e) {
2093                 throw new RuntimeException("Package manager has died", e);
2094             }
2095         }
2096
2097         @Override
2098         public List<ResolveInfo> queryBroadcastReceivers(Intent intent, int flags) {
2099             try {
2100                 return mPM.queryIntentReceivers(
2101                     intent,
2102                     intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2103                     flags);
2104             } catch (RemoteException e) {
2105                 throw new RuntimeException("Package manager has died", e);
2106             }
2107         }
2108
2109         @Override
2110         public ResolveInfo resolveService(Intent intent, int flags) {
2111             try {
2112                 return mPM.resolveService(
2113                     intent,
2114                     intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2115                     flags);
2116             } catch (RemoteException e) {
2117                 throw new RuntimeException("Package manager has died", e);
2118             }
2119         }
2120
2121         @Override
2122         public List<ResolveInfo> queryIntentServices(Intent intent, int flags) {
2123             try {
2124                 return mPM.queryIntentServices(
2125                     intent,
2126                     intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2127                     flags);
2128             } catch (RemoteException e) {
2129                 throw new RuntimeException("Package manager has died", e);
2130             }
2131         }
2132
2133         @Override
2134         public ProviderInfo resolveContentProvider(String name,
2135                 int flags) {
2136             try {
2137                 return mPM.resolveContentProvider(name, flags);
2138             } catch (RemoteException e) {
2139                 throw new RuntimeException("Package manager has died", e);
2140             }
2141         }
2142
2143         @Override
2144         public List<ProviderInfo> queryContentProviders(String processName,
2145                 int uid, int flags) {
2146             try {
2147                 return mPM.queryContentProviders(processName, uid, flags);
2148             } catch (RemoteException e) {
2149                 throw new RuntimeException("Package manager has died", e);
2150             }
2151         }
2152
2153         @Override
2154         public InstrumentationInfo getInstrumentationInfo(
2155                 ComponentName className, int flags)
2156                 throws NameNotFoundException {
2157             try {
2158                 InstrumentationInfo ii = mPM.getInstrumentationInfo(
2159                         className, flags);
2160                 if (ii != null) {
2161                     return ii;
2162                 }
2163             } catch (RemoteException e) {
2164                 throw new RuntimeException("Package manager has died", e);
2165             }
2166
2167             throw new NameNotFoundException(className.toString());
2168         }
2169
2170         @Override
2171         public List<InstrumentationInfo> queryInstrumentation(
2172                 String targetPackage, int flags) {
2173             try {
2174                 return mPM.queryInstrumentation(targetPackage, flags);
2175             } catch (RemoteException e) {
2176                 throw new RuntimeException("Package manager has died", e);
2177             }
2178         }
2179
2180         @Override public Drawable getDrawable(String packageName, int resid,
2181                 ApplicationInfo appInfo) {
2182             ResourceName name = new ResourceName(packageName, resid);
2183             Drawable dr = getCachedIcon(name);
2184             if (dr != null) {
2185                 return dr;
2186             }
2187             if (appInfo == null) {
2188                 try {
2189                     appInfo = getApplicationInfo(packageName, 0);
2190                 } catch (NameNotFoundException e) {
2191                     return null;
2192                 }
2193             }
2194             try {
2195                 Resources r = getResourcesForApplication(appInfo);
2196                 dr = r.getDrawable(resid);
2197                 if (false) {
2198                     RuntimeException e = new RuntimeException("here");
2199                     e.fillInStackTrace();
2200                     Log.w(TAG, "Getting drawable 0x" + Integer.toHexString(resid)
2201                             + " from package " + packageName
2202                             + ": app scale=" + r.getCompatibilityInfo().applicationScale
2203                             + ", caller scale=" + mContext.getResources().getCompatibilityInfo().applicationScale,
2204                             e);
2205                 }
2206                 if (DEBUG_ICONS) Log.v(TAG, "Getting drawable 0x"
2207                         + Integer.toHexString(resid) + " from " + r
2208                         + ": " + dr);
2209                 putCachedIcon(name, dr);
2210                 return dr;
2211             } catch (NameNotFoundException e) {
2212                 Log.w("PackageManager", "Failure retrieving resources for"
2213                         + appInfo.packageName);
2214             } catch (RuntimeException e) {
2215                 // If an exception was thrown, fall through to return
2216                 // default icon.
2217                 Log.w("PackageManager", "Failure retrieving icon 0x"
2218                         + Integer.toHexString(resid) + " in package "
2219                         + packageName, e);
2220             }
2221             return null;
2222         }
2223
2224         @Override public Drawable getActivityIcon(ComponentName activityName)
2225                 throws NameNotFoundException {
2226             return getActivityInfo(activityName, 0).loadIcon(this);
2227         }
2228
2229         @Override public Drawable getActivityIcon(Intent intent)
2230                 throws NameNotFoundException {
2231             if (intent.getComponent() != null) {
2232                 return getActivityIcon(intent.getComponent());
2233             }
2234
2235             ResolveInfo info = resolveActivity(
2236                 intent, PackageManager.MATCH_DEFAULT_ONLY);
2237             if (info != null) {
2238                 return info.activityInfo.loadIcon(this);
2239             }
2240
2241             throw new NameNotFoundException(intent.toURI());
2242         }
2243
2244         @Override public Drawable getDefaultActivityIcon() {
2245             return Resources.getSystem().getDrawable(
2246                 com.android.internal.R.drawable.sym_def_app_icon);
2247         }
2248
2249         @Override public Drawable getApplicationIcon(ApplicationInfo info) {
2250             return info.loadIcon(this);
2251         }
2252
2253         @Override public Drawable getApplicationIcon(String packageName)
2254                 throws NameNotFoundException {
2255             return getApplicationIcon(getApplicationInfo(packageName, 0));
2256         }
2257         
2258         @Override 
2259         public Drawable getActivityLogo(ComponentName activityName)
2260                 throws NameNotFoundException {
2261             return getActivityInfo(activityName, 0).loadLogo(this);
2262         }
2263
2264         @Override
2265         public Drawable getActivityLogo(Intent intent)
2266                 throws NameNotFoundException {
2267             if (intent.getComponent() != null) {
2268                 return getActivityLogo(intent.getComponent());
2269             }
2270
2271             ResolveInfo info = resolveActivity(
2272                     intent, PackageManager.MATCH_DEFAULT_ONLY);
2273             if (info != null) {
2274                 return info.activityInfo.loadLogo(this);
2275             }
2276
2277             throw new NameNotFoundException(intent.toUri(0));
2278         }
2279
2280         @Override
2281         public Drawable getApplicationLogo(ApplicationInfo info) {
2282             return info.loadLogo(this);
2283         }
2284
2285         @Override
2286         public Drawable getApplicationLogo(String packageName)
2287                 throws NameNotFoundException {
2288             return getApplicationLogo(getApplicationInfo(packageName, 0));
2289         }
2290
2291         @Override public Resources getResourcesForActivity(
2292                 ComponentName activityName) throws NameNotFoundException {
2293             return getResourcesForApplication(
2294                 getActivityInfo(activityName, 0).applicationInfo);
2295         }
2296
2297         @Override public Resources getResourcesForApplication(
2298                 ApplicationInfo app) throws NameNotFoundException {
2299             if (app.packageName.equals("system")) {
2300                 return mContext.mMainThread.getSystemContext().getResources();
2301             }
2302             Resources r = mContext.mMainThread.getTopLevelResources(
2303                     app.uid == Process.myUid() ? app.sourceDir
2304                     : app.publicSourceDir, mContext.mPackageInfo);
2305             if (r != null) {
2306                 return r;
2307             }
2308             throw new NameNotFoundException("Unable to open " + app.publicSourceDir);
2309         }
2310
2311         @Override public Resources getResourcesForApplication(
2312                 String appPackageName) throws NameNotFoundException {
2313             return getResourcesForApplication(
2314                 getApplicationInfo(appPackageName, 0));
2315         }
2316
2317         int mCachedSafeMode = -1;
2318         @Override public boolean isSafeMode() {
2319             try {
2320                 if (mCachedSafeMode < 0) {
2321                     mCachedSafeMode = mPM.isSafeMode() ? 1 : 0;
2322                 }
2323                 return mCachedSafeMode != 0;
2324             } catch (RemoteException e) {
2325                 throw new RuntimeException("Package manager has died", e);
2326             }
2327         }
2328
2329         static void configurationChanged() {
2330             synchronized (sSync) {
2331                 sIconCache.clear();
2332                 sStringCache.clear();
2333             }
2334         }
2335
2336         ApplicationPackageManager(ContextImpl context,
2337                 IPackageManager pm) {
2338             mContext = context;
2339             mPM = pm;
2340         }
2341
2342         private Drawable getCachedIcon(ResourceName name) {
2343             synchronized (sSync) {
2344                 WeakReference<Drawable> wr = sIconCache.get(name);
2345                 if (DEBUG_ICONS) Log.v(TAG, "Get cached weak drawable ref for "
2346                         + name + ": " + wr);
2347                 if (wr != null) {   // we have the activity
2348                     Drawable dr = wr.get();
2349                     if (dr != null) {
2350                         if (DEBUG_ICONS) Log.v(TAG, "Get cached drawable for "
2351                                 + name + ": " + dr);
2352                         return dr;