Search in sources :

Example 1 with PinnedBlockedApps

use of com.farmerbb.taskbar.util.PinnedBlockedApps 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 2 with PinnedBlockedApps

use of com.farmerbb.taskbar.util.PinnedBlockedApps 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 || !launcherApps.getActivityList(getIntent().getStringExtra("package_name"), userManager.getUserForSerialNumber(userId)).isEmpty();
    if (appIsValid)
        switch(p.getKey()) {
            case "app_info":
                U.launchApp(this, () -> launcherApps.startAppDetailsActivity(ComponentName.unflattenFromString(componentName), userManager.getUserForSerialNumber(userId), null, U.getActivityOptionsBundle(ApplicationType.APPLICATION)));
                showStartMenu = false;
                shouldHideTaskbar = true;
                contextMenuFix = false;
                break;
            case "uninstall":
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && isInMultiWindowMode() && !U.isChromeOs(this)) {
                    Intent intent2 = new Intent(ContextMenuActivity.this, DummyActivity.class);
                    intent2.putExtra("uninstall", packageName);
                    intent2.putExtra("user_id", userId);
                    try {
                        startActivity(intent2);
                    } catch (IllegalArgumentException e) {
                    /* Gracefully fail */
                    }
                } else {
                    Intent intent2 = new Intent(Intent.ACTION_DELETE, Uri.parse("package:" + packageName));
                    intent2.putExtra(Intent.EXTRA_USER, userManager.getUserForSerialNumber(userId));
                    new Handler().post(() -> {
                        try {
                            startActivity(intent2);
                        } catch (ActivityNotFoundException | IllegalArgumentException e) {
                        /* Gracefully fail */
                        }
                    });
                }
                showStartMenu = false;
                shouldHideTaskbar = true;
                contextMenuFix = false;
                break;
            case "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);
                    try {
                        startActivity(intent2, U.getActivityOptionsBundle(ApplicationType.APPLICATION));
                    } catch (IllegalArgumentException e) {
                    /* Gracefully fail */
                    }
                });
                showStartMenu = false;
                shouldHideTaskbar = true;
                contextMenuFix = false;
                break;
            case "quit_taskbar":
                Intent quitIntent = new Intent("com.farmerbb.taskbar.QUIT");
                quitIntent.setPackage(BuildConfig.APPLICATION_ID);
                sendBroadcast(quitIntent);
                showStartMenu = false;
                shouldHideTaskbar = true;
                contextMenuFix = false;
                break;
            case "pin_app":
                PinnedBlockedApps pba = PinnedBlockedApps.getInstance(this);
                if (pba.isPinned(componentName))
                    pba.removePinnedApp(this, componentName);
                else {
                    Intent intent = new Intent();
                    intent.setComponent(ComponentName.unflattenFromString(componentName));
                    LauncherActivityInfo appInfo = launcherApps.resolveActivity(intent, userManager.getUserForSerialNumber(userId));
                    if (appInfo != null) {
                        AppEntry newEntry = new AppEntry(packageName, componentName, appName, IconCache.getInstance(this).getIcon(this, getPackageManager(), appInfo), true);
                        newEntry.setUserId(userId);
                        pba.addPinnedApp(this, newEntry);
                    }
                }
                break;
            case "block_app":
                PinnedBlockedApps pba2 = PinnedBlockedApps.getInstance(this);
                if (pba2.isBlocked(componentName))
                    pba2.removeBlockedApp(this, componentName);
                else {
                    pba2.addBlockedApp(this, new AppEntry(packageName, componentName, appName, null, false));
                }
                break;
            case "show_window_sizes":
                generateWindowSizes();
                if (U.hasBrokenSetLaunchBoundsApi())
                    U.showToastLong(this, R.string.window_sizes_not_available);
                getListView().setOnItemLongClickListener((parent, view, position, id) -> {
                    String[] windowSizes = { "standard", "large", "fullscreen", "half_left", "half_right", "phone_size" };
                    SavedWindowSizes.getInstance(ContextMenuActivity.this).setWindowSize(ContextMenuActivity.this, packageName, windowSizes[position]);
                    generateWindowSizes();
                    return true;
                });
                secondaryMenu = true;
                break;
            case "window_size_standard":
            case "window_size_large":
            case "window_size_fullscreen":
            case "window_size_half_left":
            case "window_size_half_right":
            case "window_size_phone_size":
                String windowSize = p.getKey().replace("window_size_", "");
                SharedPreferences pref2 = U.getSharedPreferences(this);
                if (pref2.getBoolean("save_window_sizes", true)) {
                    SavedWindowSizes.getInstance(this).setWindowSize(this, packageName, windowSize);
                }
                U.launchApp(getApplicationContext(), packageName, componentName, userId, windowSize, false, true);
                if (U.hasBrokenSetLaunchBoundsApi())
                    U.cancelToast();
                showStartMenu = false;
                shouldHideTaskbar = true;
                contextMenuFix = false;
                break;
            case "app_shortcuts":
                getPreferenceScreen().removeAll();
                generateShortcuts();
                secondaryMenu = true;
                break;
            case "shortcut_1":
            case "shortcut_2":
            case "shortcut_3":
            case "shortcut_4":
            case "shortcut_5":
                U.startShortcut(getApplicationContext(), packageName, componentName, shortcuts.get(Integer.parseInt(p.getKey().replace("shortcut_", "")) - 1));
                showStartMenu = false;
                shouldHideTaskbar = true;
                contextMenuFix = false;
                break;
            case "start_menu_apps":
                Intent intent = null;
                SharedPreferences pref3 = U.getSharedPreferences(this);
                switch(pref3.getString("theme", "light")) {
                    case "light":
                        intent = new Intent(this, SelectAppActivity.class);
                        break;
                    case "dark":
                        intent = new Intent(this, SelectAppActivityDark.class);
                        break;
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && pref3.getBoolean("freeform_hack", false) && intent != null && isInMultiWindowMode()) {
                    intent.putExtra("no_shadow", true);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT);
                    U.launchAppMaximized(getApplicationContext(), intent);
                } else {
                    try {
                        startActivity(intent);
                    } catch (IllegalArgumentException e) {
                    /* Gracefully fail */
                    }
                }
                showStartMenu = false;
                shouldHideTaskbar = true;
                contextMenuFix = false;
                break;
            case "volume":
                AudioManager audio = (AudioManager) getSystemService(AUDIO_SERVICE);
                audio.adjustSuggestedStreamVolume(AudioManager.ADJUST_SAME, AudioManager.USE_DEFAULT_STREAM_TYPE, AudioManager.FLAG_SHOW_UI);
                showStartMenu = false;
                shouldHideTaskbar = true;
                contextMenuFix = false;
                break;
            case "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(ApplicationType.APPLICATION));
                    } catch (ActivityNotFoundException e) {
                        U.showToast(this, R.string.lock_device_not_supported);
                    } catch (IllegalArgumentException e) {
                    /* Gracefully fail */
                    }
                });
                showStartMenu = false;
                shouldHideTaskbar = true;
                contextMenuFix = false;
                break;
            case "system_settings":
                U.launchApp(this, () -> {
                    Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
                    settingsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    try {
                        startActivity(settingsIntent, U.getActivityOptionsBundle(ApplicationType.APPLICATION));
                    } catch (ActivityNotFoundException e) {
                        U.showToast(this, R.string.lock_device_not_supported);
                    } catch (IllegalArgumentException e) {
                    /* Gracefully fail */
                    }
                });
                showStartMenu = false;
                shouldHideTaskbar = true;
                contextMenuFix = false;
                break;
            case "lock_device":
                U.lockDevice(this);
                showStartMenu = false;
                shouldHideTaskbar = true;
                contextMenuFix = false;
                break;
            case "power_menu":
                U.sendAccessibilityAction(this, AccessibilityService.GLOBAL_ACTION_POWER_DIALOG);
                showStartMenu = false;
                shouldHideTaskbar = true;
                contextMenuFix = false;
                break;
            case "change_wallpaper":
                Intent intent3 = Intent.createChooser(new Intent(Intent.ACTION_SET_WALLPAPER), getString(R.string.set_wallpaper));
                intent3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                U.launchAppMaximized(getApplicationContext(), intent3);
                showStartMenu = false;
                shouldHideTaskbar = true;
                contextMenuFix = false;
                break;
            case "close":
                ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
                am.killBackgroundProcesses(packageName);
                showStartMenu = false;
                shouldHideTaskbar = true;
                contextMenuFix = false;
                break;
        }
    if (!secondaryMenu)
        finish();
    return true;
}
Also used : ActivityManager(android.app.ActivityManager) Context(android.content.Context) Bundle(android.os.Bundle) PackageManager(android.content.pm.PackageManager) SelectAppActivityDark(com.farmerbb.taskbar.activity.dark.SelectAppActivityDark) Uri(android.net.Uri) WindowManager(android.view.WindowManager) Intent(android.content.Intent) MainActivity(com.farmerbb.taskbar.MainActivity) LocalBroadcastManager(android.support.v4.content.LocalBroadcastManager) MenuHelper(com.farmerbb.taskbar.util.MenuHelper) PreferenceActivity(android.preference.PreferenceActivity) IconCache(com.farmerbb.taskbar.util.IconCache) AudioManager(android.media.AudioManager) SuppressLint(android.annotation.SuppressLint) PinnedBlockedApps(com.farmerbb.taskbar.util.PinnedBlockedApps) Handler(android.os.Handler) SavedWindowSizes(com.farmerbb.taskbar.util.SavedWindowSizes) View(android.view.View) Settings(android.provider.Settings) Build(android.os.Build) TargetApi(android.annotation.TargetApi) 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) IntentFilter(android.content.IntentFilter) U(com.farmerbb.taskbar.util.U) AppEntry(com.farmerbb.taskbar.util.AppEntry) BroadcastReceiver(android.content.BroadcastReceiver) DisplayMetrics(android.util.DisplayMetrics) FreeformHackHelper(com.farmerbb.taskbar.util.FreeformHackHelper) ResolveInfo(android.content.pm.ResolveInfo) LauncherApps(android.content.pm.LauncherApps) AccessibilityService(android.accessibilityservice.AccessibilityService) Gravity(android.view.Gravity) List(java.util.List) SharedPreferences(android.content.SharedPreferences) ActivityNotFoundException(android.content.ActivityNotFoundException) Preference(android.preference.Preference) LauncherActivityInfo(android.content.pm.LauncherActivityInfo) SharedPreferences(android.content.SharedPreferences) Handler(android.os.Handler) LauncherApps(android.content.pm.LauncherApps) Intent(android.content.Intent) MainActivity(com.farmerbb.taskbar.MainActivity) ActivityManager(android.app.ActivityManager) 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)

