android像launcher一樣獲取手機應用列表

下面代碼是獲取系統所有應用,下面判斷條件是判斷系統應用方法,如果是獲取手機所有應用可以去掉下面判斷條件

if ((applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0 ||
                    (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
 }

public static ArrayList getSystemApp(Context context, HashMap<String,SystemItem> itemDrawableMap){
        PackageManager mPackageManager = context.getApplicationContext().getPackageManager();
        LauncherApps  mLauncherApps = (LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE);
        UserManager mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
        List<UserHandle> users = mUserManager.getUserProfiles();
        List<UserHandle> profiles= users == null ? Collections.<UserHandle>emptyList() : users;

        ArrayList<Item> list = new ArrayList<>();
        //根據手機所有用戶獲取每個用戶下的應用
        for (UserHandle user : profiles) {
            // Query for the set of apps
            final List<LauncherActivityInfo> apps = mLauncherApps.getActivityList(null, user);
            // Fail if we don't have any apps
            // TODO: Fix this. Only fail for the current user.
            if (apps == null || apps.isEmpty()) {
                continue;
            }
            // Create the ApplicationInfos
            for (int i = 0; i < apps.size(); i++) {
                LauncherActivityInfo app = apps.get(i);
                // This builds the icon bitmaps.
                ComponentName componentName = app.getComponentName();
                String appName =getSystemApplicationName(componentName.getPackageName(),mPackageManager);
                if(!TextUtils.isEmpty(appName)){
                    Item model = new Item();
                    model.setName(appName);
                    SystemItem systemItem = new SystemItem();
                    systemItem.setItemName(appName);
                    systemItem.setPackName(componentName.getPackageName());
                    systemItem.setIcon(app.getIcon(0));
                    itemDrawableMap.put(model.itemName,systemItem);
                    list.add(model);
                }
            }
        }
        return list;
    }

    public static String getSystemApplicationName(String packageName, PackageManager packageManager) {
        String applicationName = null;
        try {
            ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, 0);
            //filter system app
            if ((applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0 ||
                    (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                applicationName = (String) packageManager.getApplicationLabel(applicationInfo);
            }

        } catch (PackageManager.NameNotFoundException e) {

        }
        return applicationName;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章