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