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