获取可以启动的已安装应用程序的列表

时间:2011-11-27 16:54:33

标签: android

我有自定义listPreference我想显示可以启动的应用列表(包含CATEGORY_LAUNCHER的活动)。稍后将使用该选择来启动应用程序。当我搜索解决方案时,该列表还包含无法启动的应用程序。有没有办法缩小范围?

public class AppSelectorPreference extends ListPreference {

@Override
public int findIndexOfValue(String value) {
    return 0;
    //return super.findIndexOfValue(value);
}

public AppSelectorPreference(Context context, AttributeSet attrs) {
    super(context,attrs);

    PackageManager pm = context.getPackageManager();
    List<PackageInfo> appListInfo = pm.getInstalledPackages(0); 
    CharSequence[] entries = new CharSequence[appListInfo.size()];
    CharSequence[] entryValues = new CharSequence[appListInfo.size()];

    try {
        int i = 0;
        for (PackageInfo p : appListInfo) {
            if (p.applicationInfo.uid > 10000) {
                entries[i] = p.applicationInfo.loadLabel(pm).toString();
                entryValues[i] = p.applicationInfo.packageName.toString();              

                i++;
            }         
        }
    } catch (Exception e) {

        e.printStackTrace();
    }   

    setEntries(entries);
    setEntryValues(entryValues);
}

}

2 个答案:

答案 0 :(得分:5)

解决:

    final Context context = getBaseContext();
    final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
    mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    final List<ResolveInfo> pkgAppsList = context.getPackageManager().queryIntentActivities( mainIntent, 0);
    CharSequence[] entries = new CharSequence[pkgAppsList.size()];
    CharSequence[] entryValues = new CharSequence[pkgAppsList.size()];

    int i = 0;
    for ( ResolveInfo P : pkgAppsList ) {
        entryValues[i] = (CharSequence) P.getClass().getName();
        entries[i] = P.loadLabel(context.getPackageManager());
        ++i;
    };

答案 1 :(得分:4)

@ Frazerm63我觉得你在你的代码中遗漏了这个东西

  Intent localIntent = new Intent("android.intent.action.MAIN", null);
  localIntent.addCategory("android.intent.category.LAUNCHER");
  List localList = localPackageManager.queryIntentActivities(localIntent, 0);
  Collections.sort(localList, new ResolveInfo.DisplayNameComparator(localPackageManager));

你必须在上面的代码中传递你的PackageManager对象。意思是这个localPackageManager

我不知道如何在用户代码中使用它,但这有助于让您只想过滤某些类别的应用程序。