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