ContextImpl.java revision 50576fa8152557a25e1a231c66d694fffbab34d6
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 17package android.app; 18 19import com.android.internal.policy.PolicyManager; 20import com.android.internal.util.XmlUtils; 21import com.google.android.collect.Maps; 22 23import org.xmlpull.v1.XmlPullParserException; 24 25import android.content.BroadcastReceiver; 26import android.content.ComponentName; 27import android.content.ContentResolver; 28import android.content.Context; 29import android.content.ContextWrapper; 30import android.content.IContentProvider; 31import android.content.Intent; 32import android.content.IntentFilter; 33import android.content.IIntentReceiver; 34import android.content.IntentSender; 35import android.content.ReceiverCallNotAllowedException; 36import android.content.ServiceConnection; 37import android.content.SharedPreferences; 38import android.content.pm.ActivityInfo; 39import android.content.pm.ApplicationInfo; 40import android.content.pm.ComponentInfo; 41import android.content.pm.FeatureInfo; 42import android.content.pm.IPackageDataObserver; 43import android.content.pm.IPackageDeleteObserver; 44import android.content.pm.IPackageInstallObserver; 45import android.content.pm.IPackageMoveObserver; 46import android.content.pm.IPackageManager; 47import android.content.pm.IPackageStatsObserver; 48import android.content.pm.InstrumentationInfo; 49import android.content.pm.PackageInfo; 50import android.content.pm.PackageManager; 51import android.content.pm.PermissionGroupInfo; 52import android.content.pm.PermissionInfo; 53import android.content.pm.ProviderInfo; 54import android.content.pm.ResolveInfo; 55import android.content.pm.ServiceInfo; 56import android.content.res.AssetManager; 57import android.content.res.Resources; 58import android.content.res.XmlResourceParser; 59import android.database.sqlite.SQLiteDatabase; 60import android.database.sqlite.SQLiteDatabase.CursorFactory; 61import android.graphics.Bitmap; 62import android.graphics.drawable.Drawable; 63import android.hardware.SensorManager; 64import android.location.ILocationManager; 65import android.location.LocationManager; 66import android.media.AudioManager; 67import android.net.ConnectivityManager; 68import android.net.IConnectivityManager; 69import android.net.DownloadManager; 70import android.net.ThrottleManager; 71import android.net.IThrottleManager; 72import android.net.Uri; 73import android.net.wifi.IWifiManager; 74import android.net.wifi.WifiManager; 75import android.os.Binder; 76import android.os.Bundle; 77import android.os.DropBoxManager; 78import android.os.Environment; 79import android.os.FileUtils; 80import android.os.Handler; 81import android.os.IBinder; 82import android.os.IPowerManager; 83import android.os.Looper; 84import android.os.PowerManager; 85import android.os.Process; 86import android.os.RemoteException; 87import android.os.ServiceManager; 88import android.os.Vibrator; 89import android.os.FileUtils.FileStatus; 90import android.os.storage.StorageManager; 91import android.telephony.TelephonyManager; 92import android.text.ClipboardManager; 93import android.util.AndroidRuntimeException; 94import android.util.Log; 95import android.view.ContextThemeWrapper; 96import android.view.LayoutInflater; 97import android.view.WindowManagerImpl; 98import android.view.accessibility.AccessibilityManager; 99import android.view.inputmethod.InputMethodManager; 100import android.accounts.AccountManager; 101import android.accounts.IAccountManager; 102import android.app.admin.DevicePolicyManager; 103 104import com.android.internal.os.IDropBoxManagerService; 105 106import java.io.File; 107import java.io.FileInputStream; 108import java.io.FileNotFoundException; 109import java.io.FileOutputStream; 110import java.io.IOException; 111import java.io.InputStream; 112import java.lang.ref.WeakReference; 113import java.util.ArrayList; 114import java.util.HashMap; 115import java.util.HashSet; 116import java.util.Iterator; 117import java.util.List; 118import java.util.Map; 119import java.util.Set; 120import java.util.WeakHashMap; 121import java.util.Map.Entry; 122 123class ReceiverRestrictedContext extends ContextWrapper { 124 ReceiverRestrictedContext(Context base) { 125 super(base); 126 } 127 128 @Override 129 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) { 130 return registerReceiver(receiver, filter, null, null); 131 } 132 133 @Override 134 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, 135 String broadcastPermission, Handler scheduler) { 136 throw new ReceiverCallNotAllowedException( 137 "IntentReceiver components are not allowed to register to receive intents"); 138 //ex.fillInStackTrace(); 139 //Log.e("IntentReceiver", ex.getMessage(), ex); 140 //return mContext.registerReceiver(receiver, filter, broadcastPermission, 141 // scheduler); 142 } 143 144 @Override 145 public boolean bindService(Intent service, ServiceConnection conn, int flags) { 146 throw new ReceiverCallNotAllowedException( 147 "IntentReceiver components are not allowed to bind to services"); 148 //ex.fillInStackTrace(); 149 //Log.e("IntentReceiver", ex.getMessage(), ex); 150 //return mContext.bindService(service, interfaceName, conn, flags); 151 } 152} 153 154/** 155 * Common implementation of Context API, which provides the base 156 * context object for Activity and other application components. 157 */ 158class ContextImpl extends Context { 159 private final static String TAG = "ApplicationContext"; 160 private final static boolean DEBUG = false; 161 private final static boolean DEBUG_ICONS = false; 162 163 private static final Object sSync = new Object(); 164 private static AlarmManager sAlarmManager; 165 private static PowerManager sPowerManager; 166 private static ConnectivityManager sConnectivityManager; 167 private static ThrottleManager sThrottleManager; 168 private static WifiManager sWifiManager; 169 private static LocationManager sLocationManager; 170 private static final HashMap<File, SharedPreferencesImpl> sSharedPrefs = 171 new HashMap<File, SharedPreferencesImpl>(); 172 173 private AudioManager mAudioManager; 174 /*package*/ LoadedApk mPackageInfo; 175 private Resources mResources; 176 /*package*/ ActivityThread mMainThread; 177 private Context mOuterContext; 178 private IBinder mActivityToken = null; 179 private ApplicationContentResolver mContentResolver; 180 private int mThemeResource = 0; 181 private Resources.Theme mTheme = null; 182 private PackageManager mPackageManager; 183 private NotificationManager mNotificationManager = null; 184 private ActivityManager mActivityManager = null; 185 private WallpaperManager mWallpaperManager = null; 186 private Context mReceiverRestrictedContext = null; 187 private SearchManager mSearchManager = null; 188 private SensorManager mSensorManager = null; 189 private StorageManager mStorageManager = null; 190 private Vibrator mVibrator = null; 191 private LayoutInflater mLayoutInflater = null; 192 private StatusBarManager mStatusBarManager = null; 193 private TelephonyManager mTelephonyManager = null; 194 private ClipboardManager mClipboardManager = null; 195 private boolean mRestricted; 196 private AccountManager mAccountManager; // protected by mSync 197 private DropBoxManager mDropBoxManager = null; 198 private DevicePolicyManager mDevicePolicyManager = null; 199 private UiModeManager mUiModeManager = null; 200 private DownloadManager mDownloadManager = null; 201 202 private final Object mSync = new Object(); 203 204 private File mDatabasesDir; 205 private File mPreferencesDir; 206 private File mFilesDir; 207 private File mCacheDir; 208 private File mExternalFilesDir; 209 private File mExternalCacheDir; 210 211 private static long sInstanceCount = 0; 212 213 private static final String[] EMPTY_FILE_LIST = {}; 214 215 // For debug only 216 /* 217 @Override 218 protected void finalize() throws Throwable { 219 super.finalize(); 220 --sInstanceCount; 221 } 222 */ 223 224 public static long getInstanceCount() { 225 return sInstanceCount; 226 } 227 228 @Override 229 public AssetManager getAssets() { 230 return mResources.getAssets(); 231 } 232 233 @Override 234 public Resources getResources() { 235 return mResources; 236 } 237 238 @Override 239 public PackageManager getPackageManager() { 240 if (mPackageManager != null) { 241 return mPackageManager; 242 } 243 244 IPackageManager pm = ActivityThread.getPackageManager(); 245 if (pm != null) { 246 // Doesn't matter if we make more than one instance. 247 return (mPackageManager = new ApplicationPackageManager(this, pm)); 248 } 249 250 return null; 251 } 252 253 @Override 254 public ContentResolver getContentResolver() { 255 return mContentResolver; 256 } 257 258 @Override 259 public Looper getMainLooper() { 260 return mMainThread.getLooper(); 261 } 262 263 @Override 264 public Context getApplicationContext() { 265 return (mPackageInfo != null) ? 266 mPackageInfo.getApplication() : mMainThread.getApplication(); 267 } 268 269 @Override 270 public void setTheme(int resid) { 271 mThemeResource = resid; 272 } 273 274 @Override 275 public Resources.Theme getTheme() { 276 if (mTheme == null) { 277 if (mThemeResource == 0) { 278 mThemeResource = com.android.internal.R.style.Theme; 279 } 280 mTheme = mResources.newTheme(); 281 mTheme.applyStyle(mThemeResource, true); 282 } 283 return mTheme; 284 } 285 286 @Override 287 public ClassLoader getClassLoader() { 288 return mPackageInfo != null ? 289 mPackageInfo.getClassLoader() : ClassLoader.getSystemClassLoader(); 290 } 291 292 @Override 293 public String getPackageName() { 294 if (mPackageInfo != null) { 295 return mPackageInfo.getPackageName(); 296 } 297 throw new RuntimeException("Not supported in system context"); 298 } 299 300 @Override 301 public ApplicationInfo getApplicationInfo() { 302 if (mPackageInfo != null) { 303 return mPackageInfo.getApplicationInfo(); 304 } 305 throw new RuntimeException("Not supported in system context"); 306 } 307 308 @Override 309 public String getPackageResourcePath() { 310 if (mPackageInfo != null) { 311 return mPackageInfo.getResDir(); 312 } 313 throw new RuntimeException("Not supported in system context"); 314 } 315 316 @Override 317 public String getPackageCodePath() { 318 if (mPackageInfo != null) { 319 return mPackageInfo.getAppDir(); 320 } 321 throw new RuntimeException("Not supported in system context"); 322 } 323 324 private static File makeBackupFile(File prefsFile) { 325 return new File(prefsFile.getPath() + ".bak"); 326 } 327 328 public File getSharedPrefsFile(String name) { 329 return makeFilename(getPreferencesDir(), name + ".xml"); 330 } 331 332 @Override 333 public SharedPreferences getSharedPreferences(String name, int mode) { 334 SharedPreferencesImpl sp; 335 File f = getSharedPrefsFile(name); 336 synchronized (sSharedPrefs) { 337 sp = sSharedPrefs.get(f); 338 if (sp != null && !sp.hasFileChanged()) { 339 //Log.i(TAG, "Returning existing prefs " + name + ": " + sp); 340 return sp; 341 } 342 } 343 344 FileInputStream str = null; 345 File backup = makeBackupFile(f); 346 if (backup.exists()) { 347 f.delete(); 348 backup.renameTo(f); 349 } 350 351 // Debugging 352 if (f.exists() && !f.canRead()) { 353 Log.w(TAG, "Attempt to read preferences file " + f + " without permission"); 354 } 355 356 Map map = null; 357 if (f.exists() && f.canRead()) { 358 try { 359 str = new FileInputStream(f); 360 map = XmlUtils.readMapXml(str); 361 str.close(); 362 } catch (org.xmlpull.v1.XmlPullParserException e) { 363 Log.w(TAG, "getSharedPreferences", e); 364 } catch (FileNotFoundException e) { 365 Log.w(TAG, "getSharedPreferences", e); 366 } catch (IOException e) { 367 Log.w(TAG, "getSharedPreferences", e); 368 } 369 } 370 371 synchronized (sSharedPrefs) { 372 if (sp != null) { 373 //Log.i(TAG, "Updating existing prefs " + name + " " + sp + ": " + map); 374 sp.replace(map); 375 } else { 376 sp = sSharedPrefs.get(f); 377 if (sp == null) { 378 sp = new SharedPreferencesImpl(f, mode, map); 379 sSharedPrefs.put(f, sp); 380 } 381 } 382 return sp; 383 } 384 } 385 386 private File getPreferencesDir() { 387 synchronized (mSync) { 388 if (mPreferencesDir == null) { 389 mPreferencesDir = new File(getDataDirFile(), "shared_prefs"); 390 } 391 return mPreferencesDir; 392 } 393 } 394 395 @Override 396 public FileInputStream openFileInput(String name) 397 throws FileNotFoundException { 398 File f = makeFilename(getFilesDir(), name); 399 return new FileInputStream(f); 400 } 401 402 @Override 403 public FileOutputStream openFileOutput(String name, int mode) 404 throws FileNotFoundException { 405 final boolean append = (mode&MODE_APPEND) != 0; 406 File f = makeFilename(getFilesDir(), name); 407 try { 408 FileOutputStream fos = new FileOutputStream(f, append); 409 setFilePermissionsFromMode(f.getPath(), mode, 0); 410 return fos; 411 } catch (FileNotFoundException e) { 412 } 413 414 File parent = f.getParentFile(); 415 parent.mkdir(); 416 FileUtils.setPermissions( 417 parent.getPath(), 418 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, 419 -1, -1); 420 FileOutputStream fos = new FileOutputStream(f, append); 421 setFilePermissionsFromMode(f.getPath(), mode, 0); 422 return fos; 423 } 424 425 @Override 426 public boolean deleteFile(String name) { 427 File f = makeFilename(getFilesDir(), name); 428 return f.delete(); 429 } 430 431 @Override 432 public File getFilesDir() { 433 synchronized (mSync) { 434 if (mFilesDir == null) { 435 mFilesDir = new File(getDataDirFile(), "files"); 436 } 437 if (!mFilesDir.exists()) { 438 if(!mFilesDir.mkdirs()) { 439 Log.w(TAG, "Unable to create files directory " + mFilesDir.getPath()); 440 return null; 441 } 442 FileUtils.setPermissions( 443 mFilesDir.getPath(), 444 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, 445 -1, -1); 446 } 447 return mFilesDir; 448 } 449 } 450 451 @Override 452 public File getExternalFilesDir(String type) { 453 synchronized (mSync) { 454 if (mExternalFilesDir == null) { 455 mExternalFilesDir = Environment.getExternalStorageAppFilesDirectory( 456 getPackageName()); 457 } 458 if (!mExternalFilesDir.exists()) { 459 try { 460 (new File(Environment.getExternalStorageAndroidDataDir(), 461 ".nomedia")).createNewFile(); 462 } catch (IOException e) { 463 } 464 if (!mExternalFilesDir.mkdirs()) { 465 Log.w(TAG, "Unable to create external files directory"); 466 return null; 467 } 468 } 469 if (type == null) { 470 return mExternalFilesDir; 471 } 472 File dir = new File(mExternalFilesDir, type); 473 if (!dir.exists()) { 474 if (!dir.mkdirs()) { 475 Log.w(TAG, "Unable to create external media directory " + dir); 476 return null; 477 } 478 } 479 return dir; 480 } 481 } 482 483 @Override 484 public File getCacheDir() { 485 synchronized (mSync) { 486 if (mCacheDir == null) { 487 mCacheDir = new File(getDataDirFile(), "cache"); 488 } 489 if (!mCacheDir.exists()) { 490 if(!mCacheDir.mkdirs()) { 491 Log.w(TAG, "Unable to create cache directory"); 492 return null; 493 } 494 FileUtils.setPermissions( 495 mCacheDir.getPath(), 496 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, 497 -1, -1); 498 } 499 } 500 return mCacheDir; 501 } 502 503 @Override 504 public File getExternalCacheDir() { 505 synchronized (mSync) { 506 if (mExternalCacheDir == null) { 507 mExternalCacheDir = Environment.getExternalStorageAppCacheDirectory( 508 getPackageName()); 509 } 510 if (!mExternalCacheDir.exists()) { 511 try { 512 (new File(Environment.getExternalStorageAndroidDataDir(), 513 ".nomedia")).createNewFile(); 514 } catch (IOException e) { 515 } 516 if (!mExternalCacheDir.mkdirs()) { 517 Log.w(TAG, "Unable to create external cache directory"); 518 return null; 519 } 520 } 521 return mExternalCacheDir; 522 } 523 } 524 525 @Override 526 public File getFileStreamPath(String name) { 527 return makeFilename(getFilesDir(), name); 528 } 529 530 @Override 531 public String[] fileList() { 532 final String[] list = getFilesDir().list(); 533 return (list != null) ? list : EMPTY_FILE_LIST; 534 } 535 536 @Override 537 public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory) { 538 File f = validateFilePath(name, true); 539 SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(f, factory); 540 setFilePermissionsFromMode(f.getPath(), mode, 0); 541 return db; 542 } 543 544 @Override 545 public boolean deleteDatabase(String name) { 546 try { 547 File f = validateFilePath(name, false); 548 return f.delete(); 549 } catch (Exception e) { 550 } 551 return false; 552 } 553 554 @Override 555 public File getDatabasePath(String name) { 556 return validateFilePath(name, false); 557 } 558 559 @Override 560 public String[] databaseList() { 561 final String[] list = getDatabasesDir().list(); 562 return (list != null) ? list : EMPTY_FILE_LIST; 563 } 564 565 566 private File getDatabasesDir() { 567 synchronized (mSync) { 568 if (mDatabasesDir == null) { 569 mDatabasesDir = new File(getDataDirFile(), "databases"); 570 } 571 if (mDatabasesDir.getPath().equals("databases")) { 572 mDatabasesDir = new File("/data/system"); 573 } 574 return mDatabasesDir; 575 } 576 } 577 578 @Override 579 public Drawable getWallpaper() { 580 return getWallpaperManager().getDrawable(); 581 } 582 583 @Override 584 public Drawable peekWallpaper() { 585 return getWallpaperManager().peekDrawable(); 586 } 587 588 @Override 589 public int getWallpaperDesiredMinimumWidth() { 590 return getWallpaperManager().getDesiredMinimumWidth(); 591 } 592 593 @Override 594 public int getWallpaperDesiredMinimumHeight() { 595 return getWallpaperManager().getDesiredMinimumHeight(); 596 } 597 598 @Override 599 public void setWallpaper(Bitmap bitmap) throws IOException { 600 getWallpaperManager().setBitmap(bitmap); 601 } 602 603 @Override 604 public void setWallpaper(InputStream data) throws IOException { 605 getWallpaperManager().setStream(data); 606 } 607 608 @Override 609 public void clearWallpaper() throws IOException { 610 getWallpaperManager().clear(); 611 } 612 613 @Override 614 public void startActivity(Intent intent) { 615 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) { 616 throw new AndroidRuntimeException( 617 "Calling startActivity() from outside of an Activity " 618 + " context requires the FLAG_ACTIVITY_NEW_TASK flag." 619 + " Is this really what you want?"); 620 } 621 mMainThread.getInstrumentation().execStartActivity( 622 getOuterContext(), mMainThread.getApplicationThread(), null, null, intent, -1); 623 } 624 625 @Override 626 public void startIntentSender(IntentSender intent, 627 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) 628 throws IntentSender.SendIntentException { 629 try { 630 String resolvedType = null; 631 if (fillInIntent != null) { 632 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver()); 633 } 634 int result = ActivityManagerNative.getDefault() 635 .startActivityIntentSender(mMainThread.getApplicationThread(), intent, 636 fillInIntent, resolvedType, null, null, 637 0, flagsMask, flagsValues); 638 if (result == IActivityManager.START_CANCELED) { 639 throw new IntentSender.SendIntentException(); 640 } 641 Instrumentation.checkStartActivityResult(result, null); 642 } catch (RemoteException e) { 643 } 644 } 645 646 @Override 647 public void sendBroadcast(Intent intent) { 648 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 649 try { 650 ActivityManagerNative.getDefault().broadcastIntent( 651 mMainThread.getApplicationThread(), intent, resolvedType, null, 652 Activity.RESULT_OK, null, null, null, false, false); 653 } catch (RemoteException e) { 654 } 655 } 656 657 @Override 658 public void sendBroadcast(Intent intent, String receiverPermission) { 659 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 660 try { 661 ActivityManagerNative.getDefault().broadcastIntent( 662 mMainThread.getApplicationThread(), intent, resolvedType, null, 663 Activity.RESULT_OK, null, null, receiverPermission, false, false); 664 } catch (RemoteException e) { 665 } 666 } 667 668 @Override 669 public void sendOrderedBroadcast(Intent intent, 670 String receiverPermission) { 671 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 672 try { 673 ActivityManagerNative.getDefault().broadcastIntent( 674 mMainThread.getApplicationThread(), intent, resolvedType, null, 675 Activity.RESULT_OK, null, null, receiverPermission, true, false); 676 } catch (RemoteException e) { 677 } 678 } 679 680 @Override 681 public void sendOrderedBroadcast(Intent intent, 682 String receiverPermission, BroadcastReceiver resultReceiver, 683 Handler scheduler, int initialCode, String initialData, 684 Bundle initialExtras) { 685 IIntentReceiver rd = null; 686 if (resultReceiver != null) { 687 if (mPackageInfo != null) { 688 if (scheduler == null) { 689 scheduler = mMainThread.getHandler(); 690 } 691 rd = mPackageInfo.getReceiverDispatcher( 692 resultReceiver, getOuterContext(), scheduler, 693 mMainThread.getInstrumentation(), false); 694 } else { 695 if (scheduler == null) { 696 scheduler = mMainThread.getHandler(); 697 } 698 rd = new LoadedApk.ReceiverDispatcher( 699 resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver(); 700 } 701 } 702 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 703 try { 704 ActivityManagerNative.getDefault().broadcastIntent( 705 mMainThread.getApplicationThread(), intent, resolvedType, rd, 706 initialCode, initialData, initialExtras, receiverPermission, 707 true, false); 708 } catch (RemoteException e) { 709 } 710 } 711 712 @Override 713 public void sendStickyBroadcast(Intent intent) { 714 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 715 try { 716 ActivityManagerNative.getDefault().broadcastIntent( 717 mMainThread.getApplicationThread(), intent, resolvedType, null, 718 Activity.RESULT_OK, null, null, null, false, true); 719 } catch (RemoteException e) { 720 } 721 } 722 723 @Override 724 public void sendStickyOrderedBroadcast(Intent intent, 725 BroadcastReceiver resultReceiver, 726 Handler scheduler, int initialCode, String initialData, 727 Bundle initialExtras) { 728 IIntentReceiver rd = null; 729 if (resultReceiver != null) { 730 if (mPackageInfo != null) { 731 if (scheduler == null) { 732 scheduler = mMainThread.getHandler(); 733 } 734 rd = mPackageInfo.getReceiverDispatcher( 735 resultReceiver, getOuterContext(), scheduler, 736 mMainThread.getInstrumentation(), false); 737 } else { 738 if (scheduler == null) { 739 scheduler = mMainThread.getHandler(); 740 } 741 rd = new LoadedApk.ReceiverDispatcher( 742 resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver(); 743 } 744 } 745 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 746 try { 747 ActivityManagerNative.getDefault().broadcastIntent( 748 mMainThread.getApplicationThread(), intent, resolvedType, rd, 749 initialCode, initialData, initialExtras, null, 750 true, true); 751 } catch (RemoteException e) { 752 } 753 } 754 755 @Override 756 public void removeStickyBroadcast(Intent intent) { 757 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 758 if (resolvedType != null) { 759 intent = new Intent(intent); 760 intent.setDataAndType(intent.getData(), resolvedType); 761 } 762 try { 763 ActivityManagerNative.getDefault().unbroadcastIntent( 764 mMainThread.getApplicationThread(), intent); 765 } catch (RemoteException e) { 766 } 767 } 768 769 @Override 770 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) { 771 return registerReceiver(receiver, filter, null, null); 772 } 773 774 @Override 775 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, 776 String broadcastPermission, Handler scheduler) { 777 return registerReceiverInternal(receiver, filter, broadcastPermission, 778 scheduler, getOuterContext()); 779 } 780 781 private Intent registerReceiverInternal(BroadcastReceiver receiver, 782 IntentFilter filter, String broadcastPermission, 783 Handler scheduler, Context context) { 784 IIntentReceiver rd = null; 785 if (receiver != null) { 786 if (mPackageInfo != null && context != null) { 787 if (scheduler == null) { 788 scheduler = mMainThread.getHandler(); 789 } 790 rd = mPackageInfo.getReceiverDispatcher( 791 receiver, context, scheduler, 792 mMainThread.getInstrumentation(), true); 793 } else { 794 if (scheduler == null) { 795 scheduler = mMainThread.getHandler(); 796 } 797 rd = new LoadedApk.ReceiverDispatcher( 798 receiver, context, scheduler, null, true).getIIntentReceiver(); 799 } 800 } 801 try { 802 return ActivityManagerNative.getDefault().registerReceiver( 803 mMainThread.getApplicationThread(), 804 rd, filter, broadcastPermission); 805 } catch (RemoteException e) { 806 return null; 807 } 808 } 809 810 @Override 811 public void unregisterReceiver(BroadcastReceiver receiver) { 812 if (mPackageInfo != null) { 813 IIntentReceiver rd = mPackageInfo.forgetReceiverDispatcher( 814 getOuterContext(), receiver); 815 try { 816 ActivityManagerNative.getDefault().unregisterReceiver(rd); 817 } catch (RemoteException e) { 818 } 819 } else { 820 throw new RuntimeException("Not supported in system context"); 821 } 822 } 823 824 @Override 825 public ComponentName startService(Intent service) { 826 try { 827 ComponentName cn = ActivityManagerNative.getDefault().startService( 828 mMainThread.getApplicationThread(), service, 829 service.resolveTypeIfNeeded(getContentResolver())); 830 if (cn != null && cn.getPackageName().equals("!")) { 831 throw new SecurityException( 832 "Not allowed to start service " + service 833 + " without permission " + cn.getClassName()); 834 } 835 return cn; 836 } catch (RemoteException e) { 837 return null; 838 } 839 } 840 841 @Override 842 public boolean stopService(Intent service) { 843 try { 844 int res = ActivityManagerNative.getDefault().stopService( 845 mMainThread.getApplicationThread(), service, 846 service.resolveTypeIfNeeded(getContentResolver())); 847 if (res < 0) { 848 throw new SecurityException( 849 "Not allowed to stop service " + service); 850 } 851 return res != 0; 852 } catch (RemoteException e) { 853 return false; 854 } 855 } 856 857 @Override 858 public boolean bindService(Intent service, ServiceConnection conn, 859 int flags) { 860 IServiceConnection sd; 861 if (mPackageInfo != null) { 862 sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), 863 mMainThread.getHandler(), flags); 864 } else { 865 throw new RuntimeException("Not supported in system context"); 866 } 867 try { 868 int res = ActivityManagerNative.getDefault().bindService( 869 mMainThread.getApplicationThread(), getActivityToken(), 870 service, service.resolveTypeIfNeeded(getContentResolver()), 871 sd, flags); 872 if (res < 0) { 873 throw new SecurityException( 874 "Not allowed to bind to service " + service); 875 } 876 return res != 0; 877 } catch (RemoteException e) { 878 return false; 879 } 880 } 881 882 @Override 883 public void unbindService(ServiceConnection conn) { 884 if (mPackageInfo != null) { 885 IServiceConnection sd = mPackageInfo.forgetServiceDispatcher( 886 getOuterContext(), conn); 887 try { 888 ActivityManagerNative.getDefault().unbindService(sd); 889 } catch (RemoteException e) { 890 } 891 } else { 892 throw new RuntimeException("Not supported in system context"); 893 } 894 } 895 896 @Override 897 public boolean startInstrumentation(ComponentName className, 898 String profileFile, Bundle arguments) { 899 try { 900 return ActivityManagerNative.getDefault().startInstrumentation( 901 className, profileFile, 0, arguments, null); 902 } catch (RemoteException e) { 903 // System has crashed, nothing we can do. 904 } 905 return false; 906 } 907 908 @Override 909 public Object getSystemService(String name) { 910 if (WINDOW_SERVICE.equals(name)) { 911 return WindowManagerImpl.getDefault(); 912 } else if (LAYOUT_INFLATER_SERVICE.equals(name)) { 913 synchronized (mSync) { 914 LayoutInflater inflater = mLayoutInflater; 915 if (inflater != null) { 916 return inflater; 917 } 918 mLayoutInflater = inflater = 919 PolicyManager.makeNewLayoutInflater(getOuterContext()); 920 return inflater; 921 } 922 } else if (ACTIVITY_SERVICE.equals(name)) { 923 return getActivityManager(); 924 } else if (INPUT_METHOD_SERVICE.equals(name)) { 925 return InputMethodManager.getInstance(this); 926 } else if (ALARM_SERVICE.equals(name)) { 927 return getAlarmManager(); 928 } else if (ACCOUNT_SERVICE.equals(name)) { 929 return getAccountManager(); 930 } else if (POWER_SERVICE.equals(name)) { 931 return getPowerManager(); 932 } else if (CONNECTIVITY_SERVICE.equals(name)) { 933 return getConnectivityManager(); 934 } else if (THROTTLE_SERVICE.equals(name)) { 935 return getThrottleManager(); 936 } else if (WIFI_SERVICE.equals(name)) { 937 return getWifiManager(); 938 } else if (NOTIFICATION_SERVICE.equals(name)) { 939 return getNotificationManager(); 940 } else if (KEYGUARD_SERVICE.equals(name)) { 941 return new KeyguardManager(); 942 } else if (ACCESSIBILITY_SERVICE.equals(name)) { 943 return AccessibilityManager.getInstance(this); 944 } else if (LOCATION_SERVICE.equals(name)) { 945 return getLocationManager(); 946 } else if (SEARCH_SERVICE.equals(name)) { 947 return getSearchManager(); 948 } else if (SENSOR_SERVICE.equals(name)) { 949 return getSensorManager(); 950 } else if (STORAGE_SERVICE.equals(name)) { 951 return getStorageManager(); 952 } else if (VIBRATOR_SERVICE.equals(name)) { 953 return getVibrator(); 954 } else if (STATUS_BAR_SERVICE.equals(name)) { 955 synchronized (mSync) { 956 if (mStatusBarManager == null) { 957 mStatusBarManager = new StatusBarManager(getOuterContext()); 958 } 959 return mStatusBarManager; 960 } 961 } else if (AUDIO_SERVICE.equals(name)) { 962 return getAudioManager(); 963 } else if (TELEPHONY_SERVICE.equals(name)) { 964 return getTelephonyManager(); 965 } else if (CLIPBOARD_SERVICE.equals(name)) { 966 return getClipboardManager(); 967 } else if (WALLPAPER_SERVICE.equals(name)) { 968 return getWallpaperManager(); 969 } else if (DROPBOX_SERVICE.equals(name)) { 970 return getDropBoxManager(); 971 } else if (DEVICE_POLICY_SERVICE.equals(name)) { 972 return getDevicePolicyManager(); 973 } else if (UI_MODE_SERVICE.equals(name)) { 974 return getUiModeManager(); 975 } else if (DOWNLOAD_SERVICE.equals(name)) { 976 return getDownloadManager(); 977 } 978 979 return null; 980 } 981 982 private AccountManager getAccountManager() { 983 synchronized (mSync) { 984 if (mAccountManager == null) { 985 IBinder b = ServiceManager.getService(ACCOUNT_SERVICE); 986 IAccountManager service = IAccountManager.Stub.asInterface(b); 987 mAccountManager = new AccountManager(this, service); 988 } 989 return mAccountManager; 990 } 991 } 992 993 private ActivityManager getActivityManager() { 994 synchronized (mSync) { 995 if (mActivityManager == null) { 996 mActivityManager = new ActivityManager(getOuterContext(), 997 mMainThread.getHandler()); 998 } 999 } 1000 return mActivityManager; 1001 } 1002 1003 private AlarmManager getAlarmManager() { 1004 synchronized (sSync) { 1005 if (sAlarmManager == null) { 1006 IBinder b = ServiceManager.getService(ALARM_SERVICE); 1007 IAlarmManager service = IAlarmManager.Stub.asInterface(b); 1008 sAlarmManager = new AlarmManager(service); 1009 } 1010 } 1011 return sAlarmManager; 1012 } 1013 1014 private PowerManager getPowerManager() { 1015 synchronized (sSync) { 1016 if (sPowerManager == null) { 1017 IBinder b = ServiceManager.getService(POWER_SERVICE); 1018 IPowerManager service = IPowerManager.Stub.asInterface(b); 1019 sPowerManager = new PowerManager(service, mMainThread.getHandler()); 1020 } 1021 } 1022 return sPowerManager; 1023 } 1024 1025 private ConnectivityManager getConnectivityManager() 1026 { 1027 synchronized (sSync) { 1028 if (sConnectivityManager == null) { 1029 IBinder b = ServiceManager.getService(CONNECTIVITY_SERVICE); 1030 IConnectivityManager service = IConnectivityManager.Stub.asInterface(b); 1031 sConnectivityManager = new ConnectivityManager(service); 1032 } 1033 } 1034 return sConnectivityManager; 1035 } 1036 1037 private ThrottleManager getThrottleManager() 1038 { 1039 synchronized (sSync) { 1040 if (sThrottleManager == null) { 1041 IBinder b = ServiceManager.getService(THROTTLE_SERVICE); 1042 IThrottleManager service = IThrottleManager.Stub.asInterface(b); 1043 sThrottleManager = new ThrottleManager(service); 1044 } 1045 } 1046 return sThrottleManager; 1047 } 1048 1049 private WifiManager getWifiManager() 1050 { 1051 synchronized (sSync) { 1052 if (sWifiManager == null) { 1053 IBinder b = ServiceManager.getService(WIFI_SERVICE); 1054 IWifiManager service = IWifiManager.Stub.asInterface(b); 1055 sWifiManager = new WifiManager(service, mMainThread.getHandler()); 1056 } 1057 } 1058 return sWifiManager; 1059 } 1060 1061 private NotificationManager getNotificationManager() { 1062 synchronized (mSync) { 1063 if (mNotificationManager == null) { 1064 mNotificationManager = new NotificationManager( 1065 new ContextThemeWrapper(getOuterContext(), com.android.internal.R.style.Theme_Dialog), 1066 mMainThread.getHandler()); 1067 } 1068 } 1069 return mNotificationManager; 1070 } 1071 1072 private WallpaperManager getWallpaperManager() { 1073 synchronized (mSync) { 1074 if (mWallpaperManager == null) { 1075 mWallpaperManager = new WallpaperManager(getOuterContext(), 1076 mMainThread.getHandler()); 1077 } 1078 } 1079 return mWallpaperManager; 1080 } 1081 1082 private TelephonyManager getTelephonyManager() { 1083 synchronized (mSync) { 1084 if (mTelephonyManager == null) { 1085 mTelephonyManager = new TelephonyManager(getOuterContext()); 1086 } 1087 } 1088 return mTelephonyManager; 1089 } 1090 1091 private ClipboardManager getClipboardManager() { 1092 synchronized (mSync) { 1093 if (mClipboardManager == null) { 1094 mClipboardManager = new ClipboardManager(getOuterContext(), 1095 mMainThread.getHandler()); 1096 } 1097 } 1098 return mClipboardManager; 1099 } 1100 1101 private LocationManager getLocationManager() { 1102 synchronized (sSync) { 1103 if (sLocationManager == null) { 1104 IBinder b = ServiceManager.getService(LOCATION_SERVICE); 1105 ILocationManager service = ILocationManager.Stub.asInterface(b); 1106 sLocationManager = new LocationManager(service); 1107 } 1108 } 1109 return sLocationManager; 1110 } 1111 1112 private SearchManager getSearchManager() { 1113 synchronized (mSync) { 1114 if (mSearchManager == null) { 1115 mSearchManager = new SearchManager(getOuterContext(), mMainThread.getHandler()); 1116 } 1117 } 1118 return mSearchManager; 1119 } 1120 1121 private SensorManager getSensorManager() { 1122 synchronized (mSync) { 1123 if (mSensorManager == null) { 1124 mSensorManager = new SensorManager(mMainThread.getHandler().getLooper()); 1125 } 1126 } 1127 return mSensorManager; 1128 } 1129 1130 private StorageManager getStorageManager() { 1131 synchronized (mSync) { 1132 if (mStorageManager == null) { 1133 try { 1134 mStorageManager = new StorageManager(mMainThread.getHandler().getLooper()); 1135 } catch (RemoteException rex) { 1136 Log.e(TAG, "Failed to create StorageManager", rex); 1137 mStorageManager = null; 1138 } 1139 } 1140 } 1141 return mStorageManager; 1142 } 1143 1144 private Vibrator getVibrator() { 1145 synchronized (mSync) { 1146 if (mVibrator == null) { 1147 mVibrator = new Vibrator(); 1148 } 1149 } 1150 return mVibrator; 1151 } 1152 1153 private AudioManager getAudioManager() 1154 { 1155 if (mAudioManager == null) { 1156 mAudioManager = new AudioManager(this); 1157 } 1158 return mAudioManager; 1159 } 1160 1161 /* package */ static DropBoxManager createDropBoxManager() { 1162 IBinder b = ServiceManager.getService(DROPBOX_SERVICE); 1163 IDropBoxManagerService service = IDropBoxManagerService.Stub.asInterface(b); 1164 return new DropBoxManager(service); 1165 } 1166 1167 private DropBoxManager getDropBoxManager() { 1168 synchronized (mSync) { 1169 if (mDropBoxManager == null) { 1170 mDropBoxManager = createDropBoxManager(); 1171 } 1172 } 1173 return mDropBoxManager; 1174 } 1175 1176 private DevicePolicyManager getDevicePolicyManager() { 1177 synchronized (mSync) { 1178 if (mDevicePolicyManager == null) { 1179 mDevicePolicyManager = DevicePolicyManager.create(this, 1180 mMainThread.getHandler()); 1181 } 1182 } 1183 return mDevicePolicyManager; 1184 } 1185 1186 private UiModeManager getUiModeManager() { 1187 synchronized (mSync) { 1188 if (mUiModeManager == null) { 1189 mUiModeManager = new UiModeManager(); 1190 } 1191 } 1192 return mUiModeManager; 1193 } 1194 1195 private DownloadManager getDownloadManager() { 1196 synchronized (mSync) { 1197 if (mDownloadManager == null) { 1198 mDownloadManager = new DownloadManager(getContentResolver()); 1199 } 1200 } 1201 return mDownloadManager; 1202 } 1203 1204 @Override 1205 public int checkPermission(String permission, int pid, int uid) { 1206 if (permission == null) { 1207 throw new IllegalArgumentException("permission is null"); 1208 } 1209 1210 if (!Process.supportsProcesses()) { 1211 return PackageManager.PERMISSION_GRANTED; 1212 } 1213 try { 1214 return ActivityManagerNative.getDefault().checkPermission( 1215 permission, pid, uid); 1216 } catch (RemoteException e) { 1217 return PackageManager.PERMISSION_DENIED; 1218 } 1219 } 1220 1221 @Override 1222 public int checkCallingPermission(String permission) { 1223 if (permission == null) { 1224 throw new IllegalArgumentException("permission is null"); 1225 } 1226 1227 if (!Process.supportsProcesses()) { 1228 return PackageManager.PERMISSION_GRANTED; 1229 } 1230 int pid = Binder.getCallingPid(); 1231 if (pid != Process.myPid()) { 1232 return checkPermission(permission, pid, 1233 Binder.getCallingUid()); 1234 } 1235 return PackageManager.PERMISSION_DENIED; 1236 } 1237 1238 @Override 1239 public int checkCallingOrSelfPermission(String permission) { 1240 if (permission == null) { 1241 throw new IllegalArgumentException("permission is null"); 1242 } 1243 1244 return checkPermission(permission, Binder.getCallingPid(), 1245 Binder.getCallingUid()); 1246 } 1247 1248 private void enforce( 1249 String permission, int resultOfCheck, 1250 boolean selfToo, int uid, String message) { 1251 if (resultOfCheck != PackageManager.PERMISSION_GRANTED) { 1252 throw new SecurityException( 1253 (message != null ? (message + ": ") : "") + 1254 (selfToo 1255 ? "Neither user " + uid + " nor current process has " 1256 : "User " + uid + " does not have ") + 1257 permission + 1258 "."); 1259 } 1260 } 1261 1262 public void enforcePermission( 1263 String permission, int pid, int uid, String message) { 1264 enforce(permission, 1265 checkPermission(permission, pid, uid), 1266 false, 1267 uid, 1268 message); 1269 } 1270 1271 public void enforceCallingPermission(String permission, String message) { 1272 enforce(permission, 1273 checkCallingPermission(permission), 1274 false, 1275 Binder.getCallingUid(), 1276 message); 1277 } 1278 1279 public void enforceCallingOrSelfPermission( 1280 String permission, String message) { 1281 enforce(permission, 1282 checkCallingOrSelfPermission(permission), 1283 true, 1284 Binder.getCallingUid(), 1285 message); 1286 } 1287 1288 @Override 1289 public void grantUriPermission(String toPackage, Uri uri, int modeFlags) { 1290 try { 1291 ActivityManagerNative.getDefault().grantUriPermission( 1292 mMainThread.getApplicationThread(), toPackage, uri, 1293 modeFlags); 1294 } catch (RemoteException e) { 1295 } 1296 } 1297 1298 @Override 1299 public void revokeUriPermission(Uri uri, int modeFlags) { 1300 try { 1301 ActivityManagerNative.getDefault().revokeUriPermission( 1302 mMainThread.getApplicationThread(), uri, 1303 modeFlags); 1304 } catch (RemoteException e) { 1305 } 1306 } 1307 1308 @Override 1309 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) { 1310 if (!Process.supportsProcesses()) { 1311 return PackageManager.PERMISSION_GRANTED; 1312 } 1313 try { 1314 return ActivityManagerNative.getDefault().checkUriPermission( 1315 uri, pid, uid, modeFlags); 1316 } catch (RemoteException e) { 1317 return PackageManager.PERMISSION_DENIED; 1318 } 1319 } 1320 1321 @Override 1322 public int checkCallingUriPermission(Uri uri, int modeFlags) { 1323 if (!Process.supportsProcesses()) { 1324 return PackageManager.PERMISSION_GRANTED; 1325 } 1326 int pid = Binder.getCallingPid(); 1327 if (pid != Process.myPid()) { 1328 return checkUriPermission(uri, pid, 1329 Binder.getCallingUid(), modeFlags); 1330 } 1331 return PackageManager.PERMISSION_DENIED; 1332 } 1333 1334 @Override 1335 public int checkCallingOrSelfUriPermission(Uri uri, int modeFlags) { 1336 return checkUriPermission(uri, Binder.getCallingPid(), 1337 Binder.getCallingUid(), modeFlags); 1338 } 1339 1340 @Override 1341 public int checkUriPermission(Uri uri, String readPermission, 1342 String writePermission, int pid, int uid, int modeFlags) { 1343 if (DEBUG) { 1344 Log.i("foo", "checkUriPermission: uri=" + uri + "readPermission=" 1345 + readPermission + " writePermission=" + writePermission 1346 + " pid=" + pid + " uid=" + uid + " mode" + modeFlags); 1347 } 1348 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) { 1349 if (readPermission == null 1350 || checkPermission(readPermission, pid, uid) 1351 == PackageManager.PERMISSION_GRANTED) { 1352 return PackageManager.PERMISSION_GRANTED; 1353 } 1354 } 1355 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) { 1356 if (writePermission == null 1357 || checkPermission(writePermission, pid, uid) 1358 == PackageManager.PERMISSION_GRANTED) { 1359 return PackageManager.PERMISSION_GRANTED; 1360 } 1361 } 1362 return uri != null ? checkUriPermission(uri, pid, uid, modeFlags) 1363 : PackageManager.PERMISSION_DENIED; 1364 } 1365 1366 private String uriModeFlagToString(int uriModeFlags) { 1367 switch (uriModeFlags) { 1368 case Intent.FLAG_GRANT_READ_URI_PERMISSION | 1369 Intent.FLAG_GRANT_WRITE_URI_PERMISSION: 1370 return "read and write"; 1371 case Intent.FLAG_GRANT_READ_URI_PERMISSION: 1372 return "read"; 1373 case Intent.FLAG_GRANT_WRITE_URI_PERMISSION: 1374 return "write"; 1375 } 1376 throw new IllegalArgumentException( 1377 "Unknown permission mode flags: " + uriModeFlags); 1378 } 1379 1380 private void enforceForUri( 1381 int modeFlags, int resultOfCheck, boolean selfToo, 1382 int uid, Uri uri, String message) { 1383 if (resultOfCheck != PackageManager.PERMISSION_GRANTED) { 1384 throw new SecurityException( 1385 (message != null ? (message + ": ") : "") + 1386 (selfToo 1387 ? "Neither user " + uid + " nor current process has " 1388 : "User " + uid + " does not have ") + 1389 uriModeFlagToString(modeFlags) + 1390 " permission on " + 1391 uri + 1392 "."); 1393 } 1394 } 1395 1396 public void enforceUriPermission( 1397 Uri uri, int pid, int uid, int modeFlags, String message) { 1398 enforceForUri( 1399 modeFlags, checkUriPermission(uri, pid, uid, modeFlags), 1400 false, uid, uri, message); 1401 } 1402 1403 public void enforceCallingUriPermission( 1404 Uri uri, int modeFlags, String message) { 1405 enforceForUri( 1406 modeFlags, checkCallingUriPermission(uri, modeFlags), 1407 false, Binder.getCallingUid(), uri, message); 1408 } 1409 1410 public void enforceCallingOrSelfUriPermission( 1411 Uri uri, int modeFlags, String message) { 1412 enforceForUri( 1413 modeFlags, 1414 checkCallingOrSelfUriPermission(uri, modeFlags), true, 1415 Binder.getCallingUid(), uri, message); 1416 } 1417 1418 public void enforceUriPermission( 1419 Uri uri, String readPermission, String writePermission, 1420 int pid, int uid, int modeFlags, String message) { 1421 enforceForUri(modeFlags, 1422 checkUriPermission( 1423 uri, readPermission, writePermission, pid, uid, 1424 modeFlags), 1425 false, 1426 uid, 1427 uri, 1428 message); 1429 } 1430 1431 @Override 1432 public Context createPackageContext(String packageName, int flags) 1433 throws PackageManager.NameNotFoundException { 1434 if (packageName.equals("system") || packageName.equals("android")) { 1435 return new ContextImpl(mMainThread.getSystemContext()); 1436 } 1437 1438 LoadedApk pi = 1439 mMainThread.getPackageInfo(packageName, flags); 1440 if (pi != null) { 1441 ContextImpl c = new ContextImpl(); 1442 c.mRestricted = (flags & CONTEXT_RESTRICTED) == CONTEXT_RESTRICTED; 1443 c.init(pi, null, mMainThread, mResources); 1444 if (c.mResources != null) { 1445 return c; 1446 } 1447 } 1448 1449 // Should be a better exception. 1450 throw new PackageManager.NameNotFoundException( 1451 "Application package " + packageName + " not found"); 1452 } 1453 1454 @Override 1455 public boolean isRestricted() { 1456 return mRestricted; 1457 } 1458 1459 private File getDataDirFile() { 1460 if (mPackageInfo != null) { 1461 return mPackageInfo.getDataDirFile(); 1462 } 1463 throw new RuntimeException("Not supported in system context"); 1464 } 1465 1466 @Override 1467 public File getDir(String name, int mode) { 1468 name = "app_" + name; 1469 File file = makeFilename(getDataDirFile(), name); 1470 if (!file.exists()) { 1471 file.mkdir(); 1472 setFilePermissionsFromMode(file.getPath(), mode, 1473 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH); 1474 } 1475 return file; 1476 } 1477 1478 static ContextImpl createSystemContext(ActivityThread mainThread) { 1479 ContextImpl context = new ContextImpl(); 1480 context.init(Resources.getSystem(), mainThread); 1481 return context; 1482 } 1483 1484 ContextImpl() { 1485 // For debug only 1486 //++sInstanceCount; 1487 mOuterContext = this; 1488 } 1489 1490 /** 1491 * Create a new ApplicationContext from an existing one. The new one 1492 * works and operates the same as the one it is copying. 1493 * 1494 * @param context Existing application context. 1495 */ 1496 public ContextImpl(ContextImpl context) { 1497 ++sInstanceCount; 1498 mPackageInfo = context.mPackageInfo; 1499 mResources = context.mResources; 1500 mMainThread = context.mMainThread; 1501 mContentResolver = context.mContentResolver; 1502 mOuterContext = this; 1503 } 1504 1505 final void init(LoadedApk packageInfo, 1506 IBinder activityToken, ActivityThread mainThread) { 1507 init(packageInfo, activityToken, mainThread, null); 1508 } 1509 1510 final void init(LoadedApk packageInfo, 1511 IBinder activityToken, ActivityThread mainThread, 1512 Resources container) { 1513 mPackageInfo = packageInfo; 1514 mResources = mPackageInfo.getResources(mainThread); 1515 1516 if (mResources != null && container != null 1517 && container.getCompatibilityInfo().applicationScale != 1518 mResources.getCompatibilityInfo().applicationScale) { 1519 if (DEBUG) { 1520 Log.d(TAG, "loaded context has different scaling. Using container's" + 1521 " compatiblity info:" + container.getDisplayMetrics()); 1522 } 1523 mResources = mainThread.getTopLevelResources( 1524 mPackageInfo.getResDir(), container.getCompatibilityInfo().copy()); 1525 } 1526 mMainThread = mainThread; 1527 mContentResolver = new ApplicationContentResolver(this, mainThread); 1528 1529 setActivityToken(activityToken); 1530 } 1531 1532 final void init(Resources resources, ActivityThread mainThread) { 1533 mPackageInfo = null; 1534 mResources = resources; 1535 mMainThread = mainThread; 1536 mContentResolver = new ApplicationContentResolver(this, mainThread); 1537 } 1538 1539 final void scheduleFinalCleanup(String who, String what) { 1540 mMainThread.scheduleContextCleanup(this, who, what); 1541 } 1542 1543 final void performFinalCleanup(String who, String what) { 1544 //Log.i(TAG, "Cleanup up context: " + this); 1545 mPackageInfo.removeContextRegistrations(getOuterContext(), who, what); 1546 } 1547 1548 final Context getReceiverRestrictedContext() { 1549 if (mReceiverRestrictedContext != null) { 1550 return mReceiverRestrictedContext; 1551 } 1552 return mReceiverRestrictedContext = new ReceiverRestrictedContext(getOuterContext()); 1553 } 1554 1555 final void setActivityToken(IBinder token) { 1556 mActivityToken = token; 1557 } 1558 1559 final void setOuterContext(Context context) { 1560 mOuterContext = context; 1561 } 1562 1563 final Context getOuterContext() { 1564 return mOuterContext; 1565 } 1566 1567 final IBinder getActivityToken() { 1568 return mActivityToken; 1569 } 1570 1571 private static void setFilePermissionsFromMode(String name, int mode, 1572 int extraPermissions) { 1573 int perms = FileUtils.S_IRUSR|FileUtils.S_IWUSR 1574 |FileUtils.S_IRGRP|FileUtils.S_IWGRP 1575 |extraPermissions; 1576 if ((mode&MODE_WORLD_READABLE) != 0) { 1577 perms |= FileUtils.S_IROTH; 1578 } 1579 if ((mode&MODE_WORLD_WRITEABLE) != 0) { 1580 perms |= FileUtils.S_IWOTH; 1581 } 1582 if (DEBUG) { 1583 Log.i(TAG, "File " + name + ": mode=0x" + Integer.toHexString(mode) 1584 + ", perms=0x" + Integer.toHexString(perms)); 1585 } 1586 FileUtils.setPermissions(name, perms, -1, -1); 1587 } 1588 1589 private File validateFilePath(String name, boolean createDirectory) { 1590 File dir; 1591 File f; 1592 1593 if (name.charAt(0) == File.separatorChar) { 1594 String dirPath = name.substring(0, name.lastIndexOf(File.separatorChar)); 1595 dir = new File(dirPath); 1596 name = name.substring(name.lastIndexOf(File.separatorChar)); 1597 f = new File(dir, name); 1598 } else { 1599 dir = getDatabasesDir(); 1600 f = makeFilename(dir, name); 1601 } 1602 1603 if (createDirectory && !dir.isDirectory() && dir.mkdir()) { 1604 FileUtils.setPermissions(dir.getPath(), 1605 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, 1606 -1, -1); 1607 } 1608 1609 return f; 1610 } 1611 1612 private File makeFilename(File base, String name) { 1613 if (name.indexOf(File.separatorChar) < 0) { 1614 return new File(base, name); 1615 } 1616 throw new IllegalArgumentException( 1617 "File " + name + " contains a path separator"); 1618 } 1619 1620 // ---------------------------------------------------------------------- 1621 // ---------------------------------------------------------------------- 1622 // ---------------------------------------------------------------------- 1623 1624 private static final class ApplicationContentResolver extends ContentResolver { 1625 public ApplicationContentResolver(Context context, 1626 ActivityThread mainThread) 1627 { 1628 super(context); 1629 mMainThread = mainThread; 1630 } 1631 1632 @Override 1633 protected IContentProvider acquireProvider(Context context, String name) 1634 { 1635 return mMainThread.acquireProvider(context, name); 1636 } 1637 1638 @Override 1639 public boolean releaseProvider(IContentProvider provider) 1640 { 1641 return mMainThread.releaseProvider(provider); 1642 } 1643 1644 private final ActivityThread mMainThread; 1645 } 1646 1647 // ---------------------------------------------------------------------- 1648 // ---------------------------------------------------------------------- 1649 // ---------------------------------------------------------------------- 1650 1651 /*package*/ 1652 static final class ApplicationPackageManager extends PackageManager { 1653 @Override 1654 public PackageInfo getPackageInfo(String packageName, int flags) 1655 throws NameNotFoundException { 1656 try { 1657 PackageInfo pi = mPM.getPackageInfo(packageName, flags); 1658 if (pi != null) { 1659 return pi; 1660 } 1661 } catch (RemoteException e) { 1662 throw new RuntimeException("Package manager has died", e); 1663 } 1664 1665 throw new NameNotFoundException(packageName); 1666 } 1667 1668 @Override 1669 public String[] currentToCanonicalPackageNames(String[] names) { 1670 try { 1671 return mPM.currentToCanonicalPackageNames(names); 1672 } catch (RemoteException e) { 1673 throw new RuntimeException("Package manager has died", e); 1674 } 1675 } 1676 1677 @Override 1678 public String[] canonicalToCurrentPackageNames(String[] names) { 1679 try { 1680 return mPM.canonicalToCurrentPackageNames(names); 1681 } catch (RemoteException e) { 1682 throw new RuntimeException("Package manager has died", e); 1683 } 1684 } 1685 1686 @Override 1687 public Intent getLaunchIntentForPackage(String packageName) { 1688 // First see if the package has an INFO activity; the existence of 1689 // such an activity is implied to be the desired front-door for the 1690 // overall package (such as if it has multiple launcher entries). 1691 Intent intentToResolve = new Intent(Intent.ACTION_MAIN); 1692 intentToResolve.addCategory(Intent.CATEGORY_INFO); 1693 intentToResolve.setPackage(packageName); 1694 ResolveInfo resolveInfo = resolveActivity(intentToResolve, 0); 1695 1696 // Otherwise, try to find a main launcher activity. 1697 if (resolveInfo == null) { 1698 // reuse the intent instance 1699 intentToResolve.removeCategory(Intent.CATEGORY_INFO); 1700 intentToResolve.addCategory(Intent.CATEGORY_LAUNCHER); 1701 intentToResolve.setPackage(packageName); 1702 resolveInfo = resolveActivity(intentToResolve, 0); 1703 } 1704 if (resolveInfo == null) { 1705 return null; 1706 } 1707 Intent intent = new Intent(intentToResolve); 1708 intent.setClassName(resolveInfo.activityInfo.applicationInfo.packageName, 1709 resolveInfo.activityInfo.name); 1710 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 1711 return intent; 1712 } 1713 1714 @Override 1715 public int[] getPackageGids(String packageName) 1716 throws NameNotFoundException { 1717 try { 1718 int[] gids = mPM.getPackageGids(packageName); 1719 if (gids == null || gids.length > 0) { 1720 return gids; 1721 } 1722 } catch (RemoteException e) { 1723 throw new RuntimeException("Package manager has died", e); 1724 } 1725 1726 throw new NameNotFoundException(packageName); 1727 } 1728 1729 @Override 1730 public PermissionInfo getPermissionInfo(String name, int flags) 1731 throws NameNotFoundException { 1732 try { 1733 PermissionInfo pi = mPM.getPermissionInfo(name, flags); 1734 if (pi != null) { 1735 return pi; 1736 } 1737 } catch (RemoteException e) { 1738 throw new RuntimeException("Package manager has died", e); 1739 } 1740 1741 throw new NameNotFoundException(name); 1742 } 1743 1744 @Override 1745 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) 1746 throws NameNotFoundException { 1747 try { 1748 List<PermissionInfo> pi = mPM.queryPermissionsByGroup(group, flags); 1749 if (pi != null) { 1750 return pi; 1751 } 1752 } catch (RemoteException e) { 1753 throw new RuntimeException("Package manager has died", e); 1754 } 1755 1756 throw new NameNotFoundException(group); 1757 } 1758 1759 @Override 1760 public PermissionGroupInfo getPermissionGroupInfo(String name, 1761 int flags) throws NameNotFoundException { 1762 try { 1763 PermissionGroupInfo pgi = mPM.getPermissionGroupInfo(name, flags); 1764 if (pgi != null) { 1765 return pgi; 1766 } 1767 } catch (RemoteException e) { 1768 throw new RuntimeException("Package manager has died", e); 1769 } 1770 1771 throw new NameNotFoundException(name); 1772 } 1773 1774 @Override 1775 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 1776 try { 1777 return mPM.getAllPermissionGroups(flags); 1778 } catch (RemoteException e) { 1779 throw new RuntimeException("Package manager has died", e); 1780 } 1781 } 1782 1783 @Override 1784 public ApplicationInfo getApplicationInfo(String packageName, int flags) 1785 throws NameNotFoundException { 1786 try { 1787 ApplicationInfo ai = mPM.getApplicationInfo(packageName, flags); 1788 if (ai != null) { 1789 return ai; 1790 } 1791 } catch (RemoteException e) { 1792 throw new RuntimeException("Package manager has died", e); 1793 } 1794 1795 throw new NameNotFoundException(packageName); 1796 } 1797 1798 @Override 1799 public ActivityInfo getActivityInfo(ComponentName className, int flags) 1800 throws NameNotFoundException { 1801 try { 1802 ActivityInfo ai = mPM.getActivityInfo(className, flags); 1803 if (ai != null) { 1804 return ai; 1805 } 1806 } catch (RemoteException e) { 1807 throw new RuntimeException("Package manager has died", e); 1808 } 1809 1810 throw new NameNotFoundException(className.toString()); 1811 } 1812 1813 @Override 1814 public ActivityInfo getReceiverInfo(ComponentName className, int flags) 1815 throws NameNotFoundException { 1816 try { 1817 ActivityInfo ai = mPM.getReceiverInfo(className, flags); 1818 if (ai != null) { 1819 return ai; 1820 } 1821 } catch (RemoteException e) { 1822 throw new RuntimeException("Package manager has died", e); 1823 } 1824 1825 throw new NameNotFoundException(className.toString()); 1826 } 1827 1828 @Override 1829 public ServiceInfo getServiceInfo(ComponentName className, int flags) 1830 throws NameNotFoundException { 1831 try { 1832 ServiceInfo si = mPM.getServiceInfo(className, flags); 1833 if (si != null) { 1834 return si; 1835 } 1836 } catch (RemoteException e) { 1837 throw new RuntimeException("Package manager has died", e); 1838 } 1839 1840 throw new NameNotFoundException(className.toString()); 1841 } 1842 1843 @Override 1844 public String[] getSystemSharedLibraryNames() { 1845 try { 1846 return mPM.getSystemSharedLibraryNames(); 1847 } catch (RemoteException e) { 1848 throw new RuntimeException("Package manager has died", e); 1849 } 1850 } 1851 1852 @Override 1853 public FeatureInfo[] getSystemAvailableFeatures() { 1854 try { 1855 return mPM.getSystemAvailableFeatures(); 1856 } catch (RemoteException e) { 1857 throw new RuntimeException("Package manager has died", e); 1858 } 1859 } 1860 1861 @Override 1862 public boolean hasSystemFeature(String name) { 1863 try { 1864 return mPM.hasSystemFeature(name); 1865 } catch (RemoteException e) { 1866 throw new RuntimeException("Package manager has died", e); 1867 } 1868 } 1869 1870 @Override 1871 public int checkPermission(String permName, String pkgName) { 1872 try { 1873 return mPM.checkPermission(permName, pkgName); 1874 } catch (RemoteException e) { 1875 throw new RuntimeException("Package manager has died", e); 1876 } 1877 } 1878 1879 @Override 1880 public boolean addPermission(PermissionInfo info) { 1881 try { 1882 return mPM.addPermission(info); 1883 } catch (RemoteException e) { 1884 throw new RuntimeException("Package manager has died", e); 1885 } 1886 } 1887 1888 @Override 1889 public boolean addPermissionAsync(PermissionInfo info) { 1890 try { 1891 return mPM.addPermissionAsync(info); 1892 } catch (RemoteException e) { 1893 throw new RuntimeException("Package manager has died", e); 1894 } 1895 } 1896 1897 @Override 1898 public void removePermission(String name) { 1899 try { 1900 mPM.removePermission(name); 1901 } catch (RemoteException e) { 1902 throw new RuntimeException("Package manager has died", e); 1903 } 1904 } 1905 1906 @Override 1907 public int checkSignatures(String pkg1, String pkg2) { 1908 try { 1909 return mPM.checkSignatures(pkg1, pkg2); 1910 } catch (RemoteException e) { 1911 throw new RuntimeException("Package manager has died", e); 1912 } 1913 } 1914 1915 @Override 1916 public int checkSignatures(int uid1, int uid2) { 1917 try { 1918 return mPM.checkUidSignatures(uid1, uid2); 1919 } catch (RemoteException e) { 1920 throw new RuntimeException("Package manager has died", e); 1921 } 1922 } 1923 1924 @Override 1925 public String[] getPackagesForUid(int uid) { 1926 try { 1927 return mPM.getPackagesForUid(uid); 1928 } catch (RemoteException e) { 1929 throw new RuntimeException("Package manager has died", e); 1930 } 1931 } 1932 1933 @Override 1934 public String getNameForUid(int uid) { 1935 try { 1936 return mPM.getNameForUid(uid); 1937 } catch (RemoteException e) { 1938 throw new RuntimeException("Package manager has died", e); 1939 } 1940 } 1941 1942 @Override 1943 public int getUidForSharedUser(String sharedUserName) 1944 throws NameNotFoundException { 1945 try { 1946 int uid = mPM.getUidForSharedUser(sharedUserName); 1947 if(uid != -1) { 1948 return uid; 1949 } 1950 } catch (RemoteException e) { 1951 throw new RuntimeException("Package manager has died", e); 1952 } 1953 throw new NameNotFoundException("No shared userid for user:"+sharedUserName); 1954 } 1955 1956 @Override 1957 public List<PackageInfo> getInstalledPackages(int flags) { 1958 try { 1959 return mPM.getInstalledPackages(flags); 1960 } catch (RemoteException e) { 1961 throw new RuntimeException("Package manager has died", e); 1962 } 1963 } 1964 1965 @Override 1966 public List<ApplicationInfo> getInstalledApplications(int flags) { 1967 try { 1968 return mPM.getInstalledApplications(flags); 1969 } catch (RemoteException e) { 1970 throw new RuntimeException("Package manager has died", e); 1971 } 1972 } 1973 1974 @Override 1975 public ResolveInfo resolveActivity(Intent intent, int flags) { 1976 try { 1977 return mPM.resolveIntent( 1978 intent, 1979 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 1980 flags); 1981 } catch (RemoteException e) { 1982 throw new RuntimeException("Package manager has died", e); 1983 } 1984 } 1985 1986 @Override 1987 public List<ResolveInfo> queryIntentActivities(Intent intent, 1988 int flags) { 1989 try { 1990 return mPM.queryIntentActivities( 1991 intent, 1992 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 1993 flags); 1994 } catch (RemoteException e) { 1995 throw new RuntimeException("Package manager has died", e); 1996 } 1997 } 1998 1999 @Override 2000 public List<ResolveInfo> queryIntentActivityOptions( 2001 ComponentName caller, Intent[] specifics, Intent intent, 2002 int flags) { 2003 final ContentResolver resolver = mContext.getContentResolver(); 2004 2005 String[] specificTypes = null; 2006 if (specifics != null) { 2007 final int N = specifics.length; 2008 for (int i=0; i<N; i++) { 2009 Intent sp = specifics[i]; 2010 if (sp != null) { 2011 String t = sp.resolveTypeIfNeeded(resolver); 2012 if (t != null) { 2013 if (specificTypes == null) { 2014 specificTypes = new String[N]; 2015 } 2016 specificTypes[i] = t; 2017 } 2018 } 2019 } 2020 } 2021 2022 try { 2023 return mPM.queryIntentActivityOptions(caller, specifics, 2024 specificTypes, intent, intent.resolveTypeIfNeeded(resolver), 2025 flags); 2026 } catch (RemoteException e) { 2027 throw new RuntimeException("Package manager has died", e); 2028 } 2029 } 2030 2031 @Override 2032 public List<ResolveInfo> queryBroadcastReceivers(Intent intent, int flags) { 2033 try { 2034 return mPM.queryIntentReceivers( 2035 intent, 2036 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 2037 flags); 2038 } catch (RemoteException e) { 2039 throw new RuntimeException("Package manager has died", e); 2040 } 2041 } 2042 2043 @Override 2044 public ResolveInfo resolveService(Intent intent, int flags) { 2045 try { 2046 return mPM.resolveService( 2047 intent, 2048 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 2049 flags); 2050 } catch (RemoteException e) { 2051 throw new RuntimeException("Package manager has died", e); 2052 } 2053 } 2054 2055 @Override 2056 public List<ResolveInfo> queryIntentServices(Intent intent, int flags) { 2057 try { 2058 return mPM.queryIntentServices( 2059 intent, 2060 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 2061 flags); 2062 } catch (RemoteException e) { 2063 throw new RuntimeException("Package manager has died", e); 2064 } 2065 } 2066 2067 @Override 2068 public ProviderInfo resolveContentProvider(String name, 2069 int flags) { 2070 try { 2071 return mPM.resolveContentProvider(name, flags); 2072 } catch (RemoteException e) { 2073 throw new RuntimeException("Package manager has died", e); 2074 } 2075 } 2076 2077 @Override 2078 public List<ProviderInfo> queryContentProviders(String processName, 2079 int uid, int flags) { 2080 try { 2081 return mPM.queryContentProviders(processName, uid, flags); 2082 } catch (RemoteException e) { 2083 throw new RuntimeException("Package manager has died", e); 2084 } 2085 } 2086 2087 @Override 2088 public InstrumentationInfo getInstrumentationInfo( 2089 ComponentName className, int flags) 2090 throws NameNotFoundException { 2091 try { 2092 InstrumentationInfo ii = mPM.getInstrumentationInfo( 2093 className, flags); 2094 if (ii != null) { 2095 return ii; 2096 } 2097 } catch (RemoteException e) { 2098 throw new RuntimeException("Package manager has died", e); 2099 } 2100 2101 throw new NameNotFoundException(className.toString()); 2102 } 2103 2104 @Override 2105 public List<InstrumentationInfo> queryInstrumentation( 2106 String targetPackage, int flags) { 2107 try { 2108 return mPM.queryInstrumentation(targetPackage, flags); 2109 } catch (RemoteException e) { 2110 throw new RuntimeException("Package manager has died", e); 2111 } 2112 } 2113 2114 @Override public Drawable getDrawable(String packageName, int resid, 2115 ApplicationInfo appInfo) { 2116 ResourceName name = new ResourceName(packageName, resid); 2117 Drawable dr = getCachedIcon(name); 2118 if (dr != null) { 2119 return dr; 2120 } 2121 if (appInfo == null) { 2122 try { 2123 appInfo = getApplicationInfo(packageName, 0); 2124 } catch (NameNotFoundException e) { 2125 return null; 2126 } 2127 } 2128 try { 2129 Resources r = getResourcesForApplication(appInfo); 2130 dr = r.getDrawable(resid); 2131 if (false) { 2132 RuntimeException e = new RuntimeException("here"); 2133 e.fillInStackTrace(); 2134 Log.w(TAG, "Getting drawable 0x" + Integer.toHexString(resid) 2135 + " from package " + packageName 2136 + ": app scale=" + r.getCompatibilityInfo().applicationScale 2137 + ", caller scale=" + mContext.getResources().getCompatibilityInfo().applicationScale, 2138 e); 2139 } 2140 if (DEBUG_ICONS) Log.v(TAG, "Getting drawable 0x" 2141 + Integer.toHexString(resid) + " from " + r 2142 + ": " + dr); 2143 putCachedIcon(name, dr); 2144 return dr; 2145 } catch (NameNotFoundException e) { 2146 Log.w("PackageManager", "Failure retrieving resources for" 2147 + appInfo.packageName); 2148 } catch (RuntimeException e) { 2149 // If an exception was thrown, fall through to return 2150 // default icon. 2151 Log.w("PackageManager", "Failure retrieving icon 0x" 2152 + Integer.toHexString(resid) + " in package " 2153 + packageName, e); 2154 } 2155 return null; 2156 } 2157 2158 @Override public Drawable getActivityIcon(ComponentName activityName) 2159 throws NameNotFoundException { 2160 return getActivityInfo(activityName, 0).loadIcon(this); 2161 } 2162 2163 @Override public Drawable getActivityIcon(Intent intent) 2164 throws NameNotFoundException { 2165 if (intent.getComponent() != null) { 2166 return getActivityIcon(intent.getComponent()); 2167 } 2168 2169 ResolveInfo info = resolveActivity( 2170 intent, PackageManager.MATCH_DEFAULT_ONLY); 2171 if (info != null) { 2172 return info.activityInfo.loadIcon(this); 2173 } 2174 2175 throw new NameNotFoundException(intent.toURI()); 2176 } 2177 2178 @Override public Drawable getDefaultActivityIcon() { 2179 return Resources.getSystem().getDrawable( 2180 com.android.internal.R.drawable.sym_def_app_icon); 2181 } 2182 2183 @Override public Drawable getApplicationIcon(ApplicationInfo info) { 2184 return info.loadIcon(this); 2185 } 2186 2187 @Override public Drawable getApplicationIcon(String packageName) 2188 throws NameNotFoundException { 2189 return getApplicationIcon(getApplicationInfo(packageName, 0)); 2190 } 2191 2192 @Override 2193 public Drawable getActivityLogo(ComponentName activityName) 2194 throws NameNotFoundException { 2195 return getActivityInfo(activityName, 0).loadLogo(this); 2196 } 2197 2198 @Override 2199 public Drawable getActivityLogo(Intent intent) 2200 throws NameNotFoundException { 2201 if (intent.getComponent() != null) { 2202 return getActivityLogo(intent.getComponent()); 2203 } 2204 2205 ResolveInfo info = resolveActivity( 2206 intent, PackageManager.MATCH_DEFAULT_ONLY); 2207 if (info != null) { 2208 return info.activityInfo.loadLogo(this); 2209 } 2210 2211 throw new NameNotFoundException(intent.toUri(0)); 2212 } 2213 2214 @Override 2215 public Drawable getApplicationLogo(ApplicationInfo info) { 2216 return info.loadLogo(this); 2217 } 2218 2219 @Override 2220 public Drawable getApplicationLogo(String packageName) 2221 throws NameNotFoundException { 2222 return getApplicationLogo(getApplicationInfo(packageName, 0)); 2223 } 2224 2225 @Override public Resources getResourcesForActivity( 2226 ComponentName activityName) throws NameNotFoundException { 2227 return getResourcesForApplication( 2228 getActivityInfo(activityName, 0).applicationInfo); 2229 } 2230 2231 @Override public Resources getResourcesForApplication( 2232 ApplicationInfo app) throws NameNotFoundException { 2233 if (app.packageName.equals("system")) { 2234 return mContext.mMainThread.getSystemContext().getResources(); 2235 } 2236 Resources r = mContext.mMainThread.getTopLevelResources( 2237 app.uid == Process.myUid() ? app.sourceDir 2238 : app.publicSourceDir, mContext.mPackageInfo); 2239 if (r != null) { 2240 return r; 2241 } 2242 throw new NameNotFoundException("Unable to open " + app.publicSourceDir); 2243 } 2244 2245 @Override public Resources getResourcesForApplication( 2246 String appPackageName) throws NameNotFoundException { 2247 return getResourcesForApplication( 2248 getApplicationInfo(appPackageName, 0)); 2249 } 2250 2251 int mCachedSafeMode = -1; 2252 @Override public boolean isSafeMode() { 2253 try { 2254 if (mCachedSafeMode < 0) { 2255 mCachedSafeMode = mPM.isSafeMode() ? 1 : 0; 2256 } 2257 return mCachedSafeMode != 0; 2258 } catch (RemoteException e) { 2259 throw new RuntimeException("Package manager has died", e); 2260 } 2261 } 2262 2263 static void configurationChanged() { 2264 synchronized (sSync) { 2265 sIconCache.clear(); 2266 sStringCache.clear(); 2267 } 2268 } 2269 2270 ApplicationPackageManager(ContextImpl context, 2271 IPackageManager pm) { 2272 mContext = context; 2273 mPM = pm; 2274 } 2275 2276 private Drawable getCachedIcon(ResourceName name) { 2277 synchronized (sSync) { 2278 WeakReference<Drawable> wr = sIconCache.get(name); 2279 if (DEBUG_ICONS) Log.v(TAG, "Get cached weak drawable ref for " 2280 + name + ": " + wr); 2281 if (wr != null) { // we have the activity 2282 Drawable dr = wr.get(); 2283 if (dr != null) { 2284 if (DEBUG_ICONS) Log.v(TAG, "Get cached drawable for " 2285 + name + ": " + dr); 2286 return dr; 2287 } 2288 // our entry has been purged 2289 sIconCache.remove(name); 2290 } 2291 } 2292 return null; 2293 } 2294 2295 private void putCachedIcon(ResourceName name, Drawable dr) { 2296 synchronized (sSync) { 2297 sIconCache.put(name, new WeakReference<Drawable>(dr)); 2298 if (DEBUG_ICONS) Log.v(TAG, "Added cached drawable for " 2299 + name + ": " + dr); 2300 } 2301 } 2302 2303 static final void handlePackageBroadcast(int cmd, String[] pkgList, 2304 boolean hasPkgInfo) { 2305 boolean immediateGc = false; 2306 if (cmd == IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE) { 2307 immediateGc = true; 2308 } 2309 if (pkgList != null && (pkgList.length > 0)) { 2310 boolean needCleanup = false; 2311 for (String ssp : pkgList) { 2312 synchronized (sSync) { 2313 if (sIconCache.size() > 0) { 2314 Iterator<ResourceName> it = sIconCache.keySet().iterator(); 2315 while (it.hasNext()) { 2316 ResourceName nm = it.next(); 2317 if (nm.packageName.equals(ssp)) { 2318 //Log.i(TAG, "Removing cached drawable for " + nm); 2319 it.remove(); 2320 needCleanup = true; 2321 } 2322 } 2323 } 2324 if (sStringCache.size() > 0) { 2325 Iterator<ResourceName> it = sStringCache.keySet().iterator(); 2326 while (it.hasNext()) { 2327 ResourceName nm = it.next(); 2328 if (nm.packageName.equals(ssp)) { 2329 //Log.i(TAG, "Removing cached string for " + nm); 2330 it.remove(); 2331 needCleanup = true; 2332 } 2333 } 2334 } 2335 } 2336 } 2337 if (needCleanup || hasPkgInfo) { 2338 if (immediateGc) { 2339 // Schedule an immediate gc. 2340 Runtime.getRuntime().gc(); 2341 } else { 2342 ActivityThread.currentActivityThread().scheduleGcIdler(); 2343 } 2344 } 2345 } 2346 } 2347 2348 private static final class ResourceName { 2349 final String packageName; 2350 final int iconId; 2351 2352 ResourceName(String _packageName, int _iconId) { 2353 packageName = _packageName; 2354 iconId = _iconId; 2355 } 2356 2357 ResourceName(ApplicationInfo aInfo, int _iconId) { 2358 this(aInfo.packageName, _iconId); 2359 } 2360 2361 ResourceName(ComponentInfo cInfo, int _iconId) { 2362 this(cInfo.applicationInfo.packageName, _iconId); 2363 } 2364 2365 ResourceName(ResolveInfo rInfo, int _iconId) { 2366 this(rInfo.activityInfo.applicationInfo.packageName, _iconId); 2367 } 2368 2369 @Override 2370 public boolean equals(Object o) { 2371 if (this == o) return true; 2372 if (o == null || getClass() != o.getClass()) return false; 2373 2374 ResourceName that = (ResourceName) o; 2375 2376 if (iconId != that.iconId) return false; 2377 return !(packageName != null ? 2378 !packageName.equals(that.packageName) : that.packageName != null); 2379 2380 } 2381 2382 @Override 2383 public int hashCode() { 2384 int result; 2385 result = packageName.hashCode(); 2386 result = 31 * result + iconId; 2387 return result; 2388 } 2389 2390 @Override 2391 public String toString() { 2392 return "{ResourceName " + packageName + " / " + iconId + "}"; 2393 } 2394 } 2395 2396 private CharSequence getCachedString(ResourceName name) { 2397 synchronized (sSync) { 2398 WeakReference<CharSequence> wr = sStringCache.get(name); 2399 if (wr != null) { // we have the activity 2400 CharSequence cs = wr.get(); 2401 if (cs != null) { 2402 return cs; 2403 } 2404 // our entry has been purged 2405 sStringCache.remove(name); 2406 } 2407 } 2408 return null; 2409 } 2410 2411 private void putCachedString(ResourceName name, CharSequence cs) { 2412 synchronized (sSync) { 2413 sStringCache.put(name, new WeakReference<CharSequence>(cs)); 2414 } 2415 } 2416 2417 @Override 2418 public CharSequence getText(String packageName, int resid, 2419 ApplicationInfo appInfo) { 2420 ResourceName name = new ResourceName(packageName, resid); 2421 CharSequence text = getCachedString(name); 2422 if (text != null) { 2423 return text; 2424 } 2425 if (appInfo == null) { 2426 try { 2427 appInfo = getApplicationInfo(packageName, 0); 2428 } catch (NameNotFoundException e) { 2429 return null; 2430 } 2431 } 2432 try { 2433 Resources r = getResourcesForApplication(appInfo); 2434 text = r.getText(resid); 2435 putCachedString(name, text); 2436 return text; 2437 } catch (NameNotFoundException e) { 2438 Log.w("PackageManager", "Failure retrieving resources for" 2439 + appInfo.packageName); 2440 } catch (RuntimeException e) { 2441 // If an exception was thrown, fall through to return 2442 // default icon. 2443 Log.w("PackageManager", "Failure retrieving text 0x" 2444 + Integer.toHexString(resid) + " in package " 2445 + packageName, e); 2446 } 2447 return null; 2448 } 2449 2450 @Override 2451 public XmlResourceParser getXml(String packageName, int resid, 2452 ApplicationInfo appInfo) { 2453 if (appInfo == null) { 2454 try { 2455 appInfo = getApplicationInfo(packageName, 0); 2456 } catch (NameNotFoundException e) { 2457 return null; 2458 } 2459 } 2460 try { 2461 Resources r = getResourcesForApplication(appInfo); 2462 return r.getXml(resid); 2463 } catch (RuntimeException e) { 2464 // If an exception was thrown, fall through to return 2465 // default icon. 2466 Log.w("PackageManager", "Failure retrieving xml 0x" 2467 + Integer.toHexString(resid) + " in package " 2468 + packageName, e); 2469 } catch (NameNotFoundException e) { 2470 Log.w("PackageManager", "Failure retrieving resources for" 2471 + appInfo.packageName); 2472 } 2473 return null; 2474 } 2475 2476 @Override 2477 public CharSequence getApplicationLabel(ApplicationInfo info) { 2478 return info.loadLabel(this); 2479 } 2480 2481 @Override 2482 public void installPackage(Uri packageURI, IPackageInstallObserver observer, int flags, 2483 String installerPackageName) { 2484 try { 2485 mPM.installPackage(packageURI, observer, flags, installerPackageName); 2486 } catch (RemoteException e) { 2487 // Should never happen! 2488 } 2489 } 2490 2491 @Override 2492 public void movePackage(String packageName, IPackageMoveObserver observer, int flags) { 2493 try { 2494 mPM.movePackage(packageName, observer, flags); 2495 } catch (RemoteException e) { 2496 // Should never happen! 2497 } 2498 } 2499 2500 @Override 2501 public String getInstallerPackageName(String packageName) { 2502 try { 2503 return mPM.getInstallerPackageName(packageName); 2504 } catch (RemoteException e) { 2505 // Should never happen! 2506 } 2507 return null; 2508 } 2509 2510 @Override 2511 public void deletePackage(String packageName, IPackageDeleteObserver observer, int flags) { 2512 try { 2513 mPM.deletePackage(packageName, observer, flags); 2514 } catch (RemoteException e) { 2515 // Should never happen! 2516 } 2517 } 2518 @Override 2519 public void clearApplicationUserData(String packageName, 2520 IPackageDataObserver observer) { 2521 try { 2522 mPM.clearApplicationUserData(packageName, observer); 2523 } catch (RemoteException e) { 2524 // Should never happen! 2525 } 2526 } 2527 @Override 2528 public void deleteApplicationCacheFiles(String packageName, 2529 IPackageDataObserver observer) { 2530 try { 2531 mPM.deleteApplicationCacheFiles(packageName, observer); 2532 } catch (RemoteException e) { 2533 // Should never happen! 2534 } 2535 } 2536 @Override 2537 public void freeStorageAndNotify(long idealStorageSize, IPackageDataObserver observer) { 2538 try { 2539 mPM.freeStorageAndNotify(idealStorageSize, observer); 2540 } catch (RemoteException e) { 2541 // Should never happen! 2542 } 2543 } 2544 2545 @Override 2546 public void freeStorage(long freeStorageSize, IntentSender pi) { 2547 try { 2548 mPM.freeStorage(freeStorageSize, pi); 2549 } catch (RemoteException e) { 2550 // Should never happen! 2551 } 2552 } 2553 2554 @Override 2555 public void getPackageSizeInfo(String packageName, 2556 IPackageStatsObserver observer) { 2557 try { 2558 mPM.getPackageSizeInfo(packageName, observer); 2559 } catch (RemoteException e) { 2560 // Should never happen! 2561 } 2562 } 2563 @Override 2564 public void addPackageToPreferred(String packageName) { 2565 try { 2566 mPM.addPackageToPreferred(packageName); 2567 } catch (RemoteException e) { 2568 // Should never happen! 2569 } 2570 } 2571 2572 @Override 2573 public void removePackageFromPreferred(String packageName) { 2574 try { 2575 mPM.removePackageFromPreferred(packageName); 2576 } catch (RemoteException e) { 2577 // Should never happen! 2578 } 2579 } 2580 2581 @Override 2582 public List<PackageInfo> getPreferredPackages(int flags) { 2583 try { 2584 return mPM.getPreferredPackages(flags); 2585 } catch (RemoteException e) { 2586 // Should never happen! 2587 } 2588 return new ArrayList<PackageInfo>(); 2589 } 2590 2591 @Override 2592 public void addPreferredActivity(IntentFilter filter, 2593 int match, ComponentName[] set, ComponentName activity) { 2594 try { 2595 mPM.addPreferredActivity(filter, match, set, activity); 2596 } catch (RemoteException e) { 2597 // Should never happen! 2598 } 2599 } 2600 2601 @Override 2602 public void replacePreferredActivity(IntentFilter filter, 2603 int match, ComponentName[] set, ComponentName activity) { 2604 try { 2605 mPM.replacePreferredActivity(filter, match, set, activity); 2606 } catch (RemoteException e) { 2607 // Should never happen! 2608 } 2609 } 2610 2611 @Override 2612 public void clearPackagePreferredActivities(String packageName) { 2613 try { 2614 mPM.clearPackagePreferredActivities(packageName); 2615 } catch (RemoteException e) { 2616 // Should never happen! 2617 } 2618 } 2619 2620 @Override 2621 public int getPreferredActivities(List<IntentFilter> outFilters, 2622 List<ComponentName> outActivities, String packageName) { 2623 try { 2624 return mPM.getPreferredActivities(outFilters, outActivities, packageName); 2625 } catch (RemoteException e) { 2626 // Should never happen! 2627 } 2628 return 0; 2629 } 2630 2631 @Override 2632 public void setComponentEnabledSetting(ComponentName componentName, 2633 int newState, int flags) { 2634 try { 2635 mPM.setComponentEnabledSetting(componentName, newState, flags); 2636 } catch (RemoteException e) { 2637 // Should never happen! 2638 } 2639 } 2640 2641 @Override 2642 public int getComponentEnabledSetting(ComponentName componentName) { 2643 try { 2644 return mPM.getComponentEnabledSetting(componentName); 2645 } catch (RemoteException e) { 2646 // Should never happen! 2647 } 2648 return PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 2649 } 2650 2651 @Override 2652 public void setApplicationEnabledSetting(String packageName, 2653 int newState, int flags) { 2654 try { 2655 mPM.setApplicationEnabledSetting(packageName, newState, flags); 2656 } catch (RemoteException e) { 2657 // Should never happen! 2658 } 2659 } 2660 2661 @Override 2662 public int getApplicationEnabledSetting(String packageName) { 2663 try { 2664 return mPM.getApplicationEnabledSetting(packageName); 2665 } catch (RemoteException e) { 2666 // Should never happen! 2667 } 2668 return PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 2669 } 2670 2671 @Override 2672 public void setPackageObbPath(String packageName, String path) { 2673 try { 2674 mPM.setPackageObbPath(packageName, path); 2675 } catch (RemoteException e) { 2676 // Should never happen! 2677 } 2678 } 2679 2680 private final ContextImpl mContext; 2681 private final IPackageManager mPM; 2682 2683 private static final Object sSync = new Object(); 2684 private static HashMap<ResourceName, WeakReference<Drawable> > sIconCache 2685 = new HashMap<ResourceName, WeakReference<Drawable> >(); 2686 private static HashMap<ResourceName, WeakReference<CharSequence> > sStringCache 2687 = new HashMap<ResourceName, WeakReference<CharSequence> >(); 2688 } 2689 2690 // ---------------------------------------------------------------------- 2691 // ---------------------------------------------------------------------- 2692 // ---------------------------------------------------------------------- 2693 2694 private static final class SharedPreferencesImpl implements SharedPreferences { 2695 2696 private final File mFile; 2697 private final File mBackupFile; 2698 private final int mMode; 2699 private Map mMap; 2700 private final FileStatus mFileStatus = new FileStatus(); 2701 private long mTimestamp; 2702 2703 private static final Object mContent = new Object(); 2704 private WeakHashMap<OnSharedPreferenceChangeListener, Object> mListeners; 2705 2706 SharedPreferencesImpl( 2707 File file, int mode, Map initialContents) { 2708 mFile = file; 2709 mBackupFile = makeBackupFile(file); 2710 mMode = mode; 2711 mMap = initialContents != null ? initialContents : new HashMap(); 2712 if (FileUtils.getFileStatus(file.getPath(), mFileStatus)) { 2713 mTimestamp = mFileStatus.mtime; 2714 } 2715 mListeners = new WeakHashMap<OnSharedPreferenceChangeListener, Object>(); 2716 } 2717 2718 public boolean hasFileChanged() { 2719 synchronized (this) { 2720 if (!FileUtils.getFileStatus(mFile.getPath(), mFileStatus)) { 2721 return true; 2722 } 2723 return mTimestamp != mFileStatus.mtime; 2724 } 2725 } 2726 2727 public void replace(Map newContents) { 2728 if (newContents != null) { 2729 synchronized (this) { 2730 mMap = newContents; 2731 } 2732 } 2733 } 2734 2735 public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) { 2736 synchronized(this) { 2737 mListeners.put(listener, mContent); 2738 } 2739 } 2740 2741 public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) { 2742 synchronized(this) { 2743 mListeners.remove(listener); 2744 } 2745 } 2746 2747 public Map<String, ?> getAll() { 2748 synchronized(this) { 2749 //noinspection unchecked 2750 return new HashMap(mMap); 2751 } 2752 } 2753 2754 public String getString(String key, String defValue) { 2755 synchronized (this) { 2756 String v = (String)mMap.get(key); 2757 return v != null ? v : defValue; 2758 } 2759 } 2760 2761 public int getInt(String key, int defValue) { 2762 synchronized (this) { 2763 Integer v = (Integer)mMap.get(key); 2764 return v != null ? v : defValue; 2765 } 2766 } 2767 public long getLong(String key, long defValue) { 2768 synchronized (this) { 2769 Long v = (Long) mMap.get(key); 2770 return v != null ? v : defValue; 2771 } 2772 } 2773 public float getFloat(String key, float defValue) { 2774 synchronized (this) { 2775 Float v = (Float)mMap.get(key); 2776 return v != null ? v : defValue; 2777 } 2778 } 2779 public boolean getBoolean(String key, boolean defValue) { 2780 synchronized (this) { 2781 Boolean v = (Boolean)mMap.get(key); 2782 return v != null ? v : defValue; 2783 } 2784 } 2785 2786 public boolean contains(String key) { 2787 synchronized (this) { 2788 return mMap.containsKey(key); 2789 } 2790 } 2791 2792 public final class EditorImpl implements Editor { 2793 private final Map<String, Object> mModified = Maps.newHashMap(); 2794 private boolean mClear = false; 2795 2796 public Editor putString(String key, String value) { 2797 synchronized (this) { 2798 mModified.put(key, value); 2799 return this; 2800 } 2801 } 2802 public Editor putInt(String key, int value) { 2803 synchronized (this) { 2804 mModified.put(key, value); 2805 return this; 2806 } 2807 } 2808 public Editor putLong(String key, long value) { 2809 synchronized (this) { 2810 mModified.put(key, value); 2811 return this; 2812 } 2813 } 2814 public Editor putFloat(String key, float value) { 2815 synchronized (this) { 2816 mModified.put(key, value); 2817 return this; 2818 } 2819 } 2820 public Editor putBoolean(String key, boolean value) { 2821 synchronized (this) { 2822 mModified.put(key, value); 2823 return this; 2824 } 2825 } 2826 2827 public Editor remove(String key) { 2828 synchronized (this) { 2829 mModified.put(key, this); 2830 return this; 2831 } 2832 } 2833 2834 public Editor clear() { 2835 synchronized (this) { 2836 mClear = true; 2837 return this; 2838 } 2839 } 2840 2841 public boolean commit() { 2842 boolean returnValue; 2843 2844 boolean hasListeners; 2845 List<String> keysModified = null; 2846 Set<OnSharedPreferenceChangeListener> listeners = null; 2847 2848 synchronized (SharedPreferencesImpl.this) { 2849 hasListeners = mListeners.size() > 0; 2850 if (hasListeners) { 2851 keysModified = new ArrayList<String>(); 2852 listeners = 2853 new HashSet<OnSharedPreferenceChangeListener>(mListeners.keySet()); 2854 } 2855 2856 synchronized (this) { 2857 if (mClear) { 2858 mMap.clear(); 2859 mClear = false; 2860 } 2861 2862 for (Entry<String, Object> e : mModified.entrySet()) { 2863 String k = e.getKey(); 2864 Object v = e.getValue(); 2865 if (v == this) { 2866 mMap.remove(k); 2867 } else { 2868 mMap.put(k, v); 2869 } 2870 2871 if (hasListeners) { 2872 keysModified.add(k); 2873 } 2874 } 2875 2876 mModified.clear(); 2877 } 2878 2879 returnValue = writeFileLocked(); 2880 } 2881 2882 if (hasListeners) { 2883 for (int i = keysModified.size() - 1; i >= 0; i--) { 2884 final String key = keysModified.get(i); 2885 for (OnSharedPreferenceChangeListener listener : listeners) { 2886 if (listener != null) { 2887 listener.onSharedPreferenceChanged(SharedPreferencesImpl.this, key); 2888 } 2889 } 2890 } 2891 } 2892 2893 return returnValue; 2894 } 2895 } 2896 2897 public Editor edit() { 2898 return new EditorImpl(); 2899 } 2900 2901 private FileOutputStream createFileOutputStream(File file) { 2902 FileOutputStream str = null; 2903 try { 2904 str = new FileOutputStream(file); 2905 } catch (FileNotFoundException e) { 2906 File parent = file.getParentFile(); 2907 if (!parent.mkdir()) { 2908 Log.e(TAG, "Couldn't create directory for SharedPreferences file " + file); 2909 return null; 2910 } 2911 FileUtils.setPermissions( 2912 parent.getPath(), 2913 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, 2914 -1, -1); 2915 try { 2916 str = new FileOutputStream(file); 2917 } catch (FileNotFoundException e2) { 2918 Log.e(TAG, "Couldn't create SharedPreferences file " + file, e2); 2919 } 2920 } 2921 return str; 2922 } 2923 2924 private boolean writeFileLocked() { 2925 // Rename the current file so it may be used as a backup during the next read 2926 if (mFile.exists()) { 2927 if (!mBackupFile.exists()) { 2928 if (!mFile.renameTo(mBackupFile)) { 2929 Log.e(TAG, "Couldn't rename file " + mFile 2930 + " to backup file " + mBackupFile); 2931 return false; 2932 } 2933 } else { 2934 mFile.delete(); 2935 } 2936 } 2937 2938 // Attempt to write the file, delete the backup and return true as atomically as 2939 // possible. If any exception occurs, delete the new file; next time we will restore 2940 // from the backup. 2941 try { 2942 FileOutputStream str = createFileOutputStream(mFile); 2943 if (str == null) { 2944 return false; 2945 } 2946 XmlUtils.writeMapXml(mMap, str); 2947 str.close(); 2948 setFilePermissionsFromMode(mFile.getPath(), mMode, 0); 2949 if (FileUtils.getFileStatus(mFile.getPath(), mFileStatus)) { 2950 mTimestamp = mFileStatus.mtime; 2951 } 2952 2953 // Writing was successful, delete the backup file if there is one. 2954 mBackupFile.delete(); 2955 return true; 2956 } catch (XmlPullParserException e) { 2957 Log.w(TAG, "writeFileLocked: Got exception:", e); 2958 } catch (IOException e) { 2959 Log.w(TAG, "writeFileLocked: Got exception:", e); 2960 } 2961 // Clean up an unsuccessfully written file 2962 if (mFile.exists()) { 2963 if (!mFile.delete()) { 2964 Log.e(TAG, "Couldn't clean up partially-written file " + mFile); 2965 } 2966 } 2967 return false; 2968 } 2969 } 2970} 2971