ContextImpl.java revision 247fe74c934cb3fba85aae7e051a8044f460fb11
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; 21 22import org.xmlpull.v1.XmlPullParserException; 23 24import android.content.BroadcastReceiver; 25import android.content.ComponentName; 26import android.content.ContentResolver; 27import android.content.Context; 28import android.content.ContextWrapper; 29import android.content.IContentProvider; 30import android.content.Intent; 31import android.content.IntentFilter; 32import android.content.IIntentReceiver; 33import android.content.IntentSender; 34import android.content.ReceiverCallNotAllowedException; 35import android.content.ServiceConnection; 36import android.content.SharedPreferences; 37import android.content.pm.ApplicationInfo; 38import android.content.pm.ComponentInfo; 39import android.content.pm.FeatureInfo; 40import android.content.pm.IPackageDataObserver; 41import android.content.pm.IPackageDeleteObserver; 42import android.content.pm.IPackageInstallObserver; 43import android.content.pm.IPackageMoveObserver; 44import android.content.pm.IPackageManager; 45import android.content.pm.IPackageStatsObserver; 46import android.content.pm.PackageManager; 47import android.content.res.AssetManager; 48import android.content.res.Resources; 49import android.database.DatabaseErrorHandler; 50import android.database.sqlite.SQLiteDatabase; 51import android.database.sqlite.SQLiteDatabase.CursorFactory; 52import android.graphics.Bitmap; 53import android.graphics.drawable.Drawable; 54import android.hardware.SensorManager; 55import android.location.CountryDetector; 56import android.location.ICountryDetector; 57import android.location.ILocationManager; 58import android.location.LocationManager; 59import android.media.AudioManager; 60import android.net.ConnectivityManager; 61import android.net.IConnectivityManager; 62import android.net.ThrottleManager; 63import android.net.IThrottleManager; 64import android.net.Uri; 65import android.net.wifi.IWifiManager; 66import android.net.wifi.WifiManager; 67import android.nfc.NfcManager; 68import android.os.Binder; 69import android.os.Build; 70import android.os.Bundle; 71import android.os.DropBoxManager; 72import android.os.Environment; 73import android.os.FileUtils; 74import android.os.Handler; 75import android.os.IBinder; 76import android.os.IPowerManager; 77import android.os.Looper; 78import android.os.PowerManager; 79import android.os.Process; 80import android.os.RemoteException; 81import android.os.ServiceManager; 82import android.os.Vibrator; 83import android.os.FileUtils.FileStatus; 84import android.os.storage.StorageManager; 85import android.telephony.TelephonyManager; 86import android.content.ClipboardManager; 87import android.util.AndroidRuntimeException; 88import android.util.Log; 89import android.view.ContextThemeWrapper; 90import android.view.LayoutInflater; 91import android.view.WindowManagerImpl; 92import android.view.accessibility.AccessibilityManager; 93import android.view.inputmethod.InputMethodManager; 94import android.accounts.AccountManager; 95import android.accounts.IAccountManager; 96import android.app.admin.DevicePolicyManager; 97import com.android.internal.os.IDropBoxManagerService; 98 99import java.io.File; 100import java.io.FileInputStream; 101import java.io.FileNotFoundException; 102import java.io.FileOutputStream; 103import java.io.IOException; 104import java.io.InputStream; 105import java.util.ArrayList; 106import java.util.HashMap; 107import java.util.List; 108import java.util.Map; 109import java.util.Set; 110 111class ReceiverRestrictedContext extends ContextWrapper { 112 ReceiverRestrictedContext(Context base) { 113 super(base); 114 } 115 116 @Override 117 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) { 118 return registerReceiver(receiver, filter, null, null); 119 } 120 121 @Override 122 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, 123 String broadcastPermission, Handler scheduler) { 124 throw new ReceiverCallNotAllowedException( 125 "IntentReceiver components are not allowed to register to receive intents"); 126 //ex.fillInStackTrace(); 127 //Log.e("IntentReceiver", ex.getMessage(), ex); 128 //return mContext.registerReceiver(receiver, filter, broadcastPermission, 129 // scheduler); 130 } 131 132 @Override 133 public boolean bindService(Intent service, ServiceConnection conn, int flags) { 134 throw new ReceiverCallNotAllowedException( 135 "IntentReceiver components are not allowed to bind to services"); 136 //ex.fillInStackTrace(); 137 //Log.e("IntentReceiver", ex.getMessage(), ex); 138 //return mContext.bindService(service, interfaceName, conn, flags); 139 } 140} 141 142/** 143 * Common implementation of Context API, which provides the base 144 * context object for Activity and other application components. 145 */ 146class ContextImpl extends Context { 147 private final static String TAG = "ApplicationContext"; 148 private final static boolean DEBUG = false; 149 150 private static final HashMap<String, SharedPreferencesImpl> sSharedPrefs = 151 new HashMap<String, SharedPreferencesImpl>(); 152 153 /*package*/ LoadedApk mPackageInfo; 154 private Resources mResources; 155 /*package*/ ActivityThread mMainThread; 156 private Context mOuterContext; 157 private IBinder mActivityToken = null; 158 private ApplicationContentResolver mContentResolver; 159 private int mThemeResource = 0; 160 private Resources.Theme mTheme = null; 161 private PackageManager mPackageManager; 162 private Context mReceiverRestrictedContext = null; 163 private boolean mRestricted; 164 165 private final Object mSync = new Object(); 166 167 private File mDatabasesDir; 168 private File mPreferencesDir; 169 private File mFilesDir; 170 private File mCacheDir; 171 private File mExternalFilesDir; 172 private File mExternalCacheDir; 173 174 private static final String[] EMPTY_FILE_LIST = {}; 175 176 /** 177 * Override this class when the system service constructor needs a 178 * ContextImpl. Else, use StaticServiceFetcher below. 179 */ 180 /*package*/ static class ServiceFetcher { 181 int mContextCacheIndex = -1; 182 183 /** 184 * Main entrypoint; only override if you don't need caching. 185 */ 186 public Object getService(ContextImpl ctx) { 187 ArrayList<Object> cache = ctx.mServiceCache; 188 Object service; 189 synchronized (cache) { 190 if (cache.size() == 0) { 191 // Initialize the cache vector on first access. 192 // At this point sNextPerContextServiceCacheIndex 193 // is the number of potential services that are 194 // cached per-Context. 195 for (int i = 0; i < sNextPerContextServiceCacheIndex; i++) { 196 cache.add(null); 197 } 198 } else { 199 service = cache.get(mContextCacheIndex); 200 if (service != null) { 201 return service; 202 } 203 } 204 service = createService(ctx); 205 cache.set(mContextCacheIndex, service); 206 return service; 207 } 208 } 209 210 /** 211 * Override this to create a new per-Context instance of the 212 * service. getService() will handle locking and caching. 213 */ 214 public Object createService(ContextImpl ctx) { 215 throw new RuntimeException("Not implemented"); 216 } 217 } 218 219 /** 220 * Override this class for services to be cached process-wide. 221 */ 222 abstract static class StaticServiceFetcher extends ServiceFetcher { 223 private Object mCachedInstance; 224 225 @Override 226 public final Object getService(ContextImpl unused) { 227 synchronized (StaticServiceFetcher.this) { 228 Object service = mCachedInstance; 229 if (service != null) { 230 return service; 231 } 232 return mCachedInstance = createStaticService(); 233 } 234 } 235 236 public abstract Object createStaticService(); 237 } 238 239 private static final HashMap<String, ServiceFetcher> SYSTEM_SERVICE_MAP = 240 new HashMap<String, ServiceFetcher>(); 241 242 private static int sNextPerContextServiceCacheIndex = 0; 243 private static void registerService(String serviceName, ServiceFetcher fetcher) { 244 if (!(fetcher instanceof StaticServiceFetcher)) { 245 fetcher.mContextCacheIndex = sNextPerContextServiceCacheIndex++; 246 } 247 SYSTEM_SERVICE_MAP.put(serviceName, fetcher); 248 } 249 250 // This one's defined separately and given a variable name so it 251 // can be re-used by getWallpaperManager(), avoiding a HashMap 252 // lookup. 253 private static ServiceFetcher WALLPAPER_FETCHER = new ServiceFetcher() { 254 public Object createService(ContextImpl ctx) { 255 return new WallpaperManager(ctx.getOuterContext(), 256 ctx.mMainThread.getHandler()); 257 }}; 258 259 static { 260 registerService(ACCESSIBILITY_SERVICE, new ServiceFetcher() { 261 public Object getService(ContextImpl ctx) { 262 return AccessibilityManager.getInstance(ctx); 263 }}); 264 265 registerService(ACCOUNT_SERVICE, new ServiceFetcher() { 266 public Object createService(ContextImpl ctx) { 267 IBinder b = ServiceManager.getService(ACCOUNT_SERVICE); 268 IAccountManager service = IAccountManager.Stub.asInterface(b); 269 return new AccountManager(ctx, service); 270 }}); 271 272 registerService(ACTIVITY_SERVICE, new ServiceFetcher() { 273 public Object createService(ContextImpl ctx) { 274 return new ActivityManager(ctx.getOuterContext(), ctx.mMainThread.getHandler()); 275 }}); 276 277 registerService(ALARM_SERVICE, new StaticServiceFetcher() { 278 public Object createStaticService() { 279 IBinder b = ServiceManager.getService(ALARM_SERVICE); 280 IAlarmManager service = IAlarmManager.Stub.asInterface(b); 281 return new AlarmManager(service); 282 }}); 283 284 registerService(AUDIO_SERVICE, new ServiceFetcher() { 285 public Object createService(ContextImpl ctx) { 286 return new AudioManager(ctx); 287 }}); 288 289 registerService(CLIPBOARD_SERVICE, new ServiceFetcher() { 290 public Object createService(ContextImpl ctx) { 291 return new ClipboardManager(ctx.getOuterContext(), 292 ctx.mMainThread.getHandler()); 293 }}); 294 295 registerService(CONNECTIVITY_SERVICE, new StaticServiceFetcher() { 296 public Object createStaticService() { 297 IBinder b = ServiceManager.getService(CONNECTIVITY_SERVICE); 298 return new ConnectivityManager(IConnectivityManager.Stub.asInterface(b)); 299 }}); 300 301 registerService(COUNTRY_DETECTOR, new StaticServiceFetcher() { 302 public Object createStaticService() { 303 IBinder b = ServiceManager.getService(COUNTRY_DETECTOR); 304 return new CountryDetector(ICountryDetector.Stub.asInterface(b)); 305 }}); 306 307 registerService(DEVICE_POLICY_SERVICE, new ServiceFetcher() { 308 public Object createService(ContextImpl ctx) { 309 return DevicePolicyManager.create(ctx, ctx.mMainThread.getHandler()); 310 }}); 311 312 registerService(DOWNLOAD_SERVICE, new ServiceFetcher() { 313 public Object createService(ContextImpl ctx) { 314 return new DownloadManager(ctx.getContentResolver(), ctx.getPackageName()); 315 }}); 316 317 registerService(NFC_SERVICE, new ServiceFetcher() { 318 public Object createService(ContextImpl ctx) { 319 return new NfcManager(ctx); 320 }}); 321 322 registerService(DROPBOX_SERVICE, new StaticServiceFetcher() { 323 public Object createStaticService() { 324 return createDropBoxManager(); 325 }}); 326 327 registerService(INPUT_METHOD_SERVICE, new ServiceFetcher() { 328 public Object createService(ContextImpl ctx) { 329 return InputMethodManager.getInstance(ctx); 330 }}); 331 332 registerService(KEYGUARD_SERVICE, new ServiceFetcher() { 333 public Object getService(ContextImpl ctx) { 334 // TODO: why isn't this caching it? It wasn't 335 // before, so I'm preserving the old behavior and 336 // using getService(), instead of createService() 337 // which would do the caching. 338 return new KeyguardManager(); 339 }}); 340 341 registerService(LAYOUT_INFLATER_SERVICE, new ServiceFetcher() { 342 public Object createService(ContextImpl ctx) { 343 return PolicyManager.makeNewLayoutInflater(ctx.getOuterContext()); 344 }}); 345 346 registerService(LOCATION_SERVICE, new StaticServiceFetcher() { 347 public Object createStaticService() { 348 IBinder b = ServiceManager.getService(LOCATION_SERVICE); 349 return new LocationManager(ILocationManager.Stub.asInterface(b)); 350 }}); 351 352 registerService(NOTIFICATION_SERVICE, new ServiceFetcher() { 353 public Object createService(ContextImpl ctx) { 354 final Context outerContext = ctx.getOuterContext(); 355 return new NotificationManager( 356 new ContextThemeWrapper(outerContext, 357 outerContext.getApplicationInfo().targetSdkVersion >= 358 Build.VERSION_CODES.HONEYCOMB 359 ? com.android.internal.R.style.Theme_Holo_Dialog 360 : com.android.internal.R.style.Theme_Dialog), 361 ctx.mMainThread.getHandler()); 362 }}); 363 364 // Note: this was previously cached in a static variable, but 365 // constructed using mMainThread.getHandler(), so converting 366 // it to be a regular Context-cached service... 367 registerService(POWER_SERVICE, new ServiceFetcher() { 368 public Object createService(ContextImpl ctx) { 369 IBinder b = ServiceManager.getService(POWER_SERVICE); 370 IPowerManager service = IPowerManager.Stub.asInterface(b); 371 return new PowerManager(service, ctx.mMainThread.getHandler()); 372 }}); 373 374 registerService(SEARCH_SERVICE, new ServiceFetcher() { 375 public Object createService(ContextImpl ctx) { 376 return new SearchManager(ctx.getOuterContext(), 377 ctx.mMainThread.getHandler()); 378 }}); 379 380 registerService(SENSOR_SERVICE, new ServiceFetcher() { 381 public Object createService(ContextImpl ctx) { 382 return new SensorManager(ctx.mMainThread.getHandler().getLooper()); 383 }}); 384 385 registerService(STATUS_BAR_SERVICE, new ServiceFetcher() { 386 public Object createService(ContextImpl ctx) { 387 return new StatusBarManager(ctx.getOuterContext()); 388 }}); 389 390 registerService(STORAGE_SERVICE, new ServiceFetcher() { 391 public Object createService(ContextImpl ctx) { 392 try { 393 return new StorageManager(ctx.mMainThread.getHandler().getLooper()); 394 } catch (RemoteException rex) { 395 Log.e(TAG, "Failed to create StorageManager", rex); 396 return null; 397 } 398 }}); 399 400 registerService(TELEPHONY_SERVICE, new ServiceFetcher() { 401 public Object createService(ContextImpl ctx) { 402 return new TelephonyManager(ctx.getOuterContext()); 403 }}); 404 405 registerService(THROTTLE_SERVICE, new StaticServiceFetcher() { 406 public Object createStaticService() { 407 IBinder b = ServiceManager.getService(THROTTLE_SERVICE); 408 return new ThrottleManager(IThrottleManager.Stub.asInterface(b)); 409 }}); 410 411 registerService(UI_MODE_SERVICE, new ServiceFetcher() { 412 public Object createService(ContextImpl ctx) { 413 return new UiModeManager(); 414 }}); 415 416 registerService(VIBRATOR_SERVICE, new ServiceFetcher() { 417 public Object createService(ContextImpl ctx) { 418 return new Vibrator(); 419 }}); 420 421 registerService(WALLPAPER_SERVICE, WALLPAPER_FETCHER); 422 423 registerService(WIFI_SERVICE, new ServiceFetcher() { 424 public Object createService(ContextImpl ctx) { 425 IBinder b = ServiceManager.getService(WIFI_SERVICE); 426 IWifiManager service = IWifiManager.Stub.asInterface(b); 427 return new WifiManager(service, ctx.mMainThread.getHandler()); 428 }}); 429 430 registerService(WINDOW_SERVICE, new ServiceFetcher() { 431 public Object getService(ContextImpl ctx) { 432 return WindowManagerImpl.getDefault(); 433 }}); 434 } 435 436 // The system service cache for the system services that are 437 // cached per-ContextImpl. Package-scoped to avoid accessor 438 // methods. 439 final ArrayList<Object> mServiceCache = new ArrayList<Object>(); 440 441 @Override 442 public AssetManager getAssets() { 443 return mResources.getAssets(); 444 } 445 446 @Override 447 public Resources getResources() { 448 return mResources; 449 } 450 451 @Override 452 public PackageManager getPackageManager() { 453 if (mPackageManager != null) { 454 return mPackageManager; 455 } 456 457 IPackageManager pm = ActivityThread.getPackageManager(); 458 if (pm != null) { 459 // Doesn't matter if we make more than one instance. 460 return (mPackageManager = new ApplicationPackageManager(this, pm)); 461 } 462 463 return null; 464 } 465 466 @Override 467 public ContentResolver getContentResolver() { 468 return mContentResolver; 469 } 470 471 @Override 472 public Looper getMainLooper() { 473 return mMainThread.getLooper(); 474 } 475 476 @Override 477 public Context getApplicationContext() { 478 return (mPackageInfo != null) ? 479 mPackageInfo.getApplication() : mMainThread.getApplication(); 480 } 481 482 @Override 483 public void setTheme(int resid) { 484 mThemeResource = resid; 485 } 486 487 @Override 488 public int getThemeResId() { 489 return mThemeResource; 490 } 491 492 @Override 493 public Resources.Theme getTheme() { 494 if (mTheme == null) { 495 if (mThemeResource == 0) { 496 final Context outerContext = getOuterContext(); 497 mThemeResource = (outerContext.getApplicationInfo().targetSdkVersion 498 >= Build.VERSION_CODES.HONEYCOMB) 499 ? com.android.internal.R.style.Theme_Holo 500 : com.android.internal.R.style.Theme; 501 } 502 mTheme = mResources.newTheme(); 503 mTheme.applyStyle(mThemeResource, true); 504 } 505 return mTheme; 506 } 507 508 @Override 509 public ClassLoader getClassLoader() { 510 return mPackageInfo != null ? 511 mPackageInfo.getClassLoader() : ClassLoader.getSystemClassLoader(); 512 } 513 514 @Override 515 public String getPackageName() { 516 if (mPackageInfo != null) { 517 return mPackageInfo.getPackageName(); 518 } 519 throw new RuntimeException("Not supported in system context"); 520 } 521 522 @Override 523 public ApplicationInfo getApplicationInfo() { 524 if (mPackageInfo != null) { 525 return mPackageInfo.getApplicationInfo(); 526 } 527 throw new RuntimeException("Not supported in system context"); 528 } 529 530 @Override 531 public String getPackageResourcePath() { 532 if (mPackageInfo != null) { 533 return mPackageInfo.getResDir(); 534 } 535 throw new RuntimeException("Not supported in system context"); 536 } 537 538 @Override 539 public String getPackageCodePath() { 540 if (mPackageInfo != null) { 541 return mPackageInfo.getAppDir(); 542 } 543 throw new RuntimeException("Not supported in system context"); 544 } 545 546 public File getSharedPrefsFile(String name) { 547 return makeFilename(getPreferencesDir(), name + ".xml"); 548 } 549 550 @Override 551 public SharedPreferences getSharedPreferences(String name, int mode) { 552 SharedPreferencesImpl sp; 553 synchronized (sSharedPrefs) { 554 sp = sSharedPrefs.get(name); 555 if (sp == null) { 556 File prefsFile = getSharedPrefsFile(name); 557 sp = new SharedPreferencesImpl(prefsFile, mode); 558 sSharedPrefs.put(name, sp); 559 return sp; 560 } 561 } 562 if ((mode & Context.MODE_MULTI_PROCESS) != 0 || 563 getApplicationInfo().targetSdkVersion < android.os.Build.VERSION_CODES.HONEYCOMB) { 564 // If somebody else (some other process) changed the prefs 565 // file behind our back, we reload it. This has been the 566 // historical (if undocumented) behavior. 567 sp.startReloadIfChangedUnexpectedly(); 568 } 569 return sp; 570 } 571 572 private File getPreferencesDir() { 573 synchronized (mSync) { 574 if (mPreferencesDir == null) { 575 mPreferencesDir = new File(getDataDirFile(), "shared_prefs"); 576 } 577 return mPreferencesDir; 578 } 579 } 580 581 @Override 582 public FileInputStream openFileInput(String name) 583 throws FileNotFoundException { 584 File f = makeFilename(getFilesDir(), name); 585 return new FileInputStream(f); 586 } 587 588 @Override 589 public FileOutputStream openFileOutput(String name, int mode) 590 throws FileNotFoundException { 591 final boolean append = (mode&MODE_APPEND) != 0; 592 File f = makeFilename(getFilesDir(), name); 593 try { 594 FileOutputStream fos = new FileOutputStream(f, append); 595 setFilePermissionsFromMode(f.getPath(), mode, 0); 596 return fos; 597 } catch (FileNotFoundException e) { 598 } 599 600 File parent = f.getParentFile(); 601 parent.mkdir(); 602 FileUtils.setPermissions( 603 parent.getPath(), 604 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, 605 -1, -1); 606 FileOutputStream fos = new FileOutputStream(f, append); 607 setFilePermissionsFromMode(f.getPath(), mode, 0); 608 return fos; 609 } 610 611 @Override 612 public boolean deleteFile(String name) { 613 File f = makeFilename(getFilesDir(), name); 614 return f.delete(); 615 } 616 617 @Override 618 public File getFilesDir() { 619 synchronized (mSync) { 620 if (mFilesDir == null) { 621 mFilesDir = new File(getDataDirFile(), "files"); 622 } 623 if (!mFilesDir.exists()) { 624 if(!mFilesDir.mkdirs()) { 625 Log.w(TAG, "Unable to create files directory " + mFilesDir.getPath()); 626 return null; 627 } 628 FileUtils.setPermissions( 629 mFilesDir.getPath(), 630 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, 631 -1, -1); 632 } 633 return mFilesDir; 634 } 635 } 636 637 @Override 638 public File getExternalFilesDir(String type) { 639 synchronized (mSync) { 640 if (mExternalFilesDir == null) { 641 mExternalFilesDir = Environment.getExternalStorageAppFilesDirectory( 642 getPackageName()); 643 } 644 if (!mExternalFilesDir.exists()) { 645 try { 646 (new File(Environment.getExternalStorageAndroidDataDir(), 647 ".nomedia")).createNewFile(); 648 } catch (IOException e) { 649 } 650 if (!mExternalFilesDir.mkdirs()) { 651 Log.w(TAG, "Unable to create external files directory"); 652 return null; 653 } 654 } 655 if (type == null) { 656 return mExternalFilesDir; 657 } 658 File dir = new File(mExternalFilesDir, type); 659 if (!dir.exists()) { 660 if (!dir.mkdirs()) { 661 Log.w(TAG, "Unable to create external media directory " + dir); 662 return null; 663 } 664 } 665 return dir; 666 } 667 } 668 669 @Override 670 public File getCacheDir() { 671 synchronized (mSync) { 672 if (mCacheDir == null) { 673 mCacheDir = new File(getDataDirFile(), "cache"); 674 } 675 if (!mCacheDir.exists()) { 676 if(!mCacheDir.mkdirs()) { 677 Log.w(TAG, "Unable to create cache directory"); 678 return null; 679 } 680 FileUtils.setPermissions( 681 mCacheDir.getPath(), 682 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, 683 -1, -1); 684 } 685 } 686 return mCacheDir; 687 } 688 689 @Override 690 public File getExternalCacheDir() { 691 synchronized (mSync) { 692 if (mExternalCacheDir == null) { 693 mExternalCacheDir = Environment.getExternalStorageAppCacheDirectory( 694 getPackageName()); 695 } 696 if (!mExternalCacheDir.exists()) { 697 try { 698 (new File(Environment.getExternalStorageAndroidDataDir(), 699 ".nomedia")).createNewFile(); 700 } catch (IOException e) { 701 } 702 if (!mExternalCacheDir.mkdirs()) { 703 Log.w(TAG, "Unable to create external cache directory"); 704 return null; 705 } 706 } 707 return mExternalCacheDir; 708 } 709 } 710 711 @Override 712 public File getFileStreamPath(String name) { 713 return makeFilename(getFilesDir(), name); 714 } 715 716 @Override 717 public String[] fileList() { 718 final String[] list = getFilesDir().list(); 719 return (list != null) ? list : EMPTY_FILE_LIST; 720 } 721 722 @Override 723 public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory) { 724 File f = validateFilePath(name, true); 725 SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(f, factory); 726 setFilePermissionsFromMode(f.getPath(), mode, 0); 727 return db; 728 } 729 730 @Override 731 public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory, 732 DatabaseErrorHandler errorHandler) { 733 File f = validateFilePath(name, true); 734 SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(f.getPath(), factory, errorHandler); 735 setFilePermissionsFromMode(f.getPath(), mode, 0); 736 return db; 737 } 738 739 @Override 740 public boolean deleteDatabase(String name) { 741 try { 742 File f = validateFilePath(name, false); 743 return f.delete(); 744 } catch (Exception e) { 745 } 746 return false; 747 } 748 749 @Override 750 public File getDatabasePath(String name) { 751 return validateFilePath(name, false); 752 } 753 754 @Override 755 public String[] databaseList() { 756 final String[] list = getDatabasesDir().list(); 757 return (list != null) ? list : EMPTY_FILE_LIST; 758 } 759 760 761 private File getDatabasesDir() { 762 synchronized (mSync) { 763 if (mDatabasesDir == null) { 764 mDatabasesDir = new File(getDataDirFile(), "databases"); 765 } 766 if (mDatabasesDir.getPath().equals("databases")) { 767 mDatabasesDir = new File("/data/system"); 768 } 769 return mDatabasesDir; 770 } 771 } 772 773 @Override 774 public Drawable getWallpaper() { 775 return getWallpaperManager().getDrawable(); 776 } 777 778 @Override 779 public Drawable peekWallpaper() { 780 return getWallpaperManager().peekDrawable(); 781 } 782 783 @Override 784 public int getWallpaperDesiredMinimumWidth() { 785 return getWallpaperManager().getDesiredMinimumWidth(); 786 } 787 788 @Override 789 public int getWallpaperDesiredMinimumHeight() { 790 return getWallpaperManager().getDesiredMinimumHeight(); 791 } 792 793 @Override 794 public void setWallpaper(Bitmap bitmap) throws IOException { 795 getWallpaperManager().setBitmap(bitmap); 796 } 797 798 @Override 799 public void setWallpaper(InputStream data) throws IOException { 800 getWallpaperManager().setStream(data); 801 } 802 803 @Override 804 public void clearWallpaper() throws IOException { 805 getWallpaperManager().clear(); 806 } 807 808 @Override 809 public void startActivity(Intent intent) { 810 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) { 811 throw new AndroidRuntimeException( 812 "Calling startActivity() from outside of an Activity " 813 + " context requires the FLAG_ACTIVITY_NEW_TASK flag." 814 + " Is this really what you want?"); 815 } 816 mMainThread.getInstrumentation().execStartActivity( 817 getOuterContext(), mMainThread.getApplicationThread(), null, 818 (Activity)null, intent, -1); 819 } 820 821 @Override 822 public void startActivities(Intent[] intents) { 823 if ((intents[0].getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) { 824 throw new AndroidRuntimeException( 825 "Calling startActivities() from outside of an Activity " 826 + " context requires the FLAG_ACTIVITY_NEW_TASK flag on first Intent." 827 + " Is this really what you want?"); 828 } 829 mMainThread.getInstrumentation().execStartActivities( 830 getOuterContext(), mMainThread.getApplicationThread(), null, 831 (Activity)null, intents); 832 } 833 834 @Override 835 public void startIntentSender(IntentSender intent, 836 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) 837 throws IntentSender.SendIntentException { 838 try { 839 String resolvedType = null; 840 if (fillInIntent != null) { 841 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver()); 842 } 843 int result = ActivityManagerNative.getDefault() 844 .startActivityIntentSender(mMainThread.getApplicationThread(), intent, 845 fillInIntent, resolvedType, null, null, 846 0, flagsMask, flagsValues); 847 if (result == IActivityManager.START_CANCELED) { 848 throw new IntentSender.SendIntentException(); 849 } 850 Instrumentation.checkStartActivityResult(result, null); 851 } catch (RemoteException e) { 852 } 853 } 854 855 @Override 856 public void sendBroadcast(Intent intent) { 857 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 858 try { 859 ActivityManagerNative.getDefault().broadcastIntent( 860 mMainThread.getApplicationThread(), intent, resolvedType, null, 861 Activity.RESULT_OK, null, null, null, false, false); 862 } catch (RemoteException e) { 863 } 864 } 865 866 @Override 867 public void sendBroadcast(Intent intent, String receiverPermission) { 868 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 869 try { 870 ActivityManagerNative.getDefault().broadcastIntent( 871 mMainThread.getApplicationThread(), intent, resolvedType, null, 872 Activity.RESULT_OK, null, null, receiverPermission, false, false); 873 } catch (RemoteException e) { 874 } 875 } 876 877 @Override 878 public void sendOrderedBroadcast(Intent intent, 879 String receiverPermission) { 880 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 881 try { 882 ActivityManagerNative.getDefault().broadcastIntent( 883 mMainThread.getApplicationThread(), intent, resolvedType, null, 884 Activity.RESULT_OK, null, null, receiverPermission, true, false); 885 } catch (RemoteException e) { 886 } 887 } 888 889 @Override 890 public void sendOrderedBroadcast(Intent intent, 891 String receiverPermission, BroadcastReceiver resultReceiver, 892 Handler scheduler, int initialCode, String initialData, 893 Bundle initialExtras) { 894 IIntentReceiver rd = null; 895 if (resultReceiver != null) { 896 if (mPackageInfo != null) { 897 if (scheduler == null) { 898 scheduler = mMainThread.getHandler(); 899 } 900 rd = mPackageInfo.getReceiverDispatcher( 901 resultReceiver, getOuterContext(), scheduler, 902 mMainThread.getInstrumentation(), false); 903 } else { 904 if (scheduler == null) { 905 scheduler = mMainThread.getHandler(); 906 } 907 rd = new LoadedApk.ReceiverDispatcher( 908 resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver(); 909 } 910 } 911 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 912 try { 913 ActivityManagerNative.getDefault().broadcastIntent( 914 mMainThread.getApplicationThread(), intent, resolvedType, rd, 915 initialCode, initialData, initialExtras, receiverPermission, 916 true, false); 917 } catch (RemoteException e) { 918 } 919 } 920 921 @Override 922 public void sendStickyBroadcast(Intent intent) { 923 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 924 try { 925 ActivityManagerNative.getDefault().broadcastIntent( 926 mMainThread.getApplicationThread(), intent, resolvedType, null, 927 Activity.RESULT_OK, null, null, null, false, true); 928 } catch (RemoteException e) { 929 } 930 } 931 932 @Override 933 public void sendStickyOrderedBroadcast(Intent intent, 934 BroadcastReceiver resultReceiver, 935 Handler scheduler, int initialCode, String initialData, 936 Bundle initialExtras) { 937 IIntentReceiver rd = null; 938 if (resultReceiver != null) { 939 if (mPackageInfo != null) { 940 if (scheduler == null) { 941 scheduler = mMainThread.getHandler(); 942 } 943 rd = mPackageInfo.getReceiverDispatcher( 944 resultReceiver, getOuterContext(), scheduler, 945 mMainThread.getInstrumentation(), false); 946 } else { 947 if (scheduler == null) { 948 scheduler = mMainThread.getHandler(); 949 } 950 rd = new LoadedApk.ReceiverDispatcher( 951 resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver(); 952 } 953 } 954 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 955 try { 956 ActivityManagerNative.getDefault().broadcastIntent( 957 mMainThread.getApplicationThread(), intent, resolvedType, rd, 958 initialCode, initialData, initialExtras, null, 959 true, true); 960 } catch (RemoteException e) { 961 } 962 } 963 964 @Override 965 public void removeStickyBroadcast(Intent intent) { 966 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 967 if (resolvedType != null) { 968 intent = new Intent(intent); 969 intent.setDataAndType(intent.getData(), resolvedType); 970 } 971 try { 972 ActivityManagerNative.getDefault().unbroadcastIntent( 973 mMainThread.getApplicationThread(), intent); 974 } catch (RemoteException e) { 975 } 976 } 977 978 @Override 979 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) { 980 return registerReceiver(receiver, filter, null, null); 981 } 982 983 @Override 984 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, 985 String broadcastPermission, Handler scheduler) { 986 return registerReceiverInternal(receiver, filter, broadcastPermission, 987 scheduler, getOuterContext()); 988 } 989 990 private Intent registerReceiverInternal(BroadcastReceiver receiver, 991 IntentFilter filter, String broadcastPermission, 992 Handler scheduler, Context context) { 993 IIntentReceiver rd = null; 994 if (receiver != null) { 995 if (mPackageInfo != null && context != null) { 996 if (scheduler == null) { 997 scheduler = mMainThread.getHandler(); 998 } 999 rd = mPackageInfo.getReceiverDispatcher( 1000 receiver, context, scheduler, 1001 mMainThread.getInstrumentation(), true); 1002 } else { 1003 if (scheduler == null) { 1004 scheduler = mMainThread.getHandler(); 1005 } 1006 rd = new LoadedApk.ReceiverDispatcher( 1007 receiver, context, scheduler, null, true).getIIntentReceiver(); 1008 } 1009 } 1010 try { 1011 return ActivityManagerNative.getDefault().registerReceiver( 1012 mMainThread.getApplicationThread(), 1013 rd, filter, broadcastPermission); 1014 } catch (RemoteException e) { 1015 return null; 1016 } 1017 } 1018 1019 @Override 1020 public void unregisterReceiver(BroadcastReceiver receiver) { 1021 if (mPackageInfo != null) { 1022 IIntentReceiver rd = mPackageInfo.forgetReceiverDispatcher( 1023 getOuterContext(), receiver); 1024 try { 1025 ActivityManagerNative.getDefault().unregisterReceiver(rd); 1026 } catch (RemoteException e) { 1027 } 1028 } else { 1029 throw new RuntimeException("Not supported in system context"); 1030 } 1031 } 1032 1033 @Override 1034 public ComponentName startService(Intent service) { 1035 try { 1036 ComponentName cn = ActivityManagerNative.getDefault().startService( 1037 mMainThread.getApplicationThread(), service, 1038 service.resolveTypeIfNeeded(getContentResolver())); 1039 if (cn != null && cn.getPackageName().equals("!")) { 1040 throw new SecurityException( 1041 "Not allowed to start service " + service 1042 + " without permission " + cn.getClassName()); 1043 } 1044 return cn; 1045 } catch (RemoteException e) { 1046 return null; 1047 } 1048 } 1049 1050 @Override 1051 public boolean stopService(Intent service) { 1052 try { 1053 int res = ActivityManagerNative.getDefault().stopService( 1054 mMainThread.getApplicationThread(), service, 1055 service.resolveTypeIfNeeded(getContentResolver())); 1056 if (res < 0) { 1057 throw new SecurityException( 1058 "Not allowed to stop service " + service); 1059 } 1060 return res != 0; 1061 } catch (RemoteException e) { 1062 return false; 1063 } 1064 } 1065 1066 @Override 1067 public boolean bindService(Intent service, ServiceConnection conn, 1068 int flags) { 1069 IServiceConnection sd; 1070 if (mPackageInfo != null) { 1071 sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), 1072 mMainThread.getHandler(), flags); 1073 } else { 1074 throw new RuntimeException("Not supported in system context"); 1075 } 1076 try { 1077 int res = ActivityManagerNative.getDefault().bindService( 1078 mMainThread.getApplicationThread(), getActivityToken(), 1079 service, service.resolveTypeIfNeeded(getContentResolver()), 1080 sd, flags); 1081 if (res < 0) { 1082 throw new SecurityException( 1083 "Not allowed to bind to service " + service); 1084 } 1085 return res != 0; 1086 } catch (RemoteException e) { 1087 return false; 1088 } 1089 } 1090 1091 @Override 1092 public void unbindService(ServiceConnection conn) { 1093 if (mPackageInfo != null) { 1094 IServiceConnection sd = mPackageInfo.forgetServiceDispatcher( 1095 getOuterContext(), conn); 1096 try { 1097 ActivityManagerNative.getDefault().unbindService(sd); 1098 } catch (RemoteException e) { 1099 } 1100 } else { 1101 throw new RuntimeException("Not supported in system context"); 1102 } 1103 } 1104 1105 @Override 1106 public boolean startInstrumentation(ComponentName className, 1107 String profileFile, Bundle arguments) { 1108 try { 1109 return ActivityManagerNative.getDefault().startInstrumentation( 1110 className, profileFile, 0, arguments, null); 1111 } catch (RemoteException e) { 1112 // System has crashed, nothing we can do. 1113 } 1114 return false; 1115 } 1116 1117 @Override 1118 public Object getSystemService(String name) { 1119 ServiceFetcher fetcher = SYSTEM_SERVICE_MAP.get(name); 1120 return fetcher == null ? null : fetcher.getService(this); 1121 } 1122 1123 private WallpaperManager getWallpaperManager() { 1124 return (WallpaperManager) WALLPAPER_FETCHER.getService(this); 1125 } 1126 1127 /* package */ static DropBoxManager createDropBoxManager() { 1128 IBinder b = ServiceManager.getService(DROPBOX_SERVICE); 1129 IDropBoxManagerService service = IDropBoxManagerService.Stub.asInterface(b); 1130 if (service == null) { 1131 // Don't return a DropBoxManager that will NPE upon use. 1132 // This also avoids caching a broken DropBoxManager in 1133 // getDropBoxManager during early boot, before the 1134 // DROPBOX_SERVICE is registered. 1135 return null; 1136 } 1137 return new DropBoxManager(service); 1138 } 1139 1140 @Override 1141 public int checkPermission(String permission, int pid, int uid) { 1142 if (permission == null) { 1143 throw new IllegalArgumentException("permission is null"); 1144 } 1145 1146 if (!Process.supportsProcesses()) { 1147 return PackageManager.PERMISSION_GRANTED; 1148 } 1149 try { 1150 return ActivityManagerNative.getDefault().checkPermission( 1151 permission, pid, uid); 1152 } catch (RemoteException e) { 1153 return PackageManager.PERMISSION_DENIED; 1154 } 1155 } 1156 1157 @Override 1158 public int checkCallingPermission(String permission) { 1159 if (permission == null) { 1160 throw new IllegalArgumentException("permission is null"); 1161 } 1162 1163 if (!Process.supportsProcesses()) { 1164 return PackageManager.PERMISSION_GRANTED; 1165 } 1166 int pid = Binder.getCallingPid(); 1167 if (pid != Process.myPid()) { 1168 return checkPermission(permission, pid, 1169 Binder.getCallingUid()); 1170 } 1171 return PackageManager.PERMISSION_DENIED; 1172 } 1173 1174 @Override 1175 public int checkCallingOrSelfPermission(String permission) { 1176 if (permission == null) { 1177 throw new IllegalArgumentException("permission is null"); 1178 } 1179 1180 return checkPermission(permission, Binder.getCallingPid(), 1181 Binder.getCallingUid()); 1182 } 1183 1184 private void enforce( 1185 String permission, int resultOfCheck, 1186 boolean selfToo, int uid, String message) { 1187 if (resultOfCheck != PackageManager.PERMISSION_GRANTED) { 1188 throw new SecurityException( 1189 (message != null ? (message + ": ") : "") + 1190 (selfToo 1191 ? "Neither user " + uid + " nor current process has " 1192 : "User " + uid + " does not have ") + 1193 permission + 1194 "."); 1195 } 1196 } 1197 1198 public void enforcePermission( 1199 String permission, int pid, int uid, String message) { 1200 enforce(permission, 1201 checkPermission(permission, pid, uid), 1202 false, 1203 uid, 1204 message); 1205 } 1206 1207 public void enforceCallingPermission(String permission, String message) { 1208 enforce(permission, 1209 checkCallingPermission(permission), 1210 false, 1211 Binder.getCallingUid(), 1212 message); 1213 } 1214 1215 public void enforceCallingOrSelfPermission( 1216 String permission, String message) { 1217 enforce(permission, 1218 checkCallingOrSelfPermission(permission), 1219 true, 1220 Binder.getCallingUid(), 1221 message); 1222 } 1223 1224 @Override 1225 public void grantUriPermission(String toPackage, Uri uri, int modeFlags) { 1226 try { 1227 ActivityManagerNative.getDefault().grantUriPermission( 1228 mMainThread.getApplicationThread(), toPackage, uri, 1229 modeFlags); 1230 } catch (RemoteException e) { 1231 } 1232 } 1233 1234 @Override 1235 public void revokeUriPermission(Uri uri, int modeFlags) { 1236 try { 1237 ActivityManagerNative.getDefault().revokeUriPermission( 1238 mMainThread.getApplicationThread(), uri, 1239 modeFlags); 1240 } catch (RemoteException e) { 1241 } 1242 } 1243 1244 @Override 1245 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) { 1246 if (!Process.supportsProcesses()) { 1247 return PackageManager.PERMISSION_GRANTED; 1248 } 1249 try { 1250 return ActivityManagerNative.getDefault().checkUriPermission( 1251 uri, pid, uid, modeFlags); 1252 } catch (RemoteException e) { 1253 return PackageManager.PERMISSION_DENIED; 1254 } 1255 } 1256 1257 @Override 1258 public int checkCallingUriPermission(Uri uri, int modeFlags) { 1259 if (!Process.supportsProcesses()) { 1260 return PackageManager.PERMISSION_GRANTED; 1261 } 1262 int pid = Binder.getCallingPid(); 1263 if (pid != Process.myPid()) { 1264 return checkUriPermission(uri, pid, 1265 Binder.getCallingUid(), modeFlags); 1266 } 1267 return PackageManager.PERMISSION_DENIED; 1268 } 1269 1270 @Override 1271 public int checkCallingOrSelfUriPermission(Uri uri, int modeFlags) { 1272 return checkUriPermission(uri, Binder.getCallingPid(), 1273 Binder.getCallingUid(), modeFlags); 1274 } 1275 1276 @Override 1277 public int checkUriPermission(Uri uri, String readPermission, 1278 String writePermission, int pid, int uid, int modeFlags) { 1279 if (DEBUG) { 1280 Log.i("foo", "checkUriPermission: uri=" + uri + "readPermission=" 1281 + readPermission + " writePermission=" + writePermission 1282 + " pid=" + pid + " uid=" + uid + " mode" + modeFlags); 1283 } 1284 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) { 1285 if (readPermission == null 1286 || checkPermission(readPermission, pid, uid) 1287 == PackageManager.PERMISSION_GRANTED) { 1288 return PackageManager.PERMISSION_GRANTED; 1289 } 1290 } 1291 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) { 1292 if (writePermission == null 1293 || checkPermission(writePermission, pid, uid) 1294 == PackageManager.PERMISSION_GRANTED) { 1295 return PackageManager.PERMISSION_GRANTED; 1296 } 1297 } 1298 return uri != null ? checkUriPermission(uri, pid, uid, modeFlags) 1299 : PackageManager.PERMISSION_DENIED; 1300 } 1301 1302 private String uriModeFlagToString(int uriModeFlags) { 1303 switch (uriModeFlags) { 1304 case Intent.FLAG_GRANT_READ_URI_PERMISSION | 1305 Intent.FLAG_GRANT_WRITE_URI_PERMISSION: 1306 return "read and write"; 1307 case Intent.FLAG_GRANT_READ_URI_PERMISSION: 1308 return "read"; 1309 case Intent.FLAG_GRANT_WRITE_URI_PERMISSION: 1310 return "write"; 1311 } 1312 throw new IllegalArgumentException( 1313 "Unknown permission mode flags: " + uriModeFlags); 1314 } 1315 1316 private void enforceForUri( 1317 int modeFlags, int resultOfCheck, boolean selfToo, 1318 int uid, Uri uri, String message) { 1319 if (resultOfCheck != PackageManager.PERMISSION_GRANTED) { 1320 throw new SecurityException( 1321 (message != null ? (message + ": ") : "") + 1322 (selfToo 1323 ? "Neither user " + uid + " nor current process has " 1324 : "User " + uid + " does not have ") + 1325 uriModeFlagToString(modeFlags) + 1326 " permission on " + 1327 uri + 1328 "."); 1329 } 1330 } 1331 1332 public void enforceUriPermission( 1333 Uri uri, int pid, int uid, int modeFlags, String message) { 1334 enforceForUri( 1335 modeFlags, checkUriPermission(uri, pid, uid, modeFlags), 1336 false, uid, uri, message); 1337 } 1338 1339 public void enforceCallingUriPermission( 1340 Uri uri, int modeFlags, String message) { 1341 enforceForUri( 1342 modeFlags, checkCallingUriPermission(uri, modeFlags), 1343 false, Binder.getCallingUid(), uri, message); 1344 } 1345 1346 public void enforceCallingOrSelfUriPermission( 1347 Uri uri, int modeFlags, String message) { 1348 enforceForUri( 1349 modeFlags, 1350 checkCallingOrSelfUriPermission(uri, modeFlags), true, 1351 Binder.getCallingUid(), uri, message); 1352 } 1353 1354 public void enforceUriPermission( 1355 Uri uri, String readPermission, String writePermission, 1356 int pid, int uid, int modeFlags, String message) { 1357 enforceForUri(modeFlags, 1358 checkUriPermission( 1359 uri, readPermission, writePermission, pid, uid, 1360 modeFlags), 1361 false, 1362 uid, 1363 uri, 1364 message); 1365 } 1366 1367 @Override 1368 public Context createPackageContext(String packageName, int flags) 1369 throws PackageManager.NameNotFoundException { 1370 if (packageName.equals("system") || packageName.equals("android")) { 1371 return new ContextImpl(mMainThread.getSystemContext()); 1372 } 1373 1374 LoadedApk pi = 1375 mMainThread.getPackageInfo(packageName, flags); 1376 if (pi != null) { 1377 ContextImpl c = new ContextImpl(); 1378 c.mRestricted = (flags & CONTEXT_RESTRICTED) == CONTEXT_RESTRICTED; 1379 c.init(pi, null, mMainThread, mResources); 1380 if (c.mResources != null) { 1381 return c; 1382 } 1383 } 1384 1385 // Should be a better exception. 1386 throw new PackageManager.NameNotFoundException( 1387 "Application package " + packageName + " not found"); 1388 } 1389 1390 @Override 1391 public boolean isRestricted() { 1392 return mRestricted; 1393 } 1394 1395 private File getDataDirFile() { 1396 if (mPackageInfo != null) { 1397 return mPackageInfo.getDataDirFile(); 1398 } 1399 throw new RuntimeException("Not supported in system context"); 1400 } 1401 1402 @Override 1403 public File getDir(String name, int mode) { 1404 name = "app_" + name; 1405 File file = makeFilename(getDataDirFile(), name); 1406 if (!file.exists()) { 1407 file.mkdir(); 1408 setFilePermissionsFromMode(file.getPath(), mode, 1409 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH); 1410 } 1411 return file; 1412 } 1413 1414 static ContextImpl createSystemContext(ActivityThread mainThread) { 1415 ContextImpl context = new ContextImpl(); 1416 context.init(Resources.getSystem(), mainThread); 1417 return context; 1418 } 1419 1420 ContextImpl() { 1421 mOuterContext = this; 1422 } 1423 1424 /** 1425 * Create a new ApplicationContext from an existing one. The new one 1426 * works and operates the same as the one it is copying. 1427 * 1428 * @param context Existing application context. 1429 */ 1430 public ContextImpl(ContextImpl context) { 1431 mPackageInfo = context.mPackageInfo; 1432 mResources = context.mResources; 1433 mMainThread = context.mMainThread; 1434 mContentResolver = context.mContentResolver; 1435 mOuterContext = this; 1436 } 1437 1438 final void init(LoadedApk packageInfo, 1439 IBinder activityToken, ActivityThread mainThread) { 1440 init(packageInfo, activityToken, mainThread, null); 1441 } 1442 1443 final void init(LoadedApk packageInfo, 1444 IBinder activityToken, ActivityThread mainThread, 1445 Resources container) { 1446 mPackageInfo = packageInfo; 1447 mResources = mPackageInfo.getResources(mainThread); 1448 1449 if (mResources != null && container != null 1450 && container.getCompatibilityInfo().applicationScale != 1451 mResources.getCompatibilityInfo().applicationScale) { 1452 if (DEBUG) { 1453 Log.d(TAG, "loaded context has different scaling. Using container's" + 1454 " compatiblity info:" + container.getDisplayMetrics()); 1455 } 1456 mResources = mainThread.getTopLevelResources( 1457 mPackageInfo.getResDir(), container.getCompatibilityInfo().copy()); 1458 } 1459 mMainThread = mainThread; 1460 mContentResolver = new ApplicationContentResolver(this, mainThread); 1461 1462 setActivityToken(activityToken); 1463 } 1464 1465 final void init(Resources resources, ActivityThread mainThread) { 1466 mPackageInfo = null; 1467 mResources = resources; 1468 mMainThread = mainThread; 1469 mContentResolver = new ApplicationContentResolver(this, mainThread); 1470 } 1471 1472 final void scheduleFinalCleanup(String who, String what) { 1473 mMainThread.scheduleContextCleanup(this, who, what); 1474 } 1475 1476 final void performFinalCleanup(String who, String what) { 1477 //Log.i(TAG, "Cleanup up context: " + this); 1478 mPackageInfo.removeContextRegistrations(getOuterContext(), who, what); 1479 } 1480 1481 final Context getReceiverRestrictedContext() { 1482 if (mReceiverRestrictedContext != null) { 1483 return mReceiverRestrictedContext; 1484 } 1485 return mReceiverRestrictedContext = new ReceiverRestrictedContext(getOuterContext()); 1486 } 1487 1488 final void setActivityToken(IBinder token) { 1489 mActivityToken = token; 1490 } 1491 1492 final void setOuterContext(Context context) { 1493 mOuterContext = context; 1494 } 1495 1496 final Context getOuterContext() { 1497 return mOuterContext; 1498 } 1499 1500 final IBinder getActivityToken() { 1501 return mActivityToken; 1502 } 1503 1504 static void setFilePermissionsFromMode(String name, int mode, 1505 int extraPermissions) { 1506 int perms = FileUtils.S_IRUSR|FileUtils.S_IWUSR 1507 |FileUtils.S_IRGRP|FileUtils.S_IWGRP 1508 |extraPermissions; 1509 if ((mode&MODE_WORLD_READABLE) != 0) { 1510 perms |= FileUtils.S_IROTH; 1511 } 1512 if ((mode&MODE_WORLD_WRITEABLE) != 0) { 1513 perms |= FileUtils.S_IWOTH; 1514 } 1515 if (DEBUG) { 1516 Log.i(TAG, "File " + name + ": mode=0x" + Integer.toHexString(mode) 1517 + ", perms=0x" + Integer.toHexString(perms)); 1518 } 1519 FileUtils.setPermissions(name, perms, -1, -1); 1520 } 1521 1522 private File validateFilePath(String name, boolean createDirectory) { 1523 File dir; 1524 File f; 1525 1526 if (name.charAt(0) == File.separatorChar) { 1527 String dirPath = name.substring(0, name.lastIndexOf(File.separatorChar)); 1528 dir = new File(dirPath); 1529 name = name.substring(name.lastIndexOf(File.separatorChar)); 1530 f = new File(dir, name); 1531 } else { 1532 dir = getDatabasesDir(); 1533 f = makeFilename(dir, name); 1534 } 1535 1536 if (createDirectory && !dir.isDirectory() && dir.mkdir()) { 1537 FileUtils.setPermissions(dir.getPath(), 1538 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, 1539 -1, -1); 1540 } 1541 1542 return f; 1543 } 1544 1545 private File makeFilename(File base, String name) { 1546 if (name.indexOf(File.separatorChar) < 0) { 1547 return new File(base, name); 1548 } 1549 throw new IllegalArgumentException( 1550 "File " + name + " contains a path separator"); 1551 } 1552 1553 // ---------------------------------------------------------------------- 1554 // ---------------------------------------------------------------------- 1555 // ---------------------------------------------------------------------- 1556 1557 private static final class ApplicationContentResolver extends ContentResolver { 1558 public ApplicationContentResolver(Context context, ActivityThread mainThread) { 1559 super(context); 1560 mMainThread = mainThread; 1561 } 1562 1563 @Override 1564 protected IContentProvider acquireProvider(Context context, String name) { 1565 return mMainThread.acquireProvider(context, name); 1566 } 1567 1568 @Override 1569 protected IContentProvider acquireExistingProvider(Context context, String name) { 1570 return mMainThread.acquireExistingProvider(context, name); 1571 } 1572 1573 @Override 1574 public boolean releaseProvider(IContentProvider provider) { 1575 return mMainThread.releaseProvider(provider); 1576 } 1577 1578 private final ActivityThread mMainThread; 1579 } 1580} 1581