2 * Copyright (C) 2006 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 import com.android.internal.policy.PolicyManager;
20 import com.android.internal.util.XmlUtils;
21 import com.google.android.collect.Maps;
23 import org.xmlpull.v1.XmlPullParserException;
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;
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;
128 class ReceiverRestrictedContext extends ContextWrapper {
129 ReceiverRestrictedContext(Context base) {
134 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
135 return registerReceiver(receiver, filter, null, null);
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,
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);
160 * Common implementation of Context API, which provides the base
161 * context object for Activity and other application components.
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;
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>();
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;
210 private final Object mSync = new Object();
212 private File mDatabasesDir;
213 private File mPreferencesDir;
214 private File mFilesDir;
215 private File mCacheDir;
216 private File mExternalFilesDir;
217 private File mExternalCacheDir;
219 private static long sInstanceCount = 0;
221 private static final String[] EMPTY_FILE_LIST = {};
226 protected void finalize() throws Throwable {
232 public static long getInstanceCount() {
233 return sInstanceCount;
237 public AssetManager getAssets() {
238 return mResources.getAssets();
242 public Resources getResources() {
247 public PackageManager getPackageManager() {
248 if (mPackageManager != null) {
249 return mPackageManager;
252 IPackageManager pm = ActivityThread.getPackageManager();
254 // Doesn't matter if we make more than one instance.
255 return (mPackageManager = new ApplicationPackageManager(this, pm));
262 public ContentResolver getContentResolver() {
263 return mContentResolver;
267 public Looper getMainLooper() {
268 return mMainThread.getLooper();
272 public Context getApplicationContext() {
273 return (mPackageInfo != null) ?
274 mPackageInfo.getApplication() : mMainThread.getApplication();
278 public void setTheme(int resid) {
279 mThemeResource = resid;
283 public Resources.Theme getTheme() {
284 if (mTheme == null) {
285 if (mThemeResource == 0) {
286 mThemeResource = com.android.internal.R.style.Theme;
288 mTheme = mResources.newTheme();
289 mTheme.applyStyle(mThemeResource, true);
295 public ClassLoader getClassLoader() {
296 return mPackageInfo != null ?
297 mPackageInfo.getClassLoader() : ClassLoader.getSystemClassLoader();
301 public String getPackageName() {
302 if (mPackageInfo != null) {
303 return mPackageInfo.getPackageName();
305 throw new RuntimeException("Not supported in system context");
309 public ApplicationInfo getApplicationInfo() {
310 if (mPackageInfo != null) {
311 return mPackageInfo.getApplicationInfo();
313 throw new RuntimeException("Not supported in system context");
317 public String getPackageResourcePath() {
318 if (mPackageInfo != null) {
319 return mPackageInfo.getResDir();
321 throw new RuntimeException("Not supported in system context");
325 public String getPackageCodePath() {
326 if (mPackageInfo != null) {
327 return mPackageInfo.getAppDir();
329 throw new RuntimeException("Not supported in system context");
332 private static File makeBackupFile(File prefsFile) {
333 return new File(prefsFile.getPath() + ".bak");
336 public File getSharedPrefsFile(String name) {
337 return makeFilename(getPreferencesDir(), name + ".xml");
341 public SharedPreferences getSharedPreferences(String name, int mode) {
342 SharedPreferencesImpl sp;
344 boolean needInitialLoad = false;
345 synchronized (sSharedPrefs) {
346 sp = sSharedPrefs.get(name);
347 if (sp != null && !sp.hasFileChangedUnexpectedly()) {
350 prefsFile = getSharedPrefsFile(name);
352 sp = new SharedPreferencesImpl(prefsFile, mode, null);
353 sSharedPrefs.put(name, sp);
354 needInitialLoad = true;
359 if (needInitialLoad && sp.isLoaded()) {
360 // lost the race to load; another thread handled it
363 File backup = makeBackupFile(prefsFile);
364 if (backup.exists()) {
366 backup.renameTo(prefsFile);
370 if (prefsFile.exists() && !prefsFile.canRead()) {
371 Log.w(TAG, "Attempt to read preferences file " + prefsFile + " without permission");
375 FileStatus stat = new FileStatus();
376 if (FileUtils.getFileStatus(prefsFile.getPath(), stat) && prefsFile.canRead()) {
378 FileInputStream str = new FileInputStream(prefsFile);
379 map = XmlUtils.readMapXml(str);
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);
389 sp.replace(map, stat);
394 private File getPreferencesDir() {
395 synchronized (mSync) {
396 if (mPreferencesDir == null) {
397 mPreferencesDir = new File(getDataDirFile(), "shared_prefs");
399 return mPreferencesDir;
404 public FileInputStream openFileInput(String name)
405 throws FileNotFoundException {
406 File f = makeFilename(getFilesDir(), name);
407 return new FileInputStream(f);
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);
416 FileOutputStream fos = new FileOutputStream(f, append);
417 setFilePermissionsFromMode(f.getPath(), mode, 0);
419 } catch (FileNotFoundException e) {
422 File parent = f.getParentFile();
424 FileUtils.setPermissions(
426 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
428 FileOutputStream fos = new FileOutputStream(f, append);
429 setFilePermissionsFromMode(f.getPath(), mode, 0);
434 public boolean deleteFile(String name) {
435 File f = makeFilename(getFilesDir(), name);
440 public File getFilesDir() {
441 synchronized (mSync) {
442 if (mFilesDir == null) {
443 mFilesDir = new File(getDataDirFile(), "files");
445 if (!mFilesDir.exists()) {
446 if(!mFilesDir.mkdirs()) {
447 Log.w(TAG, "Unable to create files directory " + mFilesDir.getPath());
450 FileUtils.setPermissions(
452 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
460 public File getExternalFilesDir(String type) {
461 synchronized (mSync) {
462 if (mExternalFilesDir == null) {
463 mExternalFilesDir = Environment.getExternalStorageAppFilesDirectory(
466 if (!mExternalFilesDir.exists()) {
468 (new File(Environment.getExternalStorageAndroidDataDir(),
469 ".nomedia")).createNewFile();
470 } catch (IOException e) {
472 if (!mExternalFilesDir.mkdirs()) {
473 Log.w(TAG, "Unable to create external files directory");
478 return mExternalFilesDir;
480 File dir = new File(mExternalFilesDir, type);
483 Log.w(TAG, "Unable to create external media directory " + dir);
492 public File getCacheDir() {
493 synchronized (mSync) {
494 if (mCacheDir == null) {
495 mCacheDir = new File(getDataDirFile(), "cache");
497 if (!mCacheDir.exists()) {
498 if(!mCacheDir.mkdirs()) {
499 Log.w(TAG, "Unable to create cache directory");
502 FileUtils.setPermissions(
504 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
512 public File getExternalCacheDir() {
513 synchronized (mSync) {
514 if (mExternalCacheDir == null) {
515 mExternalCacheDir = Environment.getExternalStorageAppCacheDirectory(
518 if (!mExternalCacheDir.exists()) {
520 (new File(Environment.getExternalStorageAndroidDataDir(),
521 ".nomedia")).createNewFile();
522 } catch (IOException e) {
524 if (!mExternalCacheDir.mkdirs()) {
525 Log.w(TAG, "Unable to create external cache directory");
529 return mExternalCacheDir;
534 public File getFileStreamPath(String name) {
535 return makeFilename(getFilesDir(), name);
539 public String[] fileList() {
540 final String[] list = getFilesDir().list();
541 return (list != null) ? list : EMPTY_FILE_LIST;
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);
553 public boolean deleteDatabase(String name) {
555 File f = validateFilePath(name, false);
557 } catch (Exception e) {
563 public File getDatabasePath(String name) {
564 return validateFilePath(name, false);
568 public String[] databaseList() {
569 final String[] list = getDatabasesDir().list();
570 return (list != null) ? list : EMPTY_FILE_LIST;
574 private File getDatabasesDir() {
575 synchronized (mSync) {
576 if (mDatabasesDir == null) {
577 mDatabasesDir = new File(getDataDirFile(), "databases");
579 if (mDatabasesDir.getPath().equals("databases")) {
580 mDatabasesDir = new File("/data/system");
582 return mDatabasesDir;
587 public Drawable getWallpaper() {
588 return getWallpaperManager().getDrawable();
592 public Drawable peekWallpaper() {
593 return getWallpaperManager().peekDrawable();
597 public int getWallpaperDesiredMinimumWidth() {
598 return getWallpaperManager().getDesiredMinimumWidth();
602 public int getWallpaperDesiredMinimumHeight() {
603 return getWallpaperManager().getDesiredMinimumHeight();
607 public void setWallpaper(Bitmap bitmap) throws IOException {
608 getWallpaperManager().setBitmap(bitmap);
612 public void setWallpaper(InputStream data) throws IOException {
613 getWallpaperManager().setStream(data);
617 public void clearWallpaper() throws IOException {
618 getWallpaperManager().clear();
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?");
629 mMainThread.getInstrumentation().execStartActivity(
630 getOuterContext(), mMainThread.getApplicationThread(), null, null, intent, -1);
634 public void startIntentSender(IntentSender intent,
635 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
636 throws IntentSender.SendIntentException {
638 String resolvedType = null;
639 if (fillInIntent != null) {
640 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
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();
649 Instrumentation.checkStartActivityResult(result, null);
650 } catch (RemoteException e) {
655 public void sendBroadcast(Intent intent) {
656 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
658 ActivityManagerNative.getDefault().broadcastIntent(
659 mMainThread.getApplicationThread(), intent, resolvedType, null,
660 Activity.RESULT_OK, null, null, null, false, false);
661 } catch (RemoteException e) {
666 public void sendBroadcast(Intent intent, String receiverPermission) {
667 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
669 ActivityManagerNative.getDefault().broadcastIntent(
670 mMainThread.getApplicationThread(), intent, resolvedType, null,
671 Activity.RESULT_OK, null, null, receiverPermission, false, false);
672 } catch (RemoteException e) {
677 public void sendOrderedBroadcast(Intent intent,
678 String receiverPermission) {
679 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
681 ActivityManagerNative.getDefault().broadcastIntent(
682 mMainThread.getApplicationThread(), intent, resolvedType, null,
683 Activity.RESULT_OK, null, null, receiverPermission, true, false);
684 } catch (RemoteException e) {
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();
699 rd = mPackageInfo.getReceiverDispatcher(
700 resultReceiver, getOuterContext(), scheduler,
701 mMainThread.getInstrumentation(), false);
703 if (scheduler == null) {
704 scheduler = mMainThread.getHandler();
706 rd = new LoadedApk.ReceiverDispatcher(
707 resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
710 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
712 ActivityManagerNative.getDefault().broadcastIntent(
713 mMainThread.getApplicationThread(), intent, resolvedType, rd,
714 initialCode, initialData, initialExtras, receiverPermission,
716 } catch (RemoteException e) {
721 public void sendStickyBroadcast(Intent intent) {
722 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
724 ActivityManagerNative.getDefault().broadcastIntent(
725 mMainThread.getApplicationThread(), intent, resolvedType, null,
726 Activity.RESULT_OK, null, null, null, false, true);
727 } catch (RemoteException e) {
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();
742 rd = mPackageInfo.getReceiverDispatcher(
743 resultReceiver, getOuterContext(), scheduler,
744 mMainThread.getInstrumentation(), false);
746 if (scheduler == null) {
747 scheduler = mMainThread.getHandler();
749 rd = new LoadedApk.ReceiverDispatcher(
750 resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
753 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
755 ActivityManagerNative.getDefault().broadcastIntent(
756 mMainThread.getApplicationThread(), intent, resolvedType, rd,
757 initialCode, initialData, initialExtras, null,
759 } catch (RemoteException e) {
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);
771 ActivityManagerNative.getDefault().unbroadcastIntent(
772 mMainThread.getApplicationThread(), intent);
773 } catch (RemoteException e) {
778 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
779 return registerReceiver(receiver, filter, null, null);
783 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
784 String broadcastPermission, Handler scheduler) {
785 return registerReceiverInternal(receiver, filter, broadcastPermission,
786 scheduler, getOuterContext());
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();
798 rd = mPackageInfo.getReceiverDispatcher(
799 receiver, context, scheduler,
800 mMainThread.getInstrumentation(), true);
802 if (scheduler == null) {
803 scheduler = mMainThread.getHandler();
805 rd = new LoadedApk.ReceiverDispatcher(
806 receiver, context, scheduler, null, true).getIIntentReceiver();
810 return ActivityManagerNative.getDefault().registerReceiver(
811 mMainThread.getApplicationThread(),
812 rd, filter, broadcastPermission);
813 } catch (RemoteException e) {
819 public void unregisterReceiver(BroadcastReceiver receiver) {
820 if (mPackageInfo != null) {
821 IIntentReceiver rd = mPackageInfo.forgetReceiverDispatcher(
822 getOuterContext(), receiver);
824 ActivityManagerNative.getDefault().unregisterReceiver(rd);
825 } catch (RemoteException e) {
828 throw new RuntimeException("Not supported in system context");
833 public ComponentName startService(Intent service) {
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());
844 } catch (RemoteException e) {
850 public boolean stopService(Intent service) {
852 int res = ActivityManagerNative.getDefault().stopService(
853 mMainThread.getApplicationThread(), service,
854 service.resolveTypeIfNeeded(getContentResolver()));
856 throw new SecurityException(
857 "Not allowed to stop service " + service);
860 } catch (RemoteException e) {
866 public boolean bindService(Intent service, ServiceConnection conn,
868 IServiceConnection sd;
869 if (mPackageInfo != null) {
870 sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(),
871 mMainThread.getHandler(), flags);
873 throw new RuntimeException("Not supported in system context");
876 int res = ActivityManagerNative.getDefault().bindService(
877 mMainThread.getApplicationThread(), getActivityToken(),
878 service, service.resolveTypeIfNeeded(getContentResolver()),
881 throw new SecurityException(
882 "Not allowed to bind to service " + service);
885 } catch (RemoteException e) {
891 public void unbindService(ServiceConnection conn) {
892 if (mPackageInfo != null) {
893 IServiceConnection sd = mPackageInfo.forgetServiceDispatcher(
894 getOuterContext(), conn);
896 ActivityManagerNative.getDefault().unbindService(sd);
897 } catch (RemoteException e) {
900 throw new RuntimeException("Not supported in system context");
905 public boolean startInstrumentation(ComponentName className,
906 String profileFile, Bundle arguments) {
908 return ActivityManagerNative.getDefault().startInstrumentation(
909 className, profileFile, 0, arguments, null);
910 } catch (RemoteException e) {
911 // System has crashed, nothing we can do.
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) {
926 mLayoutInflater = inflater =
927 PolicyManager.makeNewLayoutInflater(getOuterContext());
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());
971 return mStatusBarManager;
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();
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);
1003 return mAccountManager;
1007 private ActivityManager getActivityManager() {
1008 synchronized (mSync) {
1009 if (mActivityManager == null) {
1010 mActivityManager = new ActivityManager(getOuterContext(),
1011 mMainThread.getHandler());
1014 return mActivityManager;
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);
1025 return sAlarmManager;
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());
1036 return sPowerManager;
1039 private ConnectivityManager getConnectivityManager()
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);
1048 return sConnectivityManager;
1051 private ThrottleManager getThrottleManager()
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);
1060 return sThrottleManager;
1063 private WifiManager getWifiManager()
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());
1072 return sWifiManager;
1075 private EthernetManager getEthernetManager()
1077 synchronized (sSync) {
1078 if (sEthernetManager == null) {
1079 IBinder b = ServiceManager.getService(ETHERNET_SERVICE);
1082 Log.w(TAG, "Error getting service name:" + ETHERNET_SERVICE);
1084 IEthernetManager service = IEthernetManager.Stub.asInterface(b);
1085 sEthernetManager = new EthernetManager(service, mMainThread.getHandler());
1088 return sEthernetManager;
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());
1099 return mNotificationManager;
1102 private WallpaperManager getWallpaperManager() {
1103 synchronized (mSync) {
1104 if (mWallpaperManager == null) {
1105 mWallpaperManager = new WallpaperManager(getOuterContext(),
1106 mMainThread.getHandler());
1109 return mWallpaperManager;
1112 private TelephonyManager getTelephonyManager() {
1113 synchronized (mSync) {
1114 if (mTelephonyManager == null) {
1115 mTelephonyManager = new TelephonyManager(getOuterContext());
1118 return mTelephonyManager;
1121 private ClipboardManager getClipboardManager() {
1122 synchronized (mSync) {
1123 if (mClipboardManager == null) {
1124 mClipboardManager = new ClipboardManager(getOuterContext(),
1125 mMainThread.getHandler());
1128 return mClipboardManager;
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);
1139 return sLocationManager;
1142 private SearchManager getSearchManager() {
1143 synchronized (mSync) {
1144 if (mSearchManager == null) {
1145 mSearchManager = new SearchManager(getOuterContext(), mMainThread.getHandler());
1148 return mSearchManager;
1151 private SensorManager getSensorManager() {
1152 synchronized (mSync) {
1153 if (mSensorManager == null) {
1154 mSensorManager = new SensorManager(mMainThread.getHandler().getLooper());
1157 return mSensorManager;
1160 private StorageManager getStorageManager() {
1161 synchronized (mSync) {
1162 if (mStorageManager == null) {
1164 mStorageManager = new StorageManager(mMainThread.getHandler().getLooper());
1165 } catch (RemoteException rex) {
1166 Log.e(TAG, "Failed to create StorageManager", rex);
1167 mStorageManager = null;
1171 return mStorageManager;
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);
1185 private Vibrator getVibrator() {
1186 synchronized (mSync) {
1187 if (mVibrator == null) {
1188 mVibrator = new Vibrator();
1194 private AudioManager getAudioManager()
1196 if (mAudioManager == null) {
1197 mAudioManager = new AudioManager(this);
1199 return mAudioManager;
1202 /* package */ static DropBoxManager createDropBoxManager() {
1203 IBinder b = ServiceManager.getService(DROPBOX_SERVICE);
1204 IDropBoxManagerService service = IDropBoxManagerService.Stub.asInterface(b);
1205 return new DropBoxManager(service);
1208 private DropBoxManager getDropBoxManager() {
1209 synchronized (mSync) {
1210 if (mDropBoxManager == null) {
1211 mDropBoxManager = createDropBoxManager();
1214 return mDropBoxManager;
1217 private DevicePolicyManager getDevicePolicyManager() {
1218 synchronized (mSync) {
1219 if (mDevicePolicyManager == null) {
1220 mDevicePolicyManager = DevicePolicyManager.create(this,
1221 mMainThread.getHandler());
1224 return mDevicePolicyManager;
1227 private UiModeManager getUiModeManager() {
1228 synchronized (mSync) {
1229 if (mUiModeManager == null) {
1230 mUiModeManager = new UiModeManager();
1233 return mUiModeManager;
1236 private DownloadManager getDownloadManager() {
1237 synchronized (mSync) {
1238 if (mDownloadManager == null) {
1239 mDownloadManager = new DownloadManager(getContentResolver(), getPackageName());
1242 return mDownloadManager;
1245 private NfcManager getNfcManager() {
1246 synchronized (mSync) {
1247 if (mNfcManager == null) {
1248 mNfcManager = new NfcManager(this);
1255 public int checkPermission(String permission, int pid, int uid) {
1256 if (permission == null) {
1257 throw new IllegalArgumentException("permission is null");
1260 if (!Process.supportsProcesses()) {
1261 return PackageManager.PERMISSION_GRANTED;
1264 return ActivityManagerNative.getDefault().checkPermission(
1265 permission, pid, uid);
1266 } catch (RemoteException e) {
1267 return PackageManager.PERMISSION_DENIED;
1272 public int checkCallingPermission(String permission) {
1273 if (permission == null) {
1274 throw new IllegalArgumentException("permission is null");
1277 if (!Process.supportsProcesses()) {
1278 return PackageManager.PERMISSION_GRANTED;
1280 int pid = Binder.getCallingPid();
1281 if (pid != Process.myPid()) {
1282 return checkPermission(permission, pid,
1283 Binder.getCallingUid());
1285 return PackageManager.PERMISSION_DENIED;
1289 public int checkCallingOrSelfPermission(String permission) {
1290 if (permission == null) {
1291 throw new IllegalArgumentException("permission is null");
1294 return checkPermission(permission, Binder.getCallingPid(),
1295 Binder.getCallingUid());
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 + ": ") : "") +
1305 ? "Neither user " + uid + " nor current process has "
1306 : "User " + uid + " does not have ") +
1312 public void enforcePermission(
1313 String permission, int pid, int uid, String message) {
1315 checkPermission(permission, pid, uid),
1321 public void enforceCallingPermission(String permission, String message) {
1323 checkCallingPermission(permission),
1325 Binder.getCallingUid(),
1329 public void enforceCallingOrSelfPermission(
1330 String permission, String message) {
1332 checkCallingOrSelfPermission(permission),
1334 Binder.getCallingUid(),
1339 public void grantUriPermission(String toPackage, Uri uri, int modeFlags) {
1341 ActivityManagerNative.getDefault().grantUriPermission(
1342 mMainThread.getApplicationThread(), toPackage, uri,
1344 } catch (RemoteException e) {
1349 public void revokeUriPermission(Uri uri, int modeFlags) {
1351 ActivityManagerNative.getDefault().revokeUriPermission(
1352 mMainThread.getApplicationThread(), uri,
1354 } catch (RemoteException e) {
1359 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
1360 if (!Process.supportsProcesses()) {
1361 return PackageManager.PERMISSION_GRANTED;
1364 return ActivityManagerNative.getDefault().checkUriPermission(
1365 uri, pid, uid, modeFlags);
1366 } catch (RemoteException e) {
1367 return PackageManager.PERMISSION_DENIED;
1372 public int checkCallingUriPermission(Uri uri, int modeFlags) {
1373 if (!Process.supportsProcesses()) {
1374 return PackageManager.PERMISSION_GRANTED;
1376 int pid = Binder.getCallingPid();
1377 if (pid != Process.myPid()) {
1378 return checkUriPermission(uri, pid,
1379 Binder.getCallingUid(), modeFlags);
1381 return PackageManager.PERMISSION_DENIED;
1385 public int checkCallingOrSelfUriPermission(Uri uri, int modeFlags) {
1386 return checkUriPermission(uri, Binder.getCallingPid(),
1387 Binder.getCallingUid(), modeFlags);
1391 public int checkUriPermission(Uri uri, String readPermission,
1392 String writePermission, int pid, int uid, int modeFlags) {
1394 Log.i("foo", "checkUriPermission: uri=" + uri + "readPermission="
1395 + readPermission + " writePermission=" + writePermission
1396 + " pid=" + pid + " uid=" + uid + " mode" + modeFlags);
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;
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;
1412 return uri != null ? checkUriPermission(uri, pid, uid, modeFlags)
1413 : PackageManager.PERMISSION_DENIED;
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:
1423 case Intent.FLAG_GRANT_WRITE_URI_PERMISSION:
1426 throw new IllegalArgumentException(
1427 "Unknown permission mode flags: " + uriModeFlags);
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 + ": ") : "") +
1437 ? "Neither user " + uid + " nor current process has "
1438 : "User " + uid + " does not have ") +
1439 uriModeFlagToString(modeFlags) +
1446 public void enforceUriPermission(
1447 Uri uri, int pid, int uid, int modeFlags, String message) {
1449 modeFlags, checkUriPermission(uri, pid, uid, modeFlags),
1450 false, uid, uri, message);
1453 public void enforceCallingUriPermission(
1454 Uri uri, int modeFlags, String message) {
1456 modeFlags, checkCallingUriPermission(uri, modeFlags),
1457 false, Binder.getCallingUid(), uri, message);
1460 public void enforceCallingOrSelfUriPermission(
1461 Uri uri, int modeFlags, String message) {
1464 checkCallingOrSelfUriPermission(uri, modeFlags), true,
1465 Binder.getCallingUid(), uri, message);
1468 public void enforceUriPermission(
1469 Uri uri, String readPermission, String writePermission,
1470 int pid, int uid, int modeFlags, String message) {
1471 enforceForUri(modeFlags,
1473 uri, readPermission, writePermission, pid, uid,
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());
1489 mMainThread.getPackageInfo(packageName, flags);
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) {
1499 // Should be a better exception.
1500 throw new PackageManager.NameNotFoundException(
1501 "Application package " + packageName + " not found");
1505 public boolean isRestricted() {
1509 private File getDataDirFile() {
1510 if (mPackageInfo != null) {
1511 return mPackageInfo.getDataDirFile();
1513 throw new RuntimeException("Not supported in system context");
1517 public File getDir(String name, int mode) {
1518 name = "app_" + name;
1519 File file = makeFilename(getDataDirFile(), name);
1520 if (!file.exists()) {
1522 setFilePermissionsFromMode(file.getPath(), mode,
1523 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH);
1528 static ContextImpl createSystemContext(ActivityThread mainThread) {
1529 ContextImpl context = new ContextImpl();
1530 context.init(Resources.getSystem(), mainThread);
1537 mOuterContext = this;
1541 * Create a new ApplicationContext from an existing one. The new one
1542 * works and operates the same as the one it is copying.
1544 * @param context Existing application context.
1546 public ContextImpl(ContextImpl context) {
1548 mPackageInfo = context.mPackageInfo;
1549 mResources = context.mResources;
1550 mMainThread = context.mMainThread;
1551 mContentResolver = context.mContentResolver;
1552 mOuterContext = this;
1555 final void init(LoadedApk packageInfo,
1556 IBinder activityToken, ActivityThread mainThread) {
1557 init(packageInfo, activityToken, mainThread, null);
1560 final void init(LoadedApk packageInfo,
1561 IBinder activityToken, ActivityThread mainThread,
1562 Resources container) {
1563 mPackageInfo = packageInfo;
1564 mResources = mPackageInfo.getResources(mainThread);
1566 if (mResources != null && container != null
1567 && container.getCompatibilityInfo().applicationScale !=
1568 mResources.getCompatibilityInfo().applicationScale) {
1570 Log.d(TAG, "loaded context has different scaling. Using container's" +
1571 " compatiblity info:" + container.getDisplayMetrics());
1573 mResources = mainThread.getTopLevelResources(
1574 mPackageInfo.getResDir(), container.getCompatibilityInfo().copy());
1576 mMainThread = mainThread;
1577 mContentResolver = new ApplicationContentResolver(this, mainThread);
1579 setActivityToken(activityToken);
1582 final void init(Resources resources, ActivityThread mainThread) {
1583 mPackageInfo = null;
1584 mResources = resources;
1585 mMainThread = mainThread;
1586 mContentResolver = new ApplicationContentResolver(this, mainThread);
1589 final void scheduleFinalCleanup(String who, String what) {
1590 mMainThread.scheduleContextCleanup(this, who, what);
1593 final void performFinalCleanup(String who, String what) {
1594 //Log.i(TAG, "Cleanup up context: " + this);
1595 mPackageInfo.removeContextRegistrations(getOuterContext(), who, what);
1598 final Context getReceiverRestrictedContext() {
1599 if (mReceiverRestrictedContext != null) {
1600 return mReceiverRestrictedContext;
1602 return mReceiverRestrictedContext = new ReceiverRestrictedContext(getOuterContext());
1605 final void setActivityToken(IBinder token) {
1606 mActivityToken = token;
1609 final void setOuterContext(Context context) {
1610 mOuterContext = context;
1613 final Context getOuterContext() {
1614 return mOuterContext;
1617 final IBinder getActivityToken() {
1618 return mActivityToken;
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
1626 if ((mode&MODE_WORLD_READABLE) != 0) {
1627 perms |= FileUtils.S_IROTH;
1629 if ((mode&MODE_WORLD_WRITEABLE) != 0) {
1630 perms |= FileUtils.S_IWOTH;
1633 Log.i(TAG, "File " + name + ": mode=0x" + Integer.toHexString(mode)
1634 + ", perms=0x" + Integer.toHexString(perms));
1636 FileUtils.setPermissions(name, perms, -1, -1);
1639 private File validateFilePath(String name, boolean createDirectory) {
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);
1649 dir = getDatabasesDir();
1650 f = makeFilename(dir, name);
1653 if (createDirectory && !dir.isDirectory() && dir.mkdir()) {
1654 FileUtils.setPermissions(dir.getPath(),
1655 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1662 private File makeFilename(File base, String name) {
1663 if (name.indexOf(File.separatorChar) < 0) {
1664 return new File(base, name);
1666 throw new IllegalArgumentException(
1667 "File " + name + " contains a path separator");
1670 // ----------------------------------------------------------------------
1671 // ----------------------------------------------------------------------
1672 // ----------------------------------------------------------------------
1674 private static final class ApplicationContentResolver extends ContentResolver {
1675 public ApplicationContentResolver(Context context, ActivityThread mainThread) {
1677 mMainThread = mainThread;
1681 protected IContentProvider acquireProvider(Context context, String name) {
1682 return mMainThread.acquireProvider(context, name);
1686 protected IContentProvider acquireExistingProvider(Context context, String name) {
1687 return mMainThread.acquireExistingProvider(context, name);
1691 public boolean releaseProvider(IContentProvider provider) {
1692 return mMainThread.releaseProvider(provider);
1695 private final ActivityThread mMainThread;
1698 // ----------------------------------------------------------------------
1699 // ----------------------------------------------------------------------
1700 // ----------------------------------------------------------------------
1703 static final class ApplicationPackageManager extends PackageManager {
1705 public PackageInfo getPackageInfo(String packageName, int flags)
1706 throws NameNotFoundException {
1708 PackageInfo pi = mPM.getPackageInfo(packageName, flags);
1712 } catch (RemoteException e) {
1713 throw new RuntimeException("Package manager has died", e);
1716 throw new NameNotFoundException(packageName);
1720 public String[] currentToCanonicalPackageNames(String[] names) {
1722 return mPM.currentToCanonicalPackageNames(names);
1723 } catch (RemoteException e) {
1724 throw new RuntimeException("Package manager has died", e);
1729 public String[] canonicalToCurrentPackageNames(String[] names) {
1731 return mPM.canonicalToCurrentPackageNames(names);
1732 } catch (RemoteException e) {
1733 throw new RuntimeException("Package manager has died", e);
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);
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);
1755 if (resolveInfo == null) {
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);
1766 public int[] getPackageGids(String packageName)
1767 throws NameNotFoundException {
1769 int[] gids = mPM.getPackageGids(packageName);
1770 if (gids == null || gids.length > 0) {
1773 } catch (RemoteException e) {
1774 throw new RuntimeException("Package manager has died", e);
1777 throw new NameNotFoundException(packageName);
1781 public PermissionInfo getPermissionInfo(String name, int flags)
1782 throws NameNotFoundException {
1784 PermissionInfo pi = mPM.getPermissionInfo(name, flags);
1788 } catch (RemoteException e) {
1789 throw new RuntimeException("Package manager has died", e);
1792 throw new NameNotFoundException(name);
1796 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags)
1797 throws NameNotFoundException {
1799 List<PermissionInfo> pi = mPM.queryPermissionsByGroup(group, flags);
1803 } catch (RemoteException e) {
1804 throw new RuntimeException("Package manager has died", e);
1807 throw new NameNotFoundException(group);
1811 public PermissionGroupInfo getPermissionGroupInfo(String name,
1812 int flags) throws NameNotFoundException {
1814 PermissionGroupInfo pgi = mPM.getPermissionGroupInfo(name, flags);
1818 } catch (RemoteException e) {
1819 throw new RuntimeException("Package manager has died", e);
1822 throw new NameNotFoundException(name);
1826 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1828 return mPM.getAllPermissionGroups(flags);
1829 } catch (RemoteException e) {
1830 throw new RuntimeException("Package manager has died", e);
1835 public ApplicationInfo getApplicationInfo(String packageName, int flags)
1836 throws NameNotFoundException {
1838 ApplicationInfo ai = mPM.getApplicationInfo(packageName, flags);
1842 } catch (RemoteException e) {
1843 throw new RuntimeException("Package manager has died", e);
1846 throw new NameNotFoundException(packageName);
1850 public ActivityInfo getActivityInfo(ComponentName className, int flags)
1851 throws NameNotFoundException {
1853 ActivityInfo ai = mPM.getActivityInfo(className, flags);
1857 } catch (RemoteException e) {
1858 throw new RuntimeException("Package manager has died", e);
1861 throw new NameNotFoundException(className.toString());
1865 public ActivityInfo getReceiverInfo(ComponentName className, int flags)
1866 throws NameNotFoundException {
1868 ActivityInfo ai = mPM.getReceiverInfo(className, flags);
1872 } catch (RemoteException e) {
1873 throw new RuntimeException("Package manager has died", e);
1876 throw new NameNotFoundException(className.toString());
1880 public ServiceInfo getServiceInfo(ComponentName className, int flags)
1881 throws NameNotFoundException {
1883 ServiceInfo si = mPM.getServiceInfo(className, flags);
1887 } catch (RemoteException e) {
1888 throw new RuntimeException("Package manager has died", e);
1891 throw new NameNotFoundException(className.toString());
1895 public ProviderInfo getProviderInfo(ComponentName className, int flags)
1896 throws NameNotFoundException {
1898 ProviderInfo pi = mPM.getProviderInfo(className, flags);
1902 } catch (RemoteException e) {
1903 throw new RuntimeException("Package manager has died", e);
1906 throw new NameNotFoundException(className.toString());
1910 public String[] getSystemSharedLibraryNames() {
1912 return mPM.getSystemSharedLibraryNames();
1913 } catch (RemoteException e) {
1914 throw new RuntimeException("Package manager has died", e);
1919 public FeatureInfo[] getSystemAvailableFeatures() {
1921 return mPM.getSystemAvailableFeatures();
1922 } catch (RemoteException e) {
1923 throw new RuntimeException("Package manager has died", e);
1928 public boolean hasSystemFeature(String name) {
1930 return mPM.hasSystemFeature(name);
1931 } catch (RemoteException e) {
1932 throw new RuntimeException("Package manager has died", e);
1937 public int checkPermission(String permName, String pkgName) {
1939 return mPM.checkPermission(permName, pkgName);
1940 } catch (RemoteException e) {
1941 throw new RuntimeException("Package manager has died", e);
1946 public boolean addPermission(PermissionInfo info) {
1948 return mPM.addPermission(info);
1949 } catch (RemoteException e) {
1950 throw new RuntimeException("Package manager has died", e);
1955 public boolean addPermissionAsync(PermissionInfo info) {
1957 return mPM.addPermissionAsync(info);
1958 } catch (RemoteException e) {
1959 throw new RuntimeException("Package manager has died", e);
1964 public void removePermission(String name) {
1966 mPM.removePermission(name);
1967 } catch (RemoteException e) {
1968 throw new RuntimeException("Package manager has died", e);
1973 public int checkSignatures(String pkg1, String pkg2) {
1975 return mPM.checkSignatures(pkg1, pkg2);
1976 } catch (RemoteException e) {
1977 throw new RuntimeException("Package manager has died", e);
1982 public int checkSignatures(int uid1, int uid2) {
1984 return mPM.checkUidSignatures(uid1, uid2);
1985 } catch (RemoteException e) {
1986 throw new RuntimeException("Package manager has died", e);
1991 public String[] getPackagesForUid(int uid) {
1993 return mPM.getPackagesForUid(uid);
1994 } catch (RemoteException e) {
1995 throw new RuntimeException("Package manager has died", e);
2000 public String getNameForUid(int uid) {
2002 return mPM.getNameForUid(uid);
2003 } catch (RemoteException e) {
2004 throw new RuntimeException("Package manager has died", e);
2009 public int getUidForSharedUser(String sharedUserName)
2010 throws NameNotFoundException {
2012 int uid = mPM.getUidForSharedUser(sharedUserName);
2016 } catch (RemoteException e) {
2017 throw new RuntimeException("Package manager has died", e);
2019 throw new NameNotFoundException("No shared userid for user:"+sharedUserName);
2023 public List<PackageInfo> getInstalledPackages(int flags) {
2025 return mPM.getInstalledPackages(flags);
2026 } catch (RemoteException e) {
2027 throw new RuntimeException("Package manager has died", e);
2032 public List<ApplicationInfo> getInstalledApplications(int flags) {
2034 return mPM.getInstalledApplications(flags);
2035 } catch (RemoteException e) {
2036 throw new RuntimeException("Package manager has died", e);
2041 public ResolveInfo resolveActivity(Intent intent, int flags) {
2043 return mPM.resolveIntent(
2045 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2047 } catch (RemoteException e) {
2048 throw new RuntimeException("Package manager has died", e);
2053 public List<ResolveInfo> queryIntentActivities(Intent intent,
2056 return mPM.queryIntentActivities(
2058 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2060 } catch (RemoteException e) {
2061 throw new RuntimeException("Package manager has died", e);
2066 public List<ResolveInfo> queryIntentActivityOptions(
2067 ComponentName caller, Intent[] specifics, Intent intent,
2069 final ContentResolver resolver = mContext.getContentResolver();
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];
2077 String t = sp.resolveTypeIfNeeded(resolver);
2079 if (specificTypes == null) {
2080 specificTypes = new String[N];
2082 specificTypes[i] = t;
2089 return mPM.queryIntentActivityOptions(caller, specifics,
2090 specificTypes, intent, intent.resolveTypeIfNeeded(resolver),
2092 } catch (RemoteException e) {
2093 throw new RuntimeException("Package manager has died", e);
2098 public List<ResolveInfo> queryBroadcastReceivers(Intent intent, int flags) {
2100 return mPM.queryIntentReceivers(
2102 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2104 } catch (RemoteException e) {
2105 throw new RuntimeException("Package manager has died", e);
2110 public ResolveInfo resolveService(Intent intent, int flags) {
2112 return mPM.resolveService(
2114 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2116 } catch (RemoteException e) {
2117 throw new RuntimeException("Package manager has died", e);
2122 public List<ResolveInfo> queryIntentServices(Intent intent, int flags) {
2124 return mPM.queryIntentServices(
2126 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2128 } catch (RemoteException e) {
2129 throw new RuntimeException("Package manager has died", e);
2134 public ProviderInfo resolveContentProvider(String name,
2137 return mPM.resolveContentProvider(name, flags);
2138 } catch (RemoteException e) {
2139 throw new RuntimeException("Package manager has died", e);
2144 public List<ProviderInfo> queryContentProviders(String processName,
2145 int uid, int flags) {
2147 return mPM.queryContentProviders(processName, uid, flags);
2148 } catch (RemoteException e) {
2149 throw new RuntimeException("Package manager has died", e);
2154 public InstrumentationInfo getInstrumentationInfo(
2155 ComponentName className, int flags)
2156 throws NameNotFoundException {
2158 InstrumentationInfo ii = mPM.getInstrumentationInfo(
2163 } catch (RemoteException e) {
2164 throw new RuntimeException("Package manager has died", e);
2167 throw new NameNotFoundException(className.toString());
2171 public List<InstrumentationInfo> queryInstrumentation(
2172 String targetPackage, int flags) {
2174 return mPM.queryInstrumentation(targetPackage, flags);
2175 } catch (RemoteException e) {
2176 throw new RuntimeException("Package manager has died", e);
2180 @Override public Drawable getDrawable(String packageName, int resid,
2181 ApplicationInfo appInfo) {
2182 ResourceName name = new ResourceName(packageName, resid);
2183 Drawable dr = getCachedIcon(name);
2187 if (appInfo == null) {
2189 appInfo = getApplicationInfo(packageName, 0);
2190 } catch (NameNotFoundException e) {
2195 Resources r = getResourcesForApplication(appInfo);
2196 dr = r.getDrawable(resid);
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,
2206 if (DEBUG_ICONS) Log.v(TAG, "Getting drawable 0x"
2207 + Integer.toHexString(resid) + " from " + r
2209 putCachedIcon(name, 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
2217 Log.w("PackageManager", "Failure retrieving icon 0x"
2218 + Integer.toHexString(resid) + " in package "
2224 @Override public Drawable getActivityIcon(ComponentName activityName)
2225 throws NameNotFoundException {
2226 return getActivityInfo(activityName, 0).loadIcon(this);
2229 @Override public Drawable getActivityIcon(Intent intent)
2230 throws NameNotFoundException {
2231 if (intent.getComponent() != null) {
2232 return getActivityIcon(intent.getComponent());
2235 ResolveInfo info = resolveActivity(
2236 intent, PackageManager.MATCH_DEFAULT_ONLY);
2238 return info.activityInfo.loadIcon(this);
2241 throw new NameNotFoundException(intent.toURI());
2244 @Override public Drawable getDefaultActivityIcon() {
2245 return Resources.getSystem().getDrawable(
2246 com.android.internal.R.drawable.sym_def_app_icon);
2249 @Override public Drawable getApplicationIcon(ApplicationInfo info) {
2250 return info.loadIcon(this);
2253 @Override public Drawable getApplicationIcon(String packageName)
2254 throws NameNotFoundException {
2255 return getApplicationIcon(getApplicationInfo(packageName, 0));
2259 public Drawable getActivityLogo(ComponentName activityName)
2260 throws NameNotFoundException {
2261 return getActivityInfo(activityName, 0).loadLogo(this);
2265 public Drawable getActivityLogo(Intent intent)
2266 throws NameNotFoundException {
2267 if (intent.getComponent() != null) {
2268 return getActivityLogo(intent.getComponent());
2271 ResolveInfo info = resolveActivity(
2272 intent, PackageManager.MATCH_DEFAULT_ONLY);
2274 return info.activityInfo.loadLogo(this);
2277 throw new NameNotFoundException(intent.toUri(0));
2281 public Drawable getApplicationLogo(ApplicationInfo info) {
2282 return info.loadLogo(this);
2286 public Drawable getApplicationLogo(String packageName)
2287 throws NameNotFoundException {
2288 return getApplicationLogo(getApplicationInfo(packageName, 0));
2291 @Override public Resources getResourcesForActivity(
2292 ComponentName activityName) throws NameNotFoundException {
2293 return getResourcesForApplication(
2294 getActivityInfo(activityName, 0).applicationInfo);
2297 @Override public Resources getResourcesForApplication(
2298 ApplicationInfo app) throws NameNotFoundException {
2299 if (app.packageName.equals("system")) {
2300 return mContext.mMainThread.getSystemContext().getResources();
2302 Resources r = mContext.mMainThread.getTopLevelResources(
2303 app.uid == Process.myUid() ? app.sourceDir
2304 : app.publicSourceDir, mContext.mPackageInfo);
2308 throw new NameNotFoundException("Unable to open " + app.publicSourceDir);
2311 @Override public Resources getResourcesForApplication(
2312 String appPackageName) throws NameNotFoundException {
2313 return getResourcesForApplication(
2314 getApplicationInfo(appPackageName, 0));
2317 int mCachedSafeMode = -1;
2318 @Override public boolean isSafeMode() {
2320 if (mCachedSafeMode < 0) {
2321 mCachedSafeMode = mPM.isSafeMode() ? 1 : 0;
2323 return mCachedSafeMode != 0;
2324 } catch (RemoteException e) {
2325 throw new RuntimeException("Package manager has died", e);
2329 static void configurationChanged() {
2330 synchronized (sSync) {
2332 sStringCache.clear();
2336 ApplicationPackageManager(ContextImpl context,
2337 IPackageManager pm) {
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();
2350 if (DEBUG_ICONS) Log.v(TAG, "Get cached drawable for "
2351 + name + ": " + dr);
2354 // our entry has been purged
2355 sIconCache.remove(name);
2361 private void putCachedIcon(ResourceName name, Drawable dr) {