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