Example 3 with PinnedBlockedApps

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

the class ContextMenuActivity method generateMenu.

@SuppressWarnings("deprecation")
private void generateMenu() {
    if (isStartButton) {
        addPreferencesFromResource(R.xml.pref_context_menu_open_settings);
        findPreference("open_taskbar_settings").setOnPreferenceClickListener(this);
        findPreference("start_menu_apps").setOnPreferenceClickListener(this);
        if (U.launcherIsDefault(this) && FreeformHackHelper.getInstance().isInFreeformWorkspace()) {
            addPreferencesFromResource(R.xml.pref_context_menu_change_wallpaper);
            findPreference("change_wallpaper").setOnPreferenceClickListener(this);
        }
        if (!getIntent().getBooleanExtra("dont_show_quit", false)) {
            addPreferencesFromResource(R.xml.pref_context_menu_quit);
            findPreference("quit_taskbar").setOnPreferenceClickListener(this);
        }
    } else if (isOverflowMenu) {
        if (getResources().getConfiguration().screenWidthDp >= 600 && Build.VERSION.SDK_INT <= Build.VERSION_CODES.M)
            setTitle(R.string.tools);
        else {
            addPreferencesFromResource(R.xml.pref_context_menu_header);
            findPreference("header").setTitle(R.string.tools);
        }
        addPreferencesFromResource(R.xml.pref_context_menu_overflow);
        findPreference("volume").setOnPreferenceClickListener(this);
        findPreference("system_settings").setOnPreferenceClickListener(this);
        findPreference("lock_device").setOnPreferenceClickListener(this);
        findPreference("power_menu").setOnPreferenceClickListener(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            findPreference("file_manager").setOnPreferenceClickListener(this);
        else
            getPreferenceScreen().removePreference(findPreference("file_manager"));
    } else {
        appName = getIntent().getStringExtra("app_name");
        packageName = getIntent().getStringExtra("package_name");
        componentName = getIntent().getStringExtra("component_name");
        userId = getIntent().getLongExtra("user_id", 0);
        if (getResources().getConfiguration().screenWidthDp >= 600 && Build.VERSION.SDK_INT <= Build.VERSION_CODES.M)
            setTitle(appName);
        else {
            addPreferencesFromResource(R.xml.pref_context_menu_header);
            findPreference("header").setTitle(appName);
        }
        SharedPreferences pref = U.getSharedPreferences(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && pref.getBoolean("freeform_hack", false) && !U.isGame(this, packageName)) {
            addPreferencesFromResource(R.xml.pref_context_menu_show_window_sizes);
            findPreference("show_window_sizes").setOnPreferenceClickListener(this);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
            int shortcutCount = getLauncherShortcuts();
            if (shortcutCount > 1) {
                addPreferencesFromResource(R.xml.pref_context_menu_shortcuts);
                findPreference("app_shortcuts").setOnPreferenceClickListener(this);
            } else if (shortcutCount == 1)
                generateShortcuts();
        }
        final PackageManager pm = getPackageManager();
        Intent homeIntent = new Intent(Intent.ACTION_MAIN);
        homeIntent.addCategory(Intent.CATEGORY_HOME);
        ResolveInfo defaultLauncher = pm.resolveActivity(homeIntent, PackageManager.MATCH_DEFAULT_ONLY);
        if (!packageName.contains(BuildConfig.BASE_APPLICATION_ID) && !packageName.equals(defaultLauncher.activityInfo.packageName)) {
            PinnedBlockedApps pba = PinnedBlockedApps.getInstance(this);
            if (pba.isPinned(componentName)) {
                addPreferencesFromResource(R.xml.pref_context_menu_pin);
                findPreference("pin_app").setOnPreferenceClickListener(this);
                findPreference("pin_app").setTitle(R.string.unpin_app);
            } else if (pba.isBlocked(componentName)) {
                addPreferencesFromResource(R.xml.pref_context_menu_block);
                findPreference("block_app").setOnPreferenceClickListener(this);
                findPreference("block_app").setTitle(R.string.unblock_app);
            } else {
                final int MAX_NUM_OF_COLUMNS = U.getMaxNumOfEntries(this);
                if (pba.getPinnedApps().size() < MAX_NUM_OF_COLUMNS) {
                    addPreferencesFromResource(R.xml.pref_context_menu_pin);
                    findPreference("pin_app").setOnPreferenceClickListener(this);
                    findPreference("pin_app").setTitle(R.string.pin_app);
                }
                addPreferencesFromResource(R.xml.pref_context_menu_block);
                findPreference("block_app").setOnPreferenceClickListener(this);
                findPreference("block_app").setTitle(R.string.block_app);
            }
        }
        addPreferencesFromResource(R.xml.pref_context_menu);
        findPreference("app_info").setOnPreferenceClickListener(this);
        if (isRunningApp) {
            findPreference("close").setOnPreferenceClickListener(this);
            getPreferenceScreen().removePreference(findPreference("uninstall"));
        } else {
            findPreference("uninstall").setOnPreferenceClickListener(this);
            getPreferenceScreen().removePreference(findPreference("close"));
        }
    }
}
Also used : ResolveInfo(android.content.pm.ResolveInfo) PackageManager(android.content.pm.PackageManager) SharedPreferences(android.content.SharedPreferences) Intent(android.content.Intent) PinnedBlockedApps(com.farmerbb.taskbar.util.PinnedBlockedApps) SuppressLint(android.annotation.SuppressLint)

Example 4 with PinnedBlockedApps

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

the class UninstallReceiver method onReceive.

@SuppressWarnings("Convert2streamapi")
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_PACKAGE_FULLY_REMOVED)) {
        String packageName = intent.getData().getEncodedSchemeSpecificPart();
        PinnedBlockedApps pba = PinnedBlockedApps.getInstance(context);
        List<AppEntry> pinnedApps = pba.getPinnedApps();
        List<String> componentNames = new ArrayList<>();
        for (AppEntry entry : pinnedApps) {
            if (entry.getPackageName().equals(packageName)) {
                componentNames.add(entry.getComponentName());
            }
        }
        for (String componentName : componentNames) {
            pba.removePinnedApp(context, componentName);
        }
    }
}
Also used : AppEntry(com.farmerbb.taskbar.util.AppEntry) ArrayList(java.util.ArrayList) PinnedBlockedApps(com.farmerbb.taskbar.util.PinnedBlockedApps)

