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