Android PackageManager 获取资源编号 0x00000000 的值时没有包标识符

Android PackageManager No package identifier when getting value for resource number 0x00000000

当使用 PackageManager to get a list of applications from the device, if i call pm.getApplicationIcon(app); and the application does not have an icon, the system will return the system default as it's supposed to do 时,但我在控制台中收到此错误输出:

W/ResourceType: No package identifier when getting value for resource number 0x00000000
W/PackageManager: Failure retrieving resources for com.google.android.gsf.login: Resource ID #0x0

由于我要遍历 phone 上的所有应用程序,这会变成一些非常糟糕的垃圾邮件,我希望尽可能避免。

我的代码

PackageManager pm = getActivity().getApplicationContext().getPackageManager();

for (ApplicationInfo app : pm.getInstalledApplications(0)) {
    long dataUsed = ((TrafficStats.getUidRxBytes(app.uid) + TrafficStats.getUidTxBytes(app.uid)) / 1000) / 1000;

    if ((int)dataUsed > 0) {
        String name = pm.getApplicationLabel(app).toString();
        Drawable icon = pm.getApplicationIcon(app);

        // Custom object
        DataUsageItem item = new DataUsageItem(name, icon, false, dataUsed, new int[]{ 0 , 0 , 0 , 0 , 0 , 0 , 0 });
        items.add(item);
    }
}

每个的 ApplicationInfo 都有一个 icon 字段,用于保存给定包中该可绘制对象的资源 ID。在调用 getApplicationIcon().

之前检查它是否为非零

对于那些没有图标的包——即那些 icon 字段为零的包——您可以使用 android.R.drawable.sym_def_app_icon ID 检索系统默认图标。