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