ContextImpl.java revision 4120375d46091df8527bb701882e056fbb0e6b06
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.app;
18
19import com.android.internal.policy.PolicyManager;
20
21import android.bluetooth.BluetoothAdapter;
22import android.content.BroadcastReceiver;
23import android.content.ComponentName;
24import android.content.ContentResolver;
25import android.content.Context;
26import android.content.ContextWrapper;
27import android.content.IContentProvider;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.IIntentReceiver;
31import android.content.IntentSender;
32import android.content.ReceiverCallNotAllowedException;
33import android.content.ServiceConnection;
34import android.content.SharedPreferences;
35import android.content.pm.ApplicationInfo;
36import android.content.pm.IPackageManager;
37import android.content.pm.PackageManager;
38import android.content.res.AssetManager;
39import android.content.res.CompatibilityInfo;
40import android.content.res.Configuration;
41import android.content.res.Resources;
42import android.database.DatabaseErrorHandler;
43import android.database.sqlite.SQLiteDatabase;
44import android.database.sqlite.SQLiteDatabase.CursorFactory;
45import android.graphics.Bitmap;
46import android.graphics.drawable.Drawable;
47import android.hardware.ISerialManager;
48import android.hardware.SensorManager;
49import android.hardware.SerialManager;
50import android.hardware.SystemSensorManager;
51import android.hardware.display.DisplayManager;
52import android.hardware.input.IInputManager;
53import android.hardware.input.InputManager;
54import android.hardware.usb.IUsbManager;
55import android.hardware.usb.UsbManager;
56import android.location.CountryDetector;
57import android.location.ICountryDetector;
58import android.location.ILocationManager;
59import android.location.LocationManager;
60import android.media.AudioManager;
61import android.media.MediaRouter;
62import android.net.ConnectivityManager;
63import android.net.IConnectivityManager;
64import android.net.INetworkPolicyManager;
65import android.net.NetworkPolicyManager;
66import android.net.ThrottleManager;
67import android.net.IThrottleManager;
68import android.net.Uri;
69import android.net.nsd.INsdManager;
70import android.net.nsd.NsdManager;
71import android.net.wifi.IWifiManager;
72import android.net.wifi.WifiManager;
73import android.net.wifi.p2p.IWifiP2pManager;
74import android.net.wifi.p2p.WifiP2pManager;
75import android.nfc.NfcManager;
76import android.os.Binder;
77import android.os.Bundle;
78import android.os.DropBoxManager;
79import android.os.Environment;
80import android.os.FileUtils;
81import android.os.Handler;
82import android.os.IBinder;
83import android.os.IPowerManager;
84import android.os.IUserManager;
85import android.os.Looper;
86import android.os.PowerManager;
87import android.os.Process;
88import android.os.RemoteException;
89import android.os.ServiceManager;
90import android.os.UserHandle;
91import android.os.SystemVibrator;
92import android.os.UserManager;
93import android.os.storage.StorageManager;
94import android.telephony.TelephonyManager;
95import android.content.ClipboardManager;
96import android.util.AndroidRuntimeException;
97import android.util.Log;
98import android.view.CompatibilityInfoHolder;
99import android.view.ContextThemeWrapper;
100import android.view.Display;
101import android.view.WindowManagerImpl;
102import android.view.accessibility.AccessibilityManager;
103import android.view.inputmethod.InputMethodManager;
104import android.view.textservice.TextServicesManager;
105import android.accounts.AccountManager;
106import android.accounts.IAccountManager;
107import android.app.admin.DevicePolicyManager;
108import com.android.internal.os.IDropBoxManagerService;
109
110import java.io.File;
111import java.io.FileInputStream;
112import java.io.FileNotFoundException;
113import java.io.FileOutputStream;
114import java.io.IOException;
115import java.io.InputStream;
116import java.util.ArrayList;
117import java.util.HashMap;
118
119class ReceiverRestrictedContext extends ContextWrapper {
120    ReceiverRestrictedContext(Context base) {
121        super(base);
122    }
123
124    @Override
125    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
126        return registerReceiver(receiver, filter, null, null);
127    }
128
129    @Override
130    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
131            String broadcastPermission, Handler scheduler) {
132        throw new ReceiverCallNotAllowedException(
133                "IntentReceiver components are not allowed to register to receive intents");
134        //ex.fillInStackTrace();
135        //Log.e("IntentReceiver", ex.getMessage(), ex);
136        //return mContext.registerReceiver(receiver, filter, broadcastPermission,
137        //        scheduler);
138    }
139
140    @Override
141    public boolean bindService(Intent service, ServiceConnection conn, int flags) {
142        throw new ReceiverCallNotAllowedException(
143                "IntentReceiver components are not allowed to bind to services");
144        //ex.fillInStackTrace();
145        //Log.e("IntentReceiver", ex.getMessage(), ex);
146        //return mContext.bindService(service, interfaceName, conn, flags);
147    }
148}
149
150/**
151 * Common implementation of Context API, which provides the base
152 * context object for Activity and other application components.
153 */
154class ContextImpl extends Context {
155    private final static String TAG = "ApplicationContext";
156    private final static boolean DEBUG = false;
157
158    private static final HashMap<String, SharedPreferencesImpl> sSharedPrefs =
159            new HashMap<String, SharedPreferencesImpl>();
160
161    /*package*/ LoadedApk mPackageInfo;
162    private String mBasePackageName;
163    private Resources mResources;
164    /*package*/ ActivityThread mMainThread;
165    private Context mOuterContext;
166    private IBinder mActivityToken = null;
167    private ApplicationContentResolver mContentResolver;
168    private int mThemeResource = 0;
169    private Resources.Theme mTheme = null;
170    private PackageManager mPackageManager;
171    private Context mReceiverRestrictedContext = null;
172    private boolean mRestricted;
173
174    private final Object mSync = new Object();
175
176    private File mDatabasesDir;
177    private File mPreferencesDir;
178    private File mFilesDir;
179    private File mCacheDir;
180    private File mObbDir;
181    private File mExternalFilesDir;
182    private File mExternalCacheDir;
183
184    private static final String[] EMPTY_FILE_LIST = {};
185
186    /**
187     * Override this class when the system service constructor needs a
188     * ContextImpl.  Else, use StaticServiceFetcher below.
189     */
190    /*package*/ static class ServiceFetcher {
191        int mContextCacheIndex = -1;
192
193        /**
194         * Main entrypoint; only override if you don't need caching.
195         */
196        public Object getService(ContextImpl ctx) {
197            ArrayList<Object> cache = ctx.mServiceCache;
198            Object service;
199            synchronized (cache) {
200                if (cache.size() == 0) {
201                    // Initialize the cache vector on first access.
202                    // At this point sNextPerContextServiceCacheIndex
203                    // is the number of potential services that are
204                    // cached per-Context.
205                    for (int i = 0; i < sNextPerContextServiceCacheIndex; i++) {
206                        cache.add(null);
207                    }
208                } else {
209                    service = cache.get(mContextCacheIndex);
210                    if (service != null) {
211                        return service;
212                    }
213                }
214                service = createService(ctx);
215                cache.set(mContextCacheIndex, service);
216                return service;
217            }
218        }
219
220        /**
221         * Override this to create a new per-Context instance of the
222         * service.  getService() will handle locking and caching.
223         */
224        public Object createService(ContextImpl ctx) {
225            throw new RuntimeException("Not implemented");
226        }
227    }
228
229    /**
230     * Override this class for services to be cached process-wide.
231     */
232    abstract static class StaticServiceFetcher extends ServiceFetcher {
233        private Object mCachedInstance;
234
235        @Override
236        public final Object getService(ContextImpl unused) {
237            synchronized (StaticServiceFetcher.this) {
238                Object service = mCachedInstance;
239                if (service != null) {
240                    return service;
241                }
242                return mCachedInstance = createStaticService();
243            }
244        }
245
246        public abstract Object createStaticService();
247    }
248
249    private static final HashMap<String, ServiceFetcher> SYSTEM_SERVICE_MAP =
250            new HashMap<String, ServiceFetcher>();
251
252    private static int sNextPerContextServiceCacheIndex = 0;
253    private static void registerService(String serviceName, ServiceFetcher fetcher) {
254        if (!(fetcher instanceof StaticServiceFetcher)) {
255            fetcher.mContextCacheIndex = sNextPerContextServiceCacheIndex++;
256        }
257        SYSTEM_SERVICE_MAP.put(serviceName, fetcher);
258    }
259
260    // This one's defined separately and given a variable name so it
261    // can be re-used by getWallpaperManager(), avoiding a HashMap
262    // lookup.
263    private static ServiceFetcher WALLPAPER_FETCHER = new ServiceFetcher() {
264            public Object createService(ContextImpl ctx) {
265                return new WallpaperManager(ctx.getOuterContext(),
266                        ctx.mMainThread.getHandler());
267            }};
268
269    static {
270        registerService(ACCESSIBILITY_SERVICE, new ServiceFetcher() {
271                public Object getService(ContextImpl ctx) {
272                    return AccessibilityManager.getInstance(ctx);
273                }});
274
275        registerService(ACCOUNT_SERVICE, new ServiceFetcher() {
276                public Object createService(ContextImpl ctx) {
277                    IBinder b = ServiceManager.getService(ACCOUNT_SERVICE);
278                    IAccountManager service = IAccountManager.Stub.asInterface(b);
279                    return new AccountManager(ctx, service);
280                }});
281
282        registerService(ACTIVITY_SERVICE, new ServiceFetcher() {
283                public Object createService(ContextImpl ctx) {
284                    return new ActivityManager(ctx.getOuterContext(), ctx.mMainThread.getHandler());
285                }});
286
287        registerService(ALARM_SERVICE, new StaticServiceFetcher() {
288                public Object createStaticService() {
289                    IBinder b = ServiceManager.getService(ALARM_SERVICE);
290                    IAlarmManager service = IAlarmManager.Stub.asInterface(b);
291                    return new AlarmManager(service);
292                }});
293
294        registerService(AUDIO_SERVICE, new ServiceFetcher() {
295                public Object createService(ContextImpl ctx) {
296                    return new AudioManager(ctx);
297                }});
298
299        registerService(MEDIA_ROUTER_SERVICE, new ServiceFetcher() {
300                public Object createService(ContextImpl ctx) {
301                    return new MediaRouter(ctx);
302                }});
303
304        registerService(BLUETOOTH_SERVICE, new ServiceFetcher() {
305                public Object createService(ContextImpl ctx) {
306                    return BluetoothAdapter.getDefaultAdapter();
307                }});
308
309        registerService(CLIPBOARD_SERVICE, new ServiceFetcher() {
310                public Object createService(ContextImpl ctx) {
311                    return new ClipboardManager(ctx.getOuterContext(),
312                            ctx.mMainThread.getHandler());
313                }});
314
315        registerService(CONNECTIVITY_SERVICE, new StaticServiceFetcher() {
316                public Object createStaticService() {
317                    IBinder b = ServiceManager.getService(CONNECTIVITY_SERVICE);
318                    return new ConnectivityManager(IConnectivityManager.Stub.asInterface(b));
319                }});
320
321        registerService(COUNTRY_DETECTOR, new StaticServiceFetcher() {
322                public Object createStaticService() {
323                    IBinder b = ServiceManager.getService(COUNTRY_DETECTOR);
324                    return new CountryDetector(ICountryDetector.Stub.asInterface(b));
325                }});
326
327        registerService(DEVICE_POLICY_SERVICE, new ServiceFetcher() {
328                public Object createService(ContextImpl ctx) {
329                    return DevicePolicyManager.create(ctx, ctx.mMainThread.getHandler());
330                }});
331
332        registerService(DOWNLOAD_SERVICE, new ServiceFetcher() {
333                public Object createService(ContextImpl ctx) {
334                    return new DownloadManager(ctx.getContentResolver(), ctx.getPackageName());
335                }});
336
337        registerService(NFC_SERVICE, new ServiceFetcher() {
338                public Object createService(ContextImpl ctx) {
339                    return new NfcManager(ctx);
340                }});
341
342        registerService(DROPBOX_SERVICE, new StaticServiceFetcher() {
343                public Object createStaticService() {
344                    return createDropBoxManager();
345                }});
346
347        registerService(INPUT_SERVICE, new StaticServiceFetcher() {
348                public Object createStaticService() {
349                    return InputManager.getInstance();
350                }});
351
352        registerService(DISPLAY_SERVICE, new ServiceFetcher() {
353                @Override
354                public Object createService(ContextImpl ctx) {
355                    return new DisplayManager(ctx.getOuterContext());
356                }});
357
358        registerService(INPUT_METHOD_SERVICE, new ServiceFetcher() {
359                public Object createService(ContextImpl ctx) {
360                    return InputMethodManager.getInstance(ctx);
361                }});
362
363        registerService(TEXT_SERVICES_MANAGER_SERVICE, new ServiceFetcher() {
364                public Object createService(ContextImpl ctx) {
365                    return TextServicesManager.getInstance();
366                }});
367
368        registerService(KEYGUARD_SERVICE, new ServiceFetcher() {
369                public Object getService(ContextImpl ctx) {
370                    // TODO: why isn't this caching it?  It wasn't
371                    // before, so I'm preserving the old behavior and
372                    // using getService(), instead of createService()
373                    // which would do the caching.
374                    return new KeyguardManager();
375                }});
376
377        registerService(LAYOUT_INFLATER_SERVICE, new ServiceFetcher() {
378                public Object createService(ContextImpl ctx) {
379                    return PolicyManager.makeNewLayoutInflater(ctx.getOuterContext());
380                }});
381
382        registerService(LOCATION_SERVICE, new ServiceFetcher() {
383                public Object createService(ContextImpl ctx) {
384                    IBinder b = ServiceManager.getService(LOCATION_SERVICE);
385                    return new LocationManager(ctx, ILocationManager.Stub.asInterface(b));
386                }});
387
388        registerService(NETWORK_POLICY_SERVICE, new ServiceFetcher() {
389            @Override
390            public Object createService(ContextImpl ctx) {
391                return new NetworkPolicyManager(INetworkPolicyManager.Stub.asInterface(
392                        ServiceManager.getService(NETWORK_POLICY_SERVICE)));
393            }
394        });
395
396        registerService(NOTIFICATION_SERVICE, new ServiceFetcher() {
397                public Object createService(ContextImpl ctx) {
398                    final Context outerContext = ctx.getOuterContext();
399                    return new NotificationManager(
400                        new ContextThemeWrapper(outerContext,
401                                Resources.selectSystemTheme(0,
402                                        outerContext.getApplicationInfo().targetSdkVersion,
403                                        com.android.internal.R.style.Theme_Dialog,
404                                        com.android.internal.R.style.Theme_Holo_Dialog,
405                                        com.android.internal.R.style.Theme_DeviceDefault_Dialog)),
406                        ctx.mMainThread.getHandler());
407                }});
408
409        registerService(NSD_SERVICE, new ServiceFetcher() {
410                @Override
411                public Object createService(ContextImpl ctx) {
412                    IBinder b = ServiceManager.getService(NSD_SERVICE);
413                    INsdManager service = INsdManager.Stub.asInterface(b);
414                    return new NsdManager(ctx.getOuterContext(), service);
415                }});
416
417        // Note: this was previously cached in a static variable, but
418        // constructed using mMainThread.getHandler(), so converting
419        // it to be a regular Context-cached service...
420        registerService(POWER_SERVICE, new ServiceFetcher() {
421                public Object createService(ContextImpl ctx) {
422                    IBinder b = ServiceManager.getService(POWER_SERVICE);
423                    IPowerManager service = IPowerManager.Stub.asInterface(b);
424                    return new PowerManager(ctx.getOuterContext(),
425                            service, ctx.mMainThread.getHandler());
426                }});
427
428        registerService(SEARCH_SERVICE, new ServiceFetcher() {
429                public Object createService(ContextImpl ctx) {
430                    return new SearchManager(ctx.getOuterContext(),
431                            ctx.mMainThread.getHandler());
432                }});
433
434        registerService(SENSOR_SERVICE, new ServiceFetcher() {
435                public Object createService(ContextImpl ctx) {
436                    return new SystemSensorManager(ctx.mMainThread.getHandler().getLooper());
437                }});
438
439        registerService(STATUS_BAR_SERVICE, new ServiceFetcher() {
440                public Object createService(ContextImpl ctx) {
441                    return new StatusBarManager(ctx.getOuterContext());
442                }});
443
444        registerService(STORAGE_SERVICE, new ServiceFetcher() {
445                public Object createService(ContextImpl ctx) {
446                    try {
447                        return new StorageManager(ctx.mMainThread.getHandler().getLooper());
448                    } catch (RemoteException rex) {
449                        Log.e(TAG, "Failed to create StorageManager", rex);
450                        return null;
451                    }
452                }});
453
454        registerService(TELEPHONY_SERVICE, new ServiceFetcher() {
455                public Object createService(ContextImpl ctx) {
456                    return new TelephonyManager(ctx.getOuterContext());
457                }});
458
459        registerService(THROTTLE_SERVICE, new StaticServiceFetcher() {
460                public Object createStaticService() {
461                    IBinder b = ServiceManager.getService(THROTTLE_SERVICE);
462                    return new ThrottleManager(IThrottleManager.Stub.asInterface(b));
463                }});
464
465        registerService(UI_MODE_SERVICE, new ServiceFetcher() {
466                public Object createService(ContextImpl ctx) {
467                    return new UiModeManager();
468                }});
469
470        registerService(USB_SERVICE, new ServiceFetcher() {
471                public Object createService(ContextImpl ctx) {
472                    IBinder b = ServiceManager.getService(USB_SERVICE);
473                    return new UsbManager(ctx, IUsbManager.Stub.asInterface(b));
474                }});
475
476        registerService(SERIAL_SERVICE, new ServiceFetcher() {
477                public Object createService(ContextImpl ctx) {
478                    IBinder b = ServiceManager.getService(SERIAL_SERVICE);
479                    return new SerialManager(ctx, ISerialManager.Stub.asInterface(b));
480                }});
481
482        registerService(VIBRATOR_SERVICE, new ServiceFetcher() {
483                public Object createService(ContextImpl ctx) {
484                    return new SystemVibrator();
485                }});
486
487        registerService(WALLPAPER_SERVICE, WALLPAPER_FETCHER);
488
489        registerService(WIFI_SERVICE, new ServiceFetcher() {
490                public Object createService(ContextImpl ctx) {
491                    IBinder b = ServiceManager.getService(WIFI_SERVICE);
492                    IWifiManager service = IWifiManager.Stub.asInterface(b);
493                    return new WifiManager(ctx.getOuterContext(), service);
494                }});
495
496        registerService(WIFI_P2P_SERVICE, new ServiceFetcher() {
497                public Object createService(ContextImpl ctx) {
498                    IBinder b = ServiceManager.getService(WIFI_P2P_SERVICE);
499                    IWifiP2pManager service = IWifiP2pManager.Stub.asInterface(b);
500                    return new WifiP2pManager(service);
501                }});
502
503        registerService(WINDOW_SERVICE, new ServiceFetcher() {
504                public Object getService(ContextImpl ctx) {
505                    return new WindowManagerImpl(ctx.getOuterContext(),
506                            Display.DEFAULT_DISPLAY);
507                }});
508
509        registerService(USER_SERVICE, new ServiceFetcher() {
510            public Object getService(ContextImpl ctx) {
511                IBinder b = ServiceManager.getService(USER_SERVICE);
512                IUserManager service = IUserManager.Stub.asInterface(b);
513                return new UserManager(ctx, service);
514            }});
515    }
516
517    static ContextImpl getImpl(Context context) {
518        Context nextContext;
519        while ((context instanceof ContextWrapper) &&
520                (nextContext=((ContextWrapper)context).getBaseContext()) != null) {
521            context = nextContext;
522        }
523        return (ContextImpl)context;
524    }
525
526    // The system service cache for the system services that are
527    // cached per-ContextImpl.  Package-scoped to avoid accessor
528    // methods.
529    final ArrayList<Object> mServiceCache = new ArrayList<Object>();
530
531    @Override
532    public AssetManager getAssets() {
533        return getResources().getAssets();
534    }
535
536    @Override
537    public Resources getResources() {
538        return mResources;
539    }
540
541    @Override
542    public PackageManager getPackageManager() {
543        if (mPackageManager != null) {
544            return mPackageManager;
545        }
546
547        IPackageManager pm = ActivityThread.getPackageManager();
548        if (pm != null) {
549            // Doesn't matter if we make more than one instance.
550            return (mPackageManager = new ApplicationPackageManager(this, pm));
551        }
552
553        return null;
554    }
555
556    @Override
557    public ContentResolver getContentResolver() {
558        return mContentResolver;
559    }
560
561    @Override
562    public Looper getMainLooper() {
563        return mMainThread.getLooper();
564    }
565
566    @Override
567    public Context getApplicationContext() {
568        return (mPackageInfo != null) ?
569                mPackageInfo.getApplication() : mMainThread.getApplication();
570    }
571
572    @Override
573    public void setTheme(int resid) {
574        mThemeResource = resid;
575    }
576
577    @Override
578    public int getThemeResId() {
579        return mThemeResource;
580    }
581
582    @Override
583    public Resources.Theme getTheme() {
584        if (mTheme == null) {
585            mThemeResource = Resources.selectDefaultTheme(mThemeResource,
586                    getOuterContext().getApplicationInfo().targetSdkVersion);
587            mTheme = mResources.newTheme();
588            mTheme.applyStyle(mThemeResource, true);
589        }
590        return mTheme;
591    }
592
593    @Override
594    public ClassLoader getClassLoader() {
595        return mPackageInfo != null ?
596                mPackageInfo.getClassLoader() : ClassLoader.getSystemClassLoader();
597    }
598
599    @Override
600    public String getPackageName() {
601        if (mPackageInfo != null) {
602            return mPackageInfo.getPackageName();
603        }
604        throw new RuntimeException("Not supported in system context");
605    }
606
607    @Override
608    public ApplicationInfo getApplicationInfo() {
609        if (mPackageInfo != null) {
610            return mPackageInfo.getApplicationInfo();
611        }
612        throw new RuntimeException("Not supported in system context");
613    }
614
615    @Override
616    public String getPackageResourcePath() {
617        if (mPackageInfo != null) {
618            return mPackageInfo.getResDir();
619        }
620        throw new RuntimeException("Not supported in system context");
621    }
622
623    @Override
624    public String getPackageCodePath() {
625        if (mPackageInfo != null) {
626            return mPackageInfo.getAppDir();
627        }
628        throw new RuntimeException("Not supported in system context");
629    }
630
631    public File getSharedPrefsFile(String name) {
632        return makeFilename(getPreferencesDir(), name + ".xml");
633    }
634
635    @Override
636    public SharedPreferences getSharedPreferences(String name, int mode) {
637        SharedPreferencesImpl sp;
638        synchronized (sSharedPrefs) {
639            sp = sSharedPrefs.get(name);
640            if (sp == null) {
641                File prefsFile = getSharedPrefsFile(name);
642                sp = new SharedPreferencesImpl(prefsFile, mode);
643                sSharedPrefs.put(name, sp);
644                return sp;
645            }
646        }
647        if ((mode & Context.MODE_MULTI_PROCESS) != 0 ||
648            getApplicationInfo().targetSdkVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
649            // If somebody else (some other process) changed the prefs
650            // file behind our back, we reload it.  This has been the
651            // historical (if undocumented) behavior.
652            sp.startReloadIfChangedUnexpectedly();
653        }
654        return sp;
655    }
656
657    private File getPreferencesDir() {
658        synchronized (mSync) {
659            if (mPreferencesDir == null) {
660                mPreferencesDir = new File(getDataDirFile(), "shared_prefs");
661            }
662            return mPreferencesDir;
663        }
664    }
665
666    @Override
667    public FileInputStream openFileInput(String name)
668        throws FileNotFoundException {
669        File f = makeFilename(getFilesDir(), name);
670        return new FileInputStream(f);
671    }
672
673    @Override
674    public FileOutputStream openFileOutput(String name, int mode)
675        throws FileNotFoundException {
676        final boolean append = (mode&MODE_APPEND) != 0;
677        File f = makeFilename(getFilesDir(), name);
678        try {
679            FileOutputStream fos = new FileOutputStream(f, append);
680            setFilePermissionsFromMode(f.getPath(), mode, 0);
681            return fos;
682        } catch (FileNotFoundException e) {
683        }
684
685        File parent = f.getParentFile();
686        parent.mkdir();
687        FileUtils.setPermissions(
688            parent.getPath(),
689            FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
690            -1, -1);
691        FileOutputStream fos = new FileOutputStream(f, append);
692        setFilePermissionsFromMode(f.getPath(), mode, 0);
693        return fos;
694    }
695
696    @Override
697    public boolean deleteFile(String name) {
698        File f = makeFilename(getFilesDir(), name);
699        return f.delete();
700    }
701
702    @Override
703    public File getFilesDir() {
704        synchronized (mSync) {
705            if (mFilesDir == null) {
706                mFilesDir = new File(getDataDirFile(), "files");
707            }
708            if (!mFilesDir.exists()) {
709                if(!mFilesDir.mkdirs()) {
710                    Log.w(TAG, "Unable to create files directory " + mFilesDir.getPath());
711                    return null;
712                }
713                FileUtils.setPermissions(
714                        mFilesDir.getPath(),
715                        FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
716                        -1, -1);
717            }
718            return mFilesDir;
719        }
720    }
721
722    @Override
723    public File getExternalFilesDir(String type) {
724        synchronized (mSync) {
725            if (mExternalFilesDir == null) {
726                mExternalFilesDir = Environment.getExternalStorageAppFilesDirectory(
727                        getPackageName());
728            }
729            if (!mExternalFilesDir.exists()) {
730                try {
731                    (new File(Environment.getExternalStorageAndroidDataDir(),
732                            ".nomedia")).createNewFile();
733                } catch (IOException e) {
734                }
735                if (!mExternalFilesDir.mkdirs()) {
736                    Log.w(TAG, "Unable to create external files directory");
737                    return null;
738                }
739            }
740            if (type == null) {
741                return mExternalFilesDir;
742            }
743            File dir = new File(mExternalFilesDir, type);
744            if (!dir.exists()) {
745                if (!dir.mkdirs()) {
746                    Log.w(TAG, "Unable to create external media directory " + dir);
747                    return null;
748                }
749            }
750            return dir;
751        }
752    }
753
754    @Override
755    public File getObbDir() {
756        synchronized (mSync) {
757            if (mObbDir == null) {
758                mObbDir = Environment.getExternalStorageAppObbDirectory(
759                        getPackageName());
760            }
761            return mObbDir;
762        }
763    }
764
765    @Override
766    public File getCacheDir() {
767        synchronized (mSync) {
768            if (mCacheDir == null) {
769                mCacheDir = new File(getDataDirFile(), "cache");
770            }
771            if (!mCacheDir.exists()) {
772                if(!mCacheDir.mkdirs()) {
773                    Log.w(TAG, "Unable to create cache directory " + mCacheDir.getAbsolutePath());
774                    return null;
775                }
776                FileUtils.setPermissions(
777                        mCacheDir.getPath(),
778                        FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
779                        -1, -1);
780            }
781        }
782        return mCacheDir;
783    }
784
785    @Override
786    public File getExternalCacheDir() {
787        synchronized (mSync) {
788            if (mExternalCacheDir == null) {
789                mExternalCacheDir = Environment.getExternalStorageAppCacheDirectory(
790                        getPackageName());
791            }
792            if (!mExternalCacheDir.exists()) {
793                try {
794                    (new File(Environment.getExternalStorageAndroidDataDir(),
795                            ".nomedia")).createNewFile();
796                } catch (IOException e) {
797                }
798                if (!mExternalCacheDir.mkdirs()) {
799                    Log.w(TAG, "Unable to create external cache directory");
800                    return null;
801                }
802            }
803            return mExternalCacheDir;
804        }
805    }
806
807    @Override
808    public File getFileStreamPath(String name) {
809        return makeFilename(getFilesDir(), name);
810    }
811
812    @Override
813    public String[] fileList() {
814        final String[] list = getFilesDir().list();
815        return (list != null) ? list : EMPTY_FILE_LIST;
816    }
817
818    @Override
819    public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory) {
820        return openOrCreateDatabase(name, mode, factory, null);
821    }
822
823    @Override
824    public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory,
825            DatabaseErrorHandler errorHandler) {
826        File f = validateFilePath(name, true);
827        int flags = SQLiteDatabase.CREATE_IF_NECESSARY;
828        if ((mode & MODE_ENABLE_WRITE_AHEAD_LOGGING) != 0) {
829            flags |= SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING;
830        }
831        SQLiteDatabase db = SQLiteDatabase.openDatabase(f.getPath(), factory, flags, errorHandler);
832        setFilePermissionsFromMode(f.getPath(), mode, 0);
833        return db;
834    }
835
836    @Override
837    public boolean deleteDatabase(String name) {
838        try {
839            File f = validateFilePath(name, false);
840            return SQLiteDatabase.deleteDatabase(f);
841        } catch (Exception e) {
842        }
843        return false;
844    }
845
846    @Override
847    public File getDatabasePath(String name) {
848        return validateFilePath(name, false);
849    }
850
851    @Override
852    public String[] databaseList() {
853        final String[] list = getDatabasesDir().list();
854        return (list != null) ? list : EMPTY_FILE_LIST;
855    }
856
857
858    private File getDatabasesDir() {
859        synchronized (mSync) {
860            if (mDatabasesDir == null) {
861                mDatabasesDir = new File(getDataDirFile(), "databases");
862            }
863            if (mDatabasesDir.getPath().equals("databases")) {
864                mDatabasesDir = new File("/data/system");
865            }
866            return mDatabasesDir;
867        }
868    }
869
870    @Override
871    public Drawable getWallpaper() {
872        return getWallpaperManager().getDrawable();
873    }
874
875    @Override
876    public Drawable peekWallpaper() {
877        return getWallpaperManager().peekDrawable();
878    }
879
880    @Override
881    public int getWallpaperDesiredMinimumWidth() {
882        return getWallpaperManager().getDesiredMinimumWidth();
883    }
884
885    @Override
886    public int getWallpaperDesiredMinimumHeight() {
887        return getWallpaperManager().getDesiredMinimumHeight();
888    }
889
890    @Override
891    public void setWallpaper(Bitmap bitmap) throws IOException  {
892        getWallpaperManager().setBitmap(bitmap);
893    }
894
895    @Override
896    public void setWallpaper(InputStream data) throws IOException {
897        getWallpaperManager().setStream(data);
898    }
899
900    @Override
901    public void clearWallpaper() throws IOException {
902        getWallpaperManager().clear();
903    }
904
905    @Override
906    public void startActivity(Intent intent) {
907        startActivity(intent, null);
908    }
909
910    /** @hide */
911    @Override
912    public void startActivityAsUser(Intent intent, UserHandle user) {
913        startActivityAsUser(intent, null, user);
914    }
915
916    @Override
917    public void startActivity(Intent intent, Bundle options) {
918        if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
919            throw new AndroidRuntimeException(
920                    "Calling startActivity() from outside of an Activity "
921                    + " context requires the FLAG_ACTIVITY_NEW_TASK flag."
922                    + " Is this really what you want?");
923        }
924        mMainThread.getInstrumentation().execStartActivity(
925            getOuterContext(), mMainThread.getApplicationThread(), null,
926            (Activity)null, intent, -1, options);
927    }
928
929    /** @hide */
930    @Override
931    public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) {
932        try {
933            ActivityManagerNative.getDefault().startActivityAsUser(
934                mMainThread.getApplicationThread(), intent,
935                intent.resolveTypeIfNeeded(getContentResolver()),
936                null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, null, options,
937                user.getIdentifier());
938        } catch (RemoteException re) {
939        }
940    }
941
942    @Override
943    public void startActivities(Intent[] intents) {
944        startActivities(intents, null);
945    }
946
947    @Override
948    public void startActivities(Intent[] intents, Bundle options) {
949        if ((intents[0].getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
950            throw new AndroidRuntimeException(
951                    "Calling startActivities() from outside of an Activity "
952                    + " context requires the FLAG_ACTIVITY_NEW_TASK flag on first Intent."
953                    + " Is this really what you want?");
954        }
955        mMainThread.getInstrumentation().execStartActivities(
956            getOuterContext(), mMainThread.getApplicationThread(), null,
957            (Activity)null, intents, options);
958    }
959
960    @Override
961    public void startIntentSender(IntentSender intent,
962            Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
963            throws IntentSender.SendIntentException {
964        startIntentSender(intent, fillInIntent, flagsMask, flagsValues, extraFlags, null);
965    }
966
967    @Override
968    public void startIntentSender(IntentSender intent, Intent fillInIntent,
969            int flagsMask, int flagsValues, int extraFlags, Bundle options)
970            throws IntentSender.SendIntentException {
971        try {
972            String resolvedType = null;
973            if (fillInIntent != null) {
974                fillInIntent.setAllowFds(false);
975                resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
976            }
977            int result = ActivityManagerNative.getDefault()
978                .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
979                        fillInIntent, resolvedType, null, null,
980                        0, flagsMask, flagsValues, options);
981            if (result == ActivityManager.START_CANCELED) {
982                throw new IntentSender.SendIntentException();
983            }
984            Instrumentation.checkStartActivityResult(result, null);
985        } catch (RemoteException e) {
986        }
987    }
988
989    @Override
990    public void sendBroadcast(Intent intent) {
991        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
992        try {
993            intent.setAllowFds(false);
994            ActivityManagerNative.getDefault().broadcastIntent(
995                mMainThread.getApplicationThread(), intent, resolvedType, null,
996                Activity.RESULT_OK, null, null, null, false, false,
997                UserHandle.myUserId());
998        } catch (RemoteException e) {
999        }
1000    }
1001
1002    @Override
1003    public void sendBroadcast(Intent intent, String receiverPermission) {
1004        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1005        try {
1006            intent.setAllowFds(false);
1007            ActivityManagerNative.getDefault().broadcastIntent(
1008                mMainThread.getApplicationThread(), intent, resolvedType, null,
1009                Activity.RESULT_OK, null, null, receiverPermission, false, false,
1010                UserHandle.myUserId());
1011        } catch (RemoteException e) {
1012        }
1013    }
1014
1015    @Override
1016    public void sendOrderedBroadcast(Intent intent,
1017            String receiverPermission) {
1018        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1019        try {
1020            intent.setAllowFds(false);
1021            ActivityManagerNative.getDefault().broadcastIntent(
1022                mMainThread.getApplicationThread(), intent, resolvedType, null,
1023                Activity.RESULT_OK, null, null, receiverPermission, true, false,
1024                UserHandle.myUserId());
1025        } catch (RemoteException e) {
1026        }
1027    }
1028
1029    @Override
1030    public void sendOrderedBroadcast(Intent intent,
1031            String receiverPermission, BroadcastReceiver resultReceiver,
1032            Handler scheduler, int initialCode, String initialData,
1033            Bundle initialExtras) {
1034        IIntentReceiver rd = null;
1035        if (resultReceiver != null) {
1036            if (mPackageInfo != null) {
1037                if (scheduler == null) {
1038                    scheduler = mMainThread.getHandler();
1039                }
1040                rd = mPackageInfo.getReceiverDispatcher(
1041                    resultReceiver, getOuterContext(), scheduler,
1042                    mMainThread.getInstrumentation(), false);
1043            } else {
1044                if (scheduler == null) {
1045                    scheduler = mMainThread.getHandler();
1046                }
1047                rd = new LoadedApk.ReceiverDispatcher(
1048                        resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
1049            }
1050        }
1051        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1052        try {
1053            intent.setAllowFds(false);
1054            ActivityManagerNative.getDefault().broadcastIntent(
1055                mMainThread.getApplicationThread(), intent, resolvedType, rd,
1056                initialCode, initialData, initialExtras, receiverPermission,
1057                true, false, UserHandle.myUserId());
1058        } catch (RemoteException e) {
1059        }
1060    }
1061
1062    @Override
1063    public void sendBroadcastAsUser(Intent intent, UserHandle user) {
1064        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1065        try {
1066            intent.setAllowFds(false);
1067            ActivityManagerNative.getDefault().broadcastIntent(mMainThread.getApplicationThread(),
1068                    intent, resolvedType, null, Activity.RESULT_OK, null, null, null, false, false,
1069                    user.getIdentifier());
1070        } catch (RemoteException e) {
1071        }
1072    }
1073
1074    @Override
1075    public void sendBroadcastAsUser(Intent intent, UserHandle user,
1076            String receiverPermission) {
1077        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1078        try {
1079            intent.setAllowFds(false);
1080            ActivityManagerNative.getDefault().broadcastIntent(
1081                mMainThread.getApplicationThread(), intent, resolvedType, null,
1082                Activity.RESULT_OK, null, null, receiverPermission, false, false,
1083                user.getIdentifier());
1084        } catch (RemoteException e) {
1085        }
1086    }
1087
1088    @Override
1089    public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user,
1090            String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler,
1091            int initialCode, String initialData, Bundle initialExtras) {
1092        IIntentReceiver rd = null;
1093        if (resultReceiver != null) {
1094            if (mPackageInfo != null) {
1095                if (scheduler == null) {
1096                    scheduler = mMainThread.getHandler();
1097                }
1098                rd = mPackageInfo.getReceiverDispatcher(
1099                    resultReceiver, getOuterContext(), scheduler,
1100                    mMainThread.getInstrumentation(), false);
1101            } else {
1102                if (scheduler == null) {
1103                    scheduler = mMainThread.getHandler();
1104                }
1105                rd = new LoadedApk.ReceiverDispatcher(
1106                        resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
1107            }
1108        }
1109        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1110        try {
1111            intent.setAllowFds(false);
1112            ActivityManagerNative.getDefault().broadcastIntent(
1113                mMainThread.getApplicationThread(), intent, resolvedType, rd,
1114                initialCode, initialData, initialExtras, receiverPermission,
1115                true, false, user.getIdentifier());
1116        } catch (RemoteException e) {
1117        }
1118    }
1119
1120    @Override
1121    public void sendStickyBroadcast(Intent intent) {
1122        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1123        try {
1124            intent.setAllowFds(false);
1125            ActivityManagerNative.getDefault().broadcastIntent(
1126                mMainThread.getApplicationThread(), intent, resolvedType, null,
1127                Activity.RESULT_OK, null, null, null, false, true,
1128                UserHandle.myUserId());
1129        } catch (RemoteException e) {
1130        }
1131    }
1132
1133    @Override
1134    public void sendStickyOrderedBroadcast(Intent intent,
1135            BroadcastReceiver resultReceiver,
1136            Handler scheduler, int initialCode, String initialData,
1137            Bundle initialExtras) {
1138        IIntentReceiver rd = null;
1139        if (resultReceiver != null) {
1140            if (mPackageInfo != null) {
1141                if (scheduler == null) {
1142                    scheduler = mMainThread.getHandler();
1143                }
1144                rd = mPackageInfo.getReceiverDispatcher(
1145                    resultReceiver, getOuterContext(), scheduler,
1146                    mMainThread.getInstrumentation(), false);
1147            } else {
1148                if (scheduler == null) {
1149                    scheduler = mMainThread.getHandler();
1150                }
1151                rd = new LoadedApk.ReceiverDispatcher(
1152                        resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
1153            }
1154        }
1155        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1156        try {
1157            intent.setAllowFds(false);
1158            ActivityManagerNative.getDefault().broadcastIntent(
1159                mMainThread.getApplicationThread(), intent, resolvedType, rd,
1160                initialCode, initialData, initialExtras, null,
1161                true, true, UserHandle.myUserId());
1162        } catch (RemoteException e) {
1163        }
1164    }
1165
1166    @Override
1167    public void removeStickyBroadcast(Intent intent) {
1168        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1169        if (resolvedType != null) {
1170            intent = new Intent(intent);
1171            intent.setDataAndType(intent.getData(), resolvedType);
1172        }
1173        try {
1174            intent.setAllowFds(false);
1175            ActivityManagerNative.getDefault().unbroadcastIntent(
1176                    mMainThread.getApplicationThread(), intent, UserHandle.myUserId());
1177        } catch (RemoteException e) {
1178        }
1179    }
1180
1181    @Override
1182    public void sendStickyBroadcastAsUser(Intent intent, UserHandle user) {
1183        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1184        try {
1185            intent.setAllowFds(false);
1186            ActivityManagerNative.getDefault().broadcastIntent(
1187                mMainThread.getApplicationThread(), intent, resolvedType, null,
1188                Activity.RESULT_OK, null, null, null, false, true, user.getIdentifier());
1189        } catch (RemoteException e) {
1190        }
1191    }
1192
1193    @Override
1194    public void sendStickyOrderedBroadcastAsUser(Intent intent,
1195            UserHandle user, BroadcastReceiver resultReceiver,
1196            Handler scheduler, int initialCode, String initialData,
1197            Bundle initialExtras) {
1198        IIntentReceiver rd = null;
1199        if (resultReceiver != null) {
1200            if (mPackageInfo != null) {
1201                if (scheduler == null) {
1202                    scheduler = mMainThread.getHandler();
1203                }
1204                rd = mPackageInfo.getReceiverDispatcher(
1205                    resultReceiver, getOuterContext(), scheduler,
1206                    mMainThread.getInstrumentation(), false);
1207            } else {
1208                if (scheduler == null) {
1209                    scheduler = mMainThread.getHandler();
1210                }
1211                rd = new LoadedApk.ReceiverDispatcher(
1212                        resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
1213            }
1214        }
1215        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1216        try {
1217            intent.setAllowFds(false);
1218            ActivityManagerNative.getDefault().broadcastIntent(
1219                mMainThread.getApplicationThread(), intent, resolvedType, rd,
1220                initialCode, initialData, initialExtras, null,
1221                true, true, user.getIdentifier());
1222        } catch (RemoteException e) {
1223        }
1224    }
1225
1226    @Override
1227    public void removeStickyBroadcastAsUser(Intent intent, UserHandle user) {
1228        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1229        if (resolvedType != null) {
1230            intent = new Intent(intent);
1231            intent.setDataAndType(intent.getData(), resolvedType);
1232        }
1233        try {
1234            intent.setAllowFds(false);
1235            ActivityManagerNative.getDefault().unbroadcastIntent(
1236                    mMainThread.getApplicationThread(), intent, user.getIdentifier());
1237        } catch (RemoteException e) {
1238        }
1239    }
1240
1241    @Override
1242    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
1243        return registerReceiver(receiver, filter, null, null);
1244    }
1245
1246    @Override
1247    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
1248            String broadcastPermission, Handler scheduler) {
1249        return registerReceiverInternal(receiver, filter, broadcastPermission,
1250                scheduler, getOuterContext());
1251    }
1252
1253    private Intent registerReceiverInternal(BroadcastReceiver receiver,
1254            IntentFilter filter, String broadcastPermission,
1255            Handler scheduler, Context context) {
1256        IIntentReceiver rd = null;
1257        if (receiver != null) {
1258            if (mPackageInfo != null && context != null) {
1259                if (scheduler == null) {
1260                    scheduler = mMainThread.getHandler();
1261                }
1262                rd = mPackageInfo.getReceiverDispatcher(
1263                    receiver, context, scheduler,
1264                    mMainThread.getInstrumentation(), true);
1265            } else {
1266                if (scheduler == null) {
1267                    scheduler = mMainThread.getHandler();
1268                }
1269                rd = new LoadedApk.ReceiverDispatcher(
1270                        receiver, context, scheduler, null, true).getIIntentReceiver();
1271            }
1272        }
1273        try {
1274            return ActivityManagerNative.getDefault().registerReceiver(
1275                    mMainThread.getApplicationThread(), mBasePackageName,
1276                    rd, filter, broadcastPermission);
1277        } catch (RemoteException e) {
1278            return null;
1279        }
1280    }
1281
1282    @Override
1283    public void unregisterReceiver(BroadcastReceiver receiver) {
1284        if (mPackageInfo != null) {
1285            IIntentReceiver rd = mPackageInfo.forgetReceiverDispatcher(
1286                    getOuterContext(), receiver);
1287            try {
1288                ActivityManagerNative.getDefault().unregisterReceiver(rd);
1289            } catch (RemoteException e) {
1290            }
1291        } else {
1292            throw new RuntimeException("Not supported in system context");
1293        }
1294    }
1295
1296    @Override
1297    public ComponentName startService(Intent service) {
1298        return startServiceAsUser(service, Process.myUserHandle());
1299    }
1300
1301    @Override
1302    public boolean stopService(Intent service) {
1303        return stopServiceAsUser(service, Process.myUserHandle());
1304    }
1305
1306    @Override
1307    public ComponentName startServiceAsUser(Intent service, UserHandle user) {
1308        try {
1309            service.setAllowFds(false);
1310            ComponentName cn = ActivityManagerNative.getDefault().startService(
1311                mMainThread.getApplicationThread(), service,
1312                service.resolveTypeIfNeeded(getContentResolver()), user.getIdentifier());
1313            if (cn != null && cn.getPackageName().equals("!")) {
1314                throw new SecurityException(
1315                        "Not allowed to start service " + service
1316                        + " without permission " + cn.getClassName());
1317            }
1318            return cn;
1319        } catch (RemoteException e) {
1320            return null;
1321        }
1322    }
1323
1324    @Override
1325    public boolean stopServiceAsUser(Intent service, UserHandle user) {
1326        try {
1327            service.setAllowFds(false);
1328            int res = ActivityManagerNative.getDefault().stopService(
1329                mMainThread.getApplicationThread(), service,
1330                service.resolveTypeIfNeeded(getContentResolver()), user.getIdentifier());
1331            if (res < 0) {
1332                throw new SecurityException(
1333                        "Not allowed to stop service " + service);
1334            }
1335            return res != 0;
1336        } catch (RemoteException e) {
1337            return false;
1338        }
1339    }
1340
1341    @Override
1342    public boolean bindService(Intent service, ServiceConnection conn,
1343            int flags) {
1344        return bindService(service, conn, flags, UserHandle.getUserId(Process.myUid()));
1345    }
1346
1347    /** @hide */
1348    @Override
1349    public boolean bindService(Intent service, ServiceConnection conn, int flags, int userHandle) {
1350        IServiceConnection sd;
1351        if (conn == null) {
1352            throw new IllegalArgumentException("connection is null");
1353        }
1354        if (mPackageInfo != null) {
1355            sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(),
1356                    mMainThread.getHandler(), flags);
1357        } else {
1358            throw new RuntimeException("Not supported in system context");
1359        }
1360        try {
1361            IBinder token = getActivityToken();
1362            if (token == null && (flags&BIND_AUTO_CREATE) == 0 && mPackageInfo != null
1363                    && mPackageInfo.getApplicationInfo().targetSdkVersion
1364                    < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
1365                flags |= BIND_WAIVE_PRIORITY;
1366            }
1367            service.setAllowFds(false);
1368            int res = ActivityManagerNative.getDefault().bindService(
1369                mMainThread.getApplicationThread(), getActivityToken(),
1370                service, service.resolveTypeIfNeeded(getContentResolver()),
1371                sd, flags, userHandle);
1372            if (res < 0) {
1373                throw new SecurityException(
1374                        "Not allowed to bind to service " + service);
1375            }
1376            return res != 0;
1377        } catch (RemoteException e) {
1378            return false;
1379        }
1380    }
1381
1382    @Override
1383    public void unbindService(ServiceConnection conn) {
1384        if (conn == null) {
1385            throw new IllegalArgumentException("connection is null");
1386        }
1387        if (mPackageInfo != null) {
1388            IServiceConnection sd = mPackageInfo.forgetServiceDispatcher(
1389                    getOuterContext(), conn);
1390            try {
1391                ActivityManagerNative.getDefault().unbindService(sd);
1392            } catch (RemoteException e) {
1393            }
1394        } else {
1395            throw new RuntimeException("Not supported in system context");
1396        }
1397    }
1398
1399    @Override
1400    public boolean startInstrumentation(ComponentName className,
1401            String profileFile, Bundle arguments) {
1402        try {
1403            if (arguments != null) {
1404                arguments.setAllowFds(false);
1405            }
1406            return ActivityManagerNative.getDefault().startInstrumentation(
1407                    className, profileFile, 0, arguments, null);
1408        } catch (RemoteException e) {
1409            // System has crashed, nothing we can do.
1410        }
1411        return false;
1412    }
1413
1414    @Override
1415    public Object getSystemService(String name) {
1416        ServiceFetcher fetcher = SYSTEM_SERVICE_MAP.get(name);
1417        return fetcher == null ? null : fetcher.getService(this);
1418    }
1419
1420    private WallpaperManager getWallpaperManager() {
1421        return (WallpaperManager) WALLPAPER_FETCHER.getService(this);
1422    }
1423
1424    /* package */ static DropBoxManager createDropBoxManager() {
1425        IBinder b = ServiceManager.getService(DROPBOX_SERVICE);
1426        IDropBoxManagerService service = IDropBoxManagerService.Stub.asInterface(b);
1427        if (service == null) {
1428            // Don't return a DropBoxManager that will NPE upon use.
1429            // This also avoids caching a broken DropBoxManager in
1430            // getDropBoxManager during early boot, before the
1431            // DROPBOX_SERVICE is registered.
1432            return null;
1433        }
1434        return new DropBoxManager(service);
1435    }
1436
1437    @Override
1438    public int checkPermission(String permission, int pid, int uid) {
1439        if (permission == null) {
1440            throw new IllegalArgumentException("permission is null");
1441        }
1442
1443        try {
1444            return ActivityManagerNative.getDefault().checkPermission(
1445                    permission, pid, uid);
1446        } catch (RemoteException e) {
1447            return PackageManager.PERMISSION_DENIED;
1448        }
1449    }
1450
1451    @Override
1452    public int checkCallingPermission(String permission) {
1453        if (permission == null) {
1454            throw new IllegalArgumentException("permission is null");
1455        }
1456
1457        int pid = Binder.getCallingPid();
1458        if (pid != Process.myPid()) {
1459            return checkPermission(permission, pid, Binder.getCallingUid());
1460        }
1461        return PackageManager.PERMISSION_DENIED;
1462    }
1463
1464    @Override
1465    public int checkCallingOrSelfPermission(String permission) {
1466        if (permission == null) {
1467            throw new IllegalArgumentException("permission is null");
1468        }
1469
1470        return checkPermission(permission, Binder.getCallingPid(),
1471                Binder.getCallingUid());
1472    }
1473
1474    private void enforce(
1475            String permission, int resultOfCheck,
1476            boolean selfToo, int uid, String message) {
1477        if (resultOfCheck != PackageManager.PERMISSION_GRANTED) {
1478            throw new SecurityException(
1479                    (message != null ? (message + ": ") : "") +
1480                    (selfToo
1481                     ? "Neither user " + uid + " nor current process has "
1482                     : "User " + uid + " does not have ") +
1483                    permission +
1484                    ".");
1485        }
1486    }
1487
1488    public void enforcePermission(
1489            String permission, int pid, int uid, String message) {
1490        enforce(permission,
1491                checkPermission(permission, pid, uid),
1492                false,
1493                uid,
1494                message);
1495    }
1496
1497    public void enforceCallingPermission(String permission, String message) {
1498        enforce(permission,
1499                checkCallingPermission(permission),
1500                false,
1501                Binder.getCallingUid(),
1502                message);
1503    }
1504
1505    public void enforceCallingOrSelfPermission(
1506            String permission, String message) {
1507        enforce(permission,
1508                checkCallingOrSelfPermission(permission),
1509                true,
1510                Binder.getCallingUid(),
1511                message);
1512    }
1513
1514    @Override
1515    public void grantUriPermission(String toPackage, Uri uri, int modeFlags) {
1516         try {
1517            ActivityManagerNative.getDefault().grantUriPermission(
1518                    mMainThread.getApplicationThread(), toPackage, uri,
1519                    modeFlags);
1520        } catch (RemoteException e) {
1521        }
1522    }
1523
1524    @Override
1525    public void revokeUriPermission(Uri uri, int modeFlags) {
1526         try {
1527            ActivityManagerNative.getDefault().revokeUriPermission(
1528                    mMainThread.getApplicationThread(), uri,
1529                    modeFlags);
1530        } catch (RemoteException e) {
1531        }
1532    }
1533
1534    @Override
1535    public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
1536        try {
1537            return ActivityManagerNative.getDefault().checkUriPermission(
1538                    uri, pid, uid, modeFlags);
1539        } catch (RemoteException e) {
1540            return PackageManager.PERMISSION_DENIED;
1541        }
1542    }
1543
1544    @Override
1545    public int checkCallingUriPermission(Uri uri, int modeFlags) {
1546        int pid = Binder.getCallingPid();
1547        if (pid != Process.myPid()) {
1548            return checkUriPermission(uri, pid,
1549                    Binder.getCallingUid(), modeFlags);
1550        }
1551        return PackageManager.PERMISSION_DENIED;
1552    }
1553
1554    @Override
1555    public int checkCallingOrSelfUriPermission(Uri uri, int modeFlags) {
1556        return checkUriPermission(uri, Binder.getCallingPid(),
1557                Binder.getCallingUid(), modeFlags);
1558    }
1559
1560    @Override
1561    public int checkUriPermission(Uri uri, String readPermission,
1562            String writePermission, int pid, int uid, int modeFlags) {
1563        if (DEBUG) {
1564            Log.i("foo", "checkUriPermission: uri=" + uri + "readPermission="
1565                    + readPermission + " writePermission=" + writePermission
1566                    + " pid=" + pid + " uid=" + uid + " mode" + modeFlags);
1567        }
1568        if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
1569            if (readPermission == null
1570                    || checkPermission(readPermission, pid, uid)
1571                    == PackageManager.PERMISSION_GRANTED) {
1572                return PackageManager.PERMISSION_GRANTED;
1573            }
1574        }
1575        if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
1576            if (writePermission == null
1577                    || checkPermission(writePermission, pid, uid)
1578                    == PackageManager.PERMISSION_GRANTED) {
1579                return PackageManager.PERMISSION_GRANTED;
1580            }
1581        }
1582        return uri != null ? checkUriPermission(uri, pid, uid, modeFlags)
1583                : PackageManager.PERMISSION_DENIED;
1584    }
1585
1586    private String uriModeFlagToString(int uriModeFlags) {
1587        switch (uriModeFlags) {
1588            case Intent.FLAG_GRANT_READ_URI_PERMISSION |
1589                    Intent.FLAG_GRANT_WRITE_URI_PERMISSION:
1590                return "read and write";
1591            case Intent.FLAG_GRANT_READ_URI_PERMISSION:
1592                return "read";
1593            case Intent.FLAG_GRANT_WRITE_URI_PERMISSION:
1594                return "write";
1595        }
1596        throw new IllegalArgumentException(
1597                "Unknown permission mode flags: " + uriModeFlags);
1598    }
1599
1600    private void enforceForUri(
1601            int modeFlags, int resultOfCheck, boolean selfToo,
1602            int uid, Uri uri, String message) {
1603        if (resultOfCheck != PackageManager.PERMISSION_GRANTED) {
1604            throw new SecurityException(
1605                    (message != null ? (message + ": ") : "") +
1606                    (selfToo
1607                     ? "Neither user " + uid + " nor current process has "
1608                     : "User " + uid + " does not have ") +
1609                    uriModeFlagToString(modeFlags) +
1610                    " permission on " +
1611                    uri +
1612                    ".");
1613        }
1614    }
1615
1616    public void enforceUriPermission(
1617            Uri uri, int pid, int uid, int modeFlags, String message) {
1618        enforceForUri(
1619                modeFlags, checkUriPermission(uri, pid, uid, modeFlags),
1620                false, uid, uri, message);
1621    }
1622
1623    public void enforceCallingUriPermission(
1624            Uri uri, int modeFlags, String message) {
1625        enforceForUri(
1626                modeFlags, checkCallingUriPermission(uri, modeFlags),
1627                false,
1628                Binder.getCallingUid(), uri, message);
1629    }
1630
1631    public void enforceCallingOrSelfUriPermission(
1632            Uri uri, int modeFlags, String message) {
1633        enforceForUri(
1634                modeFlags,
1635                checkCallingOrSelfUriPermission(uri, modeFlags), true,
1636                Binder.getCallingUid(), uri, message);
1637    }
1638
1639    public void enforceUriPermission(
1640            Uri uri, String readPermission, String writePermission,
1641            int pid, int uid, int modeFlags, String message) {
1642        enforceForUri(modeFlags,
1643                      checkUriPermission(
1644                              uri, readPermission, writePermission, pid, uid,
1645                              modeFlags),
1646                      false,
1647                      uid,
1648                      uri,
1649                      message);
1650    }
1651
1652    @Override
1653    public Context createPackageContext(String packageName, int flags)
1654        throws PackageManager.NameNotFoundException {
1655        if (packageName.equals("system") || packageName.equals("android")) {
1656            final ContextImpl context = new ContextImpl(mMainThread.getSystemContext());
1657            context.mBasePackageName = mBasePackageName;
1658            return context;
1659        }
1660
1661        LoadedApk pi =
1662            mMainThread.getPackageInfo(packageName, mResources.getCompatibilityInfo(), flags);
1663        if (pi != null) {
1664            ContextImpl c = new ContextImpl();
1665            c.mRestricted = (flags & CONTEXT_RESTRICTED) == CONTEXT_RESTRICTED;
1666            c.init(pi, null, mMainThread, mResources, mBasePackageName);
1667            if (c.mResources != null) {
1668                return c;
1669            }
1670        }
1671
1672        // Should be a better exception.
1673        throw new PackageManager.NameNotFoundException(
1674            "Application package " + packageName + " not found");
1675    }
1676
1677    @Override
1678    public Context createConfigurationContext(Configuration overrideConfiguration) {
1679        ContextImpl c = new ContextImpl();
1680        c.init(mPackageInfo, null, mMainThread);
1681        c.mResources = mMainThread.getTopLevelResources(
1682                mPackageInfo.getResDir(), overrideConfiguration,
1683                mResources.getCompatibilityInfo());
1684        return c;
1685    }
1686
1687    @Override
1688    public boolean isRestricted() {
1689        return mRestricted;
1690    }
1691
1692    @Override
1693    public CompatibilityInfoHolder getCompatibilityInfo() {
1694        return mPackageInfo.mCompatibilityInfo;
1695    }
1696
1697    private File getDataDirFile() {
1698        if (mPackageInfo != null) {
1699            return mPackageInfo.getDataDirFile();
1700        }
1701        throw new RuntimeException("Not supported in system context");
1702    }
1703
1704    @Override
1705    public File getDir(String name, int mode) {
1706        name = "app_" + name;
1707        File file = makeFilename(getDataDirFile(), name);
1708        if (!file.exists()) {
1709            file.mkdir();
1710            setFilePermissionsFromMode(file.getPath(), mode,
1711                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH);
1712        }
1713        return file;
1714    }
1715
1716    static ContextImpl createSystemContext(ActivityThread mainThread) {
1717        ContextImpl context = new ContextImpl();
1718        context.init(Resources.getSystem(), mainThread);
1719        return context;
1720    }
1721
1722    ContextImpl() {
1723        mOuterContext = this;
1724    }
1725
1726    /**
1727     * Create a new ApplicationContext from an existing one.  The new one
1728     * works and operates the same as the one it is copying.
1729     *
1730     * @param context Existing application context.
1731     */
1732    public ContextImpl(ContextImpl context) {
1733        mPackageInfo = context.mPackageInfo;
1734        mBasePackageName = context.mBasePackageName;
1735        mResources = context.mResources;
1736        mMainThread = context.mMainThread;
1737        mContentResolver = context.mContentResolver;
1738        mOuterContext = this;
1739    }
1740
1741    final void init(LoadedApk packageInfo,
1742            IBinder activityToken, ActivityThread mainThread) {
1743        init(packageInfo, activityToken, mainThread, null, null);
1744    }
1745
1746    final void init(LoadedApk packageInfo,
1747                IBinder activityToken, ActivityThread mainThread,
1748                Resources container, String basePackageName) {
1749        mPackageInfo = packageInfo;
1750        mBasePackageName = basePackageName != null ? basePackageName : packageInfo.mPackageName;
1751        mResources = mPackageInfo.getResources(mainThread);
1752
1753        if (mResources != null && container != null
1754                && container.getCompatibilityInfo().applicationScale !=
1755                        mResources.getCompatibilityInfo().applicationScale) {
1756            if (DEBUG) {
1757                Log.d(TAG, "loaded context has different scaling. Using container's" +
1758                        " compatiblity info:" + container.getDisplayMetrics());
1759            }
1760            mResources = mainThread.getTopLevelResources(
1761                    mPackageInfo.getResDir(), null, container.getCompatibilityInfo());
1762        }
1763        mMainThread = mainThread;
1764        mContentResolver = new ApplicationContentResolver(this, mainThread);
1765        mActivityToken = activityToken;
1766    }
1767
1768    final void init(Resources resources, ActivityThread mainThread) {
1769        mPackageInfo = null;
1770        mBasePackageName = null;
1771        mResources = resources;
1772        mMainThread = mainThread;
1773        mContentResolver = new ApplicationContentResolver(this, mainThread);
1774    }
1775
1776    final void scheduleFinalCleanup(String who, String what) {
1777        mMainThread.scheduleContextCleanup(this, who, what);
1778    }
1779
1780    final void performFinalCleanup(String who, String what) {
1781        //Log.i(TAG, "Cleanup up context: " + this);
1782        mPackageInfo.removeContextRegistrations(getOuterContext(), who, what);
1783    }
1784
1785    final Context getReceiverRestrictedContext() {
1786        if (mReceiverRestrictedContext != null) {
1787            return mReceiverRestrictedContext;
1788        }
1789        return mReceiverRestrictedContext = new ReceiverRestrictedContext(getOuterContext());
1790    }
1791
1792    final void setOuterContext(Context context) {
1793        mOuterContext = context;
1794    }
1795
1796    final Context getOuterContext() {
1797        return mOuterContext;
1798    }
1799
1800    final IBinder getActivityToken() {
1801        return mActivityToken;
1802    }
1803
1804    static void setFilePermissionsFromMode(String name, int mode,
1805            int extraPermissions) {
1806        int perms = FileUtils.S_IRUSR|FileUtils.S_IWUSR
1807            |FileUtils.S_IRGRP|FileUtils.S_IWGRP
1808            |extraPermissions;
1809        if ((mode&MODE_WORLD_READABLE) != 0) {
1810            perms |= FileUtils.S_IROTH;
1811        }
1812        if ((mode&MODE_WORLD_WRITEABLE) != 0) {
1813            perms |= FileUtils.S_IWOTH;
1814        }
1815        if (DEBUG) {
1816            Log.i(TAG, "File " + name + ": mode=0x" + Integer.toHexString(mode)
1817                  + ", perms=0x" + Integer.toHexString(perms));
1818        }
1819        FileUtils.setPermissions(name, perms, -1, -1);
1820    }
1821
1822    private File validateFilePath(String name, boolean createDirectory) {
1823        File dir;
1824        File f;
1825
1826        if (name.charAt(0) == File.separatorChar) {
1827            String dirPath = name.substring(0, name.lastIndexOf(File.separatorChar));
1828            dir = new File(dirPath);
1829            name = name.substring(name.lastIndexOf(File.separatorChar));
1830            f = new File(dir, name);
1831        } else {
1832            dir = getDatabasesDir();
1833            f = makeFilename(dir, name);
1834        }
1835
1836        if (createDirectory && !dir.isDirectory() && dir.mkdir()) {
1837            FileUtils.setPermissions(dir.getPath(),
1838                FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1839                -1, -1);
1840        }
1841
1842        return f;
1843    }
1844
1845    private File makeFilename(File base, String name) {
1846        if (name.indexOf(File.separatorChar) < 0) {
1847            return new File(base, name);
1848        }
1849        throw new IllegalArgumentException(
1850                "File " + name + " contains a path separator");
1851    }
1852
1853    // ----------------------------------------------------------------------
1854    // ----------------------------------------------------------------------
1855    // ----------------------------------------------------------------------
1856
1857    private static final class ApplicationContentResolver extends ContentResolver {
1858        public ApplicationContentResolver(Context context, ActivityThread mainThread) {
1859            super(context);
1860            mMainThread = mainThread;
1861        }
1862
1863        @Override
1864        protected IContentProvider acquireProvider(Context context, String name) {
1865            return mMainThread.acquireProvider(context, name, true);
1866        }
1867
1868        @Override
1869        protected IContentProvider acquireExistingProvider(Context context, String name) {
1870            return mMainThread.acquireExistingProvider(context, name, true);
1871        }
1872
1873        @Override
1874        public boolean releaseProvider(IContentProvider provider) {
1875            return mMainThread.releaseProvider(provider, true);
1876        }
1877
1878        @Override
1879        protected IContentProvider acquireUnstableProvider(Context c, String name) {
1880            return mMainThread.acquireProvider(c, name, false);
1881        }
1882
1883        @Override
1884        public boolean releaseUnstableProvider(IContentProvider icp) {
1885            return mMainThread.releaseProvider(icp, false);
1886        }
1887
1888        @Override
1889        public void unstableProviderDied(IContentProvider icp) {
1890            mMainThread.handleUnstableProviderDied(icp.asBinder(), true);
1891        }
1892
1893        private final ActivityThread mMainThread;
1894    }
1895}
1896