0

我可能是一个新手程序员,但 PackageManager 很复杂!我要向您展示的内容毫无意义:

我可以提取设备上的应用程序名称,但是如果我尝试保存到数组,那么我只能保存其中的一半。

        PackageManager packageManager = null;
    List<ApplicationInfo> appsListTest = new ArrayList<ApplicationInfo>();
    packageManager = context.getPackageManager();
    appsListTest = packageManager.getInstalledApplications(0);
    Log.d("LOG", " New PM : " + appsListTest.size());

    Iterator<ApplicationInfo> iterator = appsListTest.iterator();
    int counter = 0;
    String[] appName = new String[appsListTest.size()];
    while (iterator.hasNext()) {

        Log.d("LOG", String.valueOf(counter));
    //  When I print out by itself I see 64 apps. Great
        Log.d("LOG", (String) iterator.next().loadLabel(packageManager));
    //  Now when I try to save to array I only get 30
                    appName[counter] = (String) iterator.next().loadLabel(packageManager);
        counter++;


    }

这没有道理 !!!

因此,如果我注释掉 appName 数组,我将打印 Log.d 61 次。但是当我包含该数组时,我只会注销 31 次。

我将 appName 初始化为 64:

Log.d("LOG", " New PM : " + appsListTest.size());

应用程序不会崩溃或任何事情。

谁能告诉我一些关于如何获取应用程序名称、uid 和图标的代码?

4

1 回答 1

0

iterator.next() advances the list - you are advancing it twice per loop. Instead, you should save the result from iterator.next() as a variable and then use that within the loop:

while (iterator.hasNext()) {
    Log.d("LOG", String.valueOf(counter));
    // Only call iterator.next() once per loop
    ApplicationInfo info = iterator.next();
    String label = (String) info.loadLabel(packageManager);
    Log.d("LOG", label);
    appName[counter] = label;
    counter++;
}
于 2013-05-02T23:00:52.897 回答