ApplicationPackageManager.java revision db811dbc704fd8170e66951e992e83098aecf158
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.app;
18
19import android.content.ComponentName;
20import android.content.ContentResolver;
21import android.content.Intent;
22import android.content.IntentFilter;
23import android.content.IntentSender;
24import android.content.pm.ActivityInfo;
25import android.content.pm.ApplicationInfo;
26import android.content.pm.ComponentInfo;
27import android.content.pm.ContainerEncryptionParams;
28import android.content.pm.FeatureInfo;
29import android.content.pm.IPackageDataObserver;
30import android.content.pm.IPackageDeleteObserver;
31import android.content.pm.IPackageInstallObserver;
32import android.content.pm.IPackageManager;
33import android.content.pm.IPackageMoveObserver;
34import android.content.pm.IPackageStatsObserver;
35import android.content.pm.InstrumentationInfo;
36import android.content.pm.KeySet;
37import android.content.pm.ManifestDigest;
38import android.content.pm.PackageInfo;
39import android.content.pm.PackageInstaller;
40import android.content.pm.PackageItemInfo;
41import android.content.pm.PackageManager;
42import android.content.pm.ParceledListSlice;
43import android.content.pm.PermissionGroupInfo;
44import android.content.pm.PermissionInfo;
45import android.content.pm.ProviderInfo;
46import android.content.pm.ResolveInfo;
47import android.content.pm.ServiceInfo;
48import android.content.pm.VerificationParams;
49import android.content.pm.VerifierDeviceIdentity;
50import android.content.res.Resources;
51import android.content.res.XmlResourceParser;
52import android.graphics.drawable.BitmapDrawable;
53import android.graphics.drawable.Drawable;
54import android.net.Uri;
55import android.os.IBinder;
56import android.os.Process;
57import android.os.RemoteException;
58import android.os.UserHandle;
59import android.os.UserManager;
60import android.util.ArrayMap;
61import android.util.Log;
62import android.view.Display;
63
64import com.android.internal.annotations.GuardedBy;
65import com.android.internal.util.Preconditions;
66
67import dalvik.system.VMRuntime;
68
69import java.lang.ref.WeakReference;
70import java.util.ArrayList;
71import java.util.List;
72
73/*package*/
74final class ApplicationPackageManager extends PackageManager {
75    private static final String TAG = "ApplicationPackageManager";
76    private final static boolean DEBUG = false;
77    private final static boolean DEBUG_ICONS = false;
78
79    private final Object mLock = new Object();
80
81    @GuardedBy("mLock")
82    private UserManager mUserManager;
83    @GuardedBy("mLock")
84    private PackageInstaller mInstaller;
85
86    UserManager getUserManager() {
87        synchronized (mLock) {
88            if (mUserManager == null) {
89                mUserManager = UserManager.get(mContext);
90            }
91            return mUserManager;
92        }
93    }
94
95    @Override
96    public PackageInfo getPackageInfo(String packageName, int flags)
97            throws NameNotFoundException {
98        try {
99            PackageInfo pi = mPM.getPackageInfo(packageName, flags, mContext.getUserId());
100            if (pi != null) {
101                return pi;
102            }
103        } catch (RemoteException e) {
104            throw new RuntimeException("Package manager has died", e);
105        }
106
107        throw new NameNotFoundException(packageName);
108    }
109
110    @Override
111    public String[] currentToCanonicalPackageNames(String[] names) {
112        try {
113            return mPM.currentToCanonicalPackageNames(names);
114        } catch (RemoteException e) {
115            throw new RuntimeException("Package manager has died", e);
116        }
117    }
118
119    @Override
120    public String[] canonicalToCurrentPackageNames(String[] names) {
121        try {
122            return mPM.canonicalToCurrentPackageNames(names);
123        } catch (RemoteException e) {
124            throw new RuntimeException("Package manager has died", e);
125        }
126    }
127
128    @Override
129    public Intent getLaunchIntentForPackage(String packageName) {
130        // First see if the package has an INFO activity; the existence of
131        // such an activity is implied to be the desired front-door for the
132        // overall package (such as if it has multiple launcher entries).
133        Intent intentToResolve = new Intent(Intent.ACTION_MAIN);
134        intentToResolve.addCategory(Intent.CATEGORY_INFO);
135        intentToResolve.setPackage(packageName);
136        List<ResolveInfo> ris = queryIntentActivities(intentToResolve, 0);
137
138        // Otherwise, try to find a main launcher activity.
139        if (ris == null || ris.size() <= 0) {
140            // reuse the intent instance
141            intentToResolve.removeCategory(Intent.CATEGORY_INFO);
142            intentToResolve.addCategory(Intent.CATEGORY_LAUNCHER);
143            intentToResolve.setPackage(packageName);
144            ris = queryIntentActivities(intentToResolve, 0);
145        }
146        if (ris == null || ris.size() <= 0) {
147            return null;
148        }
149        Intent intent = new Intent(intentToResolve);
150        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
151        intent.setClassName(ris.get(0).activityInfo.packageName,
152                ris.get(0).activityInfo.name);
153        return intent;
154    }
155
156    @Override
157    public Intent getLeanbackLaunchIntentForPackage(String packageName) {
158        // Try to find a main leanback_launcher activity.
159        Intent intentToResolve = new Intent(Intent.ACTION_MAIN);
160        intentToResolve.addCategory(Intent.CATEGORY_LEANBACK_LAUNCHER);
161        intentToResolve.setPackage(packageName);
162        List<ResolveInfo> ris = queryIntentActivities(intentToResolve, 0);
163
164        if (ris == null || ris.size() <= 0) {
165            return null;
166        }
167        Intent intent = new Intent(intentToResolve);
168        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
169        intent.setClassName(ris.get(0).activityInfo.packageName,
170                ris.get(0).activityInfo.name);
171        return intent;
172    }
173
174    @Override
175    public int[] getPackageGids(String packageName)
176            throws NameNotFoundException {
177        try {
178            int[] gids = mPM.getPackageGids(packageName);
179            if (gids == null || gids.length > 0) {
180                return gids;
181            }
182        } catch (RemoteException e) {
183            throw new RuntimeException("Package manager has died", e);
184        }
185
186        throw new NameNotFoundException(packageName);
187    }
188
189    @Override
190    public int getPackageUid(String packageName, int userHandle)
191            throws NameNotFoundException {
192        try {
193            int uid = mPM.getPackageUid(packageName, userHandle);
194            if (uid >= 0) {
195                return uid;
196            }
197        } catch (RemoteException e) {
198            throw new RuntimeException("Package manager has died", e);
199        }
200
201        throw new NameNotFoundException(packageName);
202    }
203
204    @Override
205    public PermissionInfo getPermissionInfo(String name, int flags)
206            throws NameNotFoundException {
207        try {
208            PermissionInfo pi = mPM.getPermissionInfo(name, flags);
209            if (pi != null) {
210                return pi;
211            }
212        } catch (RemoteException e) {
213            throw new RuntimeException("Package manager has died", e);
214        }
215
216        throw new NameNotFoundException(name);
217    }
218
219    @Override
220    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags)
221            throws NameNotFoundException {
222        try {
223            List<PermissionInfo> pi = mPM.queryPermissionsByGroup(group, flags);
224            if (pi != null) {
225                return pi;
226            }
227        } catch (RemoteException e) {
228            throw new RuntimeException("Package manager has died", e);
229        }
230
231        throw new NameNotFoundException(group);
232    }
233
234    @Override
235    public PermissionGroupInfo getPermissionGroupInfo(String name,
236                                                      int flags) throws NameNotFoundException {
237        try {
238            PermissionGroupInfo pgi = mPM.getPermissionGroupInfo(name, flags);
239            if (pgi != null) {
240                return pgi;
241            }
242        } catch (RemoteException e) {
243            throw new RuntimeException("Package manager has died", e);
244        }
245
246        throw new NameNotFoundException(name);
247    }
248
249    @Override
250    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
251        try {
252            return mPM.getAllPermissionGroups(flags);
253        } catch (RemoteException e) {
254            throw new RuntimeException("Package manager has died", e);
255        }
256    }
257
258    @Override
259    public ApplicationInfo getApplicationInfo(String packageName, int flags)
260            throws NameNotFoundException {
261        try {
262            ApplicationInfo ai = mPM.getApplicationInfo(packageName, flags, mContext.getUserId());
263            if (ai != null) {
264                // This is a temporary hack. Callers must use
265                // createPackageContext(packageName).getApplicationInfo() to
266                // get the right paths.
267                maybeAdjustApplicationInfo(ai);
268                return ai;
269            }
270        } catch (RemoteException e) {
271            throw new RuntimeException("Package manager has died", e);
272        }
273
274        throw new NameNotFoundException(packageName);
275    }
276
277    private static void maybeAdjustApplicationInfo(ApplicationInfo info) {
278        // If we're dealing with a multi-arch application that has both
279        // 32 and 64 bit shared libraries, we might need to choose the secondary
280        // depending on what the current runtime's instruction set is.
281        if (info.primaryCpuAbi != null && info.secondaryCpuAbi != null) {
282            final String runtimeIsa = VMRuntime.getRuntime().vmInstructionSet();
283            final String secondaryIsa = VMRuntime.getInstructionSet(info.secondaryCpuAbi);
284
285            // If the runtimeIsa is the same as the primary isa, then we do nothing.
286            // Everything will be set up correctly because info.nativeLibraryDir will
287            // correspond to the right ISA.
288            if (runtimeIsa.equals(secondaryIsa)) {
289                info.nativeLibraryDir = info.secondaryNativeLibraryDir;
290            }
291        }
292    }
293
294
295    @Override
296    public ActivityInfo getActivityInfo(ComponentName className, int flags)
297            throws NameNotFoundException {
298        try {
299            ActivityInfo ai = mPM.getActivityInfo(className, flags, mContext.getUserId());
300            if (ai != null) {
301                return ai;
302            }
303        } catch (RemoteException e) {
304            throw new RuntimeException("Package manager has died", e);
305        }
306
307        throw new NameNotFoundException(className.toString());
308    }
309
310    @Override
311    public ActivityInfo getReceiverInfo(ComponentName className, int flags)
312            throws NameNotFoundException {
313        try {
314            ActivityInfo ai = mPM.getReceiverInfo(className, flags, mContext.getUserId());
315            if (ai != null) {
316                return ai;
317            }
318        } catch (RemoteException e) {
319            throw new RuntimeException("Package manager has died", e);
320        }
321
322        throw new NameNotFoundException(className.toString());
323    }
324
325    @Override
326    public ServiceInfo getServiceInfo(ComponentName className, int flags)
327            throws NameNotFoundException {
328        try {
329            ServiceInfo si = mPM.getServiceInfo(className, flags, mContext.getUserId());
330            if (si != null) {
331                return si;
332            }
333        } catch (RemoteException e) {
334            throw new RuntimeException("Package manager has died", e);
335        }
336
337        throw new NameNotFoundException(className.toString());
338    }
339
340    @Override
341    public ProviderInfo getProviderInfo(ComponentName className, int flags)
342            throws NameNotFoundException {
343        try {
344            ProviderInfo pi = mPM.getProviderInfo(className, flags, mContext.getUserId());
345            if (pi != null) {
346                return pi;
347            }
348        } catch (RemoteException e) {
349            throw new RuntimeException("Package manager has died", e);
350        }
351
352        throw new NameNotFoundException(className.toString());
353    }
354
355    @Override
356    public String[] getSystemSharedLibraryNames() {
357        try {
358            return mPM.getSystemSharedLibraryNames();
359        } catch (RemoteException e) {
360            throw new RuntimeException("Package manager has died", e);
361        }
362    }
363
364    @Override
365    public FeatureInfo[] getSystemAvailableFeatures() {
366        try {
367            return mPM.getSystemAvailableFeatures();
368        } catch (RemoteException e) {
369            throw new RuntimeException("Package manager has died", e);
370        }
371    }
372
373    @Override
374    public boolean hasSystemFeature(String name) {
375        try {
376            return mPM.hasSystemFeature(name);
377        } catch (RemoteException e) {
378            throw new RuntimeException("Package manager has died", e);
379        }
380    }
381
382    @Override
383    public int checkPermission(String permName, String pkgName) {
384        try {
385            return mPM.checkPermission(permName, pkgName);
386        } catch (RemoteException e) {
387            throw new RuntimeException("Package manager has died", e);
388        }
389    }
390
391    @Override
392    public boolean addPermission(PermissionInfo info) {
393        try {
394            return mPM.addPermission(info);
395        } catch (RemoteException e) {
396            throw new RuntimeException("Package manager has died", e);
397        }
398    }
399
400    @Override
401    public boolean addPermissionAsync(PermissionInfo info) {
402        try {
403            return mPM.addPermissionAsync(info);
404        } catch (RemoteException e) {
405            throw new RuntimeException("Package manager has died", e);
406        }
407    }
408
409    @Override
410    public void removePermission(String name) {
411        try {
412            mPM.removePermission(name);
413        } catch (RemoteException e) {
414            throw new RuntimeException("Package manager has died", e);
415        }
416    }
417
418    @Override
419    public void grantPermission(String packageName, String permissionName) {
420        try {
421            mPM.grantPermission(packageName, permissionName);
422        } catch (RemoteException e) {
423            throw new RuntimeException("Package manager has died", e);
424        }
425    }
426
427    @Override
428    public void revokePermission(String packageName, String permissionName) {
429        try {
430            mPM.revokePermission(packageName, permissionName);
431        } catch (RemoteException e) {
432            throw new RuntimeException("Package manager has died", e);
433        }
434    }
435
436    @Override
437    public int checkSignatures(String pkg1, String pkg2) {
438        try {
439            return mPM.checkSignatures(pkg1, pkg2);
440        } catch (RemoteException e) {
441            throw new RuntimeException("Package manager has died", e);
442        }
443    }
444
445    @Override
446    public int checkSignatures(int uid1, int uid2) {
447        try {
448            return mPM.checkUidSignatures(uid1, uid2);
449        } catch (RemoteException e) {
450            throw new RuntimeException("Package manager has died", e);
451        }
452    }
453
454    @Override
455    public String[] getPackagesForUid(int uid) {
456        try {
457            return mPM.getPackagesForUid(uid);
458        } catch (RemoteException e) {
459            throw new RuntimeException("Package manager has died", e);
460        }
461    }
462
463    @Override
464    public String getNameForUid(int uid) {
465        try {
466            return mPM.getNameForUid(uid);
467        } catch (RemoteException e) {
468            throw new RuntimeException("Package manager has died", e);
469        }
470    }
471
472    @Override
473    public int getUidForSharedUser(String sharedUserName)
474            throws NameNotFoundException {
475        try {
476            int uid = mPM.getUidForSharedUser(sharedUserName);
477            if(uid != -1) {
478                return uid;
479            }
480        } catch (RemoteException e) {
481            throw new RuntimeException("Package manager has died", e);
482        }
483        throw new NameNotFoundException("No shared userid for user:"+sharedUserName);
484    }
485
486    @SuppressWarnings("unchecked")
487    @Override
488    public List<PackageInfo> getInstalledPackages(int flags) {
489        return getInstalledPackages(flags, mContext.getUserId());
490    }
491
492    /** @hide */
493    @Override
494    public List<PackageInfo> getInstalledPackages(int flags, int userId) {
495        try {
496            ParceledListSlice<PackageInfo> slice = mPM.getInstalledPackages(flags, userId);
497            return slice.getList();
498        } catch (RemoteException e) {
499            throw new RuntimeException("Package manager has died", e);
500        }
501    }
502
503    @SuppressWarnings("unchecked")
504    @Override
505    public List<PackageInfo> getPackagesHoldingPermissions(
506            String[] permissions, int flags) {
507        final int userId = mContext.getUserId();
508        try {
509            ParceledListSlice<PackageInfo> slice = mPM.getPackagesHoldingPermissions(
510                    permissions, flags, userId);
511            return slice.getList();
512        } catch (RemoteException e) {
513            throw new RuntimeException("Package manager has died", e);
514        }
515    }
516
517    @SuppressWarnings("unchecked")
518    @Override
519    public List<ApplicationInfo> getInstalledApplications(int flags) {
520        final int userId = mContext.getUserId();
521        try {
522            ParceledListSlice<ApplicationInfo> slice = mPM.getInstalledApplications(flags, userId);
523            return slice.getList();
524        } catch (RemoteException e) {
525            throw new RuntimeException("Package manager has died", e);
526        }
527    }
528
529    @Override
530    public ResolveInfo resolveActivity(Intent intent, int flags) {
531        return resolveActivityAsUser(intent, flags, mContext.getUserId());
532    }
533
534    @Override
535    public ResolveInfo resolveActivityAsUser(Intent intent, int flags, int userId) {
536        try {
537            return mPM.resolveIntent(
538                intent,
539                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
540                flags,
541                userId);
542        } catch (RemoteException e) {
543            throw new RuntimeException("Package manager has died", e);
544        }
545    }
546
547    @Override
548    public List<ResolveInfo> queryIntentActivities(Intent intent,
549                                                   int flags) {
550        return queryIntentActivitiesAsUser(intent, flags, mContext.getUserId());
551    }
552
553    /** @hide Same as above but for a specific user */
554    @Override
555    public List<ResolveInfo> queryIntentActivitiesAsUser(Intent intent,
556                                                   int flags, int userId) {
557        try {
558            return mPM.queryIntentActivities(
559                intent,
560                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
561                flags,
562                userId);
563        } catch (RemoteException e) {
564            throw new RuntimeException("Package manager has died", e);
565        }
566    }
567
568    @Override
569    public List<ResolveInfo> queryIntentActivityOptions(
570        ComponentName caller, Intent[] specifics, Intent intent,
571        int flags) {
572        final ContentResolver resolver = mContext.getContentResolver();
573
574        String[] specificTypes = null;
575        if (specifics != null) {
576            final int N = specifics.length;
577            for (int i=0; i<N; i++) {
578                Intent sp = specifics[i];
579                if (sp != null) {
580                    String t = sp.resolveTypeIfNeeded(resolver);
581                    if (t != null) {
582                        if (specificTypes == null) {
583                            specificTypes = new String[N];
584                        }
585                        specificTypes[i] = t;
586                    }
587                }
588            }
589        }
590
591        try {
592            return mPM.queryIntentActivityOptions(caller, specifics,
593                                                  specificTypes, intent, intent.resolveTypeIfNeeded(resolver),
594                                                  flags, mContext.getUserId());
595        } catch (RemoteException e) {
596            throw new RuntimeException("Package manager has died", e);
597        }
598    }
599
600    /**
601     * @hide
602     */
603    @Override
604    public List<ResolveInfo> queryBroadcastReceivers(Intent intent, int flags, int userId) {
605        try {
606            return mPM.queryIntentReceivers(
607                intent,
608                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
609                flags,
610                userId);
611        } catch (RemoteException e) {
612            throw new RuntimeException("Package manager has died", e);
613        }
614    }
615
616    @Override
617    public List<ResolveInfo> queryBroadcastReceivers(Intent intent, int flags) {
618        return queryBroadcastReceivers(intent, flags, mContext.getUserId());
619    }
620
621    @Override
622    public ResolveInfo resolveService(Intent intent, int flags) {
623        try {
624            return mPM.resolveService(
625                intent,
626                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
627                flags,
628                mContext.getUserId());
629        } catch (RemoteException e) {
630            throw new RuntimeException("Package manager has died", e);
631        }
632    }
633
634    @Override
635    public List<ResolveInfo> queryIntentServicesAsUser(Intent intent, int flags, int userId) {
636        try {
637            return mPM.queryIntentServices(
638                intent,
639                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
640                flags,
641                userId);
642        } catch (RemoteException e) {
643            throw new RuntimeException("Package manager has died", e);
644        }
645    }
646
647    @Override
648    public List<ResolveInfo> queryIntentServices(Intent intent, int flags) {
649        return queryIntentServicesAsUser(intent, flags, mContext.getUserId());
650    }
651
652    @Override
653    public List<ResolveInfo> queryIntentContentProvidersAsUser(
654            Intent intent, int flags, int userId) {
655        try {
656            return mPM.queryIntentContentProviders(intent,
657                    intent.resolveTypeIfNeeded(mContext.getContentResolver()), flags, userId);
658        } catch (RemoteException e) {
659            throw new RuntimeException("Package manager has died", e);
660        }
661    }
662
663    @Override
664    public List<ResolveInfo> queryIntentContentProviders(Intent intent, int flags) {
665        return queryIntentContentProvidersAsUser(intent, flags, mContext.getUserId());
666    }
667
668    @Override
669    public ProviderInfo resolveContentProvider(String name, int flags) {
670        return resolveContentProviderAsUser(name, flags, mContext.getUserId());
671    }
672
673    /** @hide **/
674    @Override
675    public ProviderInfo resolveContentProviderAsUser(String name, int flags, int userId) {
676        try {
677            return mPM.resolveContentProvider(name, flags, userId);
678        } catch (RemoteException e) {
679            throw new RuntimeException("Package manager has died", e);
680        }
681    }
682
683    @Override
684    public List<ProviderInfo> queryContentProviders(String processName,
685                                                    int uid, int flags) {
686        try {
687            return mPM.queryContentProviders(processName, uid, flags);
688        } catch (RemoteException e) {
689            throw new RuntimeException("Package manager has died", e);
690        }
691    }
692
693    @Override
694    public InstrumentationInfo getInstrumentationInfo(
695        ComponentName className, int flags)
696            throws NameNotFoundException {
697        try {
698            InstrumentationInfo ii = mPM.getInstrumentationInfo(
699                className, flags);
700            if (ii != null) {
701                return ii;
702            }
703        } catch (RemoteException e) {
704            throw new RuntimeException("Package manager has died", e);
705        }
706
707        throw new NameNotFoundException(className.toString());
708    }
709
710    @Override
711    public List<InstrumentationInfo> queryInstrumentation(
712        String targetPackage, int flags) {
713        try {
714            return mPM.queryInstrumentation(targetPackage, flags);
715        } catch (RemoteException e) {
716            throw new RuntimeException("Package manager has died", e);
717        }
718    }
719
720    @Override public Drawable getDrawable(String packageName, int resid,
721                                          ApplicationInfo appInfo) {
722        ResourceName name = new ResourceName(packageName, resid);
723        Drawable dr = getCachedIcon(name);
724        if (dr != null) {
725            return dr;
726        }
727        if (appInfo == null) {
728            try {
729                appInfo = getApplicationInfo(packageName, 0);
730            } catch (NameNotFoundException e) {
731                return null;
732            }
733        }
734        try {
735            Resources r = getResourcesForApplication(appInfo);
736            dr = r.getDrawable(resid);
737            if (false) {
738                RuntimeException e = new RuntimeException("here");
739                e.fillInStackTrace();
740                Log.w(TAG, "Getting drawable 0x" + Integer.toHexString(resid)
741                      + " from package " + packageName
742                      + ": app scale=" + r.getCompatibilityInfo().applicationScale
743                      + ", caller scale=" + mContext.getResources().getCompatibilityInfo().applicationScale,
744                      e);
745            }
746            if (DEBUG_ICONS) Log.v(TAG, "Getting drawable 0x"
747                                   + Integer.toHexString(resid) + " from " + r
748                                   + ": " + dr);
749            putCachedIcon(name, dr);
750            return dr;
751        } catch (NameNotFoundException e) {
752            Log.w("PackageManager", "Failure retrieving resources for "
753                  + appInfo.packageName);
754        } catch (Resources.NotFoundException e) {
755            Log.w("PackageManager", "Failure retrieving resources for "
756                  + appInfo.packageName + ": " + e.getMessage());
757        } catch (RuntimeException e) {
758            // If an exception was thrown, fall through to return
759            // default icon.
760            Log.w("PackageManager", "Failure retrieving icon 0x"
761                  + Integer.toHexString(resid) + " in package "
762                  + packageName, e);
763        }
764        return null;
765    }
766
767    @Override public Drawable getActivityIcon(ComponentName activityName)
768            throws NameNotFoundException {
769        return getActivityInfo(activityName, 0).loadIcon(this);
770    }
771
772    @Override public Drawable getActivityIcon(Intent intent)
773            throws NameNotFoundException {
774        if (intent.getComponent() != null) {
775            return getActivityIcon(intent.getComponent());
776        }
777
778        ResolveInfo info = resolveActivity(
779            intent, PackageManager.MATCH_DEFAULT_ONLY);
780        if (info != null) {
781            return info.activityInfo.loadIcon(this);
782        }
783
784        throw new NameNotFoundException(intent.toUri(0));
785    }
786
787    @Override public Drawable getDefaultActivityIcon() {
788        return Resources.getSystem().getDrawable(
789            com.android.internal.R.drawable.sym_def_app_icon);
790    }
791
792    @Override public Drawable getApplicationIcon(ApplicationInfo info) {
793        return info.loadIcon(this);
794    }
795
796    @Override public Drawable getApplicationIcon(String packageName)
797            throws NameNotFoundException {
798        return getApplicationIcon(getApplicationInfo(packageName, 0));
799    }
800
801    @Override
802    public Drawable getActivityBanner(ComponentName activityName)
803            throws NameNotFoundException {
804        return getActivityInfo(activityName, 0).loadBanner(this);
805    }
806
807    @Override
808    public Drawable getActivityBanner(Intent intent)
809            throws NameNotFoundException {
810        if (intent.getComponent() != null) {
811            return getActivityBanner(intent.getComponent());
812        }
813
814        ResolveInfo info = resolveActivity(
815                intent, PackageManager.MATCH_DEFAULT_ONLY);
816        if (info != null) {
817            return info.activityInfo.loadBanner(this);
818        }
819
820        throw new NameNotFoundException(intent.toUri(0));
821    }
822
823    @Override
824    public Drawable getApplicationBanner(ApplicationInfo info) {
825        return info.loadBanner(this);
826    }
827
828    @Override
829    public Drawable getApplicationBanner(String packageName)
830            throws NameNotFoundException {
831        return getApplicationBanner(getApplicationInfo(packageName, 0));
832    }
833
834    @Override
835    public Drawable getActivityLogo(ComponentName activityName)
836            throws NameNotFoundException {
837        return getActivityInfo(activityName, 0).loadLogo(this);
838    }
839
840    @Override
841    public Drawable getActivityLogo(Intent intent)
842            throws NameNotFoundException {
843        if (intent.getComponent() != null) {
844            return getActivityLogo(intent.getComponent());
845        }
846
847        ResolveInfo info = resolveActivity(
848            intent, PackageManager.MATCH_DEFAULT_ONLY);
849        if (info != null) {
850            return info.activityInfo.loadLogo(this);
851        }
852
853        throw new NameNotFoundException(intent.toUri(0));
854    }
855
856    @Override
857    public Drawable getApplicationLogo(ApplicationInfo info) {
858        return info.loadLogo(this);
859    }
860
861    @Override
862    public Drawable getApplicationLogo(String packageName)
863            throws NameNotFoundException {
864        return getApplicationLogo(getApplicationInfo(packageName, 0));
865    }
866
867    @Override public Resources getResourcesForActivity(
868        ComponentName activityName) throws NameNotFoundException {
869        return getResourcesForApplication(
870            getActivityInfo(activityName, 0).applicationInfo);
871    }
872
873    @Override public Resources getResourcesForApplication(
874        ApplicationInfo app) throws NameNotFoundException {
875        if (app.packageName.equals("system")) {
876            return mContext.mMainThread.getSystemContext().getResources();
877        }
878        final boolean sameUid = (app.uid == Process.myUid());
879        Resources r = mContext.mMainThread.getTopLevelResources(
880                sameUid ? app.sourceDir : app.publicSourceDir,
881                sameUid ? app.splitSourceDirs : app.splitPublicSourceDirs,
882                app.resourceDirs, null, Display.DEFAULT_DISPLAY, null, mContext.mPackageInfo);
883        if (r != null) {
884            return r;
885        }
886        throw new NameNotFoundException("Unable to open " + app.publicSourceDir);
887    }
888
889    @Override public Resources getResourcesForApplication(
890        String appPackageName) throws NameNotFoundException {
891        return getResourcesForApplication(
892            getApplicationInfo(appPackageName, 0));
893    }
894
895    /** @hide */
896    @Override
897    public Resources getResourcesForApplicationAsUser(String appPackageName, int userId)
898            throws NameNotFoundException {
899        if (userId < 0) {
900            throw new IllegalArgumentException(
901                    "Call does not support special user #" + userId);
902        }
903        if ("system".equals(appPackageName)) {
904            return mContext.mMainThread.getSystemContext().getResources();
905        }
906        try {
907            ApplicationInfo ai = mPM.getApplicationInfo(appPackageName, 0, userId);
908            if (ai != null) {
909                return getResourcesForApplication(ai);
910            }
911        } catch (RemoteException e) {
912            throw new RuntimeException("Package manager has died", e);
913        }
914        throw new NameNotFoundException("Package " + appPackageName + " doesn't exist");
915    }
916
917    int mCachedSafeMode = -1;
918    @Override public boolean isSafeMode() {
919        try {
920            if (mCachedSafeMode < 0) {
921                mCachedSafeMode = mPM.isSafeMode() ? 1 : 0;
922            }
923            return mCachedSafeMode != 0;
924        } catch (RemoteException e) {
925            throw new RuntimeException("Package manager has died", e);
926        }
927    }
928
929    static void configurationChanged() {
930        synchronized (sSync) {
931            sIconCache.clear();
932            sStringCache.clear();
933        }
934    }
935
936    ApplicationPackageManager(ContextImpl context,
937                              IPackageManager pm) {
938        mContext = context;
939        mPM = pm;
940    }
941
942    private Drawable getCachedIcon(ResourceName name) {
943        synchronized (sSync) {
944            WeakReference<Drawable.ConstantState> wr = sIconCache.get(name);
945            if (DEBUG_ICONS) Log.v(TAG, "Get cached weak drawable ref for "
946                                   + name + ": " + wr);
947            if (wr != null) {   // we have the activity
948                Drawable.ConstantState state = wr.get();
949                if (state != null) {
950                    if (DEBUG_ICONS) {
951                        Log.v(TAG, "Get cached drawable state for " + name + ": " + state);
952                    }
953                    // Note: It's okay here to not use the newDrawable(Resources) variant
954                    //       of the API. The ConstantState comes from a drawable that was
955                    //       originally created by passing the proper app Resources instance
956                    //       which means the state should already contain the proper
957                    //       resources specific information (like density.) See
958                    //       BitmapDrawable.BitmapState for instance.
959                    return state.newDrawable();
960                }
961                // our entry has been purged
962                sIconCache.remove(name);
963            }
964        }
965        return null;
966    }
967
968    private void putCachedIcon(ResourceName name, Drawable dr) {
969        synchronized (sSync) {
970            sIconCache.put(name, new WeakReference<Drawable.ConstantState>(dr.getConstantState()));
971            if (DEBUG_ICONS) Log.v(TAG, "Added cached drawable state for " + name + ": " + dr);
972        }
973    }
974
975    static void handlePackageBroadcast(int cmd, String[] pkgList, boolean hasPkgInfo) {
976        boolean immediateGc = false;
977        if (cmd == IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE) {
978            immediateGc = true;
979        }
980        if (pkgList != null && (pkgList.length > 0)) {
981            boolean needCleanup = false;
982            for (String ssp : pkgList) {
983                synchronized (sSync) {
984                    for (int i=sIconCache.size()-1; i>=0; i--) {
985                        ResourceName nm = sIconCache.keyAt(i);
986                        if (nm.packageName.equals(ssp)) {
987                            //Log.i(TAG, "Removing cached drawable for " + nm);
988                            sIconCache.removeAt(i);
989                            needCleanup = true;
990                        }
991                    }
992                    for (int i=sStringCache.size()-1; i>=0; i--) {
993                        ResourceName nm = sStringCache.keyAt(i);
994                        if (nm.packageName.equals(ssp)) {
995                            //Log.i(TAG, "Removing cached string for " + nm);
996                            sStringCache.removeAt(i);
997                            needCleanup = true;
998                        }
999                    }
1000                }
1001            }
1002            if (needCleanup || hasPkgInfo) {
1003                if (immediateGc) {
1004                    // Schedule an immediate gc.
1005                    Runtime.getRuntime().gc();
1006                } else {
1007                    ActivityThread.currentActivityThread().scheduleGcIdler();
1008                }
1009            }
1010        }
1011    }
1012
1013    private static final class ResourceName {
1014        final String packageName;
1015        final int iconId;
1016
1017        ResourceName(String _packageName, int _iconId) {
1018            packageName = _packageName;
1019            iconId = _iconId;
1020        }
1021
1022        ResourceName(ApplicationInfo aInfo, int _iconId) {
1023            this(aInfo.packageName, _iconId);
1024        }
1025
1026        ResourceName(ComponentInfo cInfo, int _iconId) {
1027            this(cInfo.applicationInfo.packageName, _iconId);
1028        }
1029
1030        ResourceName(ResolveInfo rInfo, int _iconId) {
1031            this(rInfo.activityInfo.applicationInfo.packageName, _iconId);
1032        }
1033
1034        @Override
1035        public boolean equals(Object o) {
1036            if (this == o) return true;
1037            if (o == null || getClass() != o.getClass()) return false;
1038
1039            ResourceName that = (ResourceName) o;
1040
1041            if (iconId != that.iconId) return false;
1042            return !(packageName != null ?
1043                     !packageName.equals(that.packageName) : that.packageName != null);
1044
1045        }
1046
1047        @Override
1048        public int hashCode() {
1049            int result;
1050            result = packageName.hashCode();
1051            result = 31 * result + iconId;
1052            return result;
1053        }
1054
1055        @Override
1056        public String toString() {
1057            return "{ResourceName " + packageName + " / " + iconId + "}";
1058        }
1059    }
1060
1061    private CharSequence getCachedString(ResourceName name) {
1062        synchronized (sSync) {
1063            WeakReference<CharSequence> wr = sStringCache.get(name);
1064            if (wr != null) {   // we have the activity
1065                CharSequence cs = wr.get();
1066                if (cs != null) {
1067                    return cs;
1068                }
1069                // our entry has been purged
1070                sStringCache.remove(name);
1071            }
1072        }
1073        return null;
1074    }
1075
1076    private void putCachedString(ResourceName name, CharSequence cs) {
1077        synchronized (sSync) {
1078            sStringCache.put(name, new WeakReference<CharSequence>(cs));
1079        }
1080    }
1081
1082    @Override
1083    public CharSequence getText(String packageName, int resid,
1084                                ApplicationInfo appInfo) {
1085        ResourceName name = new ResourceName(packageName, resid);
1086        CharSequence text = getCachedString(name);
1087        if (text != null) {
1088            return text;
1089        }
1090        if (appInfo == null) {
1091            try {
1092                appInfo = getApplicationInfo(packageName, 0);
1093            } catch (NameNotFoundException e) {
1094                return null;
1095            }
1096        }
1097        try {
1098            Resources r = getResourcesForApplication(appInfo);
1099            text = r.getText(resid);
1100            putCachedString(name, text);
1101            return text;
1102        } catch (NameNotFoundException e) {
1103            Log.w("PackageManager", "Failure retrieving resources for "
1104                  + appInfo.packageName);
1105        } catch (RuntimeException e) {
1106            // If an exception was thrown, fall through to return
1107            // default icon.
1108            Log.w("PackageManager", "Failure retrieving text 0x"
1109                  + Integer.toHexString(resid) + " in package "
1110                  + packageName, e);
1111        }
1112        return null;
1113    }
1114
1115    @Override
1116    public XmlResourceParser getXml(String packageName, int resid,
1117                                    ApplicationInfo appInfo) {
1118        if (appInfo == null) {
1119            try {
1120                appInfo = getApplicationInfo(packageName, 0);
1121            } catch (NameNotFoundException e) {
1122                return null;
1123            }
1124        }
1125        try {
1126            Resources r = getResourcesForApplication(appInfo);
1127            return r.getXml(resid);
1128        } catch (RuntimeException e) {
1129            // If an exception was thrown, fall through to return
1130            // default icon.
1131            Log.w("PackageManager", "Failure retrieving xml 0x"
1132                  + Integer.toHexString(resid) + " in package "
1133                  + packageName, e);
1134        } catch (NameNotFoundException e) {
1135            Log.w("PackageManager", "Failure retrieving resources for "
1136                  + appInfo.packageName);
1137        }
1138        return null;
1139    }
1140
1141    @Override
1142    public CharSequence getApplicationLabel(ApplicationInfo info) {
1143        return info.loadLabel(this);
1144    }
1145
1146    @Override
1147    public void installPackage(Uri packageURI, IPackageInstallObserver observer, int flags,
1148                               String installerPackageName) {
1149        final VerificationParams verificationParams = new VerificationParams(null, null,
1150                null, VerificationParams.NO_UID, null);
1151        installCommon(packageURI, new LegacyPackageInstallObserver(observer), flags,
1152                installerPackageName, verificationParams, null);
1153    }
1154
1155    @Override
1156    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
1157            int flags, String installerPackageName, Uri verificationURI,
1158            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
1159        final VerificationParams verificationParams = new VerificationParams(verificationURI, null,
1160                null, VerificationParams.NO_UID, manifestDigest);
1161        installCommon(packageURI, new LegacyPackageInstallObserver(observer), flags,
1162                installerPackageName, verificationParams, encryptionParams);
1163    }
1164
1165    @Override
1166    public void installPackageWithVerificationAndEncryption(Uri packageURI,
1167            IPackageInstallObserver observer, int flags, String installerPackageName,
1168            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
1169        installCommon(packageURI, new LegacyPackageInstallObserver(observer), flags,
1170                installerPackageName, verificationParams, encryptionParams);
1171    }
1172
1173    @Override
1174    public void installPackage(Uri packageURI, PackageInstallObserver observer,
1175            int flags, String installerPackageName) {
1176        final VerificationParams verificationParams = new VerificationParams(null, null,
1177                null, VerificationParams.NO_UID, null);
1178        installCommon(packageURI, observer, flags, installerPackageName, verificationParams, null);
1179    }
1180
1181    @Override
1182    public void installPackageWithVerification(Uri packageURI,
1183            PackageInstallObserver observer, int flags, String installerPackageName,
1184            Uri verificationURI, ManifestDigest manifestDigest,
1185            ContainerEncryptionParams encryptionParams) {
1186        final VerificationParams verificationParams = new VerificationParams(verificationURI, null,
1187                null, VerificationParams.NO_UID, manifestDigest);
1188        installCommon(packageURI, observer, flags, installerPackageName, verificationParams,
1189                encryptionParams);
1190    }
1191
1192    @Override
1193    public void installPackageWithVerificationAndEncryption(Uri packageURI,
1194            PackageInstallObserver observer, int flags, String installerPackageName,
1195            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
1196        installCommon(packageURI, observer, flags, installerPackageName, verificationParams,
1197                encryptionParams);
1198    }
1199
1200    private void installCommon(Uri packageURI,
1201            PackageInstallObserver observer, int flags, String installerPackageName,
1202            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
1203        if (!"file".equals(packageURI.getScheme())) {
1204            throw new UnsupportedOperationException("Only file:// URIs are supported");
1205        }
1206        if (encryptionParams != null) {
1207            throw new UnsupportedOperationException("ContainerEncryptionParams not supported");
1208        }
1209
1210        final String originPath = packageURI.getPath();
1211        try {
1212            mPM.installPackage(originPath, observer.getBinder(), flags, installerPackageName,
1213                    verificationParams, null);
1214        } catch (RemoteException ignored) {
1215        }
1216    }
1217
1218    @Override
1219    public int installExistingPackage(String packageName)
1220            throws NameNotFoundException {
1221        try {
1222            int res = mPM.installExistingPackageAsUser(packageName, UserHandle.myUserId());
1223            if (res == INSTALL_FAILED_INVALID_URI) {
1224                throw new NameNotFoundException("Package " + packageName + " doesn't exist");
1225            }
1226            return res;
1227        } catch (RemoteException e) {
1228            // Should never happen!
1229            throw new NameNotFoundException("Package " + packageName + " doesn't exist");
1230        }
1231    }
1232
1233    @Override
1234    public void verifyPendingInstall(int id, int response) {
1235        try {
1236            mPM.verifyPendingInstall(id, response);
1237        } catch (RemoteException e) {
1238            // Should never happen!
1239        }
1240    }
1241
1242    @Override
1243    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
1244            long millisecondsToDelay) {
1245        try {
1246            mPM.extendVerificationTimeout(id, verificationCodeAtTimeout, millisecondsToDelay);
1247        } catch (RemoteException e) {
1248            // Should never happen!
1249        }
1250    }
1251
1252    @Override
1253    public void setInstallerPackageName(String targetPackage,
1254            String installerPackageName) {
1255        try {
1256            mPM.setInstallerPackageName(targetPackage, installerPackageName);
1257        } catch (RemoteException e) {
1258            // Should never happen!
1259        }
1260    }
1261
1262    @Override
1263    public void movePackage(String packageName, IPackageMoveObserver observer, int flags) {
1264        try {
1265            mPM.movePackage(packageName, observer, flags);
1266        } catch (RemoteException e) {
1267            // Should never happen!
1268        }
1269    }
1270
1271    @Override
1272    public String getInstallerPackageName(String packageName) {
1273        try {
1274            return mPM.getInstallerPackageName(packageName);
1275        } catch (RemoteException e) {
1276            // Should never happen!
1277        }
1278        return null;
1279    }
1280
1281    @Override
1282    public void deletePackage(String packageName, IPackageDeleteObserver observer, int flags) {
1283        try {
1284            mPM.deletePackageAsUser(packageName, observer, UserHandle.myUserId(), flags);
1285        } catch (RemoteException e) {
1286            // Should never happen!
1287        }
1288    }
1289
1290    @Override
1291    public void clearApplicationUserData(String packageName,
1292                                         IPackageDataObserver observer) {
1293        try {
1294            mPM.clearApplicationUserData(packageName, observer, mContext.getUserId());
1295        } catch (RemoteException e) {
1296            // Should never happen!
1297        }
1298    }
1299    @Override
1300    public void deleteApplicationCacheFiles(String packageName,
1301                                            IPackageDataObserver observer) {
1302        try {
1303            mPM.deleteApplicationCacheFiles(packageName, observer);
1304        } catch (RemoteException e) {
1305            // Should never happen!
1306        }
1307    }
1308    @Override
1309    public void freeStorageAndNotify(long idealStorageSize, IPackageDataObserver observer) {
1310        try {
1311            mPM.freeStorageAndNotify(idealStorageSize, observer);
1312        } catch (RemoteException e) {
1313            // Should never happen!
1314        }
1315    }
1316
1317    @Override
1318    public void freeStorage(long freeStorageSize, IntentSender pi) {
1319        try {
1320            mPM.freeStorage(freeStorageSize, pi);
1321        } catch (RemoteException e) {
1322            // Should never happen!
1323        }
1324    }
1325
1326    @Override
1327    public void getPackageSizeInfo(String packageName, int userHandle,
1328            IPackageStatsObserver observer) {
1329        try {
1330            mPM.getPackageSizeInfo(packageName, userHandle, observer);
1331        } catch (RemoteException e) {
1332            // Should never happen!
1333        }
1334    }
1335    @Override
1336    public void addPackageToPreferred(String packageName) {
1337        try {
1338            mPM.addPackageToPreferred(packageName);
1339        } catch (RemoteException e) {
1340            // Should never happen!
1341        }
1342    }
1343
1344    @Override
1345    public void removePackageFromPreferred(String packageName) {
1346        try {
1347            mPM.removePackageFromPreferred(packageName);
1348        } catch (RemoteException e) {
1349            // Should never happen!
1350        }
1351    }
1352
1353    @Override
1354    public List<PackageInfo> getPreferredPackages(int flags) {
1355        try {
1356            return mPM.getPreferredPackages(flags);
1357        } catch (RemoteException e) {
1358            // Should never happen!
1359        }
1360        return new ArrayList<PackageInfo>();
1361    }
1362
1363    @Override
1364    public void addPreferredActivity(IntentFilter filter,
1365                                     int match, ComponentName[] set, ComponentName activity) {
1366        try {
1367            mPM.addPreferredActivity(filter, match, set, activity, mContext.getUserId());
1368        } catch (RemoteException e) {
1369            // Should never happen!
1370        }
1371    }
1372
1373    @Override
1374    public void addPreferredActivity(IntentFilter filter, int match,
1375            ComponentName[] set, ComponentName activity, int userId) {
1376        try {
1377            mPM.addPreferredActivity(filter, match, set, activity, userId);
1378        } catch (RemoteException e) {
1379            // Should never happen!
1380        }
1381    }
1382
1383    @Override
1384    public void replacePreferredActivity(IntentFilter filter,
1385                                         int match, ComponentName[] set, ComponentName activity) {
1386        try {
1387            mPM.replacePreferredActivity(filter, match, set, activity, UserHandle.myUserId());
1388        } catch (RemoteException e) {
1389            // Should never happen!
1390        }
1391    }
1392
1393    @Override
1394    public void replacePreferredActivityAsUser(IntentFilter filter,
1395                                         int match, ComponentName[] set, ComponentName activity,
1396                                         int userId) {
1397        try {
1398            mPM.replacePreferredActivity(filter, match, set, activity, userId);
1399        } catch (RemoteException e) {
1400            // Should never happen!
1401        }
1402    }
1403
1404    @Override
1405    public void clearPackagePreferredActivities(String packageName) {
1406        try {
1407            mPM.clearPackagePreferredActivities(packageName);
1408        } catch (RemoteException e) {
1409            // Should never happen!
1410        }
1411    }
1412
1413    @Override
1414    public int getPreferredActivities(List<IntentFilter> outFilters,
1415                                      List<ComponentName> outActivities, String packageName) {
1416        try {
1417            return mPM.getPreferredActivities(outFilters, outActivities, packageName);
1418        } catch (RemoteException e) {
1419            // Should never happen!
1420        }
1421        return 0;
1422    }
1423
1424    @Override
1425    public ComponentName getHomeActivities(List<ResolveInfo> outActivities) {
1426        try {
1427            return mPM.getHomeActivities(outActivities);
1428        } catch (RemoteException e) {
1429            // Should never happen!
1430        }
1431        return null;
1432    }
1433
1434    @Override
1435    public void setComponentEnabledSetting(ComponentName componentName,
1436                                           int newState, int flags) {
1437        try {
1438            mPM.setComponentEnabledSetting(componentName, newState, flags, mContext.getUserId());
1439        } catch (RemoteException e) {
1440            // Should never happen!
1441        }
1442    }
1443
1444    @Override
1445    public int getComponentEnabledSetting(ComponentName componentName) {
1446        try {
1447            return mPM.getComponentEnabledSetting(componentName, mContext.getUserId());
1448        } catch (RemoteException e) {
1449            // Should never happen!
1450        }
1451        return PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
1452    }
1453
1454    @Override
1455    public void setApplicationEnabledSetting(String packageName,
1456                                             int newState, int flags) {
1457        try {
1458            mPM.setApplicationEnabledSetting(packageName, newState, flags,
1459                    mContext.getUserId(), mContext.getOpPackageName());
1460        } catch (RemoteException e) {
1461            // Should never happen!
1462        }
1463    }
1464
1465    @Override
1466    public int getApplicationEnabledSetting(String packageName) {
1467        try {
1468            return mPM.getApplicationEnabledSetting(packageName, mContext.getUserId());
1469        } catch (RemoteException e) {
1470            // Should never happen!
1471        }
1472        return PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
1473    }
1474
1475    @Override
1476    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
1477            UserHandle user) {
1478        try {
1479            return mPM.setApplicationHiddenSettingAsUser(packageName, hidden,
1480                    user.getIdentifier());
1481        } catch (RemoteException re) {
1482            // Should never happen!
1483        }
1484        return false;
1485    }
1486
1487    @Override
1488    public boolean getApplicationHiddenSettingAsUser(String packageName, UserHandle user) {
1489        try {
1490            return mPM.getApplicationHiddenSettingAsUser(packageName, user.getIdentifier());
1491        } catch (RemoteException re) {
1492            // Should never happen!
1493        }
1494        return false;
1495    }
1496
1497    /** @hide */
1498    @Override
1499    public KeySet getKeySetByAlias(String packageName, String alias) {
1500        Preconditions.checkNotNull(packageName);
1501        Preconditions.checkNotNull(alias);
1502        KeySet ks;
1503        try {
1504            ks = mPM.getKeySetByAlias(packageName, alias);
1505        } catch (RemoteException e) {
1506            return null;
1507        }
1508        return ks;
1509    }
1510
1511    /** @hide */
1512    @Override
1513    public KeySet getSigningKeySet(String packageName) {
1514        Preconditions.checkNotNull(packageName);
1515        KeySet ks;
1516        try {
1517            ks = mPM.getSigningKeySet(packageName);
1518        } catch (RemoteException e) {
1519            return null;
1520        }
1521        return ks;
1522    }
1523
1524    /** @hide */
1525    @Override
1526    public boolean isSignedBy(String packageName, KeySet ks) {
1527        Preconditions.checkNotNull(packageName);
1528        Preconditions.checkNotNull(ks);
1529        try {
1530            return mPM.isPackageSignedByKeySet(packageName, ks);
1531        } catch (RemoteException e) {
1532            return false;
1533        }
1534    }
1535
1536    /** @hide */
1537    @Override
1538    public boolean isSignedByExactly(String packageName, KeySet ks) {
1539        Preconditions.checkNotNull(packageName);
1540        Preconditions.checkNotNull(ks);
1541        try {
1542            return mPM.isPackageSignedByKeySetExactly(packageName, ks);
1543        } catch (RemoteException e) {
1544            return false;
1545        }
1546    }
1547
1548    /**
1549     * @hide
1550     */
1551    @Override
1552    public VerifierDeviceIdentity getVerifierDeviceIdentity() {
1553        try {
1554            return mPM.getVerifierDeviceIdentity();
1555        } catch (RemoteException e) {
1556            // Should never happen!
1557        }
1558        return null;
1559    }
1560
1561    @Override
1562    public PackageInstaller getPackageInstaller() {
1563        synchronized (mLock) {
1564            if (mInstaller == null) {
1565                try {
1566                    mInstaller = new PackageInstaller(mContext, this, mPM.getPackageInstaller(),
1567                            mContext.getPackageName(), mContext.getUserId());
1568                } catch (RemoteException e) {
1569                    throw e.rethrowAsRuntimeException();
1570                }
1571            }
1572            return mInstaller;
1573        }
1574    }
1575
1576    @Override
1577    public boolean isPackageAvailable(String packageName) {
1578        try {
1579            return mPM.isPackageAvailable(packageName, mContext.getUserId());
1580        } catch (RemoteException e) {
1581            throw e.rethrowAsRuntimeException();
1582        }
1583    }
1584
1585    /**
1586     * @hide
1587     */
1588    @Override
1589    public void addCrossProfileIntentFilter(IntentFilter filter, int sourceUserId, int targetUserId,
1590            int flags) {
1591        try {
1592            mPM.addCrossProfileIntentFilter(filter, mContext.getOpPackageName(),
1593                    mContext.getUserId(), sourceUserId, targetUserId, flags);
1594        } catch (RemoteException e) {
1595            // Should never happen!
1596        }
1597    }
1598
1599    /**
1600     * @hide
1601     */
1602    public void addCrossProfileIntentsForPackage(String packageName,
1603            int sourceUserId, int targetUserId) {
1604        try {
1605            mPM.addCrossProfileIntentsForPackage(packageName, sourceUserId, targetUserId);
1606        } catch (RemoteException e) {
1607            // Should never happen!
1608        }
1609    }
1610
1611    /**
1612     * @hide
1613     */
1614    public void removeCrossProfileIntentsForPackage(String packageName,
1615            int sourceUserId, int targetUserId) {
1616        try {
1617            mPM.removeCrossProfileIntentsForPackage(packageName, sourceUserId, targetUserId);
1618        } catch (RemoteException e) {
1619            // Should never happen!
1620        }
1621    }
1622
1623    /**
1624     * @hide
1625     */
1626    @Override
1627    public void clearCrossProfileIntentFilters(int sourceUserId) {
1628        try {
1629            mPM.clearCrossProfileIntentFilters(sourceUserId, mContext.getOpPackageName(),
1630                    mContext.getUserId());
1631        } catch (RemoteException e) {
1632            // Should never happen!
1633        }
1634    }
1635
1636    /**
1637     * @hide
1638     */
1639    public Drawable loadItemIcon(PackageItemInfo itemInfo, ApplicationInfo appInfo) {
1640        if (itemInfo.showUserIcon != UserHandle.USER_NULL) {
1641            return new BitmapDrawable(getUserManager().getUserIcon(itemInfo.showUserIcon));
1642        }
1643        Drawable dr = null;
1644        if (itemInfo.packageName != null) {
1645            dr = getDrawable(itemInfo.packageName, itemInfo.icon, appInfo);
1646        }
1647        if (dr == null) {
1648            dr = itemInfo.loadDefaultIcon(this);
1649        }
1650        return getUserManager().getBadgedDrawableForUser(dr,
1651                new UserHandle(mContext.getUserId()));
1652    }
1653
1654    private final ContextImpl mContext;
1655    private final IPackageManager mPM;
1656
1657    private static final Object sSync = new Object();
1658    private static ArrayMap<ResourceName, WeakReference<Drawable.ConstantState>> sIconCache
1659            = new ArrayMap<ResourceName, WeakReference<Drawable.ConstantState>>();
1660    private static ArrayMap<ResourceName, WeakReference<CharSequence>> sStringCache
1661            = new ArrayMap<ResourceName, WeakReference<CharSequence>>();
1662}
1663