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