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