2014-01-09 35 views
3
private List<App> loadInstalledApps(boolean includeSysApps) { 
    PackageManager appInfo = getPackageManager(); 
    List<ApplicationInfo> listInfo = appInfo.getInstalledApplications(PackageManager.GET_META_DATA); 
    Collections.sort(listInfo, new ApplicationInfo.DisplayNameComparator(appInfo)); 

    List<App> data = new ArrayList<App>(); 
    for (int index = 0; index < listInfo.size(); index++) { 
     try { 

      ApplicationInfo content = listInfo.get(index); 
      if ((content.flags != ApplicationInfo.FLAG_SYSTEM) && content.enabled) { 
       if (content.icon != 0) { 
        App item = new App(); 

        if(!item.isFavourite()) 
        { 
        item.setTitle(getPackageManager().getApplicationLabel(content).toString()); 
        item.setPackageName(content.packageName); 
        item.setIcon(getPackageManager().getDrawable(content.packageName, content.icon, content)); 
        long installed = appInfo.getPackageInfo(content.packageName, 0).firstInstallTime; 
        Date installedDate = new Date(installed); 

        // create a date time formatter 
        SimpleDateFormat formatter = new SimpleDateFormat(
          "dd/MM/yyyy"); 
       String firstInstallDate = formatter.format(installedDate); 
       item.setSize(firstInstallDate);    
      data.add(item); 
        } 
        else if(item.isFavourite()) 
        { 
         item.setTitle(getPackageManager().getApplicationLabel(content).toString()); 
         item.setPackageName(content.packageName); 
         item.setIcon(getPackageManager().getDrawable(content.packageName, content.icon, content)); 
         data.add(item); 

        } 
       } 
      } 
     } catch (Exception e) { 

     } 
    } 
return data; 
} 
+0

現在發生了什麼? –

回答

2

使用比較之下,而不是DisplayNameComparator

public static class InstallTimeComparator implements Comparator<ApplicationInfo> { 

    private final PackageManager mPackageManager; 

    public InstallTimeComparator(PackageManager packageManager) { 
     mPackageManager = packageManager; 
    } 

    @Override 
    public int compare(ApplicationInfo lhs, ApplicationInfo rhs) { 
     try { 
      long lhsInstallTime = mPackageManager.getPackageInfo(lhs.packageName, 0).firstInstallTime; 
      long rhsInstallTime = mPackageManager.getPackageInfo(rhs.packageName, 0).firstInstallTime; 
      if (lhsInstallTime < rhsInstallTime) { 
       return -1; 
      } else if (rhsInstallTime < lhsInstallTime) { 
       return 1; 
      } else { 
       return 0; 
      } 
     } catch (PackageManager.NameNotFoundException e) { 
      e.printStackTrace(); 
      return 0; 
     } 
    } 
} 

的使用將是這樣的:

Collections.sort(listInfo, new InstallTimeComparator(appInfo)); 

如果要反轉順序,請如下:

Collections.sort(listInfo, Collections.reverseOrder(new InstallTimeComparator(appInfo))); 

我沒有檢查過上面的代碼,所以它可能包含一些錯誤,但你會明白。

相關問題