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