Example usage for android.content.pm PackageManager MATCH_DEFAULT_ONLY

List of usage examples for android.content.pm PackageManager MATCH_DEFAULT_ONLY

Introduction

In this page you can find the example usage for android.content.pm PackageManager MATCH_DEFAULT_ONLY.

Prototype

int MATCH_DEFAULT_ONLY

To view the source code for android.content.pm PackageManager MATCH_DEFAULT_ONLY.

Click Source Link

Document

Resolution and querying flag: if set, only filters that support the android.content.Intent#CATEGORY_DEFAULT will be considered for matching.

Usage

From source file:com.android.launcher3.allapps.AllAppsGridAdapter.java

public void setSearchController(AllAppsSearchBarController searchController) {
    mSearchController = searchController;

    // Resolve the market app handling additional searches
    PackageManager pm = mLauncher.getPackageManager();
    ResolveInfo marketInfo = pm.resolveActivity(mSearchController.createMarketSearchIntent(""),
            PackageManager.MATCH_DEFAULT_ONLY);
    if (marketInfo != null) {
        mMarketAppName = marketInfo.loadLabel(pm).toString();
    }/*from  w  ww.  jav a  2 s.co m*/
}

From source file:org.chromium.chrome.browser.download.OMADownloadHandler.java

/**
 * Returns the first MIME type in the OMA download that can be opened on the device.
 *
 * @param pm PackageManger for the current context.
 * @param omaInfo Information about the OMA content.
 * @return the MIME type can be opened by the device.
 *///  w  w  w.  j  a  v  a  2  s  .  c  o  m
static String getOpennableType(PackageManager pm, OMAInfo omaInfo) {
    if (omaInfo.isValueEmpty(OMA_OBJECT_URI)) {
        return null;
    }
    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri uri = Uri.parse(omaInfo.getValue(OMA_OBJECT_URI));
    for (String type : omaInfo.getTypes()) {
        if (!type.equalsIgnoreCase(OMA_DRM_MESSAGE_MIME) && !type.equalsIgnoreCase(OMA_DRM_CONTENT_MIME)
                && !type.equalsIgnoreCase(OMA_DOWNLOAD_DESCRIPTOR_MIME)
                && !type.equalsIgnoreCase(OMA_DRM_RIGHTS_MIME)) {
            intent.setDataAndType(uri, type);
            ResolveInfo resolveInfo = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
            if (resolveInfo != null) {
                return type;
            }
        }
    }
    return null;
}

From source file:android.com.example.contactslist.ui.ContactDetailFragment.java

