ResolveInfo getIconResource()给出了非常奇怪的结果(不正确的图标)

时间:2015-05-22 10:23:05

标签: java android arraylist android-arrayadapter android-package-managers

我正在创建手机上安装的应用程序列表。我正在使用PackageManagerResolveInfo检索所有已安装的应用程序。由于内存问题,我使用的是getIconResource()而不是loadIcon()

我的问题是如何使用iconResource在int中显示正确的图标,int?

编辑:添加代码

这是我创建包含已安装应用的列表的部分,存储在Arraylist apps

private void loadApps(){
        manager = getPackageManager();
        apps = new ArrayList<AppDetail>();

        if(apps.size()==0) {
            Intent i = new Intent(Intent.ACTION_MAIN, null);
            i.addCategory(Intent.CATEGORY_LAUNCHER);
            List<ResolveInfo> availableActivities = manager.queryIntentActivities(i, 0);
            for (ResolveInfo ri : availableActivities) {
                AppDetail app = new AppDetail();
                app.label = ri.loadLabel(manager);
                app.name = ri.activityInfo.packageName;
                app.icon = ri.activityInfo.getIconResource();
                app.allowed = false;
                apps.add(app);
            }
            Log.i("applist", apps.toString());
        }
    }

在ArrayAdapter中,我想将图标放在ImageView中

ImageView appIcon = (ImageView)convertView.findViewById(R.id.item_app_icon);
            int id = apps.get(position).icon;
            appIcon.setImageResource(id);

这是手机上的结果,它显示奇怪的图标(有些应用甚至使用谷歌加图标:

enter image description here

它还提供了有关无法找到资源的错误:

W/ResourceType﹕ getEntry failing because entryIndex 1 is beyond type entryCount 1 W/ResourceType﹕ Failure getting entry for 0x7f030001 (t=2 e=1) in package 0 (error -2147483647) W/ImageView﹕ Unable to find resource: 2130903041

1 个答案:

答案 0 :(得分:3)

问题是我从错误的地方检索图像。这是获得正确图标的代码:

ImageView appIcon = (ImageView)convertView.findViewById(R.id.item_app_icon);
            String packageName = apps.get(position).name.toString();

            try {
                Drawable icon = getPackageManager().getApplicationIcon(packageName);
                appIcon.setImageDrawable(icon);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }