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