/**
 * Builds an address LinearLayout based on address information from the Contacts Provider.
 * Each address for the contact gets its own LinearLayout object; for example, if the contact
 * has three postal addresses, then 3 LinearLayouts are generated.
 *
 * @param addressType From/*  w ww  .  ja v  a2 s.c  om*/
 * {@link StructuredPostal#TYPE}
 * @param addressTypeLabel From
 * {@link StructuredPostal#LABEL}
 * @param address From
 * {@link StructuredPostal#FORMATTED_ADDRESS}
 * @return A LinearLayout to add to the contact details layout,
 *         populated with the provided address details.
 */
private LinearLayout buildAddressLayout(int addressType, String addressTypeLabel, final String address) {

    // Inflates the address layout
    final LinearLayout addressLayout = (LinearLayout) LayoutInflater.from(getActivity())
            .inflate(R.layout.contact_detail_item, mDetailsLayout, false);

    // Gets handles to the view objects in the layout
    final TextView headerTextView = (TextView) addressLayout.findViewById(R.id.contact_detail_header);
    final TextView addressTextView = (TextView) addressLayout.findViewById(R.id.contact_detail_item);
    final ImageButton viewAddressButton = (ImageButton) addressLayout.findViewById(R.id.button_view_address);

    // If there's no addresses for the contact, shows the empty view and message, and hides the
    // header and button.
    if (addressTypeLabel == null && addressType == 0) {
        headerTextView.setVisibility(View.GONE);
        viewAddressButton.setVisibility(View.GONE);
        addressTextView.setText(R.string.no_address);
    } else {
        // Gets postal address label type
        CharSequence label = StructuredPostal.getTypeLabel(getResources(), addressType, addressTypeLabel);

        // Sets TextView objects in the layout
        headerTextView.setText(label);
        addressTextView.setText(address);

        // Defines an onClickListener object for the address button
        viewAddressButton.setOnClickListener(new View.OnClickListener() {
            // Defines what to do when users click the address button
            @Override
            public void onClick(View view) {

                final Intent viewIntent = new Intent(Intent.ACTION_VIEW, constructGeoUri(address));

                // A PackageManager instance is needed to verify that there's a default app
                // that handles ACTION_VIEW and a geo Uri.
                final PackageManager packageManager = getActivity().getPackageManager();

                // Checks for an activity that can handle this intent. Preferred in this
                // case over Intent.createChooser() as it will still let the user choose
                // a default (or use a previously set default) for geo Uris.
                if (packageManager.resolveActivity(viewIntent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
                    startActivity(viewIntent);
                } else {
                    // If no default is found, displays a message that no activity can handle
                    // the view button.
                    Toast.makeText(getActivity(), R.string.no_intent_found, Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
    return addressLayout;
}

From source file:com.air.mobilebrowser.BrowserActivity.java

/**
 * Determine if the application is set as the default
 * home.//from   w w w. j  a  v a  2s .  co  m
 * @return true if the default home package is the secure browser, false
 * otherwise.
 */
public boolean validateHomePackage() {
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);

    PackageManager pm = getPackageManager();
    final ResolveInfo mInfo = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
    String homePackage = mInfo.activityInfo.packageName;
    return homePackage.equals(getPackageName());
}

From source file:com.google.zxing.client.android.result.ResultHandler.java

final void openGoogleShopper(String query) {

    // Construct Intent to launch Shopper
    Intent intent = new Intent(Intent.ACTION_SEARCH);
    intent.setClassName(GOOGLE_SHOPPER_PACKAGE, GOOGLE_SHOPPER_ACTIVITY);
    intent.putExtra(SearchManager.QUERY, query);

    // Is it available?
    PackageManager pm = activity.getPackageManager();
    Collection<?> availableApps = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);

    if (availableApps != null && !availableApps.isEmpty()) {
        // If something can handle it, start it
        activity.startActivity(intent);// w w w . jav a  2  s  .  co m
    } else {
        // Otherwise offer to install it from Market.
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle(R.string.msg_google_shopper_missing);
        builder.setMessage(R.string.msg_install_google_shopper);
        builder.setIcon(R.drawable.shopper_icon);
        builder.setPositiveButton(R.string.button_ok, shopperMarketListener);
        builder.setNegativeButton(R.string.button_cancel, null);
        builder.show();
    }
}

From source file:com.mycelium.wallet.activity.modern.ModernMain.java

private void shareTransactionHistory() {
    WalletAccount account = _mbwManager.getSelectedAccount();
    MetadataStorage metaData = _mbwManager.getMetadataStorage();
    try {/*from ww w  .  j a va 2s .  c  o m*/
        String fileName = "MyceliumExport_" + System.currentTimeMillis() + ".csv";
        File historyData = DataExport.getTxHistoryCsv(account, metaData, getFileStreamPath(fileName));
        PackageManager packageManager = Preconditions.checkNotNull(getPackageManager());
        PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), PackageManager.GET_PROVIDERS);
        for (ProviderInfo info : packageInfo.providers) {
            if (info.name.equals("android.support.v4.content.FileProvider")) {
                String authority = info.authority;
                Uri uri = FileProvider.getUriForFile(this, authority, historyData);
                Intent intent = ShareCompat.IntentBuilder.from(this).setStream(uri) // uri from FileProvider
                        .setType("text/plain")
                        .setSubject(getResources().getString(R.string.transaction_history_title))
                        .setText(getResources().getString(R.string.transaction_history_title)).getIntent()
                        .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                List<ResolveInfo> resInfoList = packageManager.queryIntentActivities(intent,
                        PackageManager.MATCH_DEFAULT_ONLY);
                for (ResolveInfo resolveInfo : resInfoList) {
                    String packageName = resolveInfo.activityInfo.packageName;
                    grantUriPermission(packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
                startActivity(Intent.createChooser(intent,
                        getResources().getString(R.string.share_transaction_history)));
            }
        }
    } catch (IOException | PackageManager.NameNotFoundException e) {
        _toaster.toast("Export failed. Check your logs", false);
        e.printStackTrace();
    }
}

From source file:com.brq.wallet.activity.modern.ModernMain.java

private void shareTransactionHistory() {
    WalletAccount account = _mbwManager.getSelectedAccount();
    MetadataStorage metaData = _mbwManager.getMetadataStorage();
    try {/*from   w ww  .  jav  a  2  s. c  o m*/
        String fileName = "MyceliumExport_" + System.currentTimeMillis() + ".csv";
        File historyData = DataExport.getTxHistoryCsv(account, metaData, getFileStreamPath(fileName));
        PackageManager packageManager = Preconditions.checkNotNull(getPackageManager());
        PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), PackageManager.GET_PROVIDERS);
        for (ProviderInfo info : packageInfo.providers) {
            if (info.name.equals("android.support.v4.content.FileProvider")) {
                String authority = info.authority;
                Uri uri = FileProvider.getUriForFile(this, authority, historyData);
                Intent intent = ShareCompat.IntentBuilder.from(this).setStream(uri) // uri from FileProvider
                        .setType("text/plain")
                        .setSubject(getResources().getString(R.string.transaction_history_title))
                        .setText(getResources().getString(R.string.transaction_history_title)).getIntent()
                        .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                List<ResolveInfo> resInfoList = packageManager.queryIntentActivities(intent,
                        PackageManager.MATCH_DEFAULT_ONLY);
                for (ResolveInfo resolveInfo : resInfoList) {
                    String packageName = resolveInfo.activityInfo.packageName;
                    grantUriPermission(packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
                startActivity(Intent.createChooser(intent,
                        getResources().getString(R.string.share_transaction_history)));
            }
        }
    } catch (IOException e) {
        _toaster.toast("Export failed. Check your logs", false);
        e.printStackTrace();
    } catch (PackageManager.NameNotFoundException e) {
        _toaster.toast("Export failed. Check your logs", false);
        e.printStackTrace();
    }
}

From source file:es.example.contacts.ui.ContactDetailFragment.java

/**
 * Builds an address LinearLayout based on address information from the Contacts Provider.
 * Each address for the contact gets its own LinearLayout object; for example, if the contact
 * has three postal addresses, then 3 LinearLayouts are generated.
 *
 * @param addressType From//w  ww  . j  a  v a  2  s  .  c o m
 * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#TYPE}
 * @param addressTypeLabel From
 * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#LABEL}
 * @param address From
 * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#FORMATTED_ADDRESS}
 * @param phone From
 * {@link android.provider.ContactsContract.CommonDataKinds.Phone#NUMBER}
 * @param data1 From
 * {@link android.provider.ContactsContract.Data#DATA1}
 * @param _id From
 * {@link android.provider.ContactsContract#}
 * @return A LinearLayout to add to the contact details layout,
 *         populated with the provided address details.
 */
private LinearLayout buildAddressLayout(int addressType, String addressTypeLabel, final String address,
        final String phone, final String data1, final String _id, final String _name) {

    // Inflates the address layout
    final LinearLayout addressLayout = (LinearLayout) LayoutInflater.from(getActivity())
            .inflate(R.layout.contact_detail_item, mDetailsLayout, false);

    // Gets handles to the view objects in the layout
    final TextView headerTextView = (TextView) addressLayout.findViewById(R.id.contact_detail_header);
    final TextView addressTextView = (TextView) addressLayout.findViewById(R.id.contact_detail_item);
    final ImageButton viewAddressButton = (ImageButton) addressLayout.findViewById(R.id.button_view_address);
    final TextView phoneTextView = (TextView) addressLayout.findViewById(R.id.contact_phone);
    final SeekBar levelSeekBar = (SeekBar) addressLayout.findViewById(R.id.contact_level);
    final ImageButton saveButton = (ImageButton) addressLayout.findViewById(R.id.button_save);

    Integer prioridad = Integer.parseInt(data1 == null ? "4" : data1);
    // If there's no addresses for the contact, shows the empty view and message, and hides the
    // header and button.
    if (addressTypeLabel == null && addressType == 0 && phone == null) {
        headerTextView.setVisibility(View.GONE);
        viewAddressButton.setVisibility(View.GONE);
        addressTextView.setText(R.string.no_address);
    } else {
        // Gets postal address label type
        CharSequence label = StructuredPostal.getTypeLabel(getResources(), addressType, addressTypeLabel);

        // Sets TextView objects in the layout
        headerTextView.setText(label);
        addressTextView.setText(address);
        phoneTextView.setText(phone);
        levelSeekBar.setProgress(prioridad);

        // Defines an onClickListener object for the address button
        viewAddressButton.setOnClickListener(new View.OnClickListener() {
            // Defines what to do when users click the address button
            @Override
            public void onClick(View view) {

                final Intent viewIntent = new Intent(Intent.ACTION_VIEW, constructGeoUri(address));

                // A PackageManager instance is needed to verify that there's a default app
                // that handles ACTION_VIEW and a geo Uri.
                final PackageManager packageManager = getActivity().getPackageManager();

                // Checks for an activity that can handle this intent. Preferred in this
                // case over Intent.createChooser() as it will still let the user choose
                // a default (or use a previously set default) for geo Uris.
                if (packageManager.resolveActivity(viewIntent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
                    startActivity(viewIntent);
                } else {
                    // If no default is found, displays a message that no activity can handle
                    // the view button.
                    Toast.makeText(getActivity(), R.string.no_intent_found, Toast.LENGTH_SHORT).show();
                }
            }
        });

        // Defines an onClickListener object for the save button
        saveButton.setOnClickListener(new View.OnClickListener() {
            // Defines what to do when users click the address button
            @Override
            public void onClick(View view) {
                // Creates a new intent for sending to the device's contacts application
                // Creates a new array of ContentProviderOperation objects.
                ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

                Integer prioridad = levelSeekBar.getProgress();
                Log.d("ContactDetalFragment", _id);

                ContentProviderOperation.Builder op;
                if (data1 == null) {
                    Uri uri = addCallerIsSyncAdapterParameter(Data.CONTENT_URI, true);
                    ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).build());

                    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                            .withValue(ContactsContract.Data.MIMETYPE,
                                    ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                            .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, _name)
                            .build());

                    op = ContentProviderOperation.newInsert(Data.CONTENT_URI)
                            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                            .withValue(Data.DATA1, prioridad).withValue(Data.MIMETYPE, LEVEL_MIME_TYPE);

                } else {
                    String where = Data.MIMETYPE + " = ? ";
                    String[] params = new String[] { LEVEL_MIME_TYPE, };

                    op = ContentProviderOperation.newUpdate(Data.CONTENT_URI).withSelection(where, params)
                            .withValue(Data.DATA1, prioridad);

                }
                ops.add(op.build());
                try {
                    ContentProviderResult[] results = view.getContext().getContentResolver()
                            .applyBatch(ContactsContract.AUTHORITY, ops);
                } catch (Exception e) {
                    CharSequence txt = getString(R.string.contactUpdateFailure);
                    int duration = Toast.LENGTH_SHORT;
                    Toast toast = Toast.makeText(view.getContext(), txt, duration);
                    toast.show();
                    // Log exception
                    Log.e(TAG, "Exception encountered while inserting contact: " + e);
                }
            }
        });

    }
    return addressLayout;
}

From source file:eu.nubomedia.nubomedia_kurento_health_communicator_android.kc_and_communicator.util.FileUtils.java

private static boolean isIntentAvailable(Context context, String action) {
    final PackageManager packageManager = context.getPackageManager();
    final Intent intent = new Intent(action);
    List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;
}

From source file:com.farmerbb.taskbar.service.TaskbarService.java

@SuppressWarnings("Convert2streamapi")
@TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
private void updateRecentApps(final boolean firstRefresh) {
    SharedPreferences pref = U.getSharedPreferences(this);
    final PackageManager pm = getPackageManager();
    final List<AppEntry> entries = new ArrayList<>();
    List<LauncherActivityInfo> launcherAppCache = new ArrayList<>();
    int maxNumOfEntries = U.getMaxNumOfEntries(this);
    int realNumOfPinnedApps = 0;
    boolean fullLength = pref.getBoolean("full_length", false);

    PinnedBlockedApps pba = PinnedBlockedApps.getInstance(this);
    List<AppEntry> pinnedApps = pba.getPinnedApps();
    List<AppEntry> blockedApps = pba.getBlockedApps();
    List<String> applicationIdsToRemove = new ArrayList<>();

    // Filter out anything on the pinned/blocked apps lists
    if (pinnedApps.size() > 0) {
        UserManager userManager = (UserManager) getSystemService(USER_SERVICE);
        LauncherApps launcherApps = (LauncherApps) getSystemService(LAUNCHER_APPS_SERVICE);

        for (AppEntry entry : pinnedApps) {
            boolean packageEnabled = launcherApps.isPackageEnabled(entry.getPackageName(),
                    userManager.getUserForSerialNumber(entry.getUserId(this)));

            if (packageEnabled)
                entries.add(entry);//from w w w  .java 2  s  .  c  o m
            else
                realNumOfPinnedApps--;

            applicationIdsToRemove.add(entry.getPackageName());
        }

        realNumOfPinnedApps = realNumOfPinnedApps + pinnedApps.size();
    }

    if (blockedApps.size() > 0) {
        for (AppEntry entry : blockedApps) {
            applicationIdsToRemove.add(entry.getPackageName());
        }
    }

    // Get list of all recently used apps
    List<AppEntry> usageStatsList = realNumOfPinnedApps < maxNumOfEntries ? getAppEntries() : new ArrayList<>();
    if (usageStatsList.size() > 0 || realNumOfPinnedApps > 0 || fullLength) {
        if (realNumOfPinnedApps < maxNumOfEntries) {
            List<AppEntry> usageStatsList2 = new ArrayList<>();
            List<AppEntry> usageStatsList3 = new ArrayList<>();
            List<AppEntry> usageStatsList4 = new ArrayList<>();
            List<AppEntry> usageStatsList5 = new ArrayList<>();
            List<AppEntry> usageStatsList6;

            Intent homeIntent = new Intent(Intent.ACTION_MAIN);
            homeIntent.addCategory(Intent.CATEGORY_HOME);
            ResolveInfo defaultLauncher = pm.resolveActivity(homeIntent, PackageManager.MATCH_DEFAULT_ONLY);

            // Filter out apps without a launcher intent
            // Also filter out the current launcher, and Taskbar itself
            for (AppEntry packageInfo : usageStatsList) {
                if (hasLauncherIntent(packageInfo.getPackageName())
                        && !packageInfo.getPackageName().contains(BuildConfig.BASE_APPLICATION_ID)
                        && !packageInfo.getPackageName().equals(defaultLauncher.activityInfo.packageName))
                    usageStatsList2.add(packageInfo);
            }

            // Filter out apps that don't fall within our current search interval
            for (AppEntry stats : usageStatsList2) {
                if (stats.getLastTimeUsed() > searchInterval || runningAppsOnly)
                    usageStatsList3.add(stats);
            }

            // Sort apps by either most recently used, or most time used
            if (!runningAppsOnly) {
                if (sortOrder.contains("most_used")) {
                    Collections.sort(usageStatsList3, (us1, us2) -> Long.compare(us2.getTotalTimeInForeground(),
                            us1.getTotalTimeInForeground()));
                } else {
                    Collections.sort(usageStatsList3,
                            (us1, us2) -> Long.compare(us2.getLastTimeUsed(), us1.getLastTimeUsed()));
                }
            }

            // Filter out any duplicate entries
            List<String> applicationIds = new ArrayList<>();
            for (AppEntry stats : usageStatsList3) {
                if (!applicationIds.contains(stats.getPackageName())) {
                    usageStatsList4.add(stats);
                    applicationIds.add(stats.getPackageName());
                }
            }

            // Filter out the currently running foreground app, if requested by the user
            if (pref.getBoolean("hide_foreground", false)) {
                UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService(
                        USAGE_STATS_SERVICE);
                UsageEvents events = mUsageStatsManager.queryEvents(searchInterval, System.currentTimeMillis());
                UsageEvents.Event eventCache = new UsageEvents.Event();
                String currentForegroundApp = null;

                while (events.hasNextEvent()) {
                    events.getNextEvent(eventCache);

                    if (eventCache.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
                        if (!(eventCache.getPackageName().contains(BuildConfig.BASE_APPLICATION_ID)
                                && !eventCache.getClassName().equals(MainActivity.class.getCanonicalName())
                                && !eventCache.getClassName().equals(HomeActivity.class.getCanonicalName())
                                && !eventCache.getClassName()
                                        .equals(InvisibleActivityFreeform.class.getCanonicalName())))
                            currentForegroundApp = eventCache.getPackageName();
                    }
                }

                if (!applicationIdsToRemove.contains(currentForegroundApp))
                    applicationIdsToRemove.add(currentForegroundApp);
            }

            for (AppEntry stats : usageStatsList4) {
                if (!applicationIdsToRemove.contains(stats.getPackageName())) {
                    usageStatsList5.add(stats);
                }
            }

            // Truncate list to a maximum length
            if (usageStatsList5.size() > maxNumOfEntries)
                usageStatsList6 = usageStatsList5.subList(0, maxNumOfEntries);
            else
                usageStatsList6 = usageStatsList5;

            // Determine if we need to reverse the order
            boolean needToReverseOrder;
            switch (U.getTaskbarPosition(this)) {
            case "bottom_right":
            case "top_right":
                needToReverseOrder = sortOrder.contains("false");
                break;
            default:
                needToReverseOrder = sortOrder.contains("true");
                break;
            }

            if (needToReverseOrder) {
                Collections.reverse(usageStatsList6);
            }

            // Generate the AppEntries for TaskbarAdapter
            int number = usageStatsList6.size() == maxNumOfEntries
                    ? usageStatsList6.size() - realNumOfPinnedApps
                    : usageStatsList6.size();

            UserManager userManager = (UserManager) getSystemService(Context.USER_SERVICE);
            LauncherApps launcherApps = (LauncherApps) getSystemService(Context.LAUNCHER_APPS_SERVICE);

            final List<UserHandle> userHandles = userManager.getUserProfiles();

            for (int i = 0; i < number; i++) {
                for (UserHandle handle : userHandles) {
                    String packageName = usageStatsList6.get(i).getPackageName();
                    List<LauncherActivityInfo> list = launcherApps.getActivityList(packageName, handle);
                    if (!list.isEmpty()) {
                        // Google App workaround
                        if (!packageName.equals("com.google.android.googlequicksearchbox"))
                            launcherAppCache.add(list.get(0));
                        else {
                            boolean added = false;
                            for (LauncherActivityInfo info : list) {
                                if (info.getName()
                                        .equals("com.google.android.googlequicksearchbox.SearchActivity")) {
                                    launcherAppCache.add(info);
                                    added = true;
                                }
                            }

                            if (!added)
                                launcherAppCache.add(list.get(0));
                        }

                        AppEntry newEntry = new AppEntry(packageName, null, null, null, false);

                        newEntry.setUserId(userManager.getSerialNumberForUser(handle));
                        entries.add(newEntry);

                        break;
                    }
                }
            }
        }

        while (entries.size() > maxNumOfEntries) {
            try {
                entries.remove(entries.size() - 1);
                launcherAppCache.remove(launcherAppCache.size() - 1);
            } catch (ArrayIndexOutOfBoundsException e) {
                /* Gracefully fail */ }
        }

        // Determine if we need to reverse the order again
        if (U.getTaskbarPosition(this).contains("vertical")) {
            Collections.reverse(entries);
            Collections.reverse(launcherAppCache);
        }

        // Now that we've generated the list of apps,
        // we need to determine if we need to redraw the Taskbar or not
        boolean shouldRedrawTaskbar = firstRefresh;

        List<String> finalApplicationIds = new ArrayList<>();
        for (AppEntry entry : entries) {
            finalApplicationIds.add(entry.getPackageName());
        }

        if (finalApplicationIds.size() != currentTaskbarIds.size() || numOfPinnedApps != realNumOfPinnedApps)
            shouldRedrawTaskbar = true;
        else {
            for (int i = 0; i < finalApplicationIds.size(); i++) {
                if (!finalApplicationIds.get(i).equals(currentTaskbarIds.get(i))) {
                    shouldRedrawTaskbar = true;
                    break;
                }
            }
        }

        if (shouldRedrawTaskbar) {
            currentTaskbarIds = finalApplicationIds;
            numOfPinnedApps = realNumOfPinnedApps;

            UserManager userManager = (UserManager) getSystemService(USER_SERVICE);

            int launcherAppCachePos = -1;
            for (int i = 0; i < entries.size(); i++) {
                if (entries.get(i).getComponentName() == null) {
                    launcherAppCachePos++;
                    LauncherActivityInfo appInfo = launcherAppCache.get(launcherAppCachePos);
                    String packageName = entries.get(i).getPackageName();

                    entries.remove(i);

                    AppEntry newEntry = new AppEntry(packageName, appInfo.getComponentName().flattenToString(),
                            appInfo.getLabel().toString(), IconCache.getInstance(TaskbarService.this)
                                    .getIcon(TaskbarService.this, pm, appInfo),
                            false);

                    newEntry.setUserId(userManager.getSerialNumberForUser(appInfo.getUser()));
                    entries.add(i, newEntry);
                }
            }

            final int numOfEntries = Math.min(entries.size(), maxNumOfEntries);

            handler.post(() -> {
                if (numOfEntries > 0 || fullLength) {
                    ViewGroup.LayoutParams params = scrollView.getLayoutParams();
                    DisplayMetrics metrics = getResources().getDisplayMetrics();
                    int recentsSize = getResources().getDimensionPixelSize(R.dimen.icon_size) * numOfEntries;
                    float maxRecentsSize = fullLength ? Float.MAX_VALUE : recentsSize;

                    if (U.getTaskbarPosition(TaskbarService.this).contains("vertical")) {
                        int maxScreenSize = metrics.heightPixels - U.getStatusBarHeight(TaskbarService.this)
                                - U.getBaseTaskbarSize(TaskbarService.this);

                        params.height = (int) Math.min(maxRecentsSize, maxScreenSize)
                                + getResources().getDimensionPixelSize(R.dimen.divider_size);

                        if (fullLength && U.getTaskbarPosition(this).contains("bottom")) {
                            try {
                                Space whitespace = (Space) layout.findViewById(R.id.whitespace);
                                ViewGroup.LayoutParams params2 = whitespace.getLayoutParams();
                                params2.height = maxScreenSize - recentsSize;
                                whitespace.setLayoutParams(params2);
                            } catch (NullPointerException e) {
                                /* Gracefully fail */ }
                        }
                    } else {
                        int maxScreenSize = metrics.widthPixels - U.getBaseTaskbarSize(TaskbarService.this);

                        params.width = (int) Math.min(maxRecentsSize, maxScreenSize)
                                + getResources().getDimensionPixelSize(R.dimen.divider_size);

                        if (fullLength && U.getTaskbarPosition(this).contains("right")) {
                            try {
                                Space whitespace = (Space) layout.findViewById(R.id.whitespace);
                                ViewGroup.LayoutParams params2 = whitespace.getLayoutParams();
                                params2.width = maxScreenSize - recentsSize;
                                whitespace.setLayoutParams(params2);
                            } catch (NullPointerException e) {
                                /* Gracefully fail */ }
                        }
                    }

                    scrollView.setLayoutParams(params);

                    taskbar.removeAllViews();
                    for (int i = 0; i < entries.size(); i++) {
                        taskbar.addView(getView(entries, i));
                    }

                    isShowingRecents = true;
                    if (shouldRefreshRecents && scrollView.getVisibility() != View.VISIBLE) {
                        if (firstRefresh)
                            scrollView.setVisibility(View.INVISIBLE);
                        else
                            scrollView.setVisibility(View.VISIBLE);
                    }

                    if (firstRefresh && scrollView.getVisibility() != View.VISIBLE)
                        new Handler().post(() -> {
                            switch (U.getTaskbarPosition(TaskbarService.this)) {
                            case "bottom_left":
                            case "bottom_right":
                            case "top_left":
                            case "top_right":
                                if (sortOrder.contains("false"))
                                    scrollView.scrollTo(0, 0);
                                else if (sortOrder.contains("true"))
                                    scrollView.scrollTo(taskbar.getWidth(), taskbar.getHeight());
                                break;
                            case "bottom_vertical_left":
                            case "bottom_vertical_right":
                            case "top_vertical_left":
                            case "top_vertical_right":
                                if (sortOrder.contains("false"))
                                    scrollView.scrollTo(taskbar.getWidth(), taskbar.getHeight());
                                else if (sortOrder.contains("true"))
                                    scrollView.scrollTo(0, 0);
                                break;
                            }

                            if (shouldRefreshRecents) {
                                scrollView.setVisibility(View.VISIBLE);
                            }
                        });
                } else {
                    isShowingRecents = false;
                    scrollView.setVisibility(View.GONE);
                }
            });
        }
    } else if (firstRefresh || currentTaskbarIds.size() > 0) {
        currentTaskbarIds.clear();
        handler.post(() -> {
            isShowingRecents = false;
            scrollView.setVisibility(View.GONE);
        });
    }
}