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