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