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