Example 5 with PinnedBlockedApps

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

the class ReceiveSettingsReceiver method onReceive.

@Override
public void onReceive(Context context, Intent intent) {
    // Ignore this broadcast if this is the free version
    if (BuildConfig.APPLICATION_ID.equals(BuildConfig.PAID_APPLICATION_ID)) {
        // Get pinned and blocked apps
        PinnedBlockedApps pba = PinnedBlockedApps.getInstance(context);
        pba.clear(context);
        String[] pinnedAppsPackageNames = intent.getStringArrayExtra("pinned_apps_package_names");
        String[] pinnedAppsComponentNames = intent.getStringArrayExtra("pinned_apps_component_names");
        String[] pinnedAppsLabels = intent.getStringArrayExtra("pinned_apps_labels");
        long[] pinnedAppsUserIds = intent.getLongArrayExtra("pinned_apps_user_ids");
        UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
        LauncherApps launcherApps = (LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE);
        if (pinnedAppsPackageNames != null && pinnedAppsComponentNames != null && pinnedAppsLabels != null)
            for (int i = 0; i < pinnedAppsPackageNames.length; i++) {
                Intent throwaway = new Intent();
                throwaway.setComponent(ComponentName.unflattenFromString(pinnedAppsComponentNames[i]));
                long userId;
                if (pinnedAppsUserIds != null)
                    userId = pinnedAppsUserIds[i];
                else
                    userId = userManager.getSerialNumberForUser(Process.myUserHandle());
                AppEntry newEntry = new AppEntry(pinnedAppsPackageNames[i], pinnedAppsComponentNames[i], pinnedAppsLabels[i], IconCache.getInstance(context).getIcon(context, context.getPackageManager(), launcherApps.resolveActivity(throwaway, userManager.getUserForSerialNumber(userId))), true);
                newEntry.setUserId(userId);
                pba.addPinnedApp(context, newEntry);
            }
        String[] blockedAppsPackageNames = intent.getStringArrayExtra("blocked_apps_package_names");
        String[] blockedAppsComponentNames = intent.getStringArrayExtra("blocked_apps_component_names");
        String[] blockedAppsLabels = intent.getStringArrayExtra("blocked_apps_labels");
        if (blockedAppsPackageNames != null && blockedAppsComponentNames != null && blockedAppsLabels != null)
            for (int i = 0; i < blockedAppsPackageNames.length; i++) {
                pba.addBlockedApp(context, new AppEntry(blockedAppsPackageNames[i], blockedAppsComponentNames[i], blockedAppsLabels[i], null, false));
            }
        // Get blacklist
        Blacklist blacklist = Blacklist.getInstance(context);
        blacklist.clear(context);
        String[] blacklistPackageNames = intent.getStringArrayExtra("blacklist_package_names");
        String[] blacklistLabels = intent.getStringArrayExtra("blacklist_labels");
        if (blacklistPackageNames != null && blacklistLabels != null)
            for (int i = 0; i < blacklistPackageNames.length; i++) {
                blacklist.addBlockedApp(context, new BlacklistEntry(blacklistPackageNames[i], blacklistLabels[i]));
            }
        // Get top apps
        TopApps topApps = TopApps.getInstance(context);
        topApps.clear(context);
        String[] topAppsPackageNames = intent.getStringArrayExtra("top_apps_package_names");
        String[] topAppsLabels = intent.getStringArrayExtra("top_apps_labels");
        if (topAppsPackageNames != null && topAppsLabels != null)
            for (int i = 0; i < topAppsPackageNames.length; i++) {
                topApps.addTopApp(context, new BlacklistEntry(topAppsPackageNames[i], topAppsLabels[i]));
            }
        // Get saved window sizes
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            SavedWindowSizes savedWindowSizes = SavedWindowSizes.getInstance(context);
            savedWindowSizes.clear(context);
            String[] savedWindowSizesComponentNames = intent.getStringArrayExtra("saved_window_sizes_component_names");
            String[] savedWindowSizesWindowSizes = intent.getStringArrayExtra("saved_window_sizes_window_sizes");
            if (savedWindowSizesComponentNames != null && savedWindowSizesWindowSizes != null)
                for (int i = 0; i < savedWindowSizesComponentNames.length; i++) {
                    savedWindowSizes.setWindowSize(context, savedWindowSizesComponentNames[i], savedWindowSizesWindowSizes[i]);
                }
        }
        // Get shared preferences
        String contents = intent.getStringExtra("preferences");
        if (contents.length() > 0)
            try {
                File file = new File(context.getFilesDir().getParent() + "/shared_prefs/" + BuildConfig.APPLICATION_ID + "_preferences.xml");
                FileOutputStream output = new FileOutputStream(file);
                output.write(contents.getBytes());
                output.close();
            } catch (IOException e) {
            /* Gracefully fail */
            }
        try {
            File file = new File(context.getFilesDir() + File.separator + "imported_successfully");
            if (file.createNewFile())
                LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("com.farmerbb.taskbar.IMPORT_FINISHED"));
        } catch (IOException e) {
        /* Gracefully fail */
        }
    }
}
Also used : SavedWindowSizes(com.farmerbb.taskbar.util.SavedWindowSizes) LauncherApps(android.content.pm.LauncherApps) Intent(android.content.Intent) IOException(java.io.IOException) AppEntry(com.farmerbb.taskbar.util.AppEntry) BlacklistEntry(com.farmerbb.taskbar.util.BlacklistEntry) UserManager(android.os.UserManager) FileOutputStream(java.io.FileOutputStream) TopApps(com.farmerbb.taskbar.util.TopApps) Blacklist(com.farmerbb.taskbar.util.Blacklist) PinnedBlockedApps(com.farmerbb.taskbar.util.PinnedBlockedApps) File(java.io.File)

Aggregations

PinnedBlockedApps (com.farmerbb.taskbar.util.PinnedBlockedApps)6 Intent (android.content.Intent)5 AppEntry (com.farmerbb.taskbar.util.AppEntry)5 SuppressLint (android.annotation.SuppressLint)3 SharedPreferences (android.content.SharedPreferences)3 LauncherApps (android.content.pm.LauncherApps)3 PackageManager (android.content.pm.PackageManager)3 ResolveInfo (android.content.pm.ResolveInfo)3 UserManager (android.os.UserManager)3 TargetApi (android.annotation.TargetApi)2 LauncherActivityInfo (android.content.pm.LauncherActivityInfo)2 Handler (android.os.Handler)2 DisplayMetrics (android.util.DisplayMetrics)2 MainActivity (com.farmerbb.taskbar.MainActivity)2 Blacklist (com.farmerbb.taskbar.util.Blacklist)2 BlacklistEntry (com.farmerbb.taskbar.util.BlacklistEntry)2 SavedWindowSizes (com.farmerbb.taskbar.util.SavedWindowSizes)2 TopApps (com.farmerbb.taskbar.util.TopApps)2 File (java.io.File)2 IOException (java.io.IOException)2