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