Android---获取应用程序列表

android中获得应用程序列表很简单,主要使用PackageManager就可以!

public class ScreenApp {
    String name;
    String packName;
    Drawable icon;
}

例如:如何获得第三方应用程序列表,即已经安装的应用程序列表,可以这样做:

PackageManager pm = mContext.getPackageManager();
List mPacks = pm.getInstalledPackages(0);
for(PackageInfo info : mPacks){
           ScreenApp mInfo = new ScreenApp();
           mInfo.setIcon(info.applicationInfo.loadIcon(pm));
           mInfo.setName(info.applicationInfo.loadLabel(pm).toString());
           mInfo.setPackageName(info.packageName);
           mInfos.add(mInfo);           
}

例如:获取系统所有的应用,即系统应用+已安装的应用

PackageManager pm = mContext.getPackageManager();
List mPacks = pm.getInstalledPackages(0);
for(PackageInfo info : mPacks){
           if((info.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) == 0){
                ScreenApp mInfo = new ScreenApp();
                mInfo.setIcon(info.applicationInfo.loadIcon(pm));
                mInfo.setName(info.applicationInfo.loadLabel(pm).toString());
                mInfo.setPackageName(info.packageName);
                mInfos.add(mInfo);
            }           
}

在第二个例子中出现了很多无法点击启动的图标,这些应用本身不是一个独立的应用,那么如何获得只包含可启动的应用列表呢?

PackageManager pm = mContext.getPackageManager();
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List mResolveInfo  = pm.queryIntentActivities(mainIntent, 0);
       for(ResolveInfo info : mResolveInfo){
            String packName = info.activityInfo.packageName;
            if(packName.equals(mContext.getPackageName())){
                continue;
            }
            ScreenApp mInfo = new ScreenApp();
            mInfo.setIcon(info.activityInfo.applicationInfo.loadIcon(pm));
            mInfo.setName(info.activityInfo.applicationInfo.loadLabel(pm).toString());
            mInfo.setPackageName(packName);
            mInfos.add(mInfo);
        }

关于获得正在运行的应用列表,看下面的例子:

ActivityManager am = (ActivityManager) getBaseApplication().getSystemService(Context.ACTIVITY_SERVICE);
List mAppProcessInfos = am.getRunningAppProcesses();

到此获得不同应用程序列表的功能就完成了。

你可能感兴趣的:(android提升)