ContextImpl.java revision 82142c21dd333307682d5f4bb09de3ab3ccfa06c
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 android.os.Build; 20 21import com.android.internal.policy.PolicyManager; 22import com.android.internal.util.Preconditions; 23 24import android.bluetooth.BluetoothManager; 25import android.content.BroadcastReceiver; 26import android.content.ComponentName; 27import android.content.ContentResolver; 28import android.content.Context; 29import android.content.ContextWrapper; 30import android.content.IContentProvider; 31import android.content.Intent; 32import android.content.IntentFilter; 33import android.content.IIntentReceiver; 34import android.content.IntentSender; 35import android.content.ReceiverCallNotAllowedException; 36import android.content.ServiceConnection; 37import android.content.SharedPreferences; 38import android.content.pm.ApplicationInfo; 39import android.content.pm.IPackageManager; 40import android.content.pm.PackageManager; 41import android.content.pm.PackageManager.NameNotFoundException; 42import android.content.res.AssetManager; 43import android.content.res.CompatibilityInfo; 44import android.content.res.Configuration; 45import android.content.res.Resources; 46import android.database.DatabaseErrorHandler; 47import android.database.sqlite.SQLiteDatabase; 48import android.database.sqlite.SQLiteDatabase.CursorFactory; 49import android.graphics.Bitmap; 50import android.graphics.drawable.Drawable; 51import android.hardware.ConsumerIrManager; 52import android.hardware.ISerialManager; 53import android.hardware.SerialManager; 54import android.hardware.SystemSensorManager; 55import android.hardware.hdmi.HdmiCecManager; 56import android.hardware.hdmi.IHdmiCecService; 57import android.hardware.camera2.CameraManager; 58import android.hardware.display.DisplayManager; 59import android.hardware.input.InputManager; 60import android.hardware.usb.IUsbManager; 61import android.hardware.usb.UsbManager; 62import android.location.CountryDetector; 63import android.location.ICountryDetector; 64import android.location.ILocationManager; 65import android.location.LocationManager; 66import android.media.AudioManager; 67import android.media.MediaRouter; 68import android.media.session.MediaSessionManager; 69import android.net.ConnectivityManager; 70import android.net.IConnectivityManager; 71import android.net.INetworkPolicyManager; 72import android.net.NetworkPolicyManager; 73import android.net.Uri; 74import android.net.nsd.INsdManager; 75import android.net.nsd.NsdManager; 76import android.net.wifi.IWifiManager; 77import android.net.wifi.WifiManager; 78import android.net.wifi.hotspot.IWifiHotspotManager; 79import android.net.wifi.hotspot.WifiHotspotManager; 80import android.net.wifi.p2p.IWifiP2pManager; 81import android.net.wifi.p2p.WifiP2pManager; 82import android.nfc.NfcManager; 83import android.os.Binder; 84import android.os.Bundle; 85import android.os.Debug; 86import android.os.DropBoxManager; 87import android.os.Environment; 88import android.os.FileUtils; 89import android.os.Handler; 90import android.os.IBinder; 91import android.os.IPowerManager; 92import android.os.IUserManager; 93import android.os.Looper; 94import android.os.PowerManager; 95import android.os.Process; 96import android.os.RemoteException; 97import android.os.ServiceManager; 98import android.os.UserHandle; 99import android.os.SystemVibrator; 100import android.os.UserManager; 101import android.os.storage.IMountService; 102import android.os.storage.StorageManager; 103import android.print.IPrintManager; 104import android.print.PrintManager; 105import android.telephony.TelephonyManager; 106import android.content.ClipboardManager; 107import android.util.AndroidRuntimeException; 108import android.util.ArrayMap; 109import android.util.Log; 110import android.util.Slog; 111import android.view.DisplayAdjustments; 112import android.view.ContextThemeWrapper; 113import android.view.Display; 114import android.view.WindowManagerImpl; 115import android.view.accessibility.AccessibilityManager; 116import android.view.accessibility.CaptioningManager; 117import android.view.inputmethod.InputMethodManager; 118import android.view.textservice.TextServicesManager; 119import android.accounts.AccountManager; 120import android.accounts.IAccountManager; 121import android.app.admin.DevicePolicyManager; 122import android.app.trust.TrustManager; 123 124import com.android.internal.annotations.GuardedBy; 125import com.android.internal.app.IAppOpsService; 126import com.android.internal.os.IDropBoxManagerService; 127 128import java.io.File; 129import java.io.FileInputStream; 130import java.io.FileNotFoundException; 131import java.io.FileOutputStream; 132import java.io.IOException; 133import java.io.InputStream; 134import java.util.ArrayList; 135import java.util.HashMap; 136 137class ReceiverRestrictedContext extends ContextWrapper { 138 ReceiverRestrictedContext(Context base) { 139 super(base); 140 } 141 142 @Override 143 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) { 144 return registerReceiver(receiver, filter, null, null); 145 } 146 147 @Override 148 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, 149 String broadcastPermission, Handler scheduler) { 150 if (receiver == null) { 151 // Allow retrieving current sticky broadcast; this is safe since we 152 // aren't actually registering a receiver. 153 return super.registerReceiver(null, filter, broadcastPermission, scheduler); 154 } else { 155 throw new ReceiverCallNotAllowedException( 156 "BroadcastReceiver components are not allowed to register to receive intents"); 157 } 158 } 159 160 @Override 161 public Intent registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user, 162 IntentFilter filter, String broadcastPermission, Handler scheduler) { 163 if (receiver == null) { 164 // Allow retrieving current sticky broadcast; this is safe since we 165 // aren't actually registering a receiver. 166 return super.registerReceiverAsUser(null, user, filter, broadcastPermission, scheduler); 167 } else { 168 throw new ReceiverCallNotAllowedException( 169 "BroadcastReceiver components are not allowed to register to receive intents"); 170 } 171 } 172 173 @Override 174 public boolean bindService(Intent service, ServiceConnection conn, int flags) { 175 throw new ReceiverCallNotAllowedException( 176 "BroadcastReceiver components are not allowed to bind to services"); 177 } 178} 179 180/** 181 * Common implementation of Context API, which provides the base 182 * context object for Activity and other application components. 183 */ 184class ContextImpl extends Context { 185 private final static String TAG = "ContextImpl"; 186 private final static boolean DEBUG = false; 187 188 /** 189 * Map from package name, to preference name, to cached preferences. 190 */ 191 private static ArrayMap<String, ArrayMap<String, SharedPreferencesImpl>> sSharedPrefs; 192 193 final ActivityThread mMainThread; 194 final LoadedApk mPackageInfo; 195 196 private final IBinder mActivityToken; 197 198 private final UserHandle mUser; 199 200 private final ApplicationContentResolver mContentResolver; 201 202 private final String mBasePackageName; 203 private final String mOpPackageName; 204 205 private final ResourcesManager mResourcesManager; 206 private final Resources mResources; 207 private final Display mDisplay; // may be null if default display 208 private final DisplayAdjustments mDisplayAdjustments = new DisplayAdjustments(); 209 private final Configuration mOverrideConfiguration; 210 211 private final boolean mRestricted; 212 213 private Context mOuterContext; 214 private int mThemeResource = 0; 215 private Resources.Theme mTheme = null; 216 private PackageManager mPackageManager; 217 private Context mReceiverRestrictedContext = null; 218 219 private final Object mSync = new Object(); 220 221 @GuardedBy("mSync") 222 private File mDatabasesDir; 223 @GuardedBy("mSync") 224 private File mPreferencesDir; 225 @GuardedBy("mSync") 226 private File mFilesDir; 227 @GuardedBy("mSync") 228 private File mCacheDir; 229 230 @GuardedBy("mSync") 231 private File[] mExternalObbDirs; 232 @GuardedBy("mSync") 233 private File[] mExternalFilesDirs; 234 @GuardedBy("mSync") 235 private File[] mExternalCacheDirs; 236 237 private static final String[] EMPTY_FILE_LIST = {}; 238 239 /** 240 * Override this class when the system service constructor needs a 241 * ContextImpl. Else, use StaticServiceFetcher below. 242 */ 243 /*package*/ static class ServiceFetcher { 244 int mContextCacheIndex = -1; 245 246 /** 247 * Main entrypoint; only override if you don't need caching. 248 */ 249 public Object getService(ContextImpl ctx) { 250 ArrayList<Object> cache = ctx.mServiceCache; 251 Object service; 252 synchronized (cache) { 253 if (cache.size() == 0) { 254 // Initialize the cache vector on first access. 255 // At this point sNextPerContextServiceCacheIndex 256 // is the number of potential services that are 257 // cached per-Context. 258 for (int i = 0; i < sNextPerContextServiceCacheIndex; i++) { 259 cache.add(null); 260 } 261 } else { 262 service = cache.get(mContextCacheIndex); 263 if (service != null) { 264 return service; 265 } 266 } 267 service = createService(ctx); 268 cache.set(mContextCacheIndex, service); 269 return service; 270 } 271 } 272 273 /** 274 * Override this to create a new per-Context instance of the 275 * service. getService() will handle locking and caching. 276 */ 277 public Object createService(ContextImpl ctx) { 278 throw new RuntimeException("Not implemented"); 279 } 280 } 281 282 /** 283 * Override this class for services to be cached process-wide. 284 */ 285 abstract static class StaticServiceFetcher extends ServiceFetcher { 286 private Object mCachedInstance; 287 288 @Override 289 public final Object getService(ContextImpl unused) { 290 synchronized (StaticServiceFetcher.this) { 291 Object service = mCachedInstance; 292 if (service != null) { 293 return service; 294 } 295 return mCachedInstance = createStaticService(); 296 } 297 } 298 299 public abstract Object createStaticService(); 300 } 301 302 private static final HashMap<String, ServiceFetcher> SYSTEM_SERVICE_MAP = 303 new HashMap<String, ServiceFetcher>(); 304 305 private static int sNextPerContextServiceCacheIndex = 0; 306 private static void registerService(String serviceName, ServiceFetcher fetcher) { 307 if (!(fetcher instanceof StaticServiceFetcher)) { 308 fetcher.mContextCacheIndex = sNextPerContextServiceCacheIndex++; 309 } 310 SYSTEM_SERVICE_MAP.put(serviceName, fetcher); 311 } 312 313 // This one's defined separately and given a variable name so it 314 // can be re-used by getWallpaperManager(), avoiding a HashMap 315 // lookup. 316 private static ServiceFetcher WALLPAPER_FETCHER = new ServiceFetcher() { 317 public Object createService(ContextImpl ctx) { 318 return new WallpaperManager(ctx.getOuterContext(), 319 ctx.mMainThread.getHandler()); 320 }}; 321 322 static { 323 registerService(ACCESSIBILITY_SERVICE, new ServiceFetcher() { 324 public Object getService(ContextImpl ctx) { 325 return AccessibilityManager.getInstance(ctx); 326 }}); 327 328 registerService(CAPTIONING_SERVICE, new ServiceFetcher() { 329 public Object getService(ContextImpl ctx) { 330 return new CaptioningManager(ctx); 331 }}); 332 333 registerService(ACCOUNT_SERVICE, new ServiceFetcher() { 334 public Object createService(ContextImpl ctx) { 335 IBinder b = ServiceManager.getService(ACCOUNT_SERVICE); 336 IAccountManager service = IAccountManager.Stub.asInterface(b); 337 return new AccountManager(ctx, service); 338 }}); 339 340 registerService(ACTIVITY_SERVICE, new ServiceFetcher() { 341 public Object createService(ContextImpl ctx) { 342 return new ActivityManager(ctx.getOuterContext(), ctx.mMainThread.getHandler()); 343 }}); 344 345 registerService(ALARM_SERVICE, new ServiceFetcher() { 346 public Object createService(ContextImpl ctx) { 347 IBinder b = ServiceManager.getService(ALARM_SERVICE); 348 IAlarmManager service = IAlarmManager.Stub.asInterface(b); 349 return new AlarmManager(service, ctx); 350 }}); 351 352 registerService(AUDIO_SERVICE, new ServiceFetcher() { 353 public Object createService(ContextImpl ctx) { 354 return new AudioManager(ctx); 355 }}); 356 357 registerService(MEDIA_ROUTER_SERVICE, new ServiceFetcher() { 358 public Object createService(ContextImpl ctx) { 359 return new MediaRouter(ctx); 360 }}); 361 362 registerService(BLUETOOTH_SERVICE, new ServiceFetcher() { 363 public Object createService(ContextImpl ctx) { 364 return new BluetoothManager(ctx); 365 }}); 366 367 registerService(HDMI_CEC_SERVICE, new StaticServiceFetcher() { 368 public Object createStaticService() { 369 IBinder b = ServiceManager.getService(HDMI_CEC_SERVICE); 370 return new HdmiCecManager(IHdmiCecService.Stub.asInterface(b)); 371 }}); 372 373 374 registerService(CLIPBOARD_SERVICE, new ServiceFetcher() { 375 public Object createService(ContextImpl ctx) { 376 return new ClipboardManager(ctx.getOuterContext(), 377 ctx.mMainThread.getHandler()); 378 }}); 379 380 registerService(CONNECTIVITY_SERVICE, new ServiceFetcher() { 381 public Object createService(ContextImpl ctx) { 382 IBinder b = ServiceManager.getService(CONNECTIVITY_SERVICE); 383 return new ConnectivityManager(IConnectivityManager.Stub.asInterface(b), 384 ctx.getPackageName()); 385 }}); 386 387 registerService(COUNTRY_DETECTOR, new StaticServiceFetcher() { 388 public Object createStaticService() { 389 IBinder b = ServiceManager.getService(COUNTRY_DETECTOR); 390 return new CountryDetector(ICountryDetector.Stub.asInterface(b)); 391 }}); 392 393 registerService(DEVICE_POLICY_SERVICE, new ServiceFetcher() { 394 public Object createService(ContextImpl ctx) { 395 return DevicePolicyManager.create(ctx, ctx.mMainThread.getHandler()); 396 }}); 397 398 registerService(DOWNLOAD_SERVICE, new ServiceFetcher() { 399 public Object createService(ContextImpl ctx) { 400 return new DownloadManager(ctx.getContentResolver(), ctx.getPackageName()); 401 }}); 402 403 registerService(NFC_SERVICE, new ServiceFetcher() { 404 public Object createService(ContextImpl ctx) { 405 return new NfcManager(ctx); 406 }}); 407 408 registerService(DROPBOX_SERVICE, new StaticServiceFetcher() { 409 public Object createStaticService() { 410 return createDropBoxManager(); 411 }}); 412 413 registerService(INPUT_SERVICE, new StaticServiceFetcher() { 414 public Object createStaticService() { 415 return InputManager.getInstance(); 416 }}); 417 418 registerService(DISPLAY_SERVICE, new ServiceFetcher() { 419 @Override 420 public Object createService(ContextImpl ctx) { 421 return new DisplayManager(ctx.getOuterContext()); 422 }}); 423 424 registerService(INPUT_METHOD_SERVICE, new StaticServiceFetcher() { 425 public Object createStaticService() { 426 return InputMethodManager.getInstance(); 427 }}); 428 429 registerService(TEXT_SERVICES_MANAGER_SERVICE, new ServiceFetcher() { 430 public Object createService(ContextImpl ctx) { 431 return TextServicesManager.getInstance(); 432 }}); 433 434 registerService(KEYGUARD_SERVICE, new ServiceFetcher() { 435 public Object getService(ContextImpl ctx) { 436 // TODO: why isn't this caching it? It wasn't 437 // before, so I'm preserving the old behavior and 438 // using getService(), instead of createService() 439 // which would do the caching. 440 return new KeyguardManager(); 441 }}); 442 443 registerService(LAYOUT_INFLATER_SERVICE, new ServiceFetcher() { 444 public Object createService(ContextImpl ctx) { 445 return PolicyManager.makeNewLayoutInflater(ctx.getOuterContext()); 446 }}); 447 448 registerService(LOCATION_SERVICE, new ServiceFetcher() { 449 public Object createService(ContextImpl ctx) { 450 IBinder b = ServiceManager.getService(LOCATION_SERVICE); 451 return new LocationManager(ctx, ILocationManager.Stub.asInterface(b)); 452 }}); 453 454 registerService(NETWORK_POLICY_SERVICE, new ServiceFetcher() { 455 @Override 456 public Object createService(ContextImpl ctx) { 457 return new NetworkPolicyManager(INetworkPolicyManager.Stub.asInterface( 458 ServiceManager.getService(NETWORK_POLICY_SERVICE))); 459 } 460 }); 461 462 registerService(NOTIFICATION_SERVICE, new ServiceFetcher() { 463 public Object createService(ContextImpl ctx) { 464 final Context outerContext = ctx.getOuterContext(); 465 return new NotificationManager( 466 new ContextThemeWrapper(outerContext, 467 Resources.selectSystemTheme(0, 468 outerContext.getApplicationInfo().targetSdkVersion, 469 com.android.internal.R.style.Theme_Dialog, 470 com.android.internal.R.style.Theme_Holo_Dialog, 471 com.android.internal.R.style.Theme_DeviceDefault_Dialog)), 472 ctx.mMainThread.getHandler()); 473 }}); 474 475 registerService(NSD_SERVICE, new ServiceFetcher() { 476 @Override 477 public Object createService(ContextImpl ctx) { 478 IBinder b = ServiceManager.getService(NSD_SERVICE); 479 INsdManager service = INsdManager.Stub.asInterface(b); 480 return new NsdManager(ctx.getOuterContext(), service); 481 }}); 482 483 // Note: this was previously cached in a static variable, but 484 // constructed using mMainThread.getHandler(), so converting 485 // it to be a regular Context-cached service... 486 registerService(POWER_SERVICE, new ServiceFetcher() { 487 public Object createService(ContextImpl ctx) { 488 IBinder b = ServiceManager.getService(POWER_SERVICE); 489 IPowerManager service = IPowerManager.Stub.asInterface(b); 490 return new PowerManager(ctx.getOuterContext(), 491 service, ctx.mMainThread.getHandler()); 492 }}); 493 494 registerService(SEARCH_SERVICE, new ServiceFetcher() { 495 public Object createService(ContextImpl ctx) { 496 return new SearchManager(ctx.getOuterContext(), 497 ctx.mMainThread.getHandler()); 498 }}); 499 500 registerService(SENSOR_SERVICE, new ServiceFetcher() { 501 public Object createService(ContextImpl ctx) { 502 return new SystemSensorManager(ctx.getOuterContext(), 503 ctx.mMainThread.getHandler().getLooper()); 504 }}); 505 506 registerService(STATUS_BAR_SERVICE, new ServiceFetcher() { 507 public Object createService(ContextImpl ctx) { 508 return new StatusBarManager(ctx.getOuterContext()); 509 }}); 510 511 registerService(STORAGE_SERVICE, new ServiceFetcher() { 512 public Object createService(ContextImpl ctx) { 513 try { 514 return new StorageManager( 515 ctx.getContentResolver(), ctx.mMainThread.getHandler().getLooper()); 516 } catch (RemoteException rex) { 517 Log.e(TAG, "Failed to create StorageManager", rex); 518 return null; 519 } 520 }}); 521 522 registerService(TELEPHONY_SERVICE, new ServiceFetcher() { 523 public Object createService(ContextImpl ctx) { 524 return new TelephonyManager(ctx.getOuterContext()); 525 }}); 526 527 registerService(UI_MODE_SERVICE, new ServiceFetcher() { 528 public Object createService(ContextImpl ctx) { 529 return new UiModeManager(); 530 }}); 531 532 registerService(USB_SERVICE, new ServiceFetcher() { 533 public Object createService(ContextImpl ctx) { 534 IBinder b = ServiceManager.getService(USB_SERVICE); 535 return new UsbManager(ctx, IUsbManager.Stub.asInterface(b)); 536 }}); 537 538 registerService(SERIAL_SERVICE, new ServiceFetcher() { 539 public Object createService(ContextImpl ctx) { 540 IBinder b = ServiceManager.getService(SERIAL_SERVICE); 541 return new SerialManager(ctx, ISerialManager.Stub.asInterface(b)); 542 }}); 543 544 registerService(VIBRATOR_SERVICE, new ServiceFetcher() { 545 public Object createService(ContextImpl ctx) { 546 return new SystemVibrator(ctx); 547 }}); 548 549 registerService(WALLPAPER_SERVICE, WALLPAPER_FETCHER); 550 551 registerService(WIFI_SERVICE, new ServiceFetcher() { 552 public Object createService(ContextImpl ctx) { 553 IBinder b = ServiceManager.getService(WIFI_SERVICE); 554 IWifiManager service = IWifiManager.Stub.asInterface(b); 555 return new WifiManager(ctx.getOuterContext(), service); 556 }}); 557 558 registerService(WIFI_HOTSPOT_SERVICE, new ServiceFetcher() { 559 public Object createService(ContextImpl ctx) { 560 IBinder b = ServiceManager.getService(WIFI_HOTSPOT_SERVICE); 561 IWifiHotspotManager service = IWifiHotspotManager.Stub.asInterface(b); 562 return new WifiHotspotManager(ctx.getOuterContext(), service); 563 }}); 564 565 registerService(WIFI_P2P_SERVICE, new ServiceFetcher() { 566 public Object createService(ContextImpl ctx) { 567 IBinder b = ServiceManager.getService(WIFI_P2P_SERVICE); 568 IWifiP2pManager service = IWifiP2pManager.Stub.asInterface(b); 569 return new WifiP2pManager(service); 570 }}); 571 572 registerService(WINDOW_SERVICE, new ServiceFetcher() { 573 Display mDefaultDisplay; 574 public Object getService(ContextImpl ctx) { 575 Display display = ctx.mDisplay; 576 if (display == null) { 577 if (mDefaultDisplay == null) { 578 DisplayManager dm = (DisplayManager)ctx.getOuterContext(). 579 getSystemService(Context.DISPLAY_SERVICE); 580 mDefaultDisplay = dm.getDisplay(Display.DEFAULT_DISPLAY); 581 } 582 display = mDefaultDisplay; 583 } 584 return new WindowManagerImpl(display); 585 }}); 586 587 registerService(USER_SERVICE, new ServiceFetcher() { 588 public Object createService(ContextImpl ctx) { 589 IBinder b = ServiceManager.getService(USER_SERVICE); 590 IUserManager service = IUserManager.Stub.asInterface(b); 591 return new UserManager(ctx, service); 592 }}); 593 594 registerService(APP_OPS_SERVICE, new ServiceFetcher() { 595 public Object createService(ContextImpl ctx) { 596 IBinder b = ServiceManager.getService(APP_OPS_SERVICE); 597 IAppOpsService service = IAppOpsService.Stub.asInterface(b); 598 return new AppOpsManager(ctx, service); 599 }}); 600 601 registerService(CAMERA_SERVICE, new ServiceFetcher() { 602 public Object createService(ContextImpl ctx) { 603 return new CameraManager(ctx); 604 } 605 }); 606 607 registerService(PRINT_SERVICE, new ServiceFetcher() { 608 public Object createService(ContextImpl ctx) { 609 IBinder iBinder = ServiceManager.getService(Context.PRINT_SERVICE); 610 IPrintManager service = IPrintManager.Stub.asInterface(iBinder); 611 return new PrintManager(ctx.getOuterContext(), service, UserHandle.myUserId(), 612 UserHandle.getAppId(Process.myUid())); 613 }}); 614 615 registerService(CONSUMER_IR_SERVICE, new ServiceFetcher() { 616 public Object createService(ContextImpl ctx) { 617 return new ConsumerIrManager(ctx); 618 }}); 619 620 registerService(MEDIA_SESSION_SERVICE, new ServiceFetcher() { 621 public Object createService(ContextImpl ctx) { 622 return new MediaSessionManager(ctx); 623 } 624 }); 625 registerService(TRUST_SERVICE, new ServiceFetcher() { 626 public Object createService(ContextImpl ctx) { 627 IBinder b = ServiceManager.getService(TRUST_SERVICE); 628 return new TrustManager(b); 629 } 630 }); 631 } 632 633 static ContextImpl getImpl(Context context) { 634 Context nextContext; 635 while ((context instanceof ContextWrapper) && 636 (nextContext=((ContextWrapper)context).getBaseContext()) != null) { 637 context = nextContext; 638 } 639 return (ContextImpl)context; 640 } 641 642 // The system service cache for the system services that are 643 // cached per-ContextImpl. Package-scoped to avoid accessor 644 // methods. 645 final ArrayList<Object> mServiceCache = new ArrayList<Object>(); 646 647 @Override 648 public AssetManager getAssets() { 649 return getResources().getAssets(); 650 } 651 652 @Override 653 public Resources getResources() { 654 return mResources; 655 } 656 657 @Override 658 public PackageManager getPackageManager() { 659 if (mPackageManager != null) { 660 return mPackageManager; 661 } 662 663 IPackageManager pm = ActivityThread.getPackageManager(); 664 if (pm != null) { 665 // Doesn't matter if we make more than one instance. 666 return (mPackageManager = new ApplicationPackageManager(this, pm)); 667 } 668 669 return null; 670 } 671 672 @Override 673 public ContentResolver getContentResolver() { 674 return mContentResolver; 675 } 676 677 @Override 678 public Looper getMainLooper() { 679 return mMainThread.getLooper(); 680 } 681 682 @Override 683 public Context getApplicationContext() { 684 return (mPackageInfo != null) ? 685 mPackageInfo.getApplication() : mMainThread.getApplication(); 686 } 687 688 @Override 689 public void setTheme(int resid) { 690 mThemeResource = resid; 691 } 692 693 @Override 694 public int getThemeResId() { 695 return mThemeResource; 696 } 697 698 @Override 699 public Resources.Theme getTheme() { 700 if (mTheme == null) { 701 mThemeResource = Resources.selectDefaultTheme(mThemeResource, 702 getOuterContext().getApplicationInfo().targetSdkVersion); 703 mTheme = mResources.newTheme(); 704 mTheme.applyStyle(mThemeResource, true); 705 } 706 return mTheme; 707 } 708 709 @Override 710 public ClassLoader getClassLoader() { 711 return mPackageInfo != null ? 712 mPackageInfo.getClassLoader() : ClassLoader.getSystemClassLoader(); 713 } 714 715 @Override 716 public String getPackageName() { 717 if (mPackageInfo != null) { 718 return mPackageInfo.getPackageName(); 719 } 720 // No mPackageInfo means this is a Context for the system itself, 721 // and this here is its name. 722 return "android"; 723 } 724 725 /** @hide */ 726 @Override 727 public String getBasePackageName() { 728 return mBasePackageName != null ? mBasePackageName : getPackageName(); 729 } 730 731 /** @hide */ 732 @Override 733 public String getOpPackageName() { 734 return mOpPackageName != null ? mOpPackageName : getBasePackageName(); 735 } 736 737 @Override 738 public ApplicationInfo getApplicationInfo() { 739 if (mPackageInfo != null) { 740 return mPackageInfo.getApplicationInfo(); 741 } 742 throw new RuntimeException("Not supported in system context"); 743 } 744 745 @Override 746 public String getPackageResourcePath() { 747 if (mPackageInfo != null) { 748 return mPackageInfo.getResDir(); 749 } 750 throw new RuntimeException("Not supported in system context"); 751 } 752 753 @Override 754 public String getPackageCodePath() { 755 if (mPackageInfo != null) { 756 return mPackageInfo.getAppDir(); 757 } 758 throw new RuntimeException("Not supported in system context"); 759 } 760 761 public File getSharedPrefsFile(String name) { 762 return makeFilename(getPreferencesDir(), name + ".xml"); 763 } 764 765 @Override 766 public SharedPreferences getSharedPreferences(String name, int mode) { 767 SharedPreferencesImpl sp; 768 synchronized (ContextImpl.class) { 769 if (sSharedPrefs == null) { 770 sSharedPrefs = new ArrayMap<String, ArrayMap<String, SharedPreferencesImpl>>(); 771 } 772 773 final String packageName = getPackageName(); 774 ArrayMap<String, SharedPreferencesImpl> packagePrefs = sSharedPrefs.get(packageName); 775 if (packagePrefs == null) { 776 packagePrefs = new ArrayMap<String, SharedPreferencesImpl>(); 777 sSharedPrefs.put(packageName, packagePrefs); 778 } 779 780 // At least one application in the world actually passes in a null 781 // name. This happened to work because when we generated the file name 782 // we would stringify it to "null.xml". Nice. 783 if (mPackageInfo.getApplicationInfo().targetSdkVersion < 784 Build.VERSION_CODES.KITKAT) { 785 if (name == null) { 786 name = "null"; 787 } 788 } 789 790 sp = packagePrefs.get(name); 791 if (sp == null) { 792 File prefsFile = getSharedPrefsFile(name); 793 sp = new SharedPreferencesImpl(prefsFile, mode); 794 packagePrefs.put(name, sp); 795 return sp; 796 } 797 } 798 if ((mode & Context.MODE_MULTI_PROCESS) != 0 || 799 getApplicationInfo().targetSdkVersion < android.os.Build.VERSION_CODES.HONEYCOMB) { 800 // If somebody else (some other process) changed the prefs 801 // file behind our back, we reload it. This has been the 802 // historical (if undocumented) behavior. 803 sp.startReloadIfChangedUnexpectedly(); 804 } 805 return sp; 806 } 807 808 private File getPreferencesDir() { 809 synchronized (mSync) { 810 if (mPreferencesDir == null) { 811 mPreferencesDir = new File(getDataDirFile(), "shared_prefs"); 812 } 813 return mPreferencesDir; 814 } 815 } 816 817 @Override 818 public FileInputStream openFileInput(String name) 819 throws FileNotFoundException { 820 File f = makeFilename(getFilesDir(), name); 821 return new FileInputStream(f); 822 } 823 824 @Override 825 public FileOutputStream openFileOutput(String name, int mode) 826 throws FileNotFoundException { 827 final boolean append = (mode&MODE_APPEND) != 0; 828 File f = makeFilename(getFilesDir(), name); 829 try { 830 FileOutputStream fos = new FileOutputStream(f, append); 831 setFilePermissionsFromMode(f.getPath(), mode, 0); 832 return fos; 833 } catch (FileNotFoundException e) { 834 } 835 836 File parent = f.getParentFile(); 837 parent.mkdir(); 838 FileUtils.setPermissions( 839 parent.getPath(), 840 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, 841 -1, -1); 842 FileOutputStream fos = new FileOutputStream(f, append); 843 setFilePermissionsFromMode(f.getPath(), mode, 0); 844 return fos; 845 } 846 847 @Override 848 public boolean deleteFile(String name) { 849 File f = makeFilename(getFilesDir(), name); 850 return f.delete(); 851 } 852 853 @Override 854 public File getFilesDir() { 855 synchronized (mSync) { 856 if (mFilesDir == null) { 857 mFilesDir = new File(getDataDirFile(), "files"); 858 } 859 if (!mFilesDir.exists()) { 860 if(!mFilesDir.mkdirs()) { 861 if (mFilesDir.exists()) { 862 // spurious failure; probably racing with another process for this app 863 return mFilesDir; 864 } 865 Log.w(TAG, "Unable to create files directory " + mFilesDir.getPath()); 866 return null; 867 } 868 FileUtils.setPermissions( 869 mFilesDir.getPath(), 870 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, 871 -1, -1); 872 } 873 return mFilesDir; 874 } 875 } 876 877 @Override 878 public File getExternalFilesDir(String type) { 879 // Operates on primary external storage 880 return getExternalFilesDirs(type)[0]; 881 } 882 883 @Override 884 public File[] getExternalFilesDirs(String type) { 885 synchronized (mSync) { 886 if (mExternalFilesDirs == null) { 887 mExternalFilesDirs = Environment.buildExternalStorageAppFilesDirs(getPackageName()); 888 } 889 890 // Splice in requested type, if any 891 File[] dirs = mExternalFilesDirs; 892 if (type != null) { 893 dirs = Environment.buildPaths(dirs, type); 894 } 895 896 // Create dirs if needed 897 return ensureDirsExistOrFilter(dirs); 898 } 899 } 900 901 @Override 902 public File getObbDir() { 903 // Operates on primary external storage 904 return getObbDirs()[0]; 905 } 906 907 @Override 908 public File[] getObbDirs() { 909 synchronized (mSync) { 910 if (mExternalObbDirs == null) { 911 mExternalObbDirs = Environment.buildExternalStorageAppObbDirs(getPackageName()); 912 } 913 914 // Create dirs if needed 915 return ensureDirsExistOrFilter(mExternalObbDirs); 916 } 917 } 918 919 @Override 920 public File getCacheDir() { 921 synchronized (mSync) { 922 if (mCacheDir == null) { 923 mCacheDir = new File(getDataDirFile(), "cache"); 924 } 925 if (!mCacheDir.exists()) { 926 if(!mCacheDir.mkdirs()) { 927 if (mCacheDir.exists()) { 928 // spurious failure; probably racing with another process for this app 929 return mCacheDir; 930 } 931 Log.w(TAG, "Unable to create cache directory " + mCacheDir.getAbsolutePath()); 932 return null; 933 } 934 FileUtils.setPermissions( 935 mCacheDir.getPath(), 936 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, 937 -1, -1); 938 } 939 } 940 return mCacheDir; 941 } 942 943 @Override 944 public File getExternalCacheDir() { 945 // Operates on primary external storage 946 return getExternalCacheDirs()[0]; 947 } 948 949 @Override 950 public File[] getExternalCacheDirs() { 951 synchronized (mSync) { 952 if (mExternalCacheDirs == null) { 953 mExternalCacheDirs = Environment.buildExternalStorageAppCacheDirs(getPackageName()); 954 } 955 956 // Create dirs if needed 957 return ensureDirsExistOrFilter(mExternalCacheDirs); 958 } 959 } 960 961 @Override 962 public File getFileStreamPath(String name) { 963 return makeFilename(getFilesDir(), name); 964 } 965 966 @Override 967 public String[] fileList() { 968 final String[] list = getFilesDir().list(); 969 return (list != null) ? list : EMPTY_FILE_LIST; 970 } 971 972 @Override 973 public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory) { 974 return openOrCreateDatabase(name, mode, factory, null); 975 } 976 977 @Override 978 public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory, 979 DatabaseErrorHandler errorHandler) { 980 File f = validateFilePath(name, true); 981 int flags = SQLiteDatabase.CREATE_IF_NECESSARY; 982 if ((mode & MODE_ENABLE_WRITE_AHEAD_LOGGING) != 0) { 983 flags |= SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING; 984 } 985 SQLiteDatabase db = SQLiteDatabase.openDatabase(f.getPath(), factory, flags, errorHandler); 986 setFilePermissionsFromMode(f.getPath(), mode, 0); 987 return db; 988 } 989 990 @Override 991 public boolean deleteDatabase(String name) { 992 try { 993 File f = validateFilePath(name, false); 994 return SQLiteDatabase.deleteDatabase(f); 995 } catch (Exception e) { 996 } 997 return false; 998 } 999 1000 @Override 1001 public File getDatabasePath(String name) { 1002 return validateFilePath(name, false); 1003 } 1004 1005 @Override 1006 public String[] databaseList() { 1007 final String[] list = getDatabasesDir().list(); 1008 return (list != null) ? list : EMPTY_FILE_LIST; 1009 } 1010 1011 1012 private File getDatabasesDir() { 1013 synchronized (mSync) { 1014 if (mDatabasesDir == null) { 1015 mDatabasesDir = new File(getDataDirFile(), "databases"); 1016 } 1017 if (mDatabasesDir.getPath().equals("databases")) { 1018 mDatabasesDir = new File("/data/system"); 1019 } 1020 return mDatabasesDir; 1021 } 1022 } 1023 1024 @Override 1025 public Drawable getWallpaper() { 1026 return getWallpaperManager().getDrawable(); 1027 } 1028 1029 @Override 1030 public Drawable peekWallpaper() { 1031 return getWallpaperManager().peekDrawable(); 1032 } 1033 1034 @Override 1035 public int getWallpaperDesiredMinimumWidth() { 1036 return getWallpaperManager().getDesiredMinimumWidth(); 1037 } 1038 1039 @Override 1040 public int getWallpaperDesiredMinimumHeight() { 1041 return getWallpaperManager().getDesiredMinimumHeight(); 1042 } 1043 1044 @Override 1045 public void setWallpaper(Bitmap bitmap) throws IOException { 1046 getWallpaperManager().setBitmap(bitmap); 1047 } 1048 1049 @Override 1050 public void setWallpaper(InputStream data) throws IOException { 1051 getWallpaperManager().setStream(data); 1052 } 1053 1054 @Override 1055 public void clearWallpaper() throws IOException { 1056 getWallpaperManager().clear(); 1057 } 1058 1059 @Override 1060 public void startActivity(Intent intent) { 1061 warnIfCallingFromSystemProcess(); 1062 startActivity(intent, null); 1063 } 1064 1065 /** @hide */ 1066 @Override 1067 public void startActivityAsUser(Intent intent, UserHandle user) { 1068 startActivityAsUser(intent, null, user); 1069 } 1070 1071 @Override 1072 public void startActivity(Intent intent, Bundle options) { 1073 warnIfCallingFromSystemProcess(); 1074 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) { 1075 throw new AndroidRuntimeException( 1076 "Calling startActivity() from outside of an Activity " 1077 + " context requires the FLAG_ACTIVITY_NEW_TASK flag." 1078 + " Is this really what you want?"); 1079 } 1080 mMainThread.getInstrumentation().execStartActivity( 1081 getOuterContext(), mMainThread.getApplicationThread(), null, 1082 (Activity)null, intent, -1, options); 1083 } 1084 1085 /** @hide */ 1086 @Override 1087 public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) { 1088 try { 1089 ActivityManagerNative.getDefault().startActivityAsUser( 1090 mMainThread.getApplicationThread(), getBasePackageName(), intent, 1091 intent.resolveTypeIfNeeded(getContentResolver()), 1092 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, null, options, 1093 user.getIdentifier()); 1094 } catch (RemoteException re) { 1095 } 1096 } 1097 1098 @Override 1099 public void startActivities(Intent[] intents) { 1100 warnIfCallingFromSystemProcess(); 1101 startActivities(intents, null); 1102 } 1103 1104 /** @hide */ 1105 @Override 1106 public void startActivitiesAsUser(Intent[] intents, Bundle options, UserHandle userHandle) { 1107 if ((intents[0].getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) { 1108 throw new AndroidRuntimeException( 1109 "Calling startActivities() from outside of an Activity " 1110 + " context requires the FLAG_ACTIVITY_NEW_TASK flag on first Intent." 1111 + " Is this really what you want?"); 1112 } 1113 mMainThread.getInstrumentation().execStartActivitiesAsUser( 1114 getOuterContext(), mMainThread.getApplicationThread(), null, 1115 (Activity)null, intents, options, userHandle.getIdentifier()); 1116 } 1117 1118 @Override 1119 public void startActivities(Intent[] intents, Bundle options) { 1120 warnIfCallingFromSystemProcess(); 1121 if ((intents[0].getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) { 1122 throw new AndroidRuntimeException( 1123 "Calling startActivities() from outside of an Activity " 1124 + " context requires the FLAG_ACTIVITY_NEW_TASK flag on first Intent." 1125 + " Is this really what you want?"); 1126 } 1127 mMainThread.getInstrumentation().execStartActivities( 1128 getOuterContext(), mMainThread.getApplicationThread(), null, 1129 (Activity)null, intents, options); 1130 } 1131 1132 @Override 1133 public void startIntentSender(IntentSender intent, 1134 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) 1135 throws IntentSender.SendIntentException { 1136 startIntentSender(intent, fillInIntent, flagsMask, flagsValues, extraFlags, null); 1137 } 1138 1139 @Override 1140 public void startIntentSender(IntentSender intent, Intent fillInIntent, 1141 int flagsMask, int flagsValues, int extraFlags, Bundle options) 1142 throws IntentSender.SendIntentException { 1143 try { 1144 String resolvedType = null; 1145 if (fillInIntent != null) { 1146 fillInIntent.migrateExtraStreamToClipData(); 1147 fillInIntent.prepareToLeaveProcess(); 1148 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver()); 1149 } 1150 int result = ActivityManagerNative.getDefault() 1151 .startActivityIntentSender(mMainThread.getApplicationThread(), intent, 1152 fillInIntent, resolvedType, null, null, 1153 0, flagsMask, flagsValues, options); 1154 if (result == ActivityManager.START_CANCELED) { 1155 throw new IntentSender.SendIntentException(); 1156 } 1157 Instrumentation.checkStartActivityResult(result, null); 1158 } catch (RemoteException e) { 1159 } 1160 } 1161 1162 @Override 1163 public void sendBroadcast(Intent intent) { 1164 warnIfCallingFromSystemProcess(); 1165 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1166 try { 1167 intent.prepareToLeaveProcess(); 1168 ActivityManagerNative.getDefault().broadcastIntent( 1169 mMainThread.getApplicationThread(), intent, resolvedType, null, 1170 Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, false, false, 1171 getUserId()); 1172 } catch (RemoteException e) { 1173 } 1174 } 1175 1176 @Override 1177 public void sendBroadcast(Intent intent, String receiverPermission) { 1178 warnIfCallingFromSystemProcess(); 1179 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1180 try { 1181 intent.prepareToLeaveProcess(); 1182 ActivityManagerNative.getDefault().broadcastIntent( 1183 mMainThread.getApplicationThread(), intent, resolvedType, null, 1184 Activity.RESULT_OK, null, null, receiverPermission, AppOpsManager.OP_NONE, 1185 false, false, getUserId()); 1186 } catch (RemoteException e) { 1187 } 1188 } 1189 1190 @Override 1191 public void sendBroadcast(Intent intent, String receiverPermission, int appOp) { 1192 warnIfCallingFromSystemProcess(); 1193 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1194 try { 1195 intent.prepareToLeaveProcess(); 1196 ActivityManagerNative.getDefault().broadcastIntent( 1197 mMainThread.getApplicationThread(), intent, resolvedType, null, 1198 Activity.RESULT_OK, null, null, receiverPermission, appOp, false, false, 1199 getUserId()); 1200 } catch (RemoteException e) { 1201 } 1202 } 1203 1204 @Override 1205 public void sendOrderedBroadcast(Intent intent, 1206 String receiverPermission) { 1207 warnIfCallingFromSystemProcess(); 1208 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1209 try { 1210 intent.prepareToLeaveProcess(); 1211 ActivityManagerNative.getDefault().broadcastIntent( 1212 mMainThread.getApplicationThread(), intent, resolvedType, null, 1213 Activity.RESULT_OK, null, null, receiverPermission, AppOpsManager.OP_NONE, true, false, 1214 getUserId()); 1215 } catch (RemoteException e) { 1216 } 1217 } 1218 1219 @Override 1220 public void sendOrderedBroadcast(Intent intent, 1221 String receiverPermission, BroadcastReceiver resultReceiver, 1222 Handler scheduler, int initialCode, String initialData, 1223 Bundle initialExtras) { 1224 sendOrderedBroadcast(intent, receiverPermission, AppOpsManager.OP_NONE, 1225 resultReceiver, scheduler, initialCode, initialData, initialExtras); 1226 } 1227 1228 @Override 1229 public void sendOrderedBroadcast(Intent intent, 1230 String receiverPermission, int appOp, BroadcastReceiver resultReceiver, 1231 Handler scheduler, int initialCode, String initialData, 1232 Bundle initialExtras) { 1233 warnIfCallingFromSystemProcess(); 1234 IIntentReceiver rd = null; 1235 if (resultReceiver != null) { 1236 if (mPackageInfo != null) { 1237 if (scheduler == null) { 1238 scheduler = mMainThread.getHandler(); 1239 } 1240 rd = mPackageInfo.getReceiverDispatcher( 1241 resultReceiver, getOuterContext(), scheduler, 1242 mMainThread.getInstrumentation(), false); 1243 } else { 1244 if (scheduler == null) { 1245 scheduler = mMainThread.getHandler(); 1246 } 1247 rd = new LoadedApk.ReceiverDispatcher( 1248 resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver(); 1249 } 1250 } 1251 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1252 try { 1253 intent.prepareToLeaveProcess(); 1254 ActivityManagerNative.getDefault().broadcastIntent( 1255 mMainThread.getApplicationThread(), intent, resolvedType, rd, 1256 initialCode, initialData, initialExtras, receiverPermission, appOp, 1257 true, false, getUserId()); 1258 } catch (RemoteException e) { 1259 } 1260 } 1261 1262 @Override 1263 public void sendBroadcastAsUser(Intent intent, UserHandle user) { 1264 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1265 try { 1266 intent.prepareToLeaveProcess(); 1267 ActivityManagerNative.getDefault().broadcastIntent(mMainThread.getApplicationThread(), 1268 intent, resolvedType, null, Activity.RESULT_OK, null, null, null, 1269 AppOpsManager.OP_NONE, false, false, user.getIdentifier()); 1270 } catch (RemoteException e) { 1271 } 1272 } 1273 1274 @Override 1275 public void sendBroadcastAsUser(Intent intent, UserHandle user, 1276 String receiverPermission) { 1277 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1278 try { 1279 intent.prepareToLeaveProcess(); 1280 ActivityManagerNative.getDefault().broadcastIntent( 1281 mMainThread.getApplicationThread(), intent, resolvedType, null, 1282 Activity.RESULT_OK, null, null, receiverPermission, AppOpsManager.OP_NONE, false, false, 1283 user.getIdentifier()); 1284 } catch (RemoteException e) { 1285 } 1286 } 1287 1288 @Override 1289 public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user, 1290 String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, 1291 int initialCode, String initialData, Bundle initialExtras) { 1292 IIntentReceiver rd = null; 1293 if (resultReceiver != null) { 1294 if (mPackageInfo != null) { 1295 if (scheduler == null) { 1296 scheduler = mMainThread.getHandler(); 1297 } 1298 rd = mPackageInfo.getReceiverDispatcher( 1299 resultReceiver, getOuterContext(), scheduler, 1300 mMainThread.getInstrumentation(), false); 1301 } else { 1302 if (scheduler == null) { 1303 scheduler = mMainThread.getHandler(); 1304 } 1305 rd = new LoadedApk.ReceiverDispatcher( 1306 resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver(); 1307 } 1308 } 1309 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1310 try { 1311 intent.prepareToLeaveProcess(); 1312 ActivityManagerNative.getDefault().broadcastIntent( 1313 mMainThread.getApplicationThread(), intent, resolvedType, rd, 1314 initialCode, initialData, initialExtras, receiverPermission, 1315 AppOpsManager.OP_NONE, true, false, user.getIdentifier()); 1316 } catch (RemoteException e) { 1317 } 1318 } 1319 1320 @Override 1321 public void sendStickyBroadcast(Intent intent) { 1322 warnIfCallingFromSystemProcess(); 1323 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1324 try { 1325 intent.prepareToLeaveProcess(); 1326 ActivityManagerNative.getDefault().broadcastIntent( 1327 mMainThread.getApplicationThread(), intent, resolvedType, null, 1328 Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, false, true, 1329 getUserId()); 1330 } catch (RemoteException e) { 1331 } 1332 } 1333 1334 @Override 1335 public void sendStickyOrderedBroadcast(Intent intent, 1336 BroadcastReceiver resultReceiver, 1337 Handler scheduler, int initialCode, String initialData, 1338 Bundle initialExtras) { 1339 warnIfCallingFromSystemProcess(); 1340 IIntentReceiver rd = null; 1341 if (resultReceiver != null) { 1342 if (mPackageInfo != null) { 1343 if (scheduler == null) { 1344 scheduler = mMainThread.getHandler(); 1345 } 1346 rd = mPackageInfo.getReceiverDispatcher( 1347 resultReceiver, getOuterContext(), scheduler, 1348 mMainThread.getInstrumentation(), false); 1349 } else { 1350 if (scheduler == null) { 1351 scheduler = mMainThread.getHandler(); 1352 } 1353 rd = new LoadedApk.ReceiverDispatcher( 1354 resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver(); 1355 } 1356 } 1357 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1358 try { 1359 intent.prepareToLeaveProcess(); 1360 ActivityManagerNative.getDefault().broadcastIntent( 1361 mMainThread.getApplicationThread(), intent, resolvedType, rd, 1362 initialCode, initialData, initialExtras, null, 1363 AppOpsManager.OP_NONE, true, true, getUserId()); 1364 } catch (RemoteException e) { 1365 } 1366 } 1367 1368 @Override 1369 public void removeStickyBroadcast(Intent intent) { 1370 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1371 if (resolvedType != null) { 1372 intent = new Intent(intent); 1373 intent.setDataAndType(intent.getData(), resolvedType); 1374 } 1375 try { 1376 intent.prepareToLeaveProcess(); 1377 ActivityManagerNative.getDefault().unbroadcastIntent( 1378 mMainThread.getApplicationThread(), intent, getUserId()); 1379 } catch (RemoteException e) { 1380 } 1381 } 1382 1383 @Override 1384 public void sendStickyBroadcastAsUser(Intent intent, UserHandle user) { 1385 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1386 try { 1387 intent.prepareToLeaveProcess(); 1388 ActivityManagerNative.getDefault().broadcastIntent( 1389 mMainThread.getApplicationThread(), intent, resolvedType, null, 1390 Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, false, true, user.getIdentifier()); 1391 } catch (RemoteException e) { 1392 } 1393 } 1394 1395 @Override 1396 public void sendStickyOrderedBroadcastAsUser(Intent intent, 1397 UserHandle user, BroadcastReceiver resultReceiver, 1398 Handler scheduler, int initialCode, String initialData, 1399 Bundle initialExtras) { 1400 IIntentReceiver rd = null; 1401 if (resultReceiver != null) { 1402 if (mPackageInfo != null) { 1403 if (scheduler == null) { 1404 scheduler = mMainThread.getHandler(); 1405 } 1406 rd = mPackageInfo.getReceiverDispatcher( 1407 resultReceiver, getOuterContext(), scheduler, 1408 mMainThread.getInstrumentation(), false); 1409 } else { 1410 if (scheduler == null) { 1411 scheduler = mMainThread.getHandler(); 1412 } 1413 rd = new LoadedApk.ReceiverDispatcher( 1414 resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver(); 1415 } 1416 } 1417 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1418 try { 1419 intent.prepareToLeaveProcess(); 1420 ActivityManagerNative.getDefault().broadcastIntent( 1421 mMainThread.getApplicationThread(), intent, resolvedType, rd, 1422 initialCode, initialData, initialExtras, null, 1423 AppOpsManager.OP_NONE, true, true, user.getIdentifier()); 1424 } catch (RemoteException e) { 1425 } 1426 } 1427 1428 @Override 1429 public void removeStickyBroadcastAsUser(Intent intent, UserHandle user) { 1430 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1431 if (resolvedType != null) { 1432 intent = new Intent(intent); 1433 intent.setDataAndType(intent.getData(), resolvedType); 1434 } 1435 try { 1436 intent.prepareToLeaveProcess(); 1437 ActivityManagerNative.getDefault().unbroadcastIntent( 1438 mMainThread.getApplicationThread(), intent, user.getIdentifier()); 1439 } catch (RemoteException e) { 1440 } 1441 } 1442 1443 @Override 1444 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) { 1445 return registerReceiver(receiver, filter, null, null); 1446 } 1447 1448 @Override 1449 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, 1450 String broadcastPermission, Handler scheduler) { 1451 return registerReceiverInternal(receiver, getUserId(), 1452 filter, broadcastPermission, scheduler, getOuterContext()); 1453 } 1454 1455 @Override 1456 public Intent registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user, 1457 IntentFilter filter, String broadcastPermission, Handler scheduler) { 1458 return registerReceiverInternal(receiver, user.getIdentifier(), 1459 filter, broadcastPermission, scheduler, getOuterContext()); 1460 } 1461 1462 private Intent registerReceiverInternal(BroadcastReceiver receiver, int userId, 1463 IntentFilter filter, String broadcastPermission, 1464 Handler scheduler, Context context) { 1465 IIntentReceiver rd = null; 1466 if (receiver != null) { 1467 if (mPackageInfo != null && context != null) { 1468 if (scheduler == null) { 1469 scheduler = mMainThread.getHandler(); 1470 } 1471 rd = mPackageInfo.getReceiverDispatcher( 1472 receiver, context, scheduler, 1473 mMainThread.getInstrumentation(), true); 1474 } else { 1475 if (scheduler == null) { 1476 scheduler = mMainThread.getHandler(); 1477 } 1478 rd = new LoadedApk.ReceiverDispatcher( 1479 receiver, context, scheduler, null, true).getIIntentReceiver(); 1480 } 1481 } 1482 try { 1483 return ActivityManagerNative.getDefault().registerReceiver( 1484 mMainThread.getApplicationThread(), mBasePackageName, 1485 rd, filter, broadcastPermission, userId); 1486 } catch (RemoteException e) { 1487 return null; 1488 } 1489 } 1490 1491 @Override 1492 public void unregisterReceiver(BroadcastReceiver receiver) { 1493 if (mPackageInfo != null) { 1494 IIntentReceiver rd = mPackageInfo.forgetReceiverDispatcher( 1495 getOuterContext(), receiver); 1496 try { 1497 ActivityManagerNative.getDefault().unregisterReceiver(rd); 1498 } catch (RemoteException e) { 1499 } 1500 } else { 1501 throw new RuntimeException("Not supported in system context"); 1502 } 1503 } 1504 1505 private void validateServiceIntent(Intent service) { 1506 if (service.getComponent() == null && service.getPackage() == null) { 1507 if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.L) { 1508 IllegalArgumentException ex = new IllegalArgumentException( 1509 "Service Intent must be explicit: " + service); 1510 throw ex; 1511 } else { 1512 Log.w(TAG, "Implicit intents with startService are not safe: " + service 1513 + " " + Debug.getCallers(2, 3)); 1514 } 1515 } 1516 } 1517 1518 @Override 1519 public ComponentName startService(Intent service) { 1520 warnIfCallingFromSystemProcess(); 1521 return startServiceCommon(service, mUser); 1522 } 1523 1524 @Override 1525 public boolean stopService(Intent service) { 1526 warnIfCallingFromSystemProcess(); 1527 return stopServiceCommon(service, mUser); 1528 } 1529 1530 @Override 1531 public ComponentName startServiceAsUser(Intent service, UserHandle user) { 1532 return startServiceCommon(service, user); 1533 } 1534 1535 private ComponentName startServiceCommon(Intent service, UserHandle user) { 1536 try { 1537 validateServiceIntent(service); 1538 service.prepareToLeaveProcess(); 1539 ComponentName cn = ActivityManagerNative.getDefault().startService( 1540 mMainThread.getApplicationThread(), service, 1541 service.resolveTypeIfNeeded(getContentResolver()), user.getIdentifier()); 1542 if (cn != null) { 1543 if (cn.getPackageName().equals("!")) { 1544 throw new SecurityException( 1545 "Not allowed to start service " + service 1546 + " without permission " + cn.getClassName()); 1547 } else if (cn.getPackageName().equals("!!")) { 1548 throw new SecurityException( 1549 "Unable to start service " + service 1550 + ": " + cn.getClassName()); 1551 } 1552 } 1553 return cn; 1554 } catch (RemoteException e) { 1555 return null; 1556 } 1557 } 1558 1559 @Override 1560 public boolean stopServiceAsUser(Intent service, UserHandle user) { 1561 return stopServiceCommon(service, user); 1562 } 1563 1564 private boolean stopServiceCommon(Intent service, UserHandle user) { 1565 try { 1566 validateServiceIntent(service); 1567 service.prepareToLeaveProcess(); 1568 int res = ActivityManagerNative.getDefault().stopService( 1569 mMainThread.getApplicationThread(), service, 1570 service.resolveTypeIfNeeded(getContentResolver()), user.getIdentifier()); 1571 if (res < 0) { 1572 throw new SecurityException( 1573 "Not allowed to stop service " + service); 1574 } 1575 return res != 0; 1576 } catch (RemoteException e) { 1577 return false; 1578 } 1579 } 1580 1581 @Override 1582 public boolean bindService(Intent service, ServiceConnection conn, 1583 int flags) { 1584 warnIfCallingFromSystemProcess(); 1585 return bindServiceCommon(service, conn, flags, Process.myUserHandle()); 1586 } 1587 1588 /** @hide */ 1589 @Override 1590 public boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags, 1591 UserHandle user) { 1592 return bindServiceCommon(service, conn, flags, user); 1593 } 1594 1595 private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags, 1596 UserHandle user) { 1597 IServiceConnection sd; 1598 if (conn == null) { 1599 throw new IllegalArgumentException("connection is null"); 1600 } 1601 if (mPackageInfo != null) { 1602 sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), 1603 mMainThread.getHandler(), flags); 1604 } else { 1605 throw new RuntimeException("Not supported in system context"); 1606 } 1607 validateServiceIntent(service); 1608 try { 1609 IBinder token = getActivityToken(); 1610 if (token == null && (flags&BIND_AUTO_CREATE) == 0 && mPackageInfo != null 1611 && mPackageInfo.getApplicationInfo().targetSdkVersion 1612 < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 1613 flags |= BIND_WAIVE_PRIORITY; 1614 } 1615 service.prepareToLeaveProcess(); 1616 int res = ActivityManagerNative.getDefault().bindService( 1617 mMainThread.getApplicationThread(), getActivityToken(), 1618 service, service.resolveTypeIfNeeded(getContentResolver()), 1619 sd, flags, user.getIdentifier()); 1620 if (res < 0) { 1621 throw new SecurityException( 1622 "Not allowed to bind to service " + service); 1623 } 1624 return res != 0; 1625 } catch (RemoteException e) { 1626 return false; 1627 } 1628 } 1629 1630 @Override 1631 public void unbindService(ServiceConnection conn) { 1632 if (conn == null) { 1633 throw new IllegalArgumentException("connection is null"); 1634 } 1635 if (mPackageInfo != null) { 1636 IServiceConnection sd = mPackageInfo.forgetServiceDispatcher( 1637 getOuterContext(), conn); 1638 try { 1639 ActivityManagerNative.getDefault().unbindService(sd); 1640 } catch (RemoteException e) { 1641 } 1642 } else { 1643 throw new RuntimeException("Not supported in system context"); 1644 } 1645 } 1646 1647 @Override 1648 public boolean startInstrumentation(ComponentName className, 1649 String profileFile, Bundle arguments) { 1650 try { 1651 if (arguments != null) { 1652 arguments.setAllowFds(false); 1653 } 1654 return ActivityManagerNative.getDefault().startInstrumentation( 1655 className, profileFile, 0, arguments, null, null, getUserId()); 1656 } catch (RemoteException e) { 1657 // System has crashed, nothing we can do. 1658 } 1659 return false; 1660 } 1661 1662 @Override 1663 public Object getSystemService(String name) { 1664 ServiceFetcher fetcher = SYSTEM_SERVICE_MAP.get(name); 1665 return fetcher == null ? null : fetcher.getService(this); 1666 } 1667 1668 private WallpaperManager getWallpaperManager() { 1669 return (WallpaperManager) WALLPAPER_FETCHER.getService(this); 1670 } 1671 1672 /* package */ static DropBoxManager createDropBoxManager() { 1673 IBinder b = ServiceManager.getService(DROPBOX_SERVICE); 1674 IDropBoxManagerService service = IDropBoxManagerService.Stub.asInterface(b); 1675 if (service == null) { 1676 // Don't return a DropBoxManager that will NPE upon use. 1677 // This also avoids caching a broken DropBoxManager in 1678 // getDropBoxManager during early boot, before the 1679 // DROPBOX_SERVICE is registered. 1680 return null; 1681 } 1682 return new DropBoxManager(service); 1683 } 1684 1685 @Override 1686 public int checkPermission(String permission, int pid, int uid) { 1687 if (permission == null) { 1688 throw new IllegalArgumentException("permission is null"); 1689 } 1690 1691 try { 1692 return ActivityManagerNative.getDefault().checkPermission( 1693 permission, pid, uid); 1694 } catch (RemoteException e) { 1695 return PackageManager.PERMISSION_DENIED; 1696 } 1697 } 1698 1699 @Override 1700 public int checkCallingPermission(String permission) { 1701 if (permission == null) { 1702 throw new IllegalArgumentException("permission is null"); 1703 } 1704 1705 int pid = Binder.getCallingPid(); 1706 if (pid != Process.myPid()) { 1707 return checkPermission(permission, pid, Binder.getCallingUid()); 1708 } 1709 return PackageManager.PERMISSION_DENIED; 1710 } 1711 1712 @Override 1713 public int checkCallingOrSelfPermission(String permission) { 1714 if (permission == null) { 1715 throw new IllegalArgumentException("permission is null"); 1716 } 1717 1718 return checkPermission(permission, Binder.getCallingPid(), 1719 Binder.getCallingUid()); 1720 } 1721 1722 private void enforce( 1723 String permission, int resultOfCheck, 1724 boolean selfToo, int uid, String message) { 1725 if (resultOfCheck != PackageManager.PERMISSION_GRANTED) { 1726 throw new SecurityException( 1727 (message != null ? (message + ": ") : "") + 1728 (selfToo 1729 ? "Neither user " + uid + " nor current process has " 1730 : "uid " + uid + " does not have ") + 1731 permission + 1732 "."); 1733 } 1734 } 1735 1736 public void enforcePermission( 1737 String permission, int pid, int uid, String message) { 1738 enforce(permission, 1739 checkPermission(permission, pid, uid), 1740 false, 1741 uid, 1742 message); 1743 } 1744 1745 public void enforceCallingPermission(String permission, String message) { 1746 enforce(permission, 1747 checkCallingPermission(permission), 1748 false, 1749 Binder.getCallingUid(), 1750 message); 1751 } 1752 1753 public void enforceCallingOrSelfPermission( 1754 String permission, String message) { 1755 enforce(permission, 1756 checkCallingOrSelfPermission(permission), 1757 true, 1758 Binder.getCallingUid(), 1759 message); 1760 } 1761 1762 @Override 1763 public void grantUriPermission(String toPackage, Uri uri, int modeFlags) { 1764 try { 1765 ActivityManagerNative.getDefault().grantUriPermission( 1766 mMainThread.getApplicationThread(), toPackage, uri, 1767 modeFlags); 1768 } catch (RemoteException e) { 1769 } 1770 } 1771 1772 @Override 1773 public void revokeUriPermission(Uri uri, int modeFlags) { 1774 try { 1775 ActivityManagerNative.getDefault().revokeUriPermission( 1776 mMainThread.getApplicationThread(), uri, 1777 modeFlags); 1778 } catch (RemoteException e) { 1779 } 1780 } 1781 1782 @Override 1783 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) { 1784 try { 1785 return ActivityManagerNative.getDefault().checkUriPermission( 1786 uri, pid, uid, modeFlags); 1787 } catch (RemoteException e) { 1788 return PackageManager.PERMISSION_DENIED; 1789 } 1790 } 1791 1792 @Override 1793 public int checkCallingUriPermission(Uri uri, int modeFlags) { 1794 int pid = Binder.getCallingPid(); 1795 if (pid != Process.myPid()) { 1796 return checkUriPermission(uri, pid, 1797 Binder.getCallingUid(), modeFlags); 1798 } 1799 return PackageManager.PERMISSION_DENIED; 1800 } 1801 1802 @Override 1803 public int checkCallingOrSelfUriPermission(Uri uri, int modeFlags) { 1804 return checkUriPermission(uri, Binder.getCallingPid(), 1805 Binder.getCallingUid(), modeFlags); 1806 } 1807 1808 @Override 1809 public int checkUriPermission(Uri uri, String readPermission, 1810 String writePermission, int pid, int uid, int modeFlags) { 1811 if (DEBUG) { 1812 Log.i("foo", "checkUriPermission: uri=" + uri + "readPermission=" 1813 + readPermission + " writePermission=" + writePermission 1814 + " pid=" + pid + " uid=" + uid + " mode" + modeFlags); 1815 } 1816 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) { 1817 if (readPermission == null 1818 || checkPermission(readPermission, pid, uid) 1819 == PackageManager.PERMISSION_GRANTED) { 1820 return PackageManager.PERMISSION_GRANTED; 1821 } 1822 } 1823 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) { 1824 if (writePermission == null 1825 || checkPermission(writePermission, pid, uid) 1826 == PackageManager.PERMISSION_GRANTED) { 1827 return PackageManager.PERMISSION_GRANTED; 1828 } 1829 } 1830 return uri != null ? checkUriPermission(uri, pid, uid, modeFlags) 1831 : PackageManager.PERMISSION_DENIED; 1832 } 1833 1834 private String uriModeFlagToString(int uriModeFlags) { 1835 switch (uriModeFlags) { 1836 case Intent.FLAG_GRANT_READ_URI_PERMISSION | 1837 Intent.FLAG_GRANT_WRITE_URI_PERMISSION: 1838 return "read and write"; 1839 case Intent.FLAG_GRANT_READ_URI_PERMISSION: 1840 return "read"; 1841 case Intent.FLAG_GRANT_WRITE_URI_PERMISSION: 1842 return "write"; 1843 } 1844 throw new IllegalArgumentException( 1845 "Unknown permission mode flags: " + uriModeFlags); 1846 } 1847 1848 private void enforceForUri( 1849 int modeFlags, int resultOfCheck, boolean selfToo, 1850 int uid, Uri uri, String message) { 1851 if (resultOfCheck != PackageManager.PERMISSION_GRANTED) { 1852 throw new SecurityException( 1853 (message != null ? (message + ": ") : "") + 1854 (selfToo 1855 ? "Neither user " + uid + " nor current process has " 1856 : "User " + uid + " does not have ") + 1857 uriModeFlagToString(modeFlags) + 1858 " permission on " + 1859 uri + 1860 "."); 1861 } 1862 } 1863 1864 public void enforceUriPermission( 1865 Uri uri, int pid, int uid, int modeFlags, String message) { 1866 enforceForUri( 1867 modeFlags, checkUriPermission(uri, pid, uid, modeFlags), 1868 false, uid, uri, message); 1869 } 1870 1871 public void enforceCallingUriPermission( 1872 Uri uri, int modeFlags, String message) { 1873 enforceForUri( 1874 modeFlags, checkCallingUriPermission(uri, modeFlags), 1875 false, 1876 Binder.getCallingUid(), uri, message); 1877 } 1878 1879 public void enforceCallingOrSelfUriPermission( 1880 Uri uri, int modeFlags, String message) { 1881 enforceForUri( 1882 modeFlags, 1883 checkCallingOrSelfUriPermission(uri, modeFlags), true, 1884 Binder.getCallingUid(), uri, message); 1885 } 1886 1887 public void enforceUriPermission( 1888 Uri uri, String readPermission, String writePermission, 1889 int pid, int uid, int modeFlags, String message) { 1890 enforceForUri(modeFlags, 1891 checkUriPermission( 1892 uri, readPermission, writePermission, pid, uid, 1893 modeFlags), 1894 false, 1895 uid, 1896 uri, 1897 message); 1898 } 1899 1900 /** 1901 * Logs a warning if the system process directly called a method such as 1902 * {@link #startService(Intent)} instead of {@link #startServiceAsUser(Intent, UserHandle)}. 1903 * The "AsUser" variants allow us to properly enforce the user's restrictions. 1904 */ 1905 private void warnIfCallingFromSystemProcess() { 1906 if (Process.myUid() == Process.SYSTEM_UID) { 1907 Slog.w(TAG, "Calling a method in the system process without a qualified user: " 1908 + Debug.getCallers(5)); 1909 } 1910 } 1911 1912 @Override 1913 public Context createPackageContext(String packageName, int flags) 1914 throws NameNotFoundException { 1915 return createPackageContextAsUser(packageName, flags, 1916 mUser != null ? mUser : Process.myUserHandle()); 1917 } 1918 1919 @Override 1920 public Context createPackageContextAsUser(String packageName, int flags, UserHandle user) 1921 throws NameNotFoundException { 1922 final boolean restricted = (flags & CONTEXT_RESTRICTED) == CONTEXT_RESTRICTED; 1923 if (packageName.equals("system") || packageName.equals("android")) { 1924 return new ContextImpl(this, mMainThread, mPackageInfo, mActivityToken, 1925 user, restricted, mDisplay, mOverrideConfiguration); 1926 } 1927 1928 LoadedApk pi = mMainThread.getPackageInfo(packageName, mResources.getCompatibilityInfo(), 1929 flags, user.getIdentifier()); 1930 if (pi != null) { 1931 ContextImpl c = new ContextImpl(this, mMainThread, pi, mActivityToken, 1932 user, restricted, mDisplay, mOverrideConfiguration); 1933 if (c.mResources != null) { 1934 return c; 1935 } 1936 } 1937 1938 // Should be a better exception. 1939 throw new PackageManager.NameNotFoundException( 1940 "Application package " + packageName + " not found"); 1941 } 1942 1943 @Override 1944 public Context createConfigurationContext(Configuration overrideConfiguration) { 1945 if (overrideConfiguration == null) { 1946 throw new IllegalArgumentException("overrideConfiguration must not be null"); 1947 } 1948 1949 return new ContextImpl(this, mMainThread, mPackageInfo, mActivityToken, 1950 mUser, mRestricted, mDisplay, overrideConfiguration); 1951 } 1952 1953 @Override 1954 public Context createDisplayContext(Display display) { 1955 if (display == null) { 1956 throw new IllegalArgumentException("display must not be null"); 1957 } 1958 1959 return new ContextImpl(this, mMainThread, mPackageInfo, mActivityToken, 1960 mUser, mRestricted, display, mOverrideConfiguration); 1961 } 1962 1963 private int getDisplayId() { 1964 return mDisplay != null ? mDisplay.getDisplayId() : Display.DEFAULT_DISPLAY; 1965 } 1966 1967 @Override 1968 public boolean isRestricted() { 1969 return mRestricted; 1970 } 1971 1972 @Override 1973 public DisplayAdjustments getDisplayAdjustments(int displayId) { 1974 return mDisplayAdjustments; 1975 } 1976 1977 private File getDataDirFile() { 1978 if (mPackageInfo != null) { 1979 return mPackageInfo.getDataDirFile(); 1980 } 1981 throw new RuntimeException("Not supported in system context"); 1982 } 1983 1984 @Override 1985 public File getDir(String name, int mode) { 1986 name = "app_" + name; 1987 File file = makeFilename(getDataDirFile(), name); 1988 if (!file.exists()) { 1989 file.mkdir(); 1990 setFilePermissionsFromMode(file.getPath(), mode, 1991 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH); 1992 } 1993 return file; 1994 } 1995 1996 /** {@hide} */ 1997 public int getUserId() { 1998 return mUser.getIdentifier(); 1999 } 2000 2001 static ContextImpl createSystemContext(ActivityThread mainThread) { 2002 LoadedApk packageInfo = new LoadedApk(mainThread); 2003 ContextImpl context = new ContextImpl(null, mainThread, 2004 packageInfo, null, null, false, null, null); 2005 context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(), 2006 context.mResourcesManager.getDisplayMetricsLocked(Display.DEFAULT_DISPLAY)); 2007 return context; 2008 } 2009 2010 static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo) { 2011 if (packageInfo == null) throw new IllegalArgumentException("packageInfo"); 2012 return new ContextImpl(null, mainThread, 2013 packageInfo, null, null, false, null, null); 2014 } 2015 2016 static ContextImpl createActivityContext(ActivityThread mainThread, 2017 LoadedApk packageInfo, IBinder activityToken) { 2018 if (packageInfo == null) throw new IllegalArgumentException("packageInfo"); 2019 if (activityToken == null) throw new IllegalArgumentException("activityInfo"); 2020 return new ContextImpl(null, mainThread, 2021 packageInfo, activityToken, null, false, null, null); 2022 } 2023 2024 private ContextImpl(ContextImpl container, ActivityThread mainThread, 2025 LoadedApk packageInfo, IBinder activityToken, UserHandle user, boolean restricted, 2026 Display display, Configuration overrideConfiguration) { 2027 mOuterContext = this; 2028 2029 mMainThread = mainThread; 2030 mActivityToken = activityToken; 2031 mRestricted = restricted; 2032 2033 if (user == null) { 2034 user = Process.myUserHandle(); 2035 } 2036 mUser = user; 2037 2038 mPackageInfo = packageInfo; 2039 mContentResolver = new ApplicationContentResolver(this, mainThread, user); 2040 mResourcesManager = ResourcesManager.getInstance(); 2041 mDisplay = display; 2042 mOverrideConfiguration = overrideConfiguration; 2043 2044 final int displayId = getDisplayId(); 2045 CompatibilityInfo compatInfo = null; 2046 if (container != null) { 2047 compatInfo = container.getDisplayAdjustments(displayId).getCompatibilityInfo(); 2048 } 2049 if (compatInfo == null && displayId == Display.DEFAULT_DISPLAY) { 2050 compatInfo = packageInfo.getCompatibilityInfo(); 2051 } 2052 mDisplayAdjustments.setCompatibilityInfo(compatInfo); 2053 mDisplayAdjustments.setActivityToken(activityToken); 2054 2055 Resources resources = packageInfo.getResources(mainThread); 2056 if (resources != null) { 2057 if (activityToken != null 2058 || displayId != Display.DEFAULT_DISPLAY 2059 || overrideConfiguration != null 2060 || (compatInfo != null && compatInfo.applicationScale 2061 != resources.getCompatibilityInfo().applicationScale)) { 2062 resources = mResourcesManager.getTopLevelResources( 2063 packageInfo.getResDir(), packageInfo.getOverlayDirs(), 2064 packageInfo.getApplicationInfo().sharedLibraryFiles, 2065 displayId, overrideConfiguration, compatInfo, activityToken); 2066 } 2067 } 2068 mResources = resources; 2069 2070 if (container != null) { 2071 mBasePackageName = container.mBasePackageName; 2072 mOpPackageName = container.mOpPackageName; 2073 } else { 2074 mBasePackageName = packageInfo.mPackageName; 2075 ApplicationInfo ainfo = packageInfo.getApplicationInfo(); 2076 if (ainfo.uid == Process.SYSTEM_UID && ainfo.uid != Process.myUid()) { 2077 // Special case: system components allow themselves to be loaded in to other 2078 // processes. For purposes of app ops, we must then consider the context as 2079 // belonging to the package of this process, not the system itself, otherwise 2080 // the package+uid verifications in app ops will fail. 2081 mOpPackageName = ActivityThread.currentPackageName(); 2082 } else { 2083 mOpPackageName = mBasePackageName; 2084 } 2085 } 2086 } 2087 2088 void installSystemApplicationInfo(ApplicationInfo info) { 2089 mPackageInfo.installSystemApplicationInfo(info); 2090 } 2091 2092 final void scheduleFinalCleanup(String who, String what) { 2093 mMainThread.scheduleContextCleanup(this, who, what); 2094 } 2095 2096 final void performFinalCleanup(String who, String what) { 2097 //Log.i(TAG, "Cleanup up context: " + this); 2098 mPackageInfo.removeContextRegistrations(getOuterContext(), who, what); 2099 } 2100 2101 final Context getReceiverRestrictedContext() { 2102 if (mReceiverRestrictedContext != null) { 2103 return mReceiverRestrictedContext; 2104 } 2105 return mReceiverRestrictedContext = new ReceiverRestrictedContext(getOuterContext()); 2106 } 2107 2108 final void setOuterContext(Context context) { 2109 mOuterContext = context; 2110 } 2111 2112 final Context getOuterContext() { 2113 return mOuterContext; 2114 } 2115 2116 final IBinder getActivityToken() { 2117 return mActivityToken; 2118 } 2119 2120 static void setFilePermissionsFromMode(String name, int mode, 2121 int extraPermissions) { 2122 int perms = FileUtils.S_IRUSR|FileUtils.S_IWUSR 2123 |FileUtils.S_IRGRP|FileUtils.S_IWGRP 2124 |extraPermissions; 2125 if ((mode&MODE_WORLD_READABLE) != 0) { 2126 perms |= FileUtils.S_IROTH; 2127 } 2128 if ((mode&MODE_WORLD_WRITEABLE) != 0) { 2129 perms |= FileUtils.S_IWOTH; 2130 } 2131 if (DEBUG) { 2132 Log.i(TAG, "File " + name + ": mode=0x" + Integer.toHexString(mode) 2133 + ", perms=0x" + Integer.toHexString(perms)); 2134 } 2135 FileUtils.setPermissions(name, perms, -1, -1); 2136 } 2137 2138 private File validateFilePath(String name, boolean createDirectory) { 2139 File dir; 2140 File f; 2141 2142 if (name.charAt(0) == File.separatorChar) { 2143 String dirPath = name.substring(0, name.lastIndexOf(File.separatorChar)); 2144 dir = new File(dirPath); 2145 name = name.substring(name.lastIndexOf(File.separatorChar)); 2146 f = new File(dir, name); 2147 } else { 2148 dir = getDatabasesDir(); 2149 f = makeFilename(dir, name); 2150 } 2151 2152 if (createDirectory && !dir.isDirectory() && dir.mkdir()) { 2153 FileUtils.setPermissions(dir.getPath(), 2154 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, 2155 -1, -1); 2156 } 2157 2158 return f; 2159 } 2160 2161 private File makeFilename(File base, String name) { 2162 if (name.indexOf(File.separatorChar) < 0) { 2163 return new File(base, name); 2164 } 2165 throw new IllegalArgumentException( 2166 "File " + name + " contains a path separator"); 2167 } 2168 2169 /** 2170 * Ensure that given directories exist, trying to create them if missing. If 2171 * unable to create, they are filtered by replacing with {@code null}. 2172 */ 2173 private File[] ensureDirsExistOrFilter(File[] dirs) { 2174 File[] result = new File[dirs.length]; 2175 for (int i = 0; i < dirs.length; i++) { 2176 File dir = dirs[i]; 2177 if (!dir.exists()) { 2178 if (!dir.mkdirs()) { 2179 // recheck existence in case of cross-process race 2180 if (!dir.exists()) { 2181 // Failing to mkdir() may be okay, since we might not have 2182 // enough permissions; ask vold to create on our behalf. 2183 final IMountService mount = IMountService.Stub.asInterface( 2184 ServiceManager.getService("mount")); 2185 int res = -1; 2186 try { 2187 res = mount.mkdirs(getPackageName(), dir.getAbsolutePath()); 2188 } catch (RemoteException e) { 2189 } 2190 if (res != 0) { 2191 Log.w(TAG, "Failed to ensure directory: " + dir); 2192 dir = null; 2193 } 2194 } 2195 } 2196 } 2197 result[i] = dir; 2198 } 2199 return result; 2200 } 2201 2202 // ---------------------------------------------------------------------- 2203 // ---------------------------------------------------------------------- 2204 // ---------------------------------------------------------------------- 2205 2206 private static final class ApplicationContentResolver extends ContentResolver { 2207 private final ActivityThread mMainThread; 2208 private final UserHandle mUser; 2209 2210 public ApplicationContentResolver( 2211 Context context, ActivityThread mainThread, UserHandle user) { 2212 super(context); 2213 mMainThread = Preconditions.checkNotNull(mainThread); 2214 mUser = Preconditions.checkNotNull(user); 2215 } 2216 2217 @Override 2218 protected IContentProvider acquireProvider(Context context, String auth) { 2219 return mMainThread.acquireProvider(context, auth, mUser.getIdentifier(), true); 2220 } 2221 2222 @Override 2223 protected IContentProvider acquireExistingProvider(Context context, String auth) { 2224 return mMainThread.acquireExistingProvider(context, auth, mUser.getIdentifier(), true); 2225 } 2226 2227 @Override 2228 public boolean releaseProvider(IContentProvider provider) { 2229 return mMainThread.releaseProvider(provider, true); 2230 } 2231 2232 @Override 2233 protected IContentProvider acquireUnstableProvider(Context c, String auth) { 2234 return mMainThread.acquireProvider(c, auth, mUser.getIdentifier(), false); 2235 } 2236 2237 @Override 2238 public boolean releaseUnstableProvider(IContentProvider icp) { 2239 return mMainThread.releaseProvider(icp, false); 2240 } 2241 2242 @Override 2243 public void unstableProviderDied(IContentProvider icp) { 2244 mMainThread.handleUnstableProviderDied(icp.asBinder(), true); 2245 } 2246 2247 @Override 2248 public void appNotRespondingViaProvider(IContentProvider icp) { 2249 mMainThread.appNotRespondingViaProvider(icp.asBinder()); 2250 } 2251 } 2252} 2253