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