ContextImpl.java revision d58429f9acdb33f05bdb233b7bba495de80cb336
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;
20import com.android.internal.util.XmlUtils;
21import com.google.android.collect.Maps;
22
23import org.xmlpull.v1.XmlPullParserException;
24
25import android.content.BroadcastReceiver;
26import android.content.ComponentName;
27import android.content.ContentResolver;
28import android.content.Context;
29import android.content.ContextWrapper;
30import android.content.IContentProvider;
31import android.content.Intent;
32import android.content.IntentFilter;
33import android.content.IIntentReceiver;
34import android.content.IntentSender;
35import android.content.ReceiverCallNotAllowedException;
36import android.content.ServiceConnection;
37import android.content.SharedPreferences;
38import android.content.pm.ActivityInfo;
39import android.content.pm.ApplicationInfo;
40import android.content.pm.ComponentInfo;
41import android.content.pm.FeatureInfo;
42import android.content.pm.IPackageDataObserver;
43import android.content.pm.IPackageDeleteObserver;
44import android.content.pm.IPackageInstallObserver;
45import android.content.pm.IPackageMoveObserver;
46import android.content.pm.IPackageManager;
47import android.content.pm.IPackageStatsObserver;
48import android.content.pm.InstrumentationInfo;
49import android.content.pm.PackageInfo;
50import android.content.pm.PackageManager;
51import android.content.pm.PermissionGroupInfo;
52import android.content.pm.PermissionInfo;
53import android.content.pm.ProviderInfo;
54import android.content.pm.ResolveInfo;
55import android.content.pm.ServiceInfo;
56import android.content.res.AssetManager;
57import android.content.res.Resources;
58import android.content.res.XmlResourceParser;
59import android.database.DatabaseErrorHandler;
60import android.database.sqlite.SQLiteDatabase;
61import android.database.sqlite.SQLiteDatabase.CursorFactory;
62import android.graphics.Bitmap;
63import android.graphics.drawable.Drawable;
64import android.hardware.SensorManager;
65import android.location.CountryDetector;
66import android.location.ICountryDetector;
67import android.location.ILocationManager;
68import android.location.LocationManager;
69import android.media.AudioManager;
70import android.net.ConnectivityManager;
71import android.net.IConnectivityManager;
72import android.net.ThrottleManager;
73import android.net.IThrottleManager;
74import android.net.Uri;
75import android.net.wifi.IWifiManager;
76import android.net.wifi.WifiManager;
77import android.os.Binder;
78import android.os.Build;
79import android.os.Bundle;
80import android.os.DropBoxManager;
81import android.os.Environment;
82import android.os.FileUtils;
83import android.os.Handler;
84import android.os.IBinder;
85import android.os.IPowerManager;
86import android.os.Looper;
87import android.os.PowerManager;
88import android.os.Process;
89import android.os.RemoteException;
90import android.os.ServiceManager;
91import android.os.Vibrator;
92import android.os.FileUtils.FileStatus;
93import android.os.storage.StorageManager;
94import android.telephony.TelephonyManager;
95import android.content.ClipboardManager;
96import android.util.AndroidRuntimeException;
97import android.util.Log;
98import android.view.ContextThemeWrapper;
99import android.view.LayoutInflater;
100import android.view.WindowManagerImpl;
101import android.view.accessibility.AccessibilityManager;
102import android.view.inputmethod.InputMethodManager;
103import android.accounts.AccountManager;
104import android.accounts.IAccountManager;
105import android.app.admin.DevicePolicyManager;
106
107import com.android.internal.os.IDropBoxManagerService;
108
109import java.io.File;
110import java.io.FileInputStream;
111import java.io.FileNotFoundException;
112import java.io.FileOutputStream;
113import java.io.IOException;
114import java.io.InputStream;
115import java.lang.ref.WeakReference;
116import java.util.ArrayList;
117import java.util.HashMap;
118import java.util.HashSet;
119import java.util.Iterator;
120import java.util.List;
121import java.util.Map;
122import java.util.Map.Entry;
123import java.util.Set;
124import java.util.WeakHashMap;
125import java.util.concurrent.CountDownLatch;
126import java.util.concurrent.ExecutorService;
127
128class ReceiverRestrictedContext extends ContextWrapper {
129    ReceiverRestrictedContext(Context base) {
130        super(base);
131    }
132
133    @Override
134    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
135        return registerReceiver(receiver, filter, null, null);
136    }
137
138    @Override
139    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
140            String broadcastPermission, Handler scheduler) {
141        throw new ReceiverCallNotAllowedException(
142                "IntentReceiver components are not allowed to register to receive intents");
143        //ex.fillInStackTrace();
144        //Log.e("IntentReceiver", ex.getMessage(), ex);
145        //return mContext.registerReceiver(receiver, filter, broadcastPermission,
146        //        scheduler);
147    }
148
149    @Override
150    public boolean bindService(Intent service, ServiceConnection conn, int flags) {
151        throw new ReceiverCallNotAllowedException(
152                "IntentReceiver components are not allowed to bind to services");
153        //ex.fillInStackTrace();
154        //Log.e("IntentReceiver", ex.getMessage(), ex);
155        //return mContext.bindService(service, interfaceName, conn, flags);
156    }
157}
158
159/**
160 * Common implementation of Context API, which provides the base
161 * context object for Activity and other application components.
162 */
163class ContextImpl extends Context {
164    private final static String TAG = "ApplicationContext";
165    private final static boolean DEBUG = false;
166    private final static boolean DEBUG_ICONS = false;
167
168    private static final Object sSync = new Object();
169    private static AlarmManager sAlarmManager;
170    private static PowerManager sPowerManager;
171    private static ConnectivityManager sConnectivityManager;
172    private static ThrottleManager sThrottleManager;
173    private static WifiManager sWifiManager;
174    private static LocationManager sLocationManager;
175    private static CountryDetector sCountryDetector;
176    private static final HashMap<String, SharedPreferencesImpl> sSharedPrefs =
177            new HashMap<String, SharedPreferencesImpl>();
178
179    private AudioManager mAudioManager;
180    /*package*/ LoadedApk mPackageInfo;
181    private Resources mResources;
182    /*package*/ ActivityThread mMainThread;
183    private Context mOuterContext;
184    private IBinder mActivityToken = null;
185    private ApplicationContentResolver mContentResolver;
186    private int mThemeResource = 0;
187    private Resources.Theme mTheme = null;
188    private PackageManager mPackageManager;
189    private NotificationManager mNotificationManager = null;
190    private ActivityManager mActivityManager = null;
191    private WallpaperManager mWallpaperManager = null;
192    private Context mReceiverRestrictedContext = null;
193    private SearchManager mSearchManager = null;
194    private SensorManager mSensorManager = null;
195    private StorageManager mStorageManager = null;
196    private Vibrator mVibrator = null;
197    private LayoutInflater mLayoutInflater = null;
198    private StatusBarManager mStatusBarManager = null;
199    private TelephonyManager mTelephonyManager = null;
200    private ClipboardManager mClipboardManager = null;
201    private boolean mRestricted;
202    private AccountManager mAccountManager; // protected by mSync
203    private DropBoxManager mDropBoxManager = null;
204    private DevicePolicyManager mDevicePolicyManager = null;
205    private UiModeManager mUiModeManager = null;
206    private DownloadManager mDownloadManager = null;
207
208    private final Object mSync = new Object();
209
210    private File mDatabasesDir;
211    private File mPreferencesDir;
212    private File mFilesDir;
213    private File mCacheDir;
214    private File mExternalFilesDir;
215    private File mExternalCacheDir;
216
217    private static final String[] EMPTY_FILE_LIST = {};
218
219    @Override
220    public AssetManager getAssets() {
221        return mResources.getAssets();
222    }
223
224    @Override
225    public Resources getResources() {
226        return mResources;
227    }
228
229    @Override
230    public PackageManager getPackageManager() {
231        if (mPackageManager != null) {
232            return mPackageManager;
233        }
234
235        IPackageManager pm = ActivityThread.getPackageManager();
236        if (pm != null) {
237            // Doesn't matter if we make more than one instance.
238            return (mPackageManager = new ApplicationPackageManager(this, pm));
239        }
240
241        return null;
242    }
243
244    @Override
245    public ContentResolver getContentResolver() {
246        return mContentResolver;
247    }
248
249    @Override
250    public Looper getMainLooper() {
251        return mMainThread.getLooper();
252    }
253
254    @Override
255    public Context getApplicationContext() {
256        return (mPackageInfo != null) ?
257                mPackageInfo.getApplication() : mMainThread.getApplication();
258    }
259
260    @Override
261    public void setTheme(int resid) {
262        mThemeResource = resid;
263    }
264
265    @Override
266    public Resources.Theme getTheme() {
267        if (mTheme == null) {
268            if (mThemeResource == 0) {
269                mThemeResource = com.android.internal.R.style.Theme;
270            }
271            mTheme = mResources.newTheme();
272            mTheme.applyStyle(mThemeResource, true);
273        }
274        return mTheme;
275    }
276
277    @Override
278    public ClassLoader getClassLoader() {
279        return mPackageInfo != null ?
280                mPackageInfo.getClassLoader() : ClassLoader.getSystemClassLoader();
281    }
282
283    @Override
284    public String getPackageName() {
285        if (mPackageInfo != null) {
286            return mPackageInfo.getPackageName();
287        }
288        throw new RuntimeException("Not supported in system context");
289    }
290
291    @Override
292    public ApplicationInfo getApplicationInfo() {
293        if (mPackageInfo != null) {
294            return mPackageInfo.getApplicationInfo();
295        }
296        throw new RuntimeException("Not supported in system context");
297    }
298
299    @Override
300    public String getPackageResourcePath() {
301        if (mPackageInfo != null) {
302            return mPackageInfo.getResDir();
303        }
304        throw new RuntimeException("Not supported in system context");
305    }
306
307    @Override
308    public String getPackageCodePath() {
309        if (mPackageInfo != null) {
310            return mPackageInfo.getAppDir();
311        }
312        throw new RuntimeException("Not supported in system context");
313    }
314
315    private static File makeBackupFile(File prefsFile) {
316        return new File(prefsFile.getPath() + ".bak");
317    }
318
319    public File getSharedPrefsFile(String name) {
320        return makeFilename(getPreferencesDir(), name + ".xml");
321    }
322
323    @Override
324    public SharedPreferences getSharedPreferences(String name, int mode) {
325        SharedPreferencesImpl sp;
326        File prefsFile;
327        boolean needInitialLoad = false;
328        synchronized (sSharedPrefs) {
329            sp = sSharedPrefs.get(name);
330            if (sp != null && !sp.hasFileChangedUnexpectedly()) {
331                return sp;
332            }
333            prefsFile = getSharedPrefsFile(name);
334            if (sp == null) {
335                sp = new SharedPreferencesImpl(prefsFile, mode, null);
336                sSharedPrefs.put(name, sp);
337                needInitialLoad = true;
338            }
339        }
340
341        synchronized (sp) {
342            if (needInitialLoad && sp.isLoaded()) {
343                // lost the race to load; another thread handled it
344                return sp;
345            }
346            File backup = makeBackupFile(prefsFile);
347            if (backup.exists()) {
348                prefsFile.delete();
349                backup.renameTo(prefsFile);
350            }
351
352            // Debugging
353            if (prefsFile.exists() && !prefsFile.canRead()) {
354                Log.w(TAG, "Attempt to read preferences file " + prefsFile + " without permission");
355            }
356
357            Map map = null;
358            if (prefsFile.exists() && prefsFile.canRead()) {
359                try {
360                    FileInputStream str = new FileInputStream(prefsFile);
361                    map = XmlUtils.readMapXml(str);
362                    str.close();
363                } catch (org.xmlpull.v1.XmlPullParserException e) {
364                    Log.w(TAG, "getSharedPreferences", e);
365                } catch (FileNotFoundException e) {
366                    Log.w(TAG, "getSharedPreferences", e);
367                } catch (IOException e) {
368                    Log.w(TAG, "getSharedPreferences", e);
369                }
370            }
371            sp.replace(map);
372        }
373        return sp;
374    }
375
376    private File getPreferencesDir() {
377        synchronized (mSync) {
378            if (mPreferencesDir == null) {
379                mPreferencesDir = new File(getDataDirFile(), "shared_prefs");
380            }
381            return mPreferencesDir;
382        }
383    }
384
385    @Override
386    public FileInputStream openFileInput(String name)
387        throws FileNotFoundException {
388        File f = makeFilename(getFilesDir(), name);
389        return new FileInputStream(f);
390    }
391
392    @Override
393    public FileOutputStream openFileOutput(String name, int mode)
394        throws FileNotFoundException {
395        final boolean append = (mode&MODE_APPEND) != 0;
396        File f = makeFilename(getFilesDir(), name);
397        try {
398            FileOutputStream fos = new FileOutputStream(f, append);
399            setFilePermissionsFromMode(f.getPath(), mode, 0);
400            return fos;
401        } catch (FileNotFoundException e) {
402        }
403
404        File parent = f.getParentFile();
405        parent.mkdir();
406        FileUtils.setPermissions(
407            parent.getPath(),
408            FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
409            -1, -1);
410        FileOutputStream fos = new FileOutputStream(f, append);
411        setFilePermissionsFromMode(f.getPath(), mode, 0);
412        return fos;
413    }
414
415    @Override
416    public boolean deleteFile(String name) {
417        File f = makeFilename(getFilesDir(), name);
418        return f.delete();
419    }
420
421    @Override
422    public File getFilesDir() {
423        synchronized (mSync) {
424            if (mFilesDir == null) {
425                mFilesDir = new File(getDataDirFile(), "files");
426            }
427            if (!mFilesDir.exists()) {
428                if(!mFilesDir.mkdirs()) {
429                    Log.w(TAG, "Unable to create files directory " + mFilesDir.getPath());
430                    return null;
431                }
432                FileUtils.setPermissions(
433                        mFilesDir.getPath(),
434                        FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
435                        -1, -1);
436            }
437            return mFilesDir;
438        }
439    }
440
441    @Override
442    public File getExternalFilesDir(String type) {
443        synchronized (mSync) {
444            if (mExternalFilesDir == null) {
445                mExternalFilesDir = Environment.getExternalStorageAppFilesDirectory(
446                        getPackageName());
447            }
448            if (!mExternalFilesDir.exists()) {
449                try {
450                    (new File(Environment.getExternalStorageAndroidDataDir(),
451                            ".nomedia")).createNewFile();
452                } catch (IOException e) {
453                }
454                if (!mExternalFilesDir.mkdirs()) {
455                    Log.w(TAG, "Unable to create external files directory");
456                    return null;
457                }
458            }
459            if (type == null) {
460                return mExternalFilesDir;
461            }
462            File dir = new File(mExternalFilesDir, type);
463            if (!dir.exists()) {
464                if (!dir.mkdirs()) {
465                    Log.w(TAG, "Unable to create external media directory " + dir);
466                    return null;
467                }
468            }
469            return dir;
470        }
471    }
472
473    @Override
474    public File getCacheDir() {
475        synchronized (mSync) {
476            if (mCacheDir == null) {
477                mCacheDir = new File(getDataDirFile(), "cache");
478            }
479            if (!mCacheDir.exists()) {
480                if(!mCacheDir.mkdirs()) {
481                    Log.w(TAG, "Unable to create cache directory");
482                    return null;
483                }
484                FileUtils.setPermissions(
485                        mCacheDir.getPath(),
486                        FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
487                        -1, -1);
488            }
489        }
490        return mCacheDir;
491    }
492
493    @Override
494    public File getExternalCacheDir() {
495        synchronized (mSync) {
496            if (mExternalCacheDir == null) {
497                mExternalCacheDir = Environment.getExternalStorageAppCacheDirectory(
498                        getPackageName());
499            }
500            if (!mExternalCacheDir.exists()) {
501                try {
502                    (new File(Environment.getExternalStorageAndroidDataDir(),
503                            ".nomedia")).createNewFile();
504                } catch (IOException e) {
505                }
506                if (!mExternalCacheDir.mkdirs()) {
507                    Log.w(TAG, "Unable to create external cache directory");
508                    return null;
509                }
510            }
511            return mExternalCacheDir;
512        }
513    }
514
515    @Override
516    public File getFileStreamPath(String name) {
517        return makeFilename(getFilesDir(), name);
518    }
519
520    @Override
521    public String[] fileList() {
522        final String[] list = getFilesDir().list();
523        return (list != null) ? list : EMPTY_FILE_LIST;
524    }
525
526    @Override
527    public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory) {
528        File f = validateFilePath(name, true);
529        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(f, factory);
530        setFilePermissionsFromMode(f.getPath(), mode, 0);
531        return db;
532    }
533
534    @Override
535    public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory,
536            DatabaseErrorHandler errorHandler) {
537        File f = validateFilePath(name, true);
538        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(f.getPath(), factory, errorHandler);
539        setFilePermissionsFromMode(f.getPath(), mode, 0);
540        return db;
541    }
542
543    @Override
544    public boolean deleteDatabase(String name) {
545        try {
546            File f = validateFilePath(name, false);
547            return f.delete();
548        } catch (Exception e) {
549        }
550        return false;
551    }
552
553    @Override
554    public File getDatabasePath(String name) {
555        return validateFilePath(name, false);
556    }
557
558    @Override
559    public String[] databaseList() {
560        final String[] list = getDatabasesDir().list();
561        return (list != null) ? list : EMPTY_FILE_LIST;
562    }
563
564
565    private File getDatabasesDir() {
566        synchronized (mSync) {
567            if (mDatabasesDir == null) {
568                mDatabasesDir = new File(getDataDirFile(), "databases");
569            }
570            if (mDatabasesDir.getPath().equals("databases")) {
571                mDatabasesDir = new File("/data/system");
572            }
573            return mDatabasesDir;
574        }
575    }
576
577    @Override
578    public Drawable getWallpaper() {
579        return getWallpaperManager().getDrawable();
580    }
581
582    @Override
583    public Drawable peekWallpaper() {
584        return getWallpaperManager().peekDrawable();
585    }
586
587    @Override
588    public int getWallpaperDesiredMinimumWidth() {
589        return getWallpaperManager().getDesiredMinimumWidth();
590    }
591
592    @Override
593    public int getWallpaperDesiredMinimumHeight() {
594        return getWallpaperManager().getDesiredMinimumHeight();
595    }
596
597    @Override
598    public void setWallpaper(Bitmap bitmap) throws IOException  {
599        getWallpaperManager().setBitmap(bitmap);
600    }
601
602    @Override
603    public void setWallpaper(InputStream data) throws IOException {
604        getWallpaperManager().setStream(data);
605    }
606
607    @Override
608    public void clearWallpaper() throws IOException {
609        getWallpaperManager().clear();
610    }
611
612    @Override
613    public void startActivity(Intent intent) {
614        if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
615            throw new AndroidRuntimeException(
616                    "Calling startActivity() from outside of an Activity "
617                    + " context requires the FLAG_ACTIVITY_NEW_TASK flag."
618                    + " Is this really what you want?");
619        }
620        mMainThread.getInstrumentation().execStartActivity(
621            getOuterContext(), mMainThread.getApplicationThread(), null,
622            (Activity)null, intent, -1);
623    }
624
625    @Override
626    public void startIntentSender(IntentSender intent,
627            Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
628            throws IntentSender.SendIntentException {
629        try {
630            String resolvedType = null;
631            if (fillInIntent != null) {
632                resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
633            }
634            int result = ActivityManagerNative.getDefault()
635                .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
636                        fillInIntent, resolvedType, null, null,
637                        0, flagsMask, flagsValues);
638            if (result == IActivityManager.START_CANCELED) {
639                throw new IntentSender.SendIntentException();
640            }
641            Instrumentation.checkStartActivityResult(result, null);
642        } catch (RemoteException e) {
643        }
644    }
645
646    @Override
647    public void sendBroadcast(Intent intent) {
648        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
649        try {
650            ActivityManagerNative.getDefault().broadcastIntent(
651                mMainThread.getApplicationThread(), intent, resolvedType, null,
652                Activity.RESULT_OK, null, null, null, false, false);
653        } catch (RemoteException e) {
654        }
655    }
656
657    @Override
658    public void sendBroadcast(Intent intent, String receiverPermission) {
659        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
660        try {
661            ActivityManagerNative.getDefault().broadcastIntent(
662                mMainThread.getApplicationThread(), intent, resolvedType, null,
663                Activity.RESULT_OK, null, null, receiverPermission, false, false);
664        } catch (RemoteException e) {
665        }
666    }
667
668    @Override
669    public void sendOrderedBroadcast(Intent intent,
670            String receiverPermission) {
671        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
672        try {
673            ActivityManagerNative.getDefault().broadcastIntent(
674                mMainThread.getApplicationThread(), intent, resolvedType, null,
675                Activity.RESULT_OK, null, null, receiverPermission, true, false);
676        } catch (RemoteException e) {
677        }
678    }
679
680    @Override
681    public void sendOrderedBroadcast(Intent intent,
682            String receiverPermission, BroadcastReceiver resultReceiver,
683            Handler scheduler, int initialCode, String initialData,
684            Bundle initialExtras) {
685        IIntentReceiver rd = null;
686        if (resultReceiver != null) {
687            if (mPackageInfo != null) {
688                if (scheduler == null) {
689                    scheduler = mMainThread.getHandler();
690                }
691                rd = mPackageInfo.getReceiverDispatcher(
692                    resultReceiver, getOuterContext(), scheduler,
693                    mMainThread.getInstrumentation(), false);
694            } else {
695                if (scheduler == null) {
696                    scheduler = mMainThread.getHandler();
697                }
698                rd = new LoadedApk.ReceiverDispatcher(
699                        resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
700            }
701        }
702        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
703        try {
704            ActivityManagerNative.getDefault().broadcastIntent(
705                mMainThread.getApplicationThread(), intent, resolvedType, rd,
706                initialCode, initialData, initialExtras, receiverPermission,
707                true, false);
708        } catch (RemoteException e) {
709        }
710    }
711
712    @Override
713    public void sendStickyBroadcast(Intent intent) {
714        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
715        try {
716            ActivityManagerNative.getDefault().broadcastIntent(
717                mMainThread.getApplicationThread(), intent, resolvedType, null,
718                Activity.RESULT_OK, null, null, null, false, true);
719        } catch (RemoteException e) {
720        }
721    }
722
723    @Override
724    public void sendStickyOrderedBroadcast(Intent intent,
725            BroadcastReceiver resultReceiver,
726            Handler scheduler, int initialCode, String initialData,
727            Bundle initialExtras) {
728        IIntentReceiver rd = null;
729        if (resultReceiver != null) {
730            if (mPackageInfo != null) {
731                if (scheduler == null) {
732                    scheduler = mMainThread.getHandler();
733                }
734                rd = mPackageInfo.getReceiverDispatcher(
735                    resultReceiver, getOuterContext(), scheduler,
736                    mMainThread.getInstrumentation(), false);
737            } else {
738                if (scheduler == null) {
739                    scheduler = mMainThread.getHandler();
740                }
741                rd = new LoadedApk.ReceiverDispatcher(
742                        resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
743            }
744        }
745        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
746        try {
747            ActivityManagerNative.getDefault().broadcastIntent(
748                mMainThread.getApplicationThread(), intent, resolvedType, rd,
749                initialCode, initialData, initialExtras, null,
750                true, true);
751        } catch (RemoteException e) {
752        }
753    }
754
755    @Override
756    public void removeStickyBroadcast(Intent intent) {
757        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
758        if (resolvedType != null) {
759            intent = new Intent(intent);
760            intent.setDataAndType(intent.getData(), resolvedType);
761        }
762        try {
763            ActivityManagerNative.getDefault().unbroadcastIntent(
764                mMainThread.getApplicationThread(), intent);
765        } catch (RemoteException e) {
766        }
767    }
768
769    @Override
770    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
771        return registerReceiver(receiver, filter, null, null);
772    }
773
774    @Override
775    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
776            String broadcastPermission, Handler scheduler) {
777        return registerReceiverInternal(receiver, filter, broadcastPermission,
778                scheduler, getOuterContext());
779    }
780
781    private Intent registerReceiverInternal(BroadcastReceiver receiver,
782            IntentFilter filter, String broadcastPermission,
783            Handler scheduler, Context context) {
784        IIntentReceiver rd = null;
785        if (receiver != null) {
786            if (mPackageInfo != null && context != null) {
787                if (scheduler == null) {
788                    scheduler = mMainThread.getHandler();
789                }
790                rd = mPackageInfo.getReceiverDispatcher(
791                    receiver, context, scheduler,
792                    mMainThread.getInstrumentation(), true);
793            } else {
794                if (scheduler == null) {
795                    scheduler = mMainThread.getHandler();
796                }
797                rd = new LoadedApk.ReceiverDispatcher(
798                        receiver, context, scheduler, null, true).getIIntentReceiver();
799            }
800        }
801        try {
802            return ActivityManagerNative.getDefault().registerReceiver(
803                    mMainThread.getApplicationThread(),
804                    rd, filter, broadcastPermission);
805        } catch (RemoteException e) {
806            return null;
807        }
808    }
809
810    @Override
811    public void unregisterReceiver(BroadcastReceiver receiver) {
812        if (mPackageInfo != null) {
813            IIntentReceiver rd = mPackageInfo.forgetReceiverDispatcher(
814                    getOuterContext(), receiver);
815            try {
816                ActivityManagerNative.getDefault().unregisterReceiver(rd);
817            } catch (RemoteException e) {
818            }
819        } else {
820            throw new RuntimeException("Not supported in system context");
821        }
822    }
823
824    @Override
825    public ComponentName startService(Intent service) {
826        try {
827            ComponentName cn = ActivityManagerNative.getDefault().startService(
828                mMainThread.getApplicationThread(), service,
829                service.resolveTypeIfNeeded(getContentResolver()));
830            if (cn != null && cn.getPackageName().equals("!")) {
831                throw new SecurityException(
832                        "Not allowed to start service " + service
833                        + " without permission " + cn.getClassName());
834            }
835            return cn;
836        } catch (RemoteException e) {
837            return null;
838        }
839    }
840
841    @Override
842    public boolean stopService(Intent service) {
843        try {
844            int res = ActivityManagerNative.getDefault().stopService(
845                mMainThread.getApplicationThread(), service,
846                service.resolveTypeIfNeeded(getContentResolver()));
847            if (res < 0) {
848                throw new SecurityException(
849                        "Not allowed to stop service " + service);
850            }
851            return res != 0;
852        } catch (RemoteException e) {
853            return false;
854        }
855    }
856
857    @Override
858    public boolean bindService(Intent service, ServiceConnection conn,
859            int flags) {
860        IServiceConnection sd;
861        if (mPackageInfo != null) {
862            sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(),
863                    mMainThread.getHandler(), flags);
864        } else {
865            throw new RuntimeException("Not supported in system context");
866        }
867        try {
868            int res = ActivityManagerNative.getDefault().bindService(
869                mMainThread.getApplicationThread(), getActivityToken(),
870                service, service.resolveTypeIfNeeded(getContentResolver()),
871                sd, flags);
872            if (res < 0) {
873                throw new SecurityException(
874                        "Not allowed to bind to service " + service);
875            }
876            return res != 0;
877        } catch (RemoteException e) {
878            return false;
879        }
880    }
881
882    @Override
883    public void unbindService(ServiceConnection conn) {
884        if (mPackageInfo != null) {
885            IServiceConnection sd = mPackageInfo.forgetServiceDispatcher(
886                    getOuterContext(), conn);
887            try {
888                ActivityManagerNative.getDefault().unbindService(sd);
889            } catch (RemoteException e) {
890            }
891        } else {
892            throw new RuntimeException("Not supported in system context");
893        }
894    }
895
896    @Override
897    public boolean startInstrumentation(ComponentName className,
898            String profileFile, Bundle arguments) {
899        try {
900            return ActivityManagerNative.getDefault().startInstrumentation(
901                    className, profileFile, 0, arguments, null);
902        } catch (RemoteException e) {
903            // System has crashed, nothing we can do.
904        }
905        return false;
906    }
907
908    @Override
909    public Object getSystemService(String name) {
910        if (WINDOW_SERVICE.equals(name)) {
911            return WindowManagerImpl.getDefault();
912        } else if (LAYOUT_INFLATER_SERVICE.equals(name)) {
913            synchronized (mSync) {
914                LayoutInflater inflater = mLayoutInflater;
915                if (inflater != null) {
916                    return inflater;
917                }
918                mLayoutInflater = inflater =
919                    PolicyManager.makeNewLayoutInflater(getOuterContext());
920                return inflater;
921            }
922        } else if (ACTIVITY_SERVICE.equals(name)) {
923            return getActivityManager();
924        } else if (INPUT_METHOD_SERVICE.equals(name)) {
925            return InputMethodManager.getInstance(this);
926        } else if (ALARM_SERVICE.equals(name)) {
927            return getAlarmManager();
928        } else if (ACCOUNT_SERVICE.equals(name)) {
929            return getAccountManager();
930        } else if (POWER_SERVICE.equals(name)) {
931            return getPowerManager();
932        } else if (CONNECTIVITY_SERVICE.equals(name)) {
933            return getConnectivityManager();
934        } else if (THROTTLE_SERVICE.equals(name)) {
935            return getThrottleManager();
936        } else if (WIFI_SERVICE.equals(name)) {
937            return getWifiManager();
938        } else if (NOTIFICATION_SERVICE.equals(name)) {
939            return getNotificationManager();
940        } else if (KEYGUARD_SERVICE.equals(name)) {
941            return new KeyguardManager();
942        } else if (ACCESSIBILITY_SERVICE.equals(name)) {
943            return AccessibilityManager.getInstance(this);
944        } else if (LOCATION_SERVICE.equals(name)) {
945            return getLocationManager();
946        } else if (COUNTRY_DETECTOR.equals(name)) {
947            return getCountryDetector();
948        } else if (SEARCH_SERVICE.equals(name)) {
949            return getSearchManager();
950        } else if (SENSOR_SERVICE.equals(name)) {
951            return getSensorManager();
952        } else if (STORAGE_SERVICE.equals(name)) {
953            return getStorageManager();
954        } else if (VIBRATOR_SERVICE.equals(name)) {
955            return getVibrator();
956        } else if (STATUS_BAR_SERVICE.equals(name)) {
957            synchronized (mSync) {
958                if (mStatusBarManager == null) {
959                    mStatusBarManager = new StatusBarManager(getOuterContext());
960                }
961                return mStatusBarManager;
962            }
963        } else if (AUDIO_SERVICE.equals(name)) {
964            return getAudioManager();
965        } else if (TELEPHONY_SERVICE.equals(name)) {
966            return getTelephonyManager();
967        } else if (CLIPBOARD_SERVICE.equals(name)) {
968            return getClipboardManager();
969        } else if (WALLPAPER_SERVICE.equals(name)) {
970            return getWallpaperManager();
971        } else if (DROPBOX_SERVICE.equals(name)) {
972            return getDropBoxManager();
973        } else if (DEVICE_POLICY_SERVICE.equals(name)) {
974            return getDevicePolicyManager();
975        } else if (UI_MODE_SERVICE.equals(name)) {
976            return getUiModeManager();
977        } else if (DOWNLOAD_SERVICE.equals(name)) {
978            return getDownloadManager();
979        }
980
981        return null;
982    }
983
984    private AccountManager getAccountManager() {
985        synchronized (mSync) {
986            if (mAccountManager == null) {
987                IBinder b = ServiceManager.getService(ACCOUNT_SERVICE);
988                IAccountManager service = IAccountManager.Stub.asInterface(b);
989                mAccountManager = new AccountManager(this, service);
990            }
991            return mAccountManager;
992        }
993    }
994
995    private ActivityManager getActivityManager() {
996        synchronized (mSync) {
997            if (mActivityManager == null) {
998                mActivityManager = new ActivityManager(getOuterContext(),
999                        mMainThread.getHandler());
1000            }
1001        }
1002        return mActivityManager;
1003    }
1004
1005    private AlarmManager getAlarmManager() {
1006        synchronized (sSync) {
1007            if (sAlarmManager == null) {
1008                IBinder b = ServiceManager.getService(ALARM_SERVICE);
1009                IAlarmManager service = IAlarmManager.Stub.asInterface(b);
1010                sAlarmManager = new AlarmManager(service);
1011            }
1012        }
1013        return sAlarmManager;
1014    }
1015
1016    private PowerManager getPowerManager() {
1017        synchronized (sSync) {
1018            if (sPowerManager == null) {
1019                IBinder b = ServiceManager.getService(POWER_SERVICE);
1020                IPowerManager service = IPowerManager.Stub.asInterface(b);
1021                sPowerManager = new PowerManager(service, mMainThread.getHandler());
1022            }
1023        }
1024        return sPowerManager;
1025    }
1026
1027    private ConnectivityManager getConnectivityManager()
1028    {
1029        synchronized (sSync) {
1030            if (sConnectivityManager == null) {
1031                IBinder b = ServiceManager.getService(CONNECTIVITY_SERVICE);
1032                IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
1033                sConnectivityManager = new ConnectivityManager(service);
1034            }
1035        }
1036        return sConnectivityManager;
1037    }
1038
1039    private ThrottleManager getThrottleManager()
1040    {
1041        synchronized (sSync) {
1042            if (sThrottleManager == null) {
1043                IBinder b = ServiceManager.getService(THROTTLE_SERVICE);
1044                IThrottleManager service = IThrottleManager.Stub.asInterface(b);
1045                sThrottleManager = new ThrottleManager(service);
1046            }
1047        }
1048        return sThrottleManager;
1049    }
1050
1051    private WifiManager getWifiManager()
1052    {
1053        synchronized (sSync) {
1054            if (sWifiManager == null) {
1055                IBinder b = ServiceManager.getService(WIFI_SERVICE);
1056                IWifiManager service = IWifiManager.Stub.asInterface(b);
1057                sWifiManager = new WifiManager(service, mMainThread.getHandler());
1058            }
1059        }
1060        return sWifiManager;
1061    }
1062
1063    private NotificationManager getNotificationManager() {
1064        synchronized (mSync) {
1065            if (mNotificationManager == null) {
1066                final Context outerContext = getOuterContext();
1067                mNotificationManager = new NotificationManager(
1068                        new ContextThemeWrapper(outerContext,
1069                                outerContext.getApplicationInfo().targetSdkVersion >=
1070                                    Build.VERSION_CODES.HONEYCOMB
1071                                ? com.android.internal.R.style.Theme_Holo_Dialog
1072                                : com.android.internal.R.style.Theme_Dialog),
1073                        mMainThread.getHandler());
1074            }
1075        }
1076        return mNotificationManager;
1077    }
1078
1079    private WallpaperManager getWallpaperManager() {
1080        synchronized (mSync) {
1081            if (mWallpaperManager == null) {
1082                mWallpaperManager = new WallpaperManager(getOuterContext(),
1083                        mMainThread.getHandler());
1084            }
1085        }
1086        return mWallpaperManager;
1087    }
1088
1089    private TelephonyManager getTelephonyManager() {
1090        synchronized (mSync) {
1091            if (mTelephonyManager == null) {
1092                mTelephonyManager = new TelephonyManager(getOuterContext());
1093            }
1094        }
1095        return mTelephonyManager;
1096    }
1097
1098    private ClipboardManager getClipboardManager() {
1099        synchronized (mSync) {
1100            if (mClipboardManager == null) {
1101                mClipboardManager = new ClipboardManager(getOuterContext(),
1102                        mMainThread.getHandler());
1103            }
1104        }
1105        return mClipboardManager;
1106    }
1107
1108    private LocationManager getLocationManager() {
1109        synchronized (sSync) {
1110            if (sLocationManager == null) {
1111                IBinder b = ServiceManager.getService(LOCATION_SERVICE);
1112                ILocationManager service = ILocationManager.Stub.asInterface(b);
1113                sLocationManager = new LocationManager(service);
1114            }
1115        }
1116        return sLocationManager;
1117    }
1118
1119    private CountryDetector getCountryDetector() {
1120        synchronized (sSync) {
1121            if (sCountryDetector == null) {
1122                IBinder b = ServiceManager.getService(COUNTRY_DETECTOR);
1123                ICountryDetector service = ICountryDetector.Stub.asInterface(b);
1124                sCountryDetector = new CountryDetector(service);
1125            }
1126        }
1127        return sCountryDetector;
1128    }
1129
1130    private SearchManager getSearchManager() {
1131        synchronized (mSync) {
1132            if (mSearchManager == null) {
1133                mSearchManager = new SearchManager(getOuterContext(), mMainThread.getHandler());
1134            }
1135        }
1136        return mSearchManager;
1137    }
1138
1139    private SensorManager getSensorManager() {
1140        synchronized (mSync) {
1141            if (mSensorManager == null) {
1142                mSensorManager = new SensorManager(mMainThread.getHandler().getLooper());
1143            }
1144        }
1145        return mSensorManager;
1146    }
1147
1148    private StorageManager getStorageManager() {
1149        synchronized (mSync) {
1150            if (mStorageManager == null) {
1151                try {
1152                    mStorageManager = new StorageManager(mMainThread.getHandler().getLooper());
1153                } catch (RemoteException rex) {
1154                    Log.e(TAG, "Failed to create StorageManager", rex);
1155                    mStorageManager = null;
1156                }
1157            }
1158        }
1159        return mStorageManager;
1160    }
1161
1162    private Vibrator getVibrator() {
1163        synchronized (mSync) {
1164            if (mVibrator == null) {
1165                mVibrator = new Vibrator();
1166            }
1167        }
1168        return mVibrator;
1169    }
1170
1171    private AudioManager getAudioManager()
1172    {
1173        if (mAudioManager == null) {
1174            mAudioManager = new AudioManager(this);
1175        }
1176        return mAudioManager;
1177    }
1178
1179    /* package */ static DropBoxManager createDropBoxManager() {
1180        IBinder b = ServiceManager.getService(DROPBOX_SERVICE);
1181        IDropBoxManagerService service = IDropBoxManagerService.Stub.asInterface(b);
1182        return new DropBoxManager(service);
1183    }
1184
1185    private DropBoxManager getDropBoxManager() {
1186        synchronized (mSync) {
1187            if (mDropBoxManager == null) {
1188                mDropBoxManager = createDropBoxManager();
1189            }
1190        }
1191        return mDropBoxManager;
1192    }
1193
1194    private DevicePolicyManager getDevicePolicyManager() {
1195        synchronized (mSync) {
1196            if (mDevicePolicyManager == null) {
1197                mDevicePolicyManager = DevicePolicyManager.create(this,
1198                        mMainThread.getHandler());
1199            }
1200        }
1201        return mDevicePolicyManager;
1202    }
1203
1204    private UiModeManager getUiModeManager() {
1205        synchronized (mSync) {
1206            if (mUiModeManager == null) {
1207                mUiModeManager = new UiModeManager();
1208            }
1209        }
1210        return mUiModeManager;
1211    }
1212
1213    private DownloadManager getDownloadManager() {
1214        synchronized (mSync) {
1215            if (mDownloadManager == null) {
1216                mDownloadManager = new DownloadManager(getContentResolver(), getPackageName());
1217            }
1218        }
1219        return mDownloadManager;
1220    }
1221
1222    @Override
1223    public int checkPermission(String permission, int pid, int uid) {
1224        if (permission == null) {
1225            throw new IllegalArgumentException("permission is null");
1226        }
1227
1228        if (!Process.supportsProcesses()) {
1229            return PackageManager.PERMISSION_GRANTED;
1230        }
1231        try {
1232            return ActivityManagerNative.getDefault().checkPermission(
1233                    permission, pid, uid);
1234        } catch (RemoteException e) {
1235            return PackageManager.PERMISSION_DENIED;
1236        }
1237    }
1238
1239    @Override
1240    public int checkCallingPermission(String permission) {
1241        if (permission == null) {
1242            throw new IllegalArgumentException("permission is null");
1243        }
1244
1245        if (!Process.supportsProcesses()) {
1246            return PackageManager.PERMISSION_GRANTED;
1247        }
1248        int pid = Binder.getCallingPid();
1249        if (pid != Process.myPid()) {
1250            return checkPermission(permission, pid,
1251                    Binder.getCallingUid());
1252        }
1253        return PackageManager.PERMISSION_DENIED;
1254    }
1255
1256    @Override
1257    public int checkCallingOrSelfPermission(String permission) {
1258        if (permission == null) {
1259            throw new IllegalArgumentException("permission is null");
1260        }
1261
1262        return checkPermission(permission, Binder.getCallingPid(),
1263                Binder.getCallingUid());
1264    }
1265
1266    private void enforce(
1267            String permission, int resultOfCheck,
1268            boolean selfToo, int uid, String message) {
1269        if (resultOfCheck != PackageManager.PERMISSION_GRANTED) {
1270            throw new SecurityException(
1271                    (message != null ? (message + ": ") : "") +
1272                    (selfToo
1273                     ? "Neither user " + uid + " nor current process has "
1274                     : "User " + uid + " does not have ") +
1275                    permission +
1276                    ".");
1277        }
1278    }
1279
1280    public void enforcePermission(
1281            String permission, int pid, int uid, String message) {
1282        enforce(permission,
1283                checkPermission(permission, pid, uid),
1284                false,
1285                uid,
1286                message);
1287    }
1288
1289    public void enforceCallingPermission(String permission, String message) {
1290        enforce(permission,
1291                checkCallingPermission(permission),
1292                false,
1293                Binder.getCallingUid(),
1294                message);
1295    }
1296
1297    public void enforceCallingOrSelfPermission(
1298            String permission, String message) {
1299        enforce(permission,
1300                checkCallingOrSelfPermission(permission),
1301                true,
1302                Binder.getCallingUid(),
1303                message);
1304    }
1305
1306    @Override
1307    public void grantUriPermission(String toPackage, Uri uri, int modeFlags) {
1308         try {
1309            ActivityManagerNative.getDefault().grantUriPermission(
1310                    mMainThread.getApplicationThread(), toPackage, uri,
1311                    modeFlags);
1312        } catch (RemoteException e) {
1313        }
1314    }
1315
1316    @Override
1317    public void revokeUriPermission(Uri uri, int modeFlags) {
1318         try {
1319            ActivityManagerNative.getDefault().revokeUriPermission(
1320                    mMainThread.getApplicationThread(), uri,
1321                    modeFlags);
1322        } catch (RemoteException e) {
1323        }
1324    }
1325
1326    @Override
1327    public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
1328        if (!Process.supportsProcesses()) {
1329            return PackageManager.PERMISSION_GRANTED;
1330        }
1331        try {
1332            return ActivityManagerNative.getDefault().checkUriPermission(
1333                    uri, pid, uid, modeFlags);
1334        } catch (RemoteException e) {
1335            return PackageManager.PERMISSION_DENIED;
1336        }
1337    }
1338
1339    @Override
1340    public int checkCallingUriPermission(Uri uri, int modeFlags) {
1341        if (!Process.supportsProcesses()) {
1342            return PackageManager.PERMISSION_GRANTED;
1343        }
1344        int pid = Binder.getCallingPid();
1345        if (pid != Process.myPid()) {
1346            return checkUriPermission(uri, pid,
1347                    Binder.getCallingUid(), modeFlags);
1348        }
1349        return PackageManager.PERMISSION_DENIED;
1350    }
1351
1352    @Override
1353    public int checkCallingOrSelfUriPermission(Uri uri, int modeFlags) {
1354        return checkUriPermission(uri, Binder.getCallingPid(),
1355                Binder.getCallingUid(), modeFlags);
1356    }
1357
1358    @Override
1359    public int checkUriPermission(Uri uri, String readPermission,
1360            String writePermission, int pid, int uid, int modeFlags) {
1361        if (DEBUG) {
1362            Log.i("foo", "checkUriPermission: uri=" + uri + "readPermission="
1363                    + readPermission + " writePermission=" + writePermission
1364                    + " pid=" + pid + " uid=" + uid + " mode" + modeFlags);
1365        }
1366        if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
1367            if (readPermission == null
1368                    || checkPermission(readPermission, pid, uid)
1369                    == PackageManager.PERMISSION_GRANTED) {
1370                return PackageManager.PERMISSION_GRANTED;
1371            }
1372        }
1373        if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
1374            if (writePermission == null
1375                    || checkPermission(writePermission, pid, uid)
1376                    == PackageManager.PERMISSION_GRANTED) {
1377                return PackageManager.PERMISSION_GRANTED;
1378            }
1379        }
1380        return uri != null ? checkUriPermission(uri, pid, uid, modeFlags)
1381                : PackageManager.PERMISSION_DENIED;
1382    }
1383
1384    private String uriModeFlagToString(int uriModeFlags) {
1385        switch (uriModeFlags) {
1386            case Intent.FLAG_GRANT_READ_URI_PERMISSION |
1387                    Intent.FLAG_GRANT_WRITE_URI_PERMISSION:
1388                return "read and write";
1389            case Intent.FLAG_GRANT_READ_URI_PERMISSION:
1390                return "read";
1391            case Intent.FLAG_GRANT_WRITE_URI_PERMISSION:
1392                return "write";
1393        }
1394        throw new IllegalArgumentException(
1395                "Unknown permission mode flags: " + uriModeFlags);
1396    }
1397
1398    private void enforceForUri(
1399            int modeFlags, int resultOfCheck, boolean selfToo,
1400            int uid, Uri uri, String message) {
1401        if (resultOfCheck != PackageManager.PERMISSION_GRANTED) {
1402            throw new SecurityException(
1403                    (message != null ? (message + ": ") : "") +
1404                    (selfToo
1405                     ? "Neither user " + uid + " nor current process has "
1406                     : "User " + uid + " does not have ") +
1407                    uriModeFlagToString(modeFlags) +
1408                    " permission on " +
1409                    uri +
1410                    ".");
1411        }
1412    }
1413
1414    public void enforceUriPermission(
1415            Uri uri, int pid, int uid, int modeFlags, String message) {
1416        enforceForUri(
1417                modeFlags, checkUriPermission(uri, pid, uid, modeFlags),
1418                false, uid, uri, message);
1419    }
1420
1421    public void enforceCallingUriPermission(
1422            Uri uri, int modeFlags, String message) {
1423        enforceForUri(
1424                modeFlags, checkCallingUriPermission(uri, modeFlags),
1425                false, Binder.getCallingUid(), uri, message);
1426    }
1427
1428    public void enforceCallingOrSelfUriPermission(
1429            Uri uri, int modeFlags, String message) {
1430        enforceForUri(
1431                modeFlags,
1432                checkCallingOrSelfUriPermission(uri, modeFlags), true,
1433                Binder.getCallingUid(), uri, message);
1434    }
1435
1436    public void enforceUriPermission(
1437            Uri uri, String readPermission, String writePermission,
1438            int pid, int uid, int modeFlags, String message) {
1439        enforceForUri(modeFlags,
1440                      checkUriPermission(
1441                              uri, readPermission, writePermission, pid, uid,
1442                              modeFlags),
1443                      false,
1444                      uid,
1445                      uri,
1446                      message);
1447    }
1448
1449    @Override
1450    public Context createPackageContext(String packageName, int flags)
1451        throws PackageManager.NameNotFoundException {
1452        if (packageName.equals("system") || packageName.equals("android")) {
1453            return new ContextImpl(mMainThread.getSystemContext());
1454        }
1455
1456        LoadedApk pi =
1457            mMainThread.getPackageInfo(packageName, flags);
1458        if (pi != null) {
1459            ContextImpl c = new ContextImpl();
1460            c.mRestricted = (flags & CONTEXT_RESTRICTED) == CONTEXT_RESTRICTED;
1461            c.init(pi, null, mMainThread, mResources);
1462            if (c.mResources != null) {
1463                return c;
1464            }
1465        }
1466
1467        // Should be a better exception.
1468        throw new PackageManager.NameNotFoundException(
1469            "Application package " + packageName + " not found");
1470    }
1471
1472    @Override
1473    public boolean isRestricted() {
1474        return mRestricted;
1475    }
1476
1477    private File getDataDirFile() {
1478        if (mPackageInfo != null) {
1479            return mPackageInfo.getDataDirFile();
1480        }
1481        throw new RuntimeException("Not supported in system context");
1482    }
1483
1484    @Override
1485    public File getDir(String name, int mode) {
1486        name = "app_" + name;
1487        File file = makeFilename(getDataDirFile(), name);
1488        if (!file.exists()) {
1489            file.mkdir();
1490            setFilePermissionsFromMode(file.getPath(), mode,
1491                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH);
1492        }
1493        return file;
1494    }
1495
1496    static ContextImpl createSystemContext(ActivityThread mainThread) {
1497        ContextImpl context = new ContextImpl();
1498        context.init(Resources.getSystem(), mainThread);
1499        return context;
1500    }
1501
1502    ContextImpl() {
1503        mOuterContext = this;
1504    }
1505
1506    /**
1507     * Create a new ApplicationContext from an existing one.  The new one
1508     * works and operates the same as the one it is copying.
1509     *
1510     * @param context Existing application context.
1511     */
1512    public ContextImpl(ContextImpl context) {
1513        mPackageInfo = context.mPackageInfo;
1514        mResources = context.mResources;
1515        mMainThread = context.mMainThread;
1516        mContentResolver = context.mContentResolver;
1517        mOuterContext = this;
1518    }
1519
1520    final void init(LoadedApk packageInfo,
1521            IBinder activityToken, ActivityThread mainThread) {
1522        init(packageInfo, activityToken, mainThread, null);
1523    }
1524
1525    final void init(LoadedApk packageInfo,
1526                IBinder activityToken, ActivityThread mainThread,
1527                Resources container) {
1528        mPackageInfo = packageInfo;
1529        mResources = mPackageInfo.getResources(mainThread);
1530
1531        if (mResources != null && container != null
1532                && container.getCompatibilityInfo().applicationScale !=
1533                        mResources.getCompatibilityInfo().applicationScale) {
1534            if (DEBUG) {
1535                Log.d(TAG, "loaded context has different scaling. Using container's" +
1536                        " compatiblity info:" + container.getDisplayMetrics());
1537            }
1538            mResources = mainThread.getTopLevelResources(
1539                    mPackageInfo.getResDir(), container.getCompatibilityInfo().copy());
1540        }
1541        mMainThread = mainThread;
1542        mContentResolver = new ApplicationContentResolver(this, mainThread);
1543
1544        setActivityToken(activityToken);
1545    }
1546
1547    final void init(Resources resources, ActivityThread mainThread) {
1548        mPackageInfo = null;
1549        mResources = resources;
1550        mMainThread = mainThread;
1551        mContentResolver = new ApplicationContentResolver(this, mainThread);
1552    }
1553
1554    final void scheduleFinalCleanup(String who, String what) {
1555        mMainThread.scheduleContextCleanup(this, who, what);
1556    }
1557
1558    final void performFinalCleanup(String who, String what) {
1559        //Log.i(TAG, "Cleanup up context: " + this);
1560        mPackageInfo.removeContextRegistrations(getOuterContext(), who, what);
1561    }
1562
1563    final Context getReceiverRestrictedContext() {
1564        if (mReceiverRestrictedContext != null) {
1565            return mReceiverRestrictedContext;
1566        }
1567        return mReceiverRestrictedContext = new ReceiverRestrictedContext(getOuterContext());
1568    }
1569
1570    final void setActivityToken(IBinder token) {
1571        mActivityToken = token;
1572    }
1573
1574    final void setOuterContext(Context context) {
1575        mOuterContext = context;
1576    }
1577
1578    final Context getOuterContext() {
1579        return mOuterContext;
1580    }
1581
1582    final IBinder getActivityToken() {
1583        return mActivityToken;
1584    }
1585
1586    private static void setFilePermissionsFromMode(String name, int mode,
1587            int extraPermissions) {
1588        int perms = FileUtils.S_IRUSR|FileUtils.S_IWUSR
1589            |FileUtils.S_IRGRP|FileUtils.S_IWGRP
1590            |extraPermissions;
1591        if ((mode&MODE_WORLD_READABLE) != 0) {
1592            perms |= FileUtils.S_IROTH;
1593        }
1594        if ((mode&MODE_WORLD_WRITEABLE) != 0) {
1595            perms |= FileUtils.S_IWOTH;
1596        }
1597        if (DEBUG) {
1598            Log.i(TAG, "File " + name + ": mode=0x" + Integer.toHexString(mode)
1599                  + ", perms=0x" + Integer.toHexString(perms));
1600        }
1601        FileUtils.setPermissions(name, perms, -1, -1);
1602    }
1603
1604    private File validateFilePath(String name, boolean createDirectory) {
1605        File dir;
1606        File f;
1607
1608        if (name.charAt(0) == File.separatorChar) {
1609            String dirPath = name.substring(0, name.lastIndexOf(File.separatorChar));
1610            dir = new File(dirPath);
1611            name = name.substring(name.lastIndexOf(File.separatorChar));
1612            f = new File(dir, name);
1613        } else {
1614            dir = getDatabasesDir();
1615            f = makeFilename(dir, name);
1616        }
1617
1618        if (createDirectory && !dir.isDirectory() && dir.mkdir()) {
1619            FileUtils.setPermissions(dir.getPath(),
1620                FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1621                -1, -1);
1622        }
1623
1624        return f;
1625    }
1626
1627    private File makeFilename(File base, String name) {
1628        if (name.indexOf(File.separatorChar) < 0) {
1629            return new File(base, name);
1630        }
1631        throw new IllegalArgumentException(
1632                "File " + name + " contains a path separator");
1633    }
1634
1635    // ----------------------------------------------------------------------
1636    // ----------------------------------------------------------------------
1637    // ----------------------------------------------------------------------
1638
1639    private static final class ApplicationContentResolver extends ContentResolver {
1640        public ApplicationContentResolver(Context context, ActivityThread mainThread) {
1641            super(context);
1642            mMainThread = mainThread;
1643        }
1644
1645        @Override
1646        protected IContentProvider acquireProvider(Context context, String name) {
1647            return mMainThread.acquireProvider(context, name);
1648        }
1649
1650        @Override
1651        protected IContentProvider acquireExistingProvider(Context context, String name) {
1652            return mMainThread.acquireExistingProvider(context, name);
1653        }
1654
1655        @Override
1656        public boolean releaseProvider(IContentProvider provider) {
1657            return mMainThread.releaseProvider(provider);
1658        }
1659
1660        private final ActivityThread mMainThread;
1661    }
1662
1663    // ----------------------------------------------------------------------
1664    // ----------------------------------------------------------------------
1665    // ----------------------------------------------------------------------
1666
1667    /*package*/
1668    static final class ApplicationPackageManager extends PackageManager {
1669        @Override
1670        public PackageInfo getPackageInfo(String packageName, int flags)
1671                throws NameNotFoundException {
1672            try {
1673                PackageInfo pi = mPM.getPackageInfo(packageName, flags);
1674                if (pi != null) {
1675                    return pi;
1676                }
1677            } catch (RemoteException e) {
1678                throw new RuntimeException("Package manager has died", e);
1679            }
1680
1681            throw new NameNotFoundException(packageName);
1682        }
1683
1684        @Override
1685        public String[] currentToCanonicalPackageNames(String[] names) {
1686            try {
1687                return mPM.currentToCanonicalPackageNames(names);
1688            } catch (RemoteException e) {
1689                throw new RuntimeException("Package manager has died", e);
1690            }
1691        }
1692
1693        @Override
1694        public String[] canonicalToCurrentPackageNames(String[] names) {
1695            try {
1696                return mPM.canonicalToCurrentPackageNames(names);
1697            } catch (RemoteException e) {
1698                throw new RuntimeException("Package manager has died", e);
1699            }
1700        }
1701
1702        @Override
1703        public Intent getLaunchIntentForPackage(String packageName) {
1704            // First see if the package has an INFO activity; the existence of
1705            // such an activity is implied to be the desired front-door for the
1706            // overall package (such as if it has multiple launcher entries).
1707            Intent intentToResolve = new Intent(Intent.ACTION_MAIN);
1708            intentToResolve.addCategory(Intent.CATEGORY_INFO);
1709            intentToResolve.setPackage(packageName);
1710            ResolveInfo resolveInfo = resolveActivity(intentToResolve, 0);
1711
1712            // Otherwise, try to find a main launcher activity.
1713            if (resolveInfo == null) {
1714                // reuse the intent instance
1715                intentToResolve.removeCategory(Intent.CATEGORY_INFO);
1716                intentToResolve.addCategory(Intent.CATEGORY_LAUNCHER);
1717                intentToResolve.setPackage(packageName);
1718                resolveInfo = resolveActivity(intentToResolve, 0);
1719            }
1720            if (resolveInfo == null) {
1721                return null;
1722            }
1723            Intent intent = new Intent(intentToResolve);
1724            intent.setClassName(resolveInfo.activityInfo.applicationInfo.packageName,
1725                                resolveInfo.activityInfo.name);
1726            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1727            return intent;
1728        }
1729
1730        @Override
1731        public int[] getPackageGids(String packageName)
1732            throws NameNotFoundException {
1733            try {
1734                int[] gids = mPM.getPackageGids(packageName);
1735                if (gids == null || gids.length > 0) {
1736                    return gids;
1737                }
1738            } catch (RemoteException e) {
1739                throw new RuntimeException("Package manager has died", e);
1740            }
1741
1742            throw new NameNotFoundException(packageName);
1743        }
1744
1745        @Override
1746        public PermissionInfo getPermissionInfo(String name, int flags)
1747            throws NameNotFoundException {
1748            try {
1749                PermissionInfo pi = mPM.getPermissionInfo(name, flags);
1750                if (pi != null) {
1751                    return pi;
1752                }
1753            } catch (RemoteException e) {
1754                throw new RuntimeException("Package manager has died", e);
1755            }
1756
1757            throw new NameNotFoundException(name);
1758        }
1759
1760        @Override
1761        public List<PermissionInfo> queryPermissionsByGroup(String group, int flags)
1762                throws NameNotFoundException {
1763            try {
1764                List<PermissionInfo> pi = mPM.queryPermissionsByGroup(group, flags);
1765                if (pi != null) {
1766                    return pi;
1767                }
1768            } catch (RemoteException e) {
1769                throw new RuntimeException("Package manager has died", e);
1770            }
1771
1772            throw new NameNotFoundException(group);
1773        }
1774
1775        @Override
1776        public PermissionGroupInfo getPermissionGroupInfo(String name,
1777                int flags) throws NameNotFoundException {
1778            try {
1779                PermissionGroupInfo pgi = mPM.getPermissionGroupInfo(name, flags);
1780                if (pgi != null) {
1781                    return pgi;
1782                }
1783            } catch (RemoteException e) {
1784                throw new RuntimeException("Package manager has died", e);
1785            }
1786
1787            throw new NameNotFoundException(name);
1788        }
1789
1790        @Override
1791        public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1792            try {
1793                return mPM.getAllPermissionGroups(flags);
1794            } catch (RemoteException e) {
1795                throw new RuntimeException("Package manager has died", e);
1796            }
1797        }
1798
1799        @Override
1800        public ApplicationInfo getApplicationInfo(String packageName, int flags)
1801            throws NameNotFoundException {
1802            try {
1803                ApplicationInfo ai = mPM.getApplicationInfo(packageName, flags);
1804                if (ai != null) {
1805                    return ai;
1806                }
1807            } catch (RemoteException e) {
1808                throw new RuntimeException("Package manager has died", e);
1809            }
1810
1811            throw new NameNotFoundException(packageName);
1812        }
1813
1814        @Override
1815        public ActivityInfo getActivityInfo(ComponentName className, int flags)
1816            throws NameNotFoundException {
1817            try {
1818                ActivityInfo ai = mPM.getActivityInfo(className, flags);
1819                if (ai != null) {
1820                    return ai;
1821                }
1822            } catch (RemoteException e) {
1823                throw new RuntimeException("Package manager has died", e);
1824            }
1825
1826            throw new NameNotFoundException(className.toString());
1827        }
1828
1829        @Override
1830        public ActivityInfo getReceiverInfo(ComponentName className, int flags)
1831            throws NameNotFoundException {
1832            try {
1833                ActivityInfo ai = mPM.getReceiverInfo(className, flags);
1834                if (ai != null) {
1835                    return ai;
1836                }
1837            } catch (RemoteException e) {
1838                throw new RuntimeException("Package manager has died", e);
1839            }
1840
1841            throw new NameNotFoundException(className.toString());
1842        }
1843
1844        @Override
1845        public ServiceInfo getServiceInfo(ComponentName className, int flags)
1846            throws NameNotFoundException {
1847            try {
1848                ServiceInfo si = mPM.getServiceInfo(className, flags);
1849                if (si != null) {
1850                    return si;
1851                }
1852            } catch (RemoteException e) {
1853                throw new RuntimeException("Package manager has died", e);
1854            }
1855
1856            throw new NameNotFoundException(className.toString());
1857        }
1858
1859        @Override
1860        public ProviderInfo getProviderInfo(ComponentName className, int flags)
1861            throws NameNotFoundException {
1862            try {
1863                ProviderInfo pi = mPM.getProviderInfo(className, flags);
1864                if (pi != null) {
1865                    return pi;
1866                }
1867            } catch (RemoteException e) {
1868                throw new RuntimeException("Package manager has died", e);
1869            }
1870
1871            throw new NameNotFoundException(className.toString());
1872        }
1873
1874        @Override
1875        public String[] getSystemSharedLibraryNames() {
1876             try {
1877                 return mPM.getSystemSharedLibraryNames();
1878             } catch (RemoteException e) {
1879                 throw new RuntimeException("Package manager has died", e);
1880             }
1881        }
1882
1883        @Override
1884        public FeatureInfo[] getSystemAvailableFeatures() {
1885            try {
1886                return mPM.getSystemAvailableFeatures();
1887            } catch (RemoteException e) {
1888                throw new RuntimeException("Package manager has died", e);
1889            }
1890        }
1891
1892        @Override
1893        public boolean hasSystemFeature(String name) {
1894            try {
1895                return mPM.hasSystemFeature(name);
1896            } catch (RemoteException e) {
1897                throw new RuntimeException("Package manager has died", e);
1898            }
1899        }
1900
1901        @Override
1902        public int checkPermission(String permName, String pkgName) {
1903            try {
1904                return mPM.checkPermission(permName, pkgName);
1905            } catch (RemoteException e) {
1906                throw new RuntimeException("Package manager has died", e);
1907            }
1908        }
1909
1910        @Override
1911        public boolean addPermission(PermissionInfo info) {
1912            try {
1913                return mPM.addPermission(info);
1914            } catch (RemoteException e) {
1915                throw new RuntimeException("Package manager has died", e);
1916            }
1917        }
1918
1919        @Override
1920        public boolean addPermissionAsync(PermissionInfo info) {
1921            try {
1922                return mPM.addPermissionAsync(info);
1923            } catch (RemoteException e) {
1924                throw new RuntimeException("Package manager has died", e);
1925            }
1926        }
1927
1928        @Override
1929        public void removePermission(String name) {
1930            try {
1931                mPM.removePermission(name);
1932            } catch (RemoteException e) {
1933                throw new RuntimeException("Package manager has died", e);
1934            }
1935        }
1936
1937        @Override
1938        public int checkSignatures(String pkg1, String pkg2) {
1939            try {
1940                return mPM.checkSignatures(pkg1, pkg2);
1941            } catch (RemoteException e) {
1942                throw new RuntimeException("Package manager has died", e);
1943            }
1944        }
1945
1946        @Override
1947        public int checkSignatures(int uid1, int uid2) {
1948            try {
1949                return mPM.checkUidSignatures(uid1, uid2);
1950            } catch (RemoteException e) {
1951                throw new RuntimeException("Package manager has died", e);
1952            }
1953        }
1954
1955        @Override
1956        public String[] getPackagesForUid(int uid) {
1957            try {
1958                return mPM.getPackagesForUid(uid);
1959            } catch (RemoteException e) {
1960                throw new RuntimeException("Package manager has died", e);
1961            }
1962        }
1963
1964        @Override
1965        public String getNameForUid(int uid) {
1966            try {
1967                return mPM.getNameForUid(uid);
1968            } catch (RemoteException e) {
1969                throw new RuntimeException("Package manager has died", e);
1970            }
1971        }
1972
1973        @Override
1974        public int getUidForSharedUser(String sharedUserName)
1975                throws NameNotFoundException {
1976            try {
1977                int uid = mPM.getUidForSharedUser(sharedUserName);
1978                if(uid != -1) {
1979                    return uid;
1980                }
1981            } catch (RemoteException e) {
1982                throw new RuntimeException("Package manager has died", e);
1983            }
1984            throw new NameNotFoundException("No shared userid for user:"+sharedUserName);
1985        }
1986
1987        @Override
1988        public List<PackageInfo> getInstalledPackages(int flags) {
1989            try {
1990                return mPM.getInstalledPackages(flags);
1991            } catch (RemoteException e) {
1992                throw new RuntimeException("Package manager has died", e);
1993            }
1994        }
1995
1996        @Override
1997        public List<ApplicationInfo> getInstalledApplications(int flags) {
1998            try {
1999                return mPM.getInstalledApplications(flags);
2000            } catch (RemoteException e) {
2001                throw new RuntimeException("Package manager has died", e);
2002            }
2003        }
2004
2005        @Override
2006        public ResolveInfo resolveActivity(Intent intent, int flags) {
2007            try {
2008                return mPM.resolveIntent(
2009                    intent,
2010                    intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2011                    flags);
2012            } catch (RemoteException e) {
2013                throw new RuntimeException("Package manager has died", e);
2014            }
2015        }
2016
2017        @Override
2018        public List<ResolveInfo> queryIntentActivities(Intent intent,
2019                int flags) {
2020            try {
2021                return mPM.queryIntentActivities(
2022                    intent,
2023                    intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2024                    flags);
2025            } catch (RemoteException e) {
2026                throw new RuntimeException("Package manager has died", e);
2027            }
2028        }
2029
2030        @Override
2031        public List<ResolveInfo> queryIntentActivityOptions(
2032                ComponentName caller, Intent[] specifics, Intent intent,
2033                int flags) {
2034            final ContentResolver resolver = mContext.getContentResolver();
2035
2036            String[] specificTypes = null;
2037            if (specifics != null) {
2038                final int N = specifics.length;
2039                for (int i=0; i<N; i++) {
2040                    Intent sp = specifics[i];
2041                    if (sp != null) {
2042                        String t = sp.resolveTypeIfNeeded(resolver);
2043                        if (t != null) {
2044                            if (specificTypes == null) {
2045                                specificTypes = new String[N];
2046                            }
2047                            specificTypes[i] = t;
2048                        }
2049                    }
2050                }
2051            }
2052
2053            try {
2054                return mPM.queryIntentActivityOptions(caller, specifics,
2055                    specificTypes, intent, intent.resolveTypeIfNeeded(resolver),
2056                    flags);
2057            } catch (RemoteException e) {
2058                throw new RuntimeException("Package manager has died", e);
2059            }
2060        }
2061
2062        @Override
2063        public List<ResolveInfo> queryBroadcastReceivers(Intent intent, int flags) {
2064            try {
2065                return mPM.queryIntentReceivers(
2066                    intent,
2067                    intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2068                    flags);
2069            } catch (RemoteException e) {
2070                throw new RuntimeException("Package manager has died", e);
2071            }
2072        }
2073
2074        @Override
2075        public ResolveInfo resolveService(Intent intent, int flags) {
2076            try {
2077                return mPM.resolveService(
2078                    intent,
2079                    intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2080                    flags);
2081            } catch (RemoteException e) {
2082                throw new RuntimeException("Package manager has died", e);
2083            }
2084        }
2085
2086        @Override
2087        public List<ResolveInfo> queryIntentServices(Intent intent, int flags) {
2088            try {
2089                return mPM.queryIntentServices(
2090                    intent,
2091                    intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2092                    flags);
2093            } catch (RemoteException e) {
2094                throw new RuntimeException("Package manager has died", e);
2095            }
2096        }
2097
2098        @Override
2099        public ProviderInfo resolveContentProvider(String name,
2100                int flags) {
2101            try {
2102                return mPM.resolveContentProvider(name, flags);
2103            } catch (RemoteException e) {
2104                throw new RuntimeException("Package manager has died", e);
2105            }
2106        }
2107
2108        @Override
2109        public List<ProviderInfo> queryContentProviders(String processName,
2110                int uid, int flags) {
2111            try {
2112                return mPM.queryContentProviders(processName, uid, flags);
2113            } catch (RemoteException e) {
2114                throw new RuntimeException("Package manager has died", e);
2115            }
2116        }
2117
2118        @Override
2119        public InstrumentationInfo getInstrumentationInfo(
2120                ComponentName className, int flags)
2121                throws NameNotFoundException {
2122            try {
2123                InstrumentationInfo ii = mPM.getInstrumentationInfo(
2124                        className, flags);
2125                if (ii != null) {
2126                    return ii;
2127                }
2128            } catch (RemoteException e) {
2129                throw new RuntimeException("Package manager has died", e);
2130            }
2131
2132            throw new NameNotFoundException(className.toString());
2133        }
2134
2135        @Override
2136        public List<InstrumentationInfo> queryInstrumentation(
2137                String targetPackage, int flags) {
2138            try {
2139                return mPM.queryInstrumentation(targetPackage, flags);
2140            } catch (RemoteException e) {
2141                throw new RuntimeException("Package manager has died", e);
2142            }
2143        }
2144
2145        @Override public Drawable getDrawable(String packageName, int resid,
2146                ApplicationInfo appInfo) {
2147            ResourceName name = new ResourceName(packageName, resid);
2148            Drawable dr = getCachedIcon(name);
2149            if (dr != null) {
2150                return dr;
2151            }
2152            if (appInfo == null) {
2153                try {
2154                    appInfo = getApplicationInfo(packageName, 0);
2155                } catch (NameNotFoundException e) {
2156                    return null;
2157                }
2158            }
2159            try {
2160                Resources r = getResourcesForApplication(appInfo);
2161                dr = r.getDrawable(resid);
2162                if (false) {
2163                    RuntimeException e = new RuntimeException("here");
2164                    e.fillInStackTrace();
2165                    Log.w(TAG, "Getting drawable 0x" + Integer.toHexString(resid)
2166                            + " from package " + packageName
2167                            + ": app scale=" + r.getCompatibilityInfo().applicationScale
2168                            + ", caller scale=" + mContext.getResources().getCompatibilityInfo().applicationScale,
2169                            e);
2170                }
2171                if (DEBUG_ICONS) Log.v(TAG, "Getting drawable 0x"
2172                        + Integer.toHexString(resid) + " from " + r
2173                        + ": " + dr);
2174                putCachedIcon(name, dr);
2175                return dr;
2176            } catch (NameNotFoundException e) {
2177                Log.w("PackageManager", "Failure retrieving resources for"
2178                        + appInfo.packageName);
2179            } catch (RuntimeException e) {
2180                // If an exception was thrown, fall through to return
2181                // default icon.
2182                Log.w("PackageManager", "Failure retrieving icon 0x"
2183                        + Integer.toHexString(resid) + " in package "
2184                        + packageName, e);
2185            }
2186            return null;
2187        }
2188
2189        @Override public Drawable getActivityIcon(ComponentName activityName)
2190                throws NameNotFoundException {
2191            return getActivityInfo(activityName, 0).loadIcon(this);
2192        }
2193
2194        @Override public Drawable getActivityIcon(Intent intent)
2195                throws NameNotFoundException {
2196            if (intent.getComponent() != null) {
2197                return getActivityIcon(intent.getComponent());
2198            }
2199
2200            ResolveInfo info = resolveActivity(
2201                intent, PackageManager.MATCH_DEFAULT_ONLY);
2202            if (info != null) {
2203                return info.activityInfo.loadIcon(this);
2204            }
2205
2206            throw new NameNotFoundException(intent.toURI());
2207        }
2208
2209        @Override public Drawable getDefaultActivityIcon() {
2210            return Resources.getSystem().getDrawable(
2211                com.android.internal.R.drawable.sym_def_app_icon);
2212        }
2213
2214        @Override public Drawable getApplicationIcon(ApplicationInfo info) {
2215            return info.loadIcon(this);
2216        }
2217
2218        @Override public Drawable getApplicationIcon(String packageName)
2219                throws NameNotFoundException {
2220            return getApplicationIcon(getApplicationInfo(packageName, 0));
2221        }
2222
2223        @Override
2224        public Drawable getActivityLogo(ComponentName activityName)
2225                throws NameNotFoundException {
2226            return getActivityInfo(activityName, 0).loadLogo(this);
2227        }
2228
2229        @Override
2230        public Drawable getActivityLogo(Intent intent)
2231                throws NameNotFoundException {
2232            if (intent.getComponent() != null) {
2233                return getActivityLogo(intent.getComponent());
2234            }
2235
2236            ResolveInfo info = resolveActivity(
2237                    intent, PackageManager.MATCH_DEFAULT_ONLY);
2238            if (info != null) {
2239                return info.activityInfo.loadLogo(this);
2240            }
2241
2242            throw new NameNotFoundException(intent.toUri(0));
2243        }
2244
2245        @Override
2246        public Drawable getApplicationLogo(ApplicationInfo info) {
2247            return info.loadLogo(this);
2248        }
2249
2250        @Override
2251        public Drawable getApplicationLogo(String packageName)
2252                throws NameNotFoundException {
2253            return getApplicationLogo(getApplicationInfo(packageName, 0));
2254        }
2255
2256        @Override public Resources getResourcesForActivity(
2257                ComponentName activityName) throws NameNotFoundException {
2258            return getResourcesForApplication(
2259                getActivityInfo(activityName, 0).applicationInfo);
2260        }
2261
2262        @Override public Resources getResourcesForApplication(
2263                ApplicationInfo app) throws NameNotFoundException {
2264            if (app.packageName.equals("system")) {
2265                return mContext.mMainThread.getSystemContext().getResources();
2266            }
2267            Resources r = mContext.mMainThread.getTopLevelResources(
2268                    app.uid == Process.myUid() ? app.sourceDir
2269                    : app.publicSourceDir, mContext.mPackageInfo);
2270            if (r != null) {
2271                return r;
2272            }
2273            throw new NameNotFoundException("Unable to open " + app.publicSourceDir);
2274        }
2275
2276        @Override public Resources getResourcesForApplication(
2277                String appPackageName) throws NameNotFoundException {
2278            return getResourcesForApplication(
2279                getApplicationInfo(appPackageName, 0));
2280        }
2281
2282        int mCachedSafeMode = -1;
2283        @Override public boolean isSafeMode() {
2284            try {
2285                if (mCachedSafeMode < 0) {
2286                    mCachedSafeMode = mPM.isSafeMode() ? 1 : 0;
2287                }
2288                return mCachedSafeMode != 0;
2289            } catch (RemoteException e) {
2290                throw new RuntimeException("Package manager has died", e);
2291            }
2292        }
2293
2294        static void configurationChanged() {
2295            synchronized (sSync) {
2296                sIconCache.clear();
2297                sStringCache.clear();
2298            }
2299        }
2300
2301        ApplicationPackageManager(ContextImpl context,
2302                IPackageManager pm) {
2303            mContext = context;
2304            mPM = pm;
2305        }
2306
2307        private Drawable getCachedIcon(ResourceName name) {
2308            synchronized (sSync) {
2309                WeakReference<Drawable> wr = sIconCache.get(name);
2310                if (DEBUG_ICONS) Log.v(TAG, "Get cached weak drawable ref for "
2311                        + name + ": " + wr);
2312                if (wr != null) {   // we have the activity
2313                    Drawable dr = wr.get();
2314                    if (dr != null) {
2315                        if (DEBUG_ICONS) Log.v(TAG, "Get cached drawable for "
2316                                + name + ": " + dr);
2317                        return dr;
2318                    }
2319                    // our entry has been purged
2320                    sIconCache.remove(name);
2321                }
2322            }
2323            return null;
2324        }
2325
2326        private void putCachedIcon(ResourceName name, Drawable dr) {
2327            synchronized (sSync) {
2328                sIconCache.put(name, new WeakReference<Drawable>(dr));
2329                if (DEBUG_ICONS) Log.v(TAG, "Added cached drawable for "
2330                        + name + ": " + dr);
2331            }
2332        }
2333
2334        static final void handlePackageBroadcast(int cmd, String[] pkgList,
2335                boolean hasPkgInfo) {
2336            boolean immediateGc = false;
2337            if (cmd == IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE) {
2338                immediateGc = true;
2339            }
2340            if (pkgList != null && (pkgList.length > 0)) {
2341                boolean needCleanup = false;
2342                for (String ssp : pkgList) {
2343                    synchronized (sSync) {
2344                        if (sIconCache.size() > 0) {
2345                            Iterator<ResourceName> it = sIconCache.keySet().iterator();
2346                            while (it.hasNext()) {
2347                                ResourceName nm = it.next();
2348                                if (nm.packageName.equals(ssp)) {
2349                                    //Log.i(TAG, "Removing cached drawable for " + nm);
2350                                    it.remove();
2351                                    needCleanup = true;
2352                                }
2353                            }
2354                        }
2355                        if (sStringCache.size() > 0) {
2356                            Iterator<ResourceName> it = sStringCache.keySet().iterator();
2357                            while (it.hasNext()) {
2358                                ResourceName nm = it.next();
2359                                if (nm.packageName.equals(ssp)) {
2360                                    //Log.i(TAG, "Removing cached string for " + nm);
2361                                    it.remove();
2362                                    needCleanup = true;
2363                                }
2364                            }
2365                        }
2366                    }
2367                }
2368                if (needCleanup || hasPkgInfo) {
2369                    if (immediateGc) {
2370                        // Schedule an immediate gc.
2371                        Runtime.getRuntime().gc();
2372                    } else {
2373                        ActivityThread.currentActivityThread().scheduleGcIdler();
2374                    }
2375                }
2376            }
2377        }
2378
2379        private static final class ResourceName {
2380            final String packageName;
2381            final int iconId;
2382
2383            ResourceName(String _packageName, int _iconId) {
2384                packageName = _packageName;
2385                iconId = _iconId;
2386            }
2387
2388            ResourceName(ApplicationInfo aInfo, int _iconId) {
2389                this(aInfo.packageName, _iconId);
2390            }
2391
2392            ResourceName(ComponentInfo cInfo, int _iconId) {
2393                this(cInfo.applicationInfo.packageName, _iconId);
2394            }
2395
2396            ResourceName(ResolveInfo rInfo, int _iconId) {
2397                this(rInfo.activityInfo.applicationInfo.packageName, _iconId);
2398            }
2399
2400            @Override
2401            public boolean equals(Object o) {
2402                if (this == o) return true;
2403                if (o == null || getClass() != o.getClass()) return false;
2404
2405                ResourceName that = (ResourceName) o;
2406
2407                if (iconId != that.iconId) return false;
2408                return !(packageName != null ?
2409                        !packageName.equals(that.packageName) : that.packageName != null);
2410
2411            }
2412
2413            @Override
2414            public int hashCode() {
2415                int result;
2416                result = packageName.hashCode();
2417                result = 31 * result + iconId;
2418                return result;
2419            }
2420
2421            @Override
2422            public String toString() {
2423                return "{ResourceName " + packageName + " / " + iconId + "}";
2424            }
2425        }
2426
2427        private CharSequence getCachedString(ResourceName name) {
2428            synchronized (sSync) {
2429                WeakReference<CharSequence> wr = sStringCache.get(name);
2430                if (wr != null) {   // we have the activity
2431                    CharSequence cs = wr.get();
2432                    if (cs != null) {
2433                        return cs;
2434                    }
2435                    // our entry has been purged
2436                    sStringCache.remove(name);
2437                }
2438            }
2439            return null;
2440        }
2441
2442        private void putCachedString(ResourceName name, CharSequence cs) {
2443            synchronized (sSync) {
2444                sStringCache.put(name, new WeakReference<CharSequence>(cs));
2445            }
2446        }
2447
2448        @Override
2449        public CharSequence getText(String packageName, int resid,
2450                ApplicationInfo appInfo) {
2451            ResourceName name = new ResourceName(packageName, resid);
2452            CharSequence text = getCachedString(name);
2453            if (text != null) {
2454                return text;
2455            }
2456            if (appInfo == null) {
2457                try {
2458                    appInfo = getApplicationInfo(packageName, 0);
2459                } catch (NameNotFoundException e) {
2460                    return null;
2461                }
2462            }
2463            try {
2464                Resources r = getResourcesForApplication(appInfo);
2465                text = r.getText(resid);
2466                putCachedString(name, text);
2467                return text;
2468            } catch (NameNotFoundException e) {
2469                Log.w("PackageManager", "Failure retrieving resources for"
2470                        + appInfo.packageName);
2471            } catch (RuntimeException e) {
2472                // If an exception was thrown, fall through to return
2473                // default icon.
2474                Log.w("PackageManager", "Failure retrieving text 0x"
2475                        + Integer.toHexString(resid) + " in package "
2476                        + packageName, e);
2477            }
2478            return null;
2479        }
2480
2481        @Override
2482        public XmlResourceParser getXml(String packageName, int resid,
2483                ApplicationInfo appInfo) {
2484            if (appInfo == null) {
2485                try {
2486                    appInfo = getApplicationInfo(packageName, 0);
2487                } catch (NameNotFoundException e) {
2488                    return null;
2489                }
2490            }
2491            try {
2492                Resources r = getResourcesForApplication(appInfo);
2493                return r.getXml(resid);
2494            } catch (RuntimeException e) {
2495                // If an exception was thrown, fall through to return
2496                // default icon.
2497                Log.w("PackageManager", "Failure retrieving xml 0x"
2498                        + Integer.toHexString(resid) + " in package "
2499                        + packageName, e);
2500            } catch (NameNotFoundException e) {
2501                Log.w("PackageManager", "Failure retrieving resources for"
2502                        + appInfo.packageName);
2503            }
2504            return null;
2505        }
2506
2507        @Override
2508        public CharSequence getApplicationLabel(ApplicationInfo info) {
2509            return info.loadLabel(this);
2510        }
2511
2512        @Override
2513        public void installPackage(Uri packageURI, IPackageInstallObserver observer, int flags,
2514                String installerPackageName) {
2515            try {
2516                mPM.installPackage(packageURI, observer, flags, installerPackageName);
2517            } catch (RemoteException e) {
2518                // Should never happen!
2519            }
2520        }
2521
2522        @Override
2523        public void movePackage(String packageName, IPackageMoveObserver observer, int flags) {
2524            try {
2525                mPM.movePackage(packageName, observer, flags);
2526            } catch (RemoteException e) {
2527                // Should never happen!
2528            }
2529        }
2530
2531        @Override
2532        public String getInstallerPackageName(String packageName) {
2533            try {
2534                return mPM.getInstallerPackageName(packageName);
2535            } catch (RemoteException e) {
2536                // Should never happen!
2537            }
2538            return null;
2539        }
2540
2541        @Override
2542        public void deletePackage(String packageName, IPackageDeleteObserver observer, int flags) {
2543            try {
2544                mPM.deletePackage(packageName, observer, flags);
2545            } catch (RemoteException e) {
2546                // Should never happen!
2547            }
2548        }
2549        @Override
2550        public void clearApplicationUserData(String packageName,
2551                IPackageDataObserver observer) {
2552            try {
2553                mPM.clearApplicationUserData(packageName, observer);
2554            } catch (RemoteException e) {
2555                // Should never happen!
2556            }
2557        }
2558        @Override
2559        public void deleteApplicationCacheFiles(String packageName,
2560                IPackageDataObserver observer) {
2561            try {
2562                mPM.deleteApplicationCacheFiles(packageName, observer);
2563            } catch (RemoteException e) {
2564                // Should never happen!
2565            }
2566        }
2567        @Override
2568        public void freeStorageAndNotify(long idealStorageSize, IPackageDataObserver observer) {
2569            try {
2570                mPM.freeStorageAndNotify(idealStorageSize, observer);
2571            } catch (RemoteException e) {
2572                // Should never happen!
2573            }
2574        }
2575
2576        @Override
2577        public void freeStorage(long freeStorageSize, IntentSender pi) {
2578            try {
2579                mPM.freeStorage(freeStorageSize, pi);
2580            } catch (RemoteException e) {
2581                // Should never happen!
2582            }
2583        }
2584
2585        @Override
2586        public void getPackageSizeInfo(String packageName,
2587                IPackageStatsObserver observer) {
2588            try {
2589                mPM.getPackageSizeInfo(packageName, observer);
2590            } catch (RemoteException e) {
2591                // Should never happen!
2592            }
2593        }
2594        @Override
2595        public void addPackageToPreferred(String packageName) {
2596            try {
2597                mPM.addPackageToPreferred(packageName);
2598            } catch (RemoteException e) {
2599                // Should never happen!
2600            }
2601        }
2602
2603        @Override
2604        public void removePackageFromPreferred(String packageName) {
2605            try {
2606                mPM.removePackageFromPreferred(packageName);
2607            } catch (RemoteException e) {
2608                // Should never happen!
2609            }
2610        }
2611
2612        @Override
2613        public List<PackageInfo> getPreferredPackages(int flags) {
2614            try {
2615                return mPM.getPreferredPackages(flags);
2616            } catch (RemoteException e) {
2617                // Should never happen!
2618            }
2619            return new ArrayList<PackageInfo>();
2620        }
2621
2622        @Override
2623        public void addPreferredActivity(IntentFilter filter,
2624                int match, ComponentName[] set, ComponentName activity) {
2625            try {
2626                mPM.addPreferredActivity(filter, match, set, activity);
2627            } catch (RemoteException e) {
2628                // Should never happen!
2629            }
2630        }
2631
2632        @Override
2633        public void replacePreferredActivity(IntentFilter filter,
2634                int match, ComponentName[] set, ComponentName activity) {
2635            try {
2636                mPM.replacePreferredActivity(filter, match, set, activity);
2637            } catch (RemoteException e) {
2638                // Should never happen!
2639            }
2640        }
2641
2642        @Override
2643        public void clearPackagePreferredActivities(String packageName) {
2644            try {
2645                mPM.clearPackagePreferredActivities(packageName);
2646            } catch (RemoteException e) {
2647                // Should never happen!
2648            }
2649        }
2650
2651        @Override
2652        public int getPreferredActivities(List<IntentFilter> outFilters,
2653                List<ComponentName> outActivities, String packageName) {
2654            try {
2655                return mPM.getPreferredActivities(outFilters, outActivities, packageName);
2656            } catch (RemoteException e) {
2657                // Should never happen!
2658            }
2659            return 0;
2660        }
2661
2662        @Override
2663        public void setComponentEnabledSetting(ComponentName componentName,
2664                int newState, int flags) {
2665            try {
2666                mPM.setComponentEnabledSetting(componentName, newState, flags);
2667            } catch (RemoteException e) {
2668                // Should never happen!
2669            }
2670        }
2671
2672        @Override
2673        public int getComponentEnabledSetting(ComponentName componentName) {
2674            try {
2675                return mPM.getComponentEnabledSetting(componentName);
2676            } catch (RemoteException e) {
2677                // Should never happen!
2678            }
2679            return PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
2680        }
2681
2682        @Override
2683        public void setApplicationEnabledSetting(String packageName,
2684                int newState, int flags) {
2685            try {
2686                mPM.setApplicationEnabledSetting(packageName, newState, flags);
2687            } catch (RemoteException e) {
2688                // Should never happen!
2689            }
2690        }
2691
2692        @Override
2693        public int getApplicationEnabledSetting(String packageName) {
2694            try {
2695                return mPM.getApplicationEnabledSetting(packageName);
2696            } catch (RemoteException e) {
2697                // Should never happen!
2698            }
2699            return PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
2700        }
2701
2702        @Override
2703        public void setPackageObbPath(String packageName, String path) {
2704            try {
2705                mPM.setPackageObbPath(packageName, path);
2706            } catch (RemoteException e) {
2707                // Should never happen!
2708            }
2709        }
2710
2711        private final ContextImpl mContext;
2712        private final IPackageManager mPM;
2713
2714        private static final Object sSync = new Object();
2715        private static HashMap<ResourceName, WeakReference<Drawable> > sIconCache
2716                = new HashMap<ResourceName, WeakReference<Drawable> >();
2717        private static HashMap<ResourceName, WeakReference<CharSequence> > sStringCache
2718                = new HashMap<ResourceName, WeakReference<CharSequence> >();
2719    }
2720
2721    // ----------------------------------------------------------------------
2722    // ----------------------------------------------------------------------
2723    // ----------------------------------------------------------------------
2724
2725    private static final class SharedPreferencesImpl implements SharedPreferences {
2726
2727        // Lock ordering rules:
2728        //  - acquire SharedPreferencesImpl.this before EditorImpl.this
2729        //  - acquire mWritingToDiskLock before EditorImpl.this
2730
2731        private final File mFile;
2732        private final File mBackupFile;
2733        private final int mMode;
2734
2735        private Map<String, Object> mMap;  // guarded by 'this'
2736        private long mTimestamp;  // guarded by 'this'
2737        private int mDiskWritesInFlight = 0;  // guarded by 'this'
2738        private boolean mLoaded = false;  // guarded by 'this'
2739
2740        private final Object mWritingToDiskLock = new Object();
2741        private static final Object mContent = new Object();
2742        private WeakHashMap<OnSharedPreferenceChangeListener, Object> mListeners;
2743
2744        SharedPreferencesImpl(
2745            File file, int mode, Map initialContents) {
2746            mFile = file;
2747            mBackupFile = makeBackupFile(file);
2748            mMode = mode;
2749            mLoaded = initialContents != null;
2750            mMap = initialContents != null ? initialContents : new HashMap<String, Object>();
2751            FileStatus stat = new FileStatus();
2752            if (FileUtils.getFileStatus(file.getPath(), stat)) {
2753                mTimestamp = stat.mtime;
2754            }
2755            mListeners = new WeakHashMap<OnSharedPreferenceChangeListener, Object>();
2756        }
2757
2758        // Has this SharedPreferences ever had values assigned to it?
2759        boolean isLoaded() {
2760            synchronized (this) {
2761                return mLoaded;
2762            }
2763        }
2764
2765        // Has the file changed out from under us?  i.e. writes that
2766        // we didn't instigate.
2767        public boolean hasFileChangedUnexpectedly() {
2768            synchronized (this) {
2769                if (mDiskWritesInFlight > 0) {
2770                    // If we know we caused it, it's not unexpected.
2771                    Log.d(TAG, "disk write in flight, not unexpected.");
2772                    return false;
2773                }
2774            }
2775            FileStatus stat = new FileStatus();
2776            if (!FileUtils.getFileStatus(mFile.getPath(), stat)) {
2777                return true;
2778            }
2779            synchronized (this) {
2780                return mTimestamp != stat.mtime;
2781            }
2782        }
2783
2784        public void replace(Map newContents) {
2785            synchronized (this) {
2786                mLoaded = true;
2787                if (newContents != null) {
2788                    mMap = newContents;
2789                }
2790            }
2791        }
2792
2793        public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
2794            synchronized(this) {
2795                mListeners.put(listener, mContent);
2796            }
2797        }
2798
2799        public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
2800            synchronized(this) {
2801                mListeners.remove(listener);
2802            }
2803        }
2804
2805        public Map<String, ?> getAll() {
2806            synchronized(this) {
2807                //noinspection unchecked
2808                return new HashMap<String, Object>(mMap);
2809            }
2810        }
2811
2812        public String getString(String key, String defValue) {
2813            synchronized (this) {
2814                String v = (String)mMap.get(key);
2815                return v != null ? v : defValue;
2816            }
2817        }
2818
2819        public Set<String> getStringSet(String key, Set<String> defValues) {
2820            synchronized (this) {
2821                Set<String> v = (Set<String>) mMap.get(key);
2822                return v != null ? v : defValues;
2823            }
2824        }
2825
2826        public int getInt(String key, int defValue) {
2827            synchronized (this) {
2828                Integer v = (Integer)mMap.get(key);
2829                return v != null ? v : defValue;
2830            }
2831        }
2832        public long getLong(String key, long defValue) {
2833            synchronized (this) {
2834                Long v = (Long)mMap.get(key);
2835                return v != null ? v : defValue;
2836            }
2837        }
2838        public float getFloat(String key, float defValue) {
2839            synchronized (this) {
2840                Float v = (Float)mMap.get(key);
2841                return v != null ? v : defValue;
2842            }
2843        }
2844        public boolean getBoolean(String key, boolean defValue) {
2845            synchronized (this) {
2846                Boolean v = (Boolean)mMap.get(key);
2847                return v != null ? v : defValue;
2848            }
2849        }
2850
2851        public boolean contains(String key) {
2852            synchronized (this) {
2853                return mMap.containsKey(key);
2854            }
2855        }
2856
2857        public Editor edit() {
2858            return new EditorImpl();
2859        }
2860
2861        // Return value from EditorImpl#commitToMemory()
2862        private static class MemoryCommitResult {
2863            public boolean changesMade;  // any keys different?
2864            public List<String> keysModified;  // may be null
2865            public Set<OnSharedPreferenceChangeListener> listeners;  // may be null
2866            public Map<?, ?> mapToWriteToDisk;
2867            public final CountDownLatch writtenToDiskLatch = new CountDownLatch(1);
2868            public volatile boolean writeToDiskResult = false;
2869
2870            public void setDiskWriteResult(boolean result) {
2871                writeToDiskResult = result;
2872                writtenToDiskLatch.countDown();
2873            }
2874        }
2875
2876        public final class EditorImpl implements Editor {
2877            private final Map<String, Object> mModified = Maps.newHashMap();
2878            private boolean mClear = false;
2879
2880            public Editor putString(String key, String value) {
2881                synchronized (this) {
2882                    mModified.put(key, value);
2883                    return this;
2884                }
2885            }
2886            public Editor putStringSet(String key, Set<String> values) {
2887                synchronized (this) {
2888                    mModified.put(key, values);
2889                    return this;
2890                }
2891            }
2892            public Editor putInt(String key, int value) {
2893                synchronized (this) {
2894                    mModified.put(key, value);
2895                    return this;
2896                }
2897            }
2898            public Editor putLong(String key, long value) {
2899                synchronized (this) {
2900                    mModified.put(key, value);
2901                    return this;
2902                }
2903            }
2904            public Editor putFloat(String key, float value) {
2905                synchronized (this) {
2906                    mModified.put(key, value);
2907                    return this;
2908                }
2909            }
2910            public Editor putBoolean(String key, boolean value) {
2911                synchronized (this) {
2912                    mModified.put(key, value);
2913                    return this;
2914                }
2915            }
2916
2917            public Editor remove(String key) {
2918                synchronized (this) {
2919                    mModified.put(key, this);
2920                    return this;
2921                }
2922            }
2923
2924            public Editor clear() {
2925                synchronized (this) {
2926                    mClear = true;
2927                    return this;
2928                }
2929            }
2930
2931            public void apply() {
2932                final MemoryCommitResult mcr = commitToMemory();
2933                final Runnable awaitCommit = new Runnable() {
2934                        public void run() {
2935                            try {
2936                                mcr.writtenToDiskLatch.await();
2937                            } catch (InterruptedException ignored) {
2938                            }
2939                        }
2940                    };
2941
2942                QueuedWork.add(awaitCommit);
2943
2944                Runnable postWriteRunnable = new Runnable() {
2945                        public void run() {
2946                            awaitCommit.run();
2947                            QueuedWork.remove(awaitCommit);
2948                        }
2949                    };
2950
2951                SharedPreferencesImpl.this.enqueueDiskWrite(mcr, postWriteRunnable);
2952
2953                // Okay to notify the listeners before it's hit disk
2954                // because the listeners should always get the same
2955                // SharedPreferences instance back, which has the
2956                // changes reflected in memory.
2957                notifyListeners(mcr);
2958            }
2959
2960            // Returns true if any changes were made
2961            private MemoryCommitResult commitToMemory() {
2962                MemoryCommitResult mcr = new MemoryCommitResult();
2963                synchronized (SharedPreferencesImpl.this) {
2964                    // We optimistically don't make a deep copy until
2965                    // a memory commit comes in when we're already
2966                    // writing to disk.
2967                    if (mDiskWritesInFlight > 0) {
2968                        // We can't modify our mMap as a currently
2969                        // in-flight write owns it.  Clone it before
2970                        // modifying it.
2971                        // noinspection unchecked
2972                        mMap = new HashMap<String, Object>(mMap);
2973                    }
2974                    mcr.mapToWriteToDisk = mMap;
2975                    mDiskWritesInFlight++;
2976
2977                    boolean hasListeners = mListeners.size() > 0;
2978                    if (hasListeners) {
2979                        mcr.keysModified = new ArrayList<String>();
2980                        mcr.listeners =
2981                            new HashSet<OnSharedPreferenceChangeListener>(mListeners.keySet());
2982                    }
2983
2984                    synchronized (this) {
2985                        if (mClear) {
2986                            if (!mMap.isEmpty()) {
2987                                mcr.changesMade = true;
2988                                mMap.clear();
2989                            }
2990                            mClear = false;
2991                        }
2992
2993                        for (Entry<String, Object> e : mModified.entrySet()) {
2994                            String k = e.getKey();
2995                            Object v = e.getValue();
2996                            if (v == this) {  // magic value for a removal mutation
2997                                if (!mMap.containsKey(k)) {
2998                                    continue;
2999                                }
3000                                mMap.remove(k);
3001                            } else {
3002                                boolean isSame = false;
3003                                if (mMap.containsKey(k)) {
3004                                    Object existingValue = mMap.get(k);
3005                                    if (existingValue != null && existingValue.equals(v)) {
3006                                        continue;
3007                                    }
3008                                }
3009                                mMap.put(k, v);
3010                            }
3011
3012                            mcr.changesMade = true;
3013                            if (hasListeners) {
3014                                mcr.keysModified.add(k);
3015                            }
3016                        }
3017
3018                        mModified.clear();
3019                    }
3020                }
3021                return mcr;
3022            }
3023
3024            public boolean commit() {
3025                MemoryCommitResult mcr = commitToMemory();
3026                SharedPreferencesImpl.this.enqueueDiskWrite(
3027                    mcr, null /* sync write on this thread okay */);
3028                try {
3029                    mcr.writtenToDiskLatch.await();
3030                } catch (InterruptedException e) {
3031                    return false;
3032                }
3033                notifyListeners(mcr);
3034                return mcr.writeToDiskResult;
3035            }
3036
3037            private void notifyListeners(final MemoryCommitResult mcr) {
3038                if (mcr.listeners == null || mcr.keysModified == null ||
3039                    mcr.keysModified.size() == 0) {
3040                    return;
3041                }
3042                if (Looper.myLooper() == Looper.getMainLooper()) {
3043                    for (int i = mcr.keysModified.size() - 1; i >= 0; i--) {
3044                        final String key = mcr.keysModified.get(i);
3045                        for (OnSharedPreferenceChangeListener listener : mcr.listeners) {
3046                            if (listener != null) {
3047                                listener.onSharedPreferenceChanged(SharedPreferencesImpl.this, key);
3048                            }
3049                        }
3050                    }
3051                } else {
3052                    // Run this function on the main thread.
3053                    ActivityThread.sMainThreadHandler.post(new Runnable() {
3054                            public void run() {
3055                                notifyListeners(mcr);
3056                            }
3057                        });
3058                }
3059            }
3060        }
3061
3062        /**
3063         * Enqueue an already-committed-to-memory result to be written
3064         * to disk.
3065         *
3066         * They will be written to disk one-at-a-time in the order
3067         * that they're enqueued.
3068         *
3069         * @param postWriteRunnable if non-null, we're being called
3070         *   from apply() and this is the runnable to run after
3071         *   the write proceeds.  if null (from a regular commit()),
3072         *   then we're allowed to do this disk write on the main
3073         *   thread (which in addition to reducing allocations and
3074         *   creating a background thread, this has the advantage that
3075         *   we catch them in userdebug StrictMode reports to convert
3076         *   them where possible to apply() ...)
3077         */
3078        private void enqueueDiskWrite(final MemoryCommitResult mcr,
3079                                      final Runnable postWriteRunnable) {
3080            final Runnable writeToDiskRunnable = new Runnable() {
3081                    public void run() {
3082                        synchronized (mWritingToDiskLock) {
3083                            writeToFile(mcr);
3084                        }
3085                        synchronized (SharedPreferencesImpl.this) {
3086                            mDiskWritesInFlight--;
3087                        }
3088                        if (postWriteRunnable != null) {
3089                            postWriteRunnable.run();
3090                        }
3091                    }
3092                };
3093
3094            final boolean isFromSyncCommit = (postWriteRunnable == null);
3095
3096            // Typical #commit() path with fewer allocations, doing a write on
3097            // the current thread.
3098            if (isFromSyncCommit) {
3099                boolean wasEmpty = false;
3100                synchronized (SharedPreferencesImpl.this) {
3101                    wasEmpty = mDiskWritesInFlight == 1;
3102                }
3103                if (wasEmpty) {
3104                    writeToDiskRunnable.run();
3105                    return;
3106                }
3107            }
3108
3109            QueuedWork.singleThreadExecutor().execute(writeToDiskRunnable);
3110        }
3111
3112        private static FileOutputStream createFileOutputStream(File file) {
3113            FileOutputStream str = null;
3114            try {
3115                str = new FileOutputStream(file);
3116            } catch (FileNotFoundException e) {
3117                File parent = file.getParentFile();
3118                if (!parent.mkdir()) {
3119                    Log.e(TAG, "Couldn't create directory for SharedPreferences file " + file);
3120                    return null;
3121                }
3122                FileUtils.setPermissions(
3123                    parent.getPath(),
3124                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3125                    -1, -1);
3126                try {
3127                    str = new FileOutputStream(file);
3128                } catch (FileNotFoundException e2) {
3129                    Log.e(TAG, "Couldn't create SharedPreferences file " + file, e2);
3130                }
3131            }
3132            return str;
3133        }
3134
3135        // Note: must hold mWritingToDiskLock
3136        private void writeToFile(MemoryCommitResult mcr) {
3137            // Rename the current file so it may be used as a backup during the next read
3138            if (mFile.exists()) {
3139                if (!mcr.changesMade) {
3140                    // If the file already exists, but no changes were
3141                    // made to the underlying map, it's wasteful to
3142                    // re-write the file.  Return as if we wrote it
3143                    // out.
3144                    mcr.setDiskWriteResult(true);
3145                    return;
3146                }
3147                if (!mBackupFile.exists()) {
3148                    if (!mFile.renameTo(mBackupFile)) {
3149                        Log.e(TAG, "Couldn't rename file " + mFile
3150                                + " to backup file " + mBackupFile);
3151                        mcr.setDiskWriteResult(false);
3152                        return;
3153                    }
3154                } else {
3155                    mFile.delete();
3156                }
3157            }
3158
3159            // Attempt to write the file, delete the backup and return true as atomically as
3160            // possible.  If any exception occurs, delete the new file; next time we will restore
3161            // from the backup.
3162            try {
3163                FileOutputStream str = createFileOutputStream(mFile);
3164                if (str == null) {
3165                    mcr.setDiskWriteResult(false);
3166                    return;
3167                }
3168                XmlUtils.writeMapXml(mcr.mapToWriteToDisk, str);
3169                str.close();
3170                setFilePermissionsFromMode(mFile.getPath(), mMode, 0);
3171                FileStatus stat = new FileStatus();
3172                if (FileUtils.getFileStatus(mFile.getPath(), stat)) {
3173                    synchronized (this) {
3174                        mTimestamp = stat.mtime;
3175                    }
3176                }
3177                // Writing was successful, delete the backup file if there is one.
3178                mBackupFile.delete();
3179                mcr.setDiskWriteResult(true);
3180                return;
3181            } catch (XmlPullParserException e) {
3182                Log.w(TAG, "writeToFile: Got exception:", e);
3183            } catch (IOException e) {
3184                Log.w(TAG, "writeToFile: Got exception:", e);
3185            }
3186            // Clean up an unsuccessfully written file
3187            if (mFile.exists()) {
3188                if (!mFile.delete()) {
3189                    Log.e(TAG, "Couldn't clean up partially-written file " + mFile);
3190                }
3191            }
3192            mcr.setDiskWriteResult(false);
3193        }
3194    }
3195}
3196