Search in sources :

Example 1 with AppEntry

use of com.farmerbb.taskbar.util.AppEntry in project Taskbar by farmerbb.

the class StartMenuService method refreshApps.

private void refreshApps(final String query, final boolean firstDraw) {
    if (thread != null)
        thread.interrupt();
    handler = new Handler();
    thread = new Thread(() -> {
        if (pm == null)
            pm = getPackageManager();
        UserManager userManager = (UserManager) getSystemService(Context.USER_SERVICE);
        LauncherApps launcherApps = (LauncherApps) getSystemService(Context.LAUNCHER_APPS_SERVICE);
        final List<UserHandle> userHandles = userManager.getUserProfiles();
        final List<LauncherActivityInfo> unfilteredList = new ArrayList<>();
        for (UserHandle handle : userHandles) {
            unfilteredList.addAll(launcherApps.getActivityList(null, handle));
        }
        final List<LauncherActivityInfo> topAppsList = new ArrayList<>();
        final List<LauncherActivityInfo> allAppsList = new ArrayList<>();
        final List<LauncherActivityInfo> list = new ArrayList<>();
        TopApps topApps = TopApps.getInstance(StartMenuService.this);
        for (LauncherActivityInfo appInfo : unfilteredList) {
            if (topApps.isTopApp(appInfo.getComponentName().flattenToString()) || topApps.isTopApp(appInfo.getName()))
                topAppsList.add(appInfo);
        }
        Blacklist blacklist = Blacklist.getInstance(StartMenuService.this);
        for (LauncherActivityInfo appInfo : unfilteredList) {
            if (!(blacklist.isBlocked(appInfo.getComponentName().flattenToString()) || blacklist.isBlocked(appInfo.getName())) && !(topApps.isTopApp(appInfo.getComponentName().flattenToString()) || topApps.isTopApp(appInfo.getName())))
                allAppsList.add(appInfo);
        }
        Collections.sort(topAppsList, comparator);
        Collections.sort(allAppsList, comparator);
        list.addAll(topAppsList);
        list.addAll(allAppsList);
        topAppsList.clear();
        allAppsList.clear();
        List<LauncherActivityInfo> queryList;
        if (query == null)
            queryList = list;
        else {
            queryList = new ArrayList<>();
            for (LauncherActivityInfo appInfo : list) {
                if (appInfo.getLabel().toString().toLowerCase().contains(query.toLowerCase()))
                    queryList.add(appInfo);
            }
        }
        // Now that we've generated the list of apps,
        // we need to determine if we need to redraw the start menu or not
        boolean shouldRedrawStartMenu = false;
        List<String> finalApplicationIds = new ArrayList<>();
        if (query == null && !firstDraw) {
            for (LauncherActivityInfo appInfo : queryList) {
                finalApplicationIds.add(appInfo.getApplicationInfo().packageName);
            }
            if (finalApplicationIds.size() != currentStartMenuIds.size())
                shouldRedrawStartMenu = true;
            else {
                for (int i = 0; i < finalApplicationIds.size(); i++) {
                    if (!finalApplicationIds.get(i).equals(currentStartMenuIds.get(i))) {
                        shouldRedrawStartMenu = true;
                        break;
                    }
                }
            }
        } else
            shouldRedrawStartMenu = true;
        if (shouldRedrawStartMenu) {
            if (query == null)
                currentStartMenuIds = finalApplicationIds;
            Drawable defaultIcon = pm.getDefaultActivityIcon();
            final List<AppEntry> entries = new ArrayList<>();
            for (LauncherActivityInfo appInfo : queryList) {
                // Attempt to work around frequently reported OutOfMemoryErrors
                String label;
                Drawable icon;
                try {
                    label = appInfo.getLabel().toString();
                    icon = IconCache.getInstance(StartMenuService.this).getIcon(StartMenuService.this, pm, appInfo);
                } catch (OutOfMemoryError e) {
                    System.gc();
                    label = appInfo.getApplicationInfo().packageName;
                    icon = defaultIcon;
                }
                AppEntry newEntry = new AppEntry(appInfo.getApplicationInfo().packageName, new ComponentName(appInfo.getApplicationInfo().packageName, appInfo.getName()).flattenToString(), label, icon, false);
                newEntry.setUserId(userManager.getSerialNumberForUser(appInfo.getUser()));
                entries.add(newEntry);
            }
            handler.post(() -> {
                String queryText = searchView.getQuery().toString();
                if (query == null && queryText.length() == 0 || query != null && query.equals(queryText)) {
                    StartMenuAdapter adapter;
                    SharedPreferences pref = U.getSharedPreferences(StartMenuService.this);
                    if (pref.getString("start_menu_layout", "list").equals("grid")) {
                        startMenu.setNumColumns(3);
                        adapter = new StartMenuAdapter(StartMenuService.this, R.layout.row_alt, entries);
                    } else
                        adapter = new StartMenuAdapter(StartMenuService.this, R.layout.row, entries);
                    int position = startMenu.getFirstVisiblePosition();
                    startMenu.setAdapter(adapter);
                    startMenu.setSelection(position);
                    if (adapter.getCount() > 0)
                        textView.setText(null);
                    else if (query != null)
                        textView.setText(getString(Patterns.WEB_URL.matcher(query).matches() ? R.string.press_enter_alt : R.string.press_enter));
                    else
                        textView.setText(getString(R.string.nothing_to_see_here));
                }
            });
        }
    });
    thread.start();
}
Also used : SharedPreferences(android.content.SharedPreferences) ArrayList(java.util.ArrayList) Drawable(android.graphics.drawable.Drawable) Handler(android.os.Handler) LauncherApps(android.content.pm.LauncherApps) AppEntry(com.farmerbb.taskbar.util.AppEntry) UserManager(android.os.UserManager) UserHandle(android.os.UserHandle) LauncherActivityInfo(android.content.pm.LauncherActivityInfo) TopApps(com.farmerbb.taskbar.util.TopApps) List(java.util.List) ArrayList(java.util.ArrayList) ComponentName(android.content.ComponentName) Blacklist(com.farmerbb.taskbar.util.Blacklist) StartMenuAdapter(com.farmerbb.taskbar.adapter.StartMenuAdapter)

Example 2 with AppEntry

use of com.farmerbb.taskbar.util.AppEntry in project Taskbar by farmerbb.

the class TaskbarService method updateRecentApps.

@SuppressWarnings("Convert2streamapi")
@TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
private void updateRecentApps(final boolean firstRefresh) {
    if (isScreenOff())
        return;
    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);
            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);
            // 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 && 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 = U.getRealDisplayMetrics(this);
                    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 = U.findViewById(layout, 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 = U.findViewById(layout, 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);
        });
    }
}
Also used : ArrayList(java.util.ArrayList) MainActivity(com.farmerbb.taskbar.MainActivity) UsageEvents(android.app.usage.UsageEvents) DisplayMetrics(android.util.DisplayMetrics) ResolveInfo(android.content.pm.ResolveInfo) PackageManager(android.content.pm.PackageManager) UserHandle(android.os.UserHandle) UsageStatsManager(android.app.usage.UsageStatsManager) PinnedBlockedApps(com.farmerbb.taskbar.util.PinnedBlockedApps) Space(android.widget.Space) SharedPreferences(android.content.SharedPreferences) InvisibleActivityFreeform(com.farmerbb.taskbar.activity.InvisibleActivityFreeform) ViewGroup(android.view.ViewGroup) Handler(android.os.Handler) LauncherApps(android.content.pm.LauncherApps) Intent(android.content.Intent) RecognizerIntent(android.speech.RecognizerIntent) SuppressLint(android.annotation.SuppressLint) Point(android.graphics.Point) AppEntry(com.farmerbb.taskbar.util.AppEntry) UserManager(android.os.UserManager) LauncherActivityInfo(android.content.pm.LauncherActivityInfo) MotionEvent(android.view.MotionEvent) TargetApi(android.annotation.TargetApi)

Example 3 with AppEntry

use of com.farmerbb.taskbar.util.AppEntry in project Taskbar by farmerbb.

the class TaskbarController method populateAppEntries.

@SuppressWarnings("SuspiciousListRemoveInLoop")
@VisibleForTesting
void populateAppEntries(Context context, PackageManager pm, List<AppEntry> entries, List<LauncherActivityInfo> launcherAppCache) {
    UserManager userManager = (UserManager) context.getSystemService(Context.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();
            long lastTimeUsed = entries.get(i).getLastTimeUsed();
            entries.remove(i);
            AppEntry newEntry = new AppEntry(packageName, appInfo.getComponentName().flattenToString(), appInfo.getLabel().toString(), IconCache.getInstance(context).getIcon(context, pm, appInfo), false);
            newEntry.setUserId(userManager.getSerialNumberForUser(appInfo.getUser()));
            newEntry.setLastTimeUsed(lastTimeUsed);
            entries.add(i, newEntry);
        }
    }
}
Also used : AppEntry(com.farmerbb.taskbar.util.AppEntry) UserManager(android.os.UserManager) LauncherActivityInfo(android.content.pm.LauncherActivityInfo) SuppressLint(android.annotation.SuppressLint) Point(android.graphics.Point) VisibleForTesting(androidx.annotation.VisibleForTesting)

Example 4 with AppEntry

use of com.farmerbb.taskbar.util.AppEntry in project Taskbar by farmerbb.

the class TaskbarController method generateAppEntries.

@VisibleForTesting
void generateAppEntries(Context context, int number, List<AppEntry> usageStatsList6, List<AppEntry> entries, List<LauncherActivityInfo> launcherAppCache) {
    UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
    LauncherApps launcherApps = (LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE);
    final List<UserHandle> userHandles = userManager.getUserProfiles();
    final String googleSearchBoxPackage = "com.google.android.googlequicksearchbox";
    final String googleSearchBoxActivity = "com.google.android.googlequicksearchbox.SearchActivity";
    for (int i = 0; i < number; i++) {
        for (UserHandle handle : userHandles) {
            String packageName = usageStatsList6.get(i).getPackageName();
            long lastTimeUsed = usageStatsList6.get(i).getLastTimeUsed();
            List<LauncherActivityInfo> list = launcherApps.getActivityList(packageName, handle);
            if (!list.isEmpty()) {
                // Google App workaround
                if (!packageName.equals(googleSearchBoxPackage)) {
                    launcherAppCache.add(list.get(0));
                } else {
                    boolean added = false;
                    for (LauncherActivityInfo info : list) {
                        if (info.getName().equals(googleSearchBoxActivity)) {
                            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));
                newEntry.setLastTimeUsed(lastTimeUsed);
                entries.add(newEntry);
                break;
            }
        }
    }
}
Also used : AppEntry(com.farmerbb.taskbar.util.AppEntry) UserManager(android.os.UserManager) UserHandle(android.os.UserHandle) LauncherActivityInfo(android.content.pm.LauncherActivityInfo) LauncherApps(android.content.pm.LauncherApps) SuppressLint(android.annotation.SuppressLint) Point(android.graphics.Point) VisibleForTesting(androidx.annotation.VisibleForTesting)

Example 5 with AppEntry

use of com.farmerbb.taskbar.util.AppEntry in project Taskbar by farmerbb.

the class ContextMenuActivity method onPreferenceClick.

@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.N_MR1)
@Override
public boolean onPreferenceClick(Preference p) {
    UserManager userManager = (UserManager) getSystemService(USER_SERVICE);
    LauncherApps launcherApps = (LauncherApps) getSystemService(LAUNCHER_APPS_SERVICE);
    boolean appIsValid = isStartButton || isOverflowMenu || desktopIcon != null || (entry != null && !launcherApps.getActivityList(entry.getPackageName(), userManager.getUserForSerialNumber(entry.getUserId(this))).isEmpty());
    secondaryMenu = false;
    if (appIsValid)
        switch(p.getKey()) {
            case PREF_APP_INFO:
                U.launchApp(this, () -> launcherApps.startAppDetailsActivity(ComponentName.unflattenFromString(entry.getComponentName()), userManager.getUserForSerialNumber(entry.getUserId(this)), null, U.getActivityOptionsBundle(this, ApplicationType.APP_PORTRAIT, getListView().getChildAt(p.getOrder()))));
                prepareToClose();
                break;
            case PREF_UNINSTALL:
                if (U.hasFreeformSupport(this) && isInMultiWindowMode()) {
                    Intent intent2 = new Intent(this, DummyActivity.class);
                    intent2.putExtra("uninstall", entry.getPackageName());
                    intent2.putExtra("user_id", entry.getUserId(this));
                    try {
                        startActivity(intent2);
                    } catch (IllegalArgumentException ignored) {
                    }
                } else {
                    Intent intent2 = new Intent(Intent.ACTION_DELETE, Uri.parse("package:" + entry.getPackageName()));
                    intent2.putExtra(Intent.EXTRA_USER, userManager.getUserForSerialNumber(entry.getUserId(this)));
                    try {
                        startActivity(intent2);
                    } catch (ActivityNotFoundException | IllegalArgumentException ignored) {
                    }
                }
                prepareToClose();
                break;
            case PREF_OPEN_TASKBAR_SETTINGS:
                U.launchApp(this, () -> {
                    Intent intent2 = new Intent(this, MainActivity.class);
                    intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    LauncherHelper helper = LauncherHelper.getInstance();
                    if (helper.isOnHomeScreen(this) || helper.isOnSecondaryHomeScreen(this))
                        U.applyOpenInNewWindow(this, intent2);
                    try {
                        startActivity(intent2, U.getActivityOptionsBundle(this, ApplicationType.APP_PORTRAIT, getListView().getChildAt(p.getOrder())));
                    } catch (IllegalArgumentException ignored) {
                    }
                });
                prepareToClose();
                break;
            case PREF_QUIT_TASKBAR:
                Intent quitIntent = new Intent(ACTION_QUIT);
                quitIntent.setPackage(getPackageName());
                sendBroadcast(quitIntent);
                prepareToClose();
                break;
            case PREF_PIN_APP:
                PinnedBlockedApps pba = PinnedBlockedApps.getInstance(this);
                if (pba.isPinned(entry.getComponentName()))
                    pba.removePinnedApp(this, entry.getComponentName());
                else {
                    Intent intent = new Intent();
                    intent.setComponent(ComponentName.unflattenFromString(entry.getComponentName()));
                    LauncherActivityInfo appInfo = launcherApps.resolveActivity(intent, userManager.getUserForSerialNumber(entry.getUserId(this)));
                    if (appInfo != null) {
                        AppEntry newEntry = new AppEntry(entry.getPackageName(), entry.getComponentName(), entry.getLabel(), IconCache.getInstance(this).getIcon(this, appInfo), true);
                        newEntry.setUserId(entry.getUserId(this));
                        pba.addPinnedApp(this, newEntry);
                    }
                }
                break;
            case PREF_BLOCK_APP:
                PinnedBlockedApps pba2 = PinnedBlockedApps.getInstance(this);
                if (pba2.isBlocked(entry.getComponentName()))
                    pba2.removeBlockedApp(this, entry.getComponentName());
                else
                    pba2.addBlockedApp(this, entry);
                break;
            case PREF_SHOW_WINDOW_SIZES:
                generateWindowSizes();
                if (U.hasBrokenSetLaunchBoundsApi())
                    U.showToastLong(this, R.string.tb_window_sizes_not_available);
                getListView().setOnItemLongClickListener((parent, view, position, id) -> {
                    String[] windowSizes = getResources().getStringArray(R.array.tb_pref_window_size_list_values);
                    SavedWindowSizes.getInstance(this).setWindowSize(this, entry.getPackageName(), windowSizes[position]);
                    generateWindowSizes();
                    return true;
                });
                secondaryMenu = true;
                break;
            case PREF_WINDOW_SIZE_STANDARD:
            case PREF_WINDOW_SIZE_LARGE:
            case PREF_WINDOW_SIZE_FULLSCREEN:
            case PREF_WINDOW_SIZE_HALF_LEFT:
            case PREF_WINDOW_SIZE_HALF_RIGHT:
            case PREF_WINDOW_SIZE_PHONE_SIZE:
                String windowSize = p.getKey().replace("window_size_", "");
                SharedPreferences pref2 = U.getSharedPreferences(this);
                if (pref2.getBoolean(PREF_SAVE_WINDOW_SIZES, true)) {
                    SavedWindowSizes.getInstance(this).setWindowSize(this, entry.getPackageName(), windowSize);
                }
                U.launchApp(U.getDisplayContext(this), entry, windowSize, false, true, getListView().getChildAt(p.getOrder()));
                if (U.hasBrokenSetLaunchBoundsApi())
                    U.cancelToast();
                prepareToClose();
                break;
            case PREF_APP_SHORTCUTS:
                getPreferenceScreen().removeAll();
                generateShortcuts();
                secondaryMenu = true;
                break;
            case PREF_SHORTCUT_1:
            case PREF_SHORTCUT_2:
            case PREF_SHORTCUT_3:
            case PREF_SHORTCUT_4:
            case PREF_SHORTCUT_5:
                U.startShortcut(U.getDisplayContext(this), entry, shortcuts.get(Integer.parseInt(p.getKey().replace("shortcut_", "")) - 1), getListView().getChildAt(p.getOrder()));
                prepareToClose();
                break;
            case PREF_START_MENU_APPS:
                Intent intent = U.getThemedIntent(this, SelectAppActivity.class);
                if (U.hasFreeformSupport(this) && U.isFreeformModeEnabled(this) && isInMultiWindowMode()) {
                    intent.putExtra("no_shadow", true);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT);
                    U.startActivityMaximized(U.getDisplayContext(this), intent);
                } else {
                    try {
                        startActivity(intent);
                    } catch (IllegalArgumentException ignored) {
                    }
                }
                prepareToClose();
                break;
            case PREF_VOLUME:
                AudioManager audio = (AudioManager) getSystemService(AUDIO_SERVICE);
                audio.adjustSuggestedStreamVolume(AudioManager.ADJUST_SAME, AudioManager.USE_DEFAULT_STREAM_TYPE, AudioManager.FLAG_SHOW_UI);
                if (LauncherHelper.getInstance().isOnSecondaryHomeScreen(this)) {
                    U.showToast(this, R.string.tb_opening_volume_control);
                    U.sendBroadcast(this, ACTION_UNDIM_SCREEN);
                }
                prepareToClose();
                break;
            case PREF_FILE_MANAGER:
                U.launchApp(this, () -> {
                    Intent fileManagerIntent;
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1)
                        fileManagerIntent = new Intent(Intent.ACTION_VIEW);
                    else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                        fileManagerIntent = new Intent("android.provider.action.BROWSE");
                    else {
                        fileManagerIntent = new Intent("android.provider.action.BROWSE_DOCUMENT_ROOT");
                        fileManagerIntent.setComponent(ComponentName.unflattenFromString("com.android.documentsui/.DocumentsActivity"));
                    }
                    fileManagerIntent.addCategory(Intent.CATEGORY_DEFAULT);
                    fileManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    fileManagerIntent.setData(Uri.parse("content://com.android.externalstorage.documents/root/primary"));
                    try {
                        startActivity(fileManagerIntent, U.getActivityOptionsBundle(this, ApplicationType.APP_PORTRAIT, getListView().getChildAt(p.getOrder())));
                    } catch (ActivityNotFoundException e) {
                        U.showToast(this, R.string.tb_lock_device_not_supported);
                    } catch (IllegalArgumentException ignored) {
                    }
                });
                prepareToClose();
                break;
            case PREF_SYSTEM_SETTINGS:
                U.launchApp(this, () -> {
                    Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
                    settingsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    try {
                        startActivity(settingsIntent, U.getActivityOptionsBundle(this, ApplicationType.APP_PORTRAIT, getListView().getChildAt(p.getOrder())));
                    } catch (ActivityNotFoundException e) {
                        U.showToast(this, R.string.tb_lock_device_not_supported);
                    } catch (IllegalArgumentException ignored) {
                    }
                });
                prepareToClose();
                break;
            case PREF_LOCK_DEVICE:
                U.lockDevice(this);
                prepareToClose();
                break;
            case PREF_POWER_MENU:
                U.sendAccessibilityAction(this, AccessibilityService.GLOBAL_ACTION_POWER_DIALOG, () -> {
                    if (LauncherHelper.getInstance().isOnSecondaryHomeScreen(this)) {
                        U.showToast(this, R.string.tb_opening_power_menu);
                        U.sendBroadcast(this, ACTION_UNDIM_SCREEN);
                    }
                });
                prepareToClose();
                break;
            case PREF_ADD_ICON_TO_DESKTOP:
                Intent intent2 = U.getThemedIntent(this, DesktopIconSelectAppActivity.class);
                intent2.putExtra("desktop_icon", desktopIcon);
                if (U.hasFreeformSupport(this) && U.isFreeformModeEnabled(this) && isInMultiWindowMode()) {
                    intent2.putExtra("no_shadow", true);
                    intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT);
                    U.startActivityMaximized(U.getDisplayContext(this), intent2);
                } else {
                    try {
                        startActivity(intent2);
                    } catch (IllegalArgumentException ignored) {
                    }
                }
                prepareToClose();
                break;
            case PREF_ARRANGE_ICONS:
                U.sendBroadcast(this, ACTION_ENTER_ICON_ARRANGE_MODE);
                break;
            case PREF_SORT_BY_NAME:
                U.sendBroadcast(this, ACTION_SORT_DESKTOP_ICONS);
                break;
            case PREF_CHANGE_WALLPAPER:
                if (LauncherHelper.getInstance().isOnSecondaryHomeScreen(this)) {
                    generateWallpaperOptions();
                    secondaryMenu = true;
                } else if (U.isChromeOs(this)) {
                    U.sendBroadcast(this, ACTION_WALLPAPER_CHANGE_REQUESTED);
                } else {
                    changeWallpaper();
                    prepareToClose();
                }
                break;
            case PREF_REMOVE_DESKTOP_ICON:
                try {
                    SharedPreferences pref5 = U.getSharedPreferences(this);
                    JSONArray jsonIcons = new JSONArray(pref5.getString(PREF_DESKTOP_ICONS, "[]"));
                    int iconToRemove = -1;
                    for (int i = 0; i < jsonIcons.length(); i++) {
                        DesktopIconInfo info = DesktopIconInfo.fromJson(jsonIcons.getJSONObject(i));
                        if (info != null && info.column == desktopIcon.column && info.row == desktopIcon.row) {
                            iconToRemove = i;
                            break;
                        }
                    }
                    if (iconToRemove > -1) {
                        jsonIcons.remove(iconToRemove);
                        pref5.edit().putString(PREF_DESKTOP_ICONS, jsonIcons.toString()).apply();
                        U.sendBroadcast(this, ACTION_REFRESH_DESKTOP_ICONS);
                    }
                } catch (JSONException ignored) {
                }
                break;
            case PREF_CHANGE_WALLPAPER_GLOBAL:
                changeWallpaper();
                prepareToClose();
                break;
            case PREF_CHANGE_WALLPAPER_DESKTOP:
                U.sendBroadcast(this, ACTION_WALLPAPER_CHANGE_REQUESTED);
                break;
            case PREF_REMOVE_DESKTOP_WALLPAPER:
                U.sendBroadcast(this, ACTION_REMOVE_DESKTOP_WALLPAPER);
                break;
        }
    if (!secondaryMenu)
        finish();
    return true;
}
Also used : Context(android.content.Context) Bundle(android.os.Bundle) PackageManager(android.content.pm.PackageManager) TaskbarPosition(com.farmerbb.taskbar.util.TaskbarPosition) Uri(android.net.Uri) WindowManager(android.view.WindowManager) Intent(android.content.Intent) PreferenceActivity(android.preference.PreferenceActivity) IconCache(com.farmerbb.taskbar.util.IconCache) AudioManager(android.media.AudioManager) DisplayInfo(com.farmerbb.taskbar.util.DisplayInfo) SuppressLint(android.annotation.SuppressLint) JSONException(org.json.JSONException) PinnedBlockedApps(com.farmerbb.taskbar.util.PinnedBlockedApps) SavedWindowSizes(com.farmerbb.taskbar.util.SavedWindowSizes) View(android.view.View) Settings(android.provider.Settings) Build(android.os.Build) TargetApi(android.annotation.TargetApi) DesktopIconInfo(com.farmerbb.taskbar.util.DesktopIconInfo) UserManager(android.os.UserManager) BuildConfig(com.farmerbb.taskbar.BuildConfig) ApplicationType(com.farmerbb.taskbar.util.ApplicationType) R(com.farmerbb.taskbar.R) ComponentName(android.content.ComponentName) ShortcutInfo(android.content.pm.ShortcutInfo) U(com.farmerbb.taskbar.util.U) AppEntry(com.farmerbb.taskbar.util.AppEntry) BroadcastReceiver(android.content.BroadcastReceiver) File(java.io.File) ResolveInfo(android.content.pm.ResolveInfo) LauncherHelper(com.farmerbb.taskbar.helper.LauncherHelper) LauncherApps(android.content.pm.LauncherApps) AccessibilityService(android.accessibilityservice.AccessibilityService) Gravity(android.view.Gravity) FreeformHackHelper(com.farmerbb.taskbar.helper.FreeformHackHelper) List(java.util.List) MenuHelper(com.farmerbb.taskbar.helper.MenuHelper) SharedPreferences(android.content.SharedPreferences) ActivityNotFoundException(android.content.ActivityNotFoundException) Preference(android.preference.Preference) LauncherActivityInfo(android.content.pm.LauncherActivityInfo) JSONArray(org.json.JSONArray) Constants(com.farmerbb.taskbar.util.Constants) SharedPreferences(android.content.SharedPreferences) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) LauncherApps(android.content.pm.LauncherApps) Intent(android.content.Intent) DesktopIconInfo(com.farmerbb.taskbar.util.DesktopIconInfo) LauncherHelper(com.farmerbb.taskbar.helper.LauncherHelper) AudioManager(android.media.AudioManager) AppEntry(com.farmerbb.taskbar.util.AppEntry) ActivityNotFoundException(android.content.ActivityNotFoundException) UserManager(android.os.UserManager) LauncherActivityInfo(android.content.pm.LauncherActivityInfo) PinnedBlockedApps(com.farmerbb.taskbar.util.PinnedBlockedApps) TargetApi(android.annotation.TargetApi)

Aggregations

AppEntry (com.farmerbb.taskbar.util.AppEntry)25 SuppressLint (android.annotation.SuppressLint)13 ArrayList (java.util.ArrayList)12 SharedPreferences (android.content.SharedPreferences)11 TargetApi (android.annotation.TargetApi)10 Point (android.graphics.Point)10 UserManager (android.os.UserManager)10 LauncherActivityInfo (android.content.pm.LauncherActivityInfo)9 Intent (android.content.Intent)8 LauncherApps (android.content.pm.LauncherApps)8 View (android.view.View)7 ComponentName (android.content.ComponentName)6 PackageManager (android.content.pm.PackageManager)6 ImageView (android.widget.ImageView)6 ActivityNotFoundException (android.content.ActivityNotFoundException)5 Drawable (android.graphics.drawable.Drawable)5 Handler (android.os.Handler)5 TextView (android.widget.TextView)5 PinnedBlockedApps (com.farmerbb.taskbar.util.PinnedBlockedApps)5 Context (android.content.Context)4