Search in sources :

Example 26 with Build

use of android.os.Build in project Taskbar by farmerbb.

the class StartMenuService method drawStartMenu.

@SuppressLint("RtlHardcoded")
private void drawStartMenu() {
    IconCache.getInstance(this).clearCache();
    final SharedPreferences pref = U.getSharedPreferences(this);
    final boolean hasHardwareKeyboard = getResources().getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS;
    switch(pref.getString("show_search_bar", "keyboard")) {
        case "always":
            shouldShowSearchBox = true;
            break;
        case "keyboard":
            shouldShowSearchBox = hasHardwareKeyboard;
            break;
        case "never":
            shouldShowSearchBox = false;
            break;
    }
    // Initialize layout params
    windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
    U.setCachedRotation(windowManager.getDefaultDisplay().getRotation());
    final WindowManager.LayoutParams params = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, CompatUtils.getOverlayType(), shouldShowSearchBox ? 0 : WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, PixelFormat.TRANSLUCENT);
    // Determine where to show the start menu on screen
    switch(U.getTaskbarPosition(this)) {
        case "bottom_left":
            layoutId = R.layout.start_menu_left;
            params.gravity = Gravity.BOTTOM | Gravity.LEFT;
            break;
        case "bottom_vertical_left":
            layoutId = R.layout.start_menu_vertical_left;
            params.gravity = Gravity.BOTTOM | Gravity.LEFT;
            break;
        case "bottom_right":
            layoutId = R.layout.start_menu_right;
            params.gravity = Gravity.BOTTOM | Gravity.RIGHT;
            break;
        case "bottom_vertical_right":
            layoutId = R.layout.start_menu_vertical_right;
            params.gravity = Gravity.BOTTOM | Gravity.RIGHT;
            break;
        case "top_left":
            layoutId = R.layout.start_menu_top_left;
            params.gravity = Gravity.TOP | Gravity.LEFT;
            break;
        case "top_vertical_left":
            layoutId = R.layout.start_menu_vertical_left;
            params.gravity = Gravity.TOP | Gravity.LEFT;
            break;
        case "top_right":
            layoutId = R.layout.start_menu_top_right;
            params.gravity = Gravity.TOP | Gravity.RIGHT;
            break;
        case "top_vertical_right":
            layoutId = R.layout.start_menu_vertical_right;
            params.gravity = Gravity.TOP | Gravity.RIGHT;
            break;
    }
    // Initialize views
    layout = (StartMenuLayout) LayoutInflater.from(U.wrapContext(this)).inflate(layoutId, null);
    startMenu = U.findViewById(layout, R.id.start_menu);
    if ((shouldShowSearchBox && !hasHardwareKeyboard) || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1)
        layout.viewHandlesBackButton();
    boolean scrollbar = pref.getBoolean("scrollbar", false);
    startMenu.setFastScrollEnabled(scrollbar);
    startMenu.setFastScrollAlwaysVisible(scrollbar);
    startMenu.setScrollBarStyle(scrollbar ? View.SCROLLBARS_OUTSIDE_INSET : View.SCROLLBARS_INSIDE_OVERLAY);
    if (pref.getBoolean("transparent_start_menu", false))
        startMenu.setBackgroundColor(0);
    if (U.visualFeedbackEnabled(this))
        startMenu.setRecyclerListener(view -> view.setBackgroundColor(0));
    searchView = U.findViewById(layout, R.id.search);
    int backgroundTint = U.getBackgroundTint(this);
    FrameLayout startMenuFrame = U.findViewById(layout, R.id.start_menu_frame);
    FrameLayout searchViewLayout = U.findViewById(layout, R.id.search_view_layout);
    startMenuFrame.setBackgroundColor(backgroundTint);
    searchViewLayout.setBackgroundColor(backgroundTint);
    if (shouldShowSearchBox) {
        if (!hasHardwareKeyboard)
            searchView.setIconifiedByDefault(true);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String query) {
                if (!hasSubmittedQuery) {
                    ListAdapter adapter = startMenu.getAdapter();
                    if (adapter != null) {
                        hasSubmittedQuery = true;
                        if (adapter.getCount() > 0) {
                            View view = adapter.getView(0, null, startMenu);
                            LinearLayout layout = U.findViewById(view, R.id.entry);
                            layout.performClick();
                        } else {
                            if (U.shouldCollapse(StartMenuService.this, true))
                                LocalBroadcastManager.getInstance(StartMenuService.this).sendBroadcast(new Intent("com.farmerbb.taskbar.HIDE_TASKBAR"));
                            else
                                LocalBroadcastManager.getInstance(StartMenuService.this).sendBroadcast(new Intent("com.farmerbb.taskbar.HIDE_START_MENU"));
                            Intent intent;
                            if (Patterns.WEB_URL.matcher(query).matches()) {
                                intent = new Intent(Intent.ACTION_VIEW);
                                intent.setData(Uri.parse(URLUtil.guessUrl(query)));
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            } else {
                                intent = new Intent(Intent.ACTION_WEB_SEARCH);
                                intent.putExtra(SearchManager.QUERY, query);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            }
                            if (intent.resolveActivity(getPackageManager()) != null)
                                startActivity(intent);
                            else {
                                Uri uri = new Uri.Builder().scheme("https").authority("www.google.com").path("search").appendQueryParameter("q", query).build();
                                intent = new Intent(Intent.ACTION_VIEW);
                                intent.setData(uri);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                try {
                                    startActivity(intent);
                                } catch (ActivityNotFoundException e) {
                                /* Gracefully fail */
                                }
                            }
                        }
                    }
                }
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                searchView.setIconified(false);
                View closeButton = searchView.findViewById(R.id.search_close_btn);
                if (closeButton != null)
                    closeButton.setVisibility(View.GONE);
                refreshApps(newText, false);
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
                    new Handler().postDelayed(() -> {
                        EditText editText = U.findViewById(searchView, R.id.search_src_text);
                        if (editText != null) {
                            editText.requestFocus();
                            editText.setSelection(editText.getText().length());
                        }
                    }, 50);
                }
                return true;
            }
        });
        searchView.setOnQueryTextFocusChangeListener((view, b) -> {
            if (!hasHardwareKeyboard) {
                ViewGroup.LayoutParams params1 = startMenu.getLayoutParams();
                params1.height = getResources().getDimensionPixelSize(b && !isSecondScreenDisablingKeyboard() ? R.dimen.start_menu_height_half : R.dimen.start_menu_height);
                startMenu.setLayoutParams(params1);
            }
            if (!b) {
                if (hasHardwareKeyboard && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1)
                    LocalBroadcastManager.getInstance(StartMenuService.this).sendBroadcast(new Intent("com.farmerbb.taskbar.HIDE_START_MENU"));
                else {
                    InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
            }
        });
        searchView.setImeOptions(EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
        LinearLayout powerButton = U.findViewById(layout, R.id.power_button);
        powerButton.setOnClickListener(view -> {
            int[] location = new int[2];
            view.getLocationOnScreen(location);
            openContextMenu(location);
        });
        powerButton.setOnGenericMotionListener((view, motionEvent) -> {
            if (motionEvent.getAction() == MotionEvent.ACTION_BUTTON_PRESS && motionEvent.getButtonState() == MotionEvent.BUTTON_SECONDARY) {
                int[] location = new int[2];
                view.getLocationOnScreen(location);
                openContextMenu(location);
            }
            return false;
        });
        searchViewLayout.setOnClickListener(view -> searchView.setIconified(false));
        startMenu.setOnItemClickListener((parent, view, position, id) -> {
            hideStartMenu(true);
            AppEntry entry = (AppEntry) parent.getAdapter().getItem(position);
            U.launchApp(StartMenuService.this, entry.getPackageName(), entry.getComponentName(), entry.getUserId(StartMenuService.this), null, false, false);
        });
        if (pref.getBoolean("transparent_start_menu", false))
            layout.findViewById(R.id.search_view_child_layout).setBackgroundColor(0);
    } else
        searchViewLayout.setVisibility(View.GONE);
    textView = U.findViewById(layout, R.id.no_apps_found);
    LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
    lbm.unregisterReceiver(toggleReceiver);
    lbm.unregisterReceiver(hideReceiver);
    lbm.unregisterReceiver(hideReceiverNoReset);
    lbm.unregisterReceiver(showSpaceReceiver);
    lbm.unregisterReceiver(hideSpaceReceiver);
    lbm.unregisterReceiver(resetReceiver);
    lbm.registerReceiver(toggleReceiver, new IntentFilter("com.farmerbb.taskbar.TOGGLE_START_MENU"));
    lbm.registerReceiver(hideReceiver, new IntentFilter("com.farmerbb.taskbar.HIDE_START_MENU"));
    lbm.registerReceiver(hideReceiverNoReset, new IntentFilter("com.farmerbb.taskbar.HIDE_START_MENU_NO_RESET"));
    lbm.registerReceiver(showSpaceReceiver, new IntentFilter("com.farmerbb.taskbar.SHOW_START_MENU_SPACE"));
    lbm.registerReceiver(hideSpaceReceiver, new IntentFilter("com.farmerbb.taskbar.HIDE_START_MENU_SPACE"));
    lbm.registerReceiver(resetReceiver, new IntentFilter("com.farmerbb.taskbar.RESET_START_MENU"));
    handler = new Handler();
    refreshApps(true);
    windowManager.addView(layout, params);
}
Also used : Rect(android.graphics.Rect) LinearLayout(android.widget.LinearLayout) GridView(android.widget.GridView) PackageManager(android.content.pm.PackageManager) SearchView(android.support.v7.widget.SearchView) Uri(android.net.Uri) WindowManager(android.view.WindowManager) FrameLayout(android.widget.FrameLayout) LocalBroadcastManager(android.support.v4.content.LocalBroadcastManager) MenuHelper(com.farmerbb.taskbar.util.MenuHelper) Drawable(android.graphics.drawable.Drawable) IconCache(com.farmerbb.taskbar.util.IconCache) IBinder(android.os.IBinder) Patterns(android.util.Patterns) TopApps(com.farmerbb.taskbar.util.TopApps) Handler(android.os.Handler) View(android.view.View) TargetApi(android.annotation.TargetApi) LauncherHelper(com.farmerbb.taskbar.util.LauncherHelper) InvisibleActivityAlt(com.farmerbb.taskbar.activity.InvisibleActivityAlt) Service(android.app.Service) IntentFilter(android.content.IntentFilter) U(com.farmerbb.taskbar.util.U) AppEntry(com.farmerbb.taskbar.util.AppEntry) CompatUtils(com.farmerbb.taskbar.util.CompatUtils) BroadcastReceiver(android.content.BroadcastReceiver) DisplayMetrics(android.util.DisplayMetrics) ViewGroup(android.view.ViewGroup) LauncherApps(android.content.pm.LauncherApps) List(java.util.List) TextView(android.widget.TextView) ListAdapter(android.widget.ListAdapter) ActivityNotFoundException(android.content.ActivityNotFoundException) LauncherActivityInfo(android.content.pm.LauncherActivityInfo) SearchManager(android.app.SearchManager) EditorInfo(android.view.inputmethod.EditorInfo) Context(android.content.Context) ContextMenuActivity(com.farmerbb.taskbar.activity.ContextMenuActivity) Intent(android.content.Intent) InvisibleActivity(com.farmerbb.taskbar.activity.InvisibleActivity) PixelFormat(android.graphics.PixelFormat) InputMethodManager(android.view.inputmethod.InputMethodManager) ArrayList(java.util.ArrayList) Blacklist(com.farmerbb.taskbar.util.Blacklist) SuppressLint(android.annotation.SuppressLint) MotionEvent(android.view.MotionEvent) StartMenuLayout(com.farmerbb.taskbar.widget.StartMenuLayout) UserHandle(android.os.UserHandle) Settings(android.provider.Settings) Build(android.os.Build) ContextMenuActivityDark(com.farmerbb.taskbar.activity.dark.ContextMenuActivityDark) Collator(java.text.Collator) UserManager(android.os.UserManager) ApplicationType(com.farmerbb.taskbar.util.ApplicationType) URLUtil(android.webkit.URLUtil) R(com.farmerbb.taskbar.R) ComponentName(android.content.ComponentName) LayoutInflater(android.view.LayoutInflater) StartMenuAdapter(com.farmerbb.taskbar.adapter.StartMenuAdapter) FreeformHackHelper(com.farmerbb.taskbar.util.FreeformHackHelper) Gravity(android.view.Gravity) SharedPreferences(android.content.SharedPreferences) Configuration(android.content.res.Configuration) Comparator(java.util.Comparator) Collections(java.util.Collections) EditText(android.widget.EditText) InputMethodManager(android.view.inputmethod.InputMethodManager) Uri(android.net.Uri) WindowManager(android.view.WindowManager) ListAdapter(android.widget.ListAdapter) EditText(android.widget.EditText) IntentFilter(android.content.IntentFilter) SharedPreferences(android.content.SharedPreferences) ViewGroup(android.view.ViewGroup) Handler(android.os.Handler) Intent(android.content.Intent) GridView(android.widget.GridView) SearchView(android.support.v7.widget.SearchView) View(android.view.View) TextView(android.widget.TextView) LocalBroadcastManager(android.support.v4.content.LocalBroadcastManager) SuppressLint(android.annotation.SuppressLint) SearchView(android.support.v7.widget.SearchView) AppEntry(com.farmerbb.taskbar.util.AppEntry) ActivityNotFoundException(android.content.ActivityNotFoundException) FrameLayout(android.widget.FrameLayout) LinearLayout(android.widget.LinearLayout) SuppressLint(android.annotation.SuppressLint)

Example 27 with Build

use of android.os.Build in project Taskbar by farmerbb.

the class MainActivity method proceedWithAppLaunch.

private void proceedWithAppLaunch(Bundle savedInstanceState) {
    setContentView(R.layout.main);
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setCustomView(R.layout.switch_layout);
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_SHOW_CUSTOM);
    }
    theSwitch = U.findViewById(this, R.id.the_switch);
    if (theSwitch != null) {
        final SharedPreferences pref = U.getSharedPreferences(this);
        theSwitch.setChecked(pref.getBoolean("taskbar_active", false));
        theSwitch.setOnCheckedChangeListener((compoundButton, b) -> {
            if (b) {
                if (U.canDrawOverlays(this)) {
                    boolean firstRun = pref.getBoolean("first_run", true);
                    startTaskbarService();
                    if (firstRun)
                        U.showRecentAppsDialog(this);
                } else {
                    U.showPermissionDialog(this);
                    compoundButton.setChecked(false);
                }
            } else
                stopTaskbarService();
        });
    }
    if (savedInstanceState == null) {
        if (!getIntent().hasExtra("theme_change"))
            getFragmentManager().beginTransaction().replace(R.id.fragmentContainer, new AboutFragment(), "AboutFragment").commit();
        else
            getFragmentManager().beginTransaction().replace(R.id.fragmentContainer, new AppearanceFragment(), "AppearanceFragment").commit();
    }
    if (!BuildConfig.APPLICATION_ID.equals(BuildConfig.BASE_APPLICATION_ID) && freeVersionInstalled()) {
        final SharedPreferences pref = U.getSharedPreferences(this);
        if (!pref.getBoolean("dont_show_uninstall_dialog", false)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.settings_imported_successfully).setMessage(R.string.import_dialog_message).setPositiveButton(R.string.action_uninstall, (dialog, which) -> {
                pref.edit().putBoolean("uninstall_dialog_shown", true).apply();
                try {
                    startActivity(new Intent(Intent.ACTION_DELETE, Uri.parse("package:" + BuildConfig.BASE_APPLICATION_ID)));
                } catch (ActivityNotFoundException e) {
                /* Gracefully fail */
                }
            });
            if (pref.getBoolean("uninstall_dialog_shown", false))
                builder.setNegativeButton(R.string.action_dont_show_again, (dialogInterface, i) -> pref.edit().putBoolean("dont_show_uninstall_dialog", true).apply());
            AlertDialog dialog = builder.create();
            dialog.show();
            dialog.setCancelable(false);
        }
        if (!pref.getBoolean("uninstall_dialog_shown", false)) {
            if (theSwitch != null)
                theSwitch.setChecked(false);
            SharedPreferences.Editor editor = pref.edit();
            String iconPack = pref.getString("icon_pack", BuildConfig.BASE_APPLICATION_ID);
            if (iconPack.contains(BuildConfig.BASE_APPLICATION_ID)) {
                editor.putString("icon_pack", BuildConfig.APPLICATION_ID);
            } else {
                U.refreshPinnedIcons(this);
            }
            editor.putBoolean("first_run", true);
            editor.apply();
        }
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
        ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);
        if (shortcutManager.getDynamicShortcuts().size() == 0) {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setClass(this, StartTaskbarActivity.class);
            intent.putExtra("is_launching_shortcut", true);
            ShortcutInfo shortcut = new ShortcutInfo.Builder(this, "start_taskbar").setShortLabel(getString(R.string.start_taskbar)).setIcon(Icon.createWithResource(this, R.drawable.shortcut_icon_start)).setIntent(intent).build();
            Intent intent2 = new Intent(Intent.ACTION_MAIN);
            intent2.setClass(this, ShortcutActivity.class);
            intent2.putExtra("is_launching_shortcut", true);
            ShortcutInfo shortcut2 = new ShortcutInfo.Builder(this, "freeform_mode").setShortLabel(getString(R.string.pref_header_freeform)).setIcon(Icon.createWithResource(this, R.drawable.shortcut_icon_freeform)).setIntent(intent2).build();
            shortcutManager.setDynamicShortcuts(Arrays.asList(shortcut, shortcut2));
        }
    }
}
Also used : AlertDialog(android.app.AlertDialog) Context(android.content.Context) Arrays(java.util.Arrays) Bundle(android.os.Bundle) PackageManager(android.content.pm.PackageManager) StartMenuService(com.farmerbb.taskbar.service.StartMenuService) Uri(android.net.Uri) Intent(android.content.Intent) FragmentTransaction(android.app.FragmentTransaction) LocalBroadcastManager(android.support.v4.content.LocalBroadcastManager) NotificationService(com.farmerbb.taskbar.service.NotificationService) StartTaskbarActivity(com.farmerbb.taskbar.activity.StartTaskbarActivity) PackageInfo(android.content.pm.PackageInfo) IconCache(com.farmerbb.taskbar.util.IconCache) AboutFragment(com.farmerbb.taskbar.fragment.AboutFragment) Icon(android.graphics.drawable.Icon) Build(android.os.Build) ActionBar(android.support.v7.app.ActionBar) LauncherHelper(com.farmerbb.taskbar.util.LauncherHelper) ComponentName(android.content.ComponentName) ShortcutInfo(android.content.pm.ShortcutInfo) IntentFilter(android.content.IntentFilter) U(com.farmerbb.taskbar.util.U) SwitchCompat(android.support.v7.widget.SwitchCompat) AppearanceFragment(com.farmerbb.taskbar.fragment.AppearanceFragment) BroadcastReceiver(android.content.BroadcastReceiver) ShortcutManager(android.content.pm.ShortcutManager) AppCompatActivity(android.support.v7.app.AppCompatActivity) FreeformHackHelper(com.farmerbb.taskbar.util.FreeformHackHelper) File(java.io.File) AlertDialog(android.app.AlertDialog) TaskbarService(com.farmerbb.taskbar.service.TaskbarService) SharedPreferences(android.content.SharedPreferences) DashboardService(com.farmerbb.taskbar.service.DashboardService) ActivityNotFoundException(android.content.ActivityNotFoundException) KeyboardShortcutActivity(com.farmerbb.taskbar.activity.KeyboardShortcutActivity) ShortcutActivity(com.farmerbb.taskbar.activity.ShortcutActivity) HomeActivity(com.farmerbb.taskbar.activity.HomeActivity) ImportSettingsActivity(com.farmerbb.taskbar.activity.ImportSettingsActivity) AboutFragment(com.farmerbb.taskbar.fragment.AboutFragment) ShortcutInfo(android.content.pm.ShortcutInfo) SharedPreferences(android.content.SharedPreferences) ShortcutManager(android.content.pm.ShortcutManager) Intent(android.content.Intent) AppearanceFragment(com.farmerbb.taskbar.fragment.AppearanceFragment) ActivityNotFoundException(android.content.ActivityNotFoundException) ActionBar(android.support.v7.app.ActionBar)

Example 28 with Build

use of android.os.Build in project butter-android by butterproject.

the class PreferencesHandler method getPreferenceItem.

@NonNull
public PrefItem getPreferenceItem(@PrefKey String key) {
    switch(key) {
        case DEFAULT_PROVIDER:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_prefs_default_view).setTitleResource(R.string.default_view).setPreferenceKey(DEFAULT_PROVIDER).setValue(getDefaultProvider()).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    String[] items = resources.getStringArray(R.array.prefs_providers);
                    return items[(Integer) item.getValue()];
                }
            }).build();
        case Prefs.DEFAULT_PLAYER:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_prefs_default_player).setTitleResource(R.string.default_player).setPreferenceKey(Prefs.DEFAULT_PLAYER).setValue(prefManager.get(Prefs.DEFAULT_PLAYER_NAME, context.getString(R.string.internal_player))).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    return (String) item.getValue();
                }
            }).build();
        case Prefs.QUALITY_DEFAULT:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_action_quality).setTitleResource(R.string.quality).setPreferenceKey(Prefs.QUALITY_DEFAULT).hasNext(true).setValue(getDefaultQuality()).setSubtitleGenerator(item -> String.format(Locale.US, "%dp", (Integer) item.getValue())).build();
        case Prefs.LOCALE:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_prefs_app_language).setTitleResource(R.string.i18n_language).setPreferenceKey(Prefs.LOCALE).hasNext(true).setValue(prefManager.get(Prefs.LOCALE, resources.getString(R.string.device_language))).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    Locale locale = LocaleUtils.toLocale((String) item.getValue());
                    return locale.getDisplayName(locale);
                }
            }).build();
        case Prefs.WIFI_ONLY:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_prefs_wifi_only).setTitleResource(R.string.stream_over_wifi_only).setPreferenceKey(Prefs.WIFI_ONLY).setValue(wifiOnly()).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    return ((Boolean) item.getValue()) ? resources.getString(R.string.enabled) : resources.getString(R.string.disabled);
                }
            }).build();
        case Prefs.SUBTITLE_COLOR:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_prefs_subtitle_color).setTitleResource(R.string.subtitle_color).setPreferenceKey(Prefs.SUBTITLE_COLOR).hasNext(true).setValue(getSubtitleColor()).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    return String.format("#%06X", 0xFFFFFF & (Integer) item.getValue());
                }
            }).build();
        case Prefs.SUBTITLE_SIZE:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_prefs_subtitle_size).setTitleResource(R.string.subtitle_size).setPreferenceKey(Prefs.SUBTITLE_SIZE).hasNext(true).setValue(getSubtitleSize()).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    return Integer.toString((Integer) item.getValue());
                }
            }).build();
        case Prefs.SUBTITLE_STROKE_COLOR:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_prefs_subtitle_stroke_color).setTitleResource(R.string.subtitle_stroke_color).setPreferenceKey(Prefs.SUBTITLE_STROKE_COLOR).hasNext(true).setValue(getSubtitleStrokeColor()).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    return String.format("#%06X", 0xFFFFFF & ((Integer) item.getValue()));
                }
            }).build();
        case Prefs.SUBTITLE_STROKE_WIDTH:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_prefs_subtitle_stroke_width).setTitleResource(R.string.subtitle_stroke_width).setPreferenceKey(Prefs.SUBTITLE_STROKE_WIDTH).hasNext(true).setValue(getSubtitleStrokeWidth()).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    return Integer.toString(((Integer) item.getValue()));
                }
            }).build();
        case Prefs.SUBTITLE_DEFAULT_LANGUAGE:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_prefs_subtitle_lang).setTitleResource(R.string.default_subtitle_language).setPreferenceKey(Prefs.SUBTITLE_DEFAULT_LANGUAGE).hasNext(true).setValue(getSubtitleDefaultLanguage()).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    String langCode = (String) item.getValue();
                    if (langCode == null) {
                        return resources.getString(R.string.no_default_set);
                    } else {
                        Locale locale = LocaleUtils.toLocale(langCode);
                        return locale.getDisplayName(locale);
                    }
                }
            }).build();
        case Prefs.LIBTORRENT_CONNECTION_LIMIT:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_prefs_connections).setTitleResource(R.string.max_connections).setPreferenceKey(Prefs.LIBTORRENT_CONNECTION_LIMIT).hasNext(true).setValue(getTorrentConnectionLimit()).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    return item.getValue() + " connections";
                }
            }).build();
        case Prefs.LIBTORRENT_DOWNLOAD_LIMIT:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_prefs_download_limit).setTitleResource(R.string.download_speed).setPreferenceKey(Prefs.LIBTORRENT_DOWNLOAD_LIMIT).hasNext(true).setValue(getTorrentDownloadLimit()).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    int limit = (int) item.getValue();
                    if (limit == 0) {
                        return resources.getString(R.string.unlimited);
                    } else {
                        return (limit / 1000) + " kB/s";
                    }
                }
            }).build();
        case Prefs.LIBTORRENT_UPLOAD_LIMIT:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_prefs_upload_limit).setTitleResource(R.string.upload_speed).setPreferenceKey(Prefs.LIBTORRENT_UPLOAD_LIMIT).hasNext(true).setValue(getTorrentUploadLimit()).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    int limit = (int) item.getValue();
                    if (limit == 0) {
                        return resources.getString(R.string.unlimited);
                    } else {
                        return (limit / 1000) + " kB/s";
                    }
                }
            }).build();
        case Prefs.STORAGE_LOCATION:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_prefs_storage_location).setTitleResource(R.string.storage_location).setPreferenceKey(Prefs.STORAGE_LOCATION).hasNext(true).setValue(getStorageLocation()).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    return ((String) item.getValue());
                }
            }).build();
        case Prefs.REMOVE_CACHE:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_prefs_remove_cache).setTitleResource(R.string.remove_cache).setPreferenceKey(Prefs.REMOVE_CACHE).setValue(removeCache()).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    return ((Boolean) item.getValue()) ? resources.getString(R.string.enabled) : resources.getString(R.string.disabled);
                }
            }).build();
        case Prefs.LIBTORRENT_AUTOMATIC_PORT:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_prefs_random).setTitleResource(R.string.automatic_port).setPreferenceKey(Prefs.LIBTORRENT_AUTOMATIC_PORT).hasNext(true).setValue(torrentAutomaticPort()).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    return ((Boolean) item.getValue()) ? resources.getString(R.string.enabled) : resources.getString(R.string.disabled);
                }
            }).build();
        case Prefs.LIBTORRENT_LISTENING_PORT:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_prefs_router).setTitleResource(R.string.listening_port).setPreferenceKey(Prefs.LIBTORRENT_LISTENING_PORT).hasNext(true).setClickable(!torrentAutomaticPort()).setValue(getTorrentListeningPort()).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    int port = (int) item.getValue();
                    if (port == -1 || torrentAutomaticPort()) {
                        return "Listening on random port";
                    } else {
                        return "Listening on port " + port;
                    }
                }
            }).build();
        case Prefs.HW_ACCELERATION:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_prefs_hw_accel).setTitleResource(R.string.hw_acceleration).setPreferenceKey(Prefs.HW_ACCELERATION).hasNext(true).setValue(getHwAcceleration()).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    int value = ((Integer) item.getValue());
                    switch(value) {
                        case VLCMediaOptions.HW_ACCELERATION_DECODING:
                            return resources.getString(R.string.hw_decoding);
                        case VLCMediaOptions.HW_ACCELERATION_DISABLED:
                            return resources.getString(R.string.disabled);
                        case VLCMediaOptions.HW_ACCELERATION_FULL:
                            return resources.getString(R.string.hw_full);
                        default:
                        case VLCMediaOptions.HW_ACCELERATION_AUTOMATIC:
                            return resources.getString(R.string.hw_automatic);
                    }
                }
            }).build();
        case Prefs.PIXEL_FORMAT:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_prefs_pixel_format).setTitleResource(R.string.pixel_format).setPreferenceKey(Prefs.PIXEL_FORMAT).hasNext(true).setValue(getPixelFormat()).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    String value = (String) item.getValue();
                    if ("YV12".equals(value)) {
                        return resources.getString(R.string.yuv);
                    } else if ("RV16".equals(value)) {
                        return resources.getString(R.string.rgb16);
                    } else {
                        return resources.getString(R.string.rgb32);
                    }
                }
            }).build();
        case Prefs.SHOW_VPN:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_nav_vpn).setTitleResource(R.string.show_vpn).setPreferenceKey(Prefs.SHOW_VPN).setValue(showVpn()).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    return ((Boolean) item.getValue()) ? resources.getString(R.string.enabled) : resources.getString(R.string.disabled);
                }
            }).build();
        case Prefs.AUTOMATIC_UPDATES:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_prefs_auto_update).setTitleResource(R.string.auto_updates).setPreferenceKey(Prefs.AUTOMATIC_UPDATES).setValue(automaticUpdates()).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    return ((Boolean) item.getValue()) ? resources.getString(R.string.enabled) : resources.getString(R.string.disabled);
                }
            }).build();
        case Prefs.CHECK_UPDATE:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_prefs_check_update).setTitleResource(R.string.check_for_updates).setPreferenceKey(Prefs.CHECK_UPDATE).setValue(prefManager.get(ButterUpdateManager.LAST_UPDATE_CHECK, 1L)).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    long timeStamp = (long) item.getValue();
                    Calendar cal = Calendar.getInstance(Locale.getDefault());
                    cal.setTimeInMillis(timeStamp);
                    String time = SimpleDateFormat.getTimeInstance(SimpleDateFormat.MEDIUM, Locale.getDefault()).format(timeStamp);
                    String date = DateFormat.format("dd-MM-yyy", cal).toString();
                    return resources.getString(R.string.last_check) + ": " + date + " " + time;
                }
            }).build();
        case Prefs.REPORT_BUG:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_prefs_report_bug).setTitleResource(R.string.report_a_bug).setPreferenceKey(Prefs.REPORT_BUG).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    return resources.getString(R.string.tap_to_open);
                }
            }).build();
        case Prefs.CHANGE_LOG:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_prefs_changelog).setTitleResource(R.string.changelog).setPreferenceKey(Prefs.CHANGE_LOG).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    return resources.getString(R.string.tap_to_open);
                }
            }).build();
        case Prefs.NOTICE:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_prefs_open_source).setTitleResource(R.string.open_source_licenses).setPreferenceKey(Prefs.NOTICE).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    return resources.getString(R.string.tap_to_open);
                }
            }).build();
        case Prefs.VERSION:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_prefs_version).setTitleResource(R.string.version).setPreferenceKey(Prefs.VERSION).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    try {
                        PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
                        return packageInfo.versionName + " - " + Build.CPU_ABI;
                    } catch (NameNotFoundException e) {
                        e.printStackTrace();
                    }
                    return "?.? (?) - ?";
                }
            }).build();
        case Prefs.ABOUT:
            return PrefItem.newBuilder().setIconResource(R.drawable.ic_prefs_about).setTitleResource(R.string.about_app).setPreferenceKey(Prefs.ABOUT).setSubtitleGenerator(new SubtitleGenerator() {

                @Override
                public String get(PrefItem item) {
                    return resources.getString(R.string.tap_to_open);
                }
            }).build();
        case Prefs.TITLE_GENERAL:
            return buildTitlePrefItem(R.string.general);
        case Prefs.TITLE_SUBTITLES:
            return buildTitlePrefItem(R.string.subtitles);
        case Prefs.TITLE_TORRENTS:
            return buildTitlePrefItem(R.string.torrents);
        case Prefs.TITLE_NETWORKING:
            return buildTitlePrefItem(R.string.networking);
        case Prefs.TITLE_ADVANCED:
            return buildTitlePrefItem(R.string.advanced);
        case Prefs.TITLE_UPDATES:
            return buildTitlePrefItem(R.string.updates);
        case Prefs.TITLE_ABOUT:
            return buildTitlePrefItem(R.string.about_app);
        default:
            throw new IllegalArgumentException("Unknown preference key:" + key);
    }
}
Also used : NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) Context(android.content.Context) SubtitleGenerator(butter.droid.base.content.preferences.PrefItem.SubtitleGenerator) SimpleDateFormat(java.text.SimpleDateFormat) StringRes(android.support.annotation.StringRes) HashMap(java.util.HashMap) NonNull(android.support.annotation.NonNull) PackageInfo(android.content.pm.PackageInfo) R(butter.droid.base.R) ArrayList(java.util.ArrayList) Format(butter.droid.provider.base.model.Format) Inject(javax.inject.Inject) Calendar(java.util.Calendar) ButterApplication(butter.droid.base.ButterApplication) PrefManager(butter.droid.base.manager.prefs.PrefManager) Locale(java.util.Locale) Map(java.util.Map) Build(android.os.Build) DEFAULT_PROVIDER(butter.droid.base.content.preferences.Prefs.DEFAULT_PROVIDER) LocaleUtils(butter.droid.base.utils.LocaleUtils) Reusable(dagger.Reusable) VLCMediaOptions(butter.droid.base.manager.internal.vlc.VLCMediaOptions) Color(android.graphics.Color) ColorInt(android.support.annotation.ColorInt) DateFormat(android.text.format.DateFormat) List(java.util.List) StorageUtils(butter.droid.base.utils.StorageUtils) Constants(butter.droid.base.Constants) Nullable(android.support.annotation.Nullable) ButterUpdateManager(butter.droid.base.manager.internal.updater.ButterUpdateManager) PrefKey(butter.droid.base.content.preferences.Prefs.PrefKey) Resources(android.content.res.Resources) Locale(java.util.Locale) SubtitleGenerator(butter.droid.base.content.preferences.PrefItem.SubtitleGenerator) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) PackageInfo(android.content.pm.PackageInfo) Calendar(java.util.Calendar) NonNull(android.support.annotation.NonNull)

Example 29 with Build

use of android.os.Build in project MaxLock by Maxr1998.

the class MaxLockPreferenceFragment method onPreferenceTreeClick.

@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
    if (preference.getKey() == null) {
        return false;
    }
    switch(screen) {
        case MAIN:
            switch(preference.getKey()) {
                case Common.ML_IMPLEMENTATION:
                    AlertDialog implementation = new AlertDialog.Builder(getContext()).setTitle(preference.getTitle()).setView(MLImplementation.createImplementationDialog(getContext())).setNegativeButton(android.R.string.ok, null).setOnDismissListener(dialog -> updateImplementationStatus()).create();
                    implementation.show();
                    return true;
                case Common.LOCKING_TYPE_SETTINGS:
                    launchFragment(this, Screen.TYPE.getScreen(), true);
                    return true;
                case Common.LOCKING_UI_SETTINGS:
                    launchFragment(this, Screen.UI.getScreen(), true);
                    return true;
                case Common.LOCKING_OPTIONS:
                    launchFragment(this, Screen.OPTIONS.getScreen(), true);
                    return true;
                case Common.IMOD_OPTIONS:
                    launchFragment(this, Screen.IMOD.getScreen(), true);
                    return true;
                case Common.CHOOSE_APPS:
                    launchFragment(this, new AppListFragment(), true);
                    return true;
                case Common.HIDE_APP_FROM_LAUNCHER:
                    TwoStatePreference hideApp = (TwoStatePreference) preference;
                    if (hideApp.isChecked()) {
                        Toast.makeText(getActivity(), R.string.reboot_required, Toast.LENGTH_SHORT).show();
                        ComponentName componentName = new ComponentName(getActivity(), "de.Maxr1998.xposed.maxlock.Main");
                        getActivity().getPackageManager().setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
                    } else {
                        ComponentName componentName = new ComponentName(getActivity(), "de.Maxr1998.xposed.maxlock.Main");
                        getActivity().getPackageManager().setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
                    }
                    return true;
                case Common.USE_DARK_STYLE:
                case Common.USE_AMOLED_BLACK:
                case Common.ENABLE_PRO:
                    getActivity().recreate();
                    return true;
                case Common.ABOUT:
                    launchFragment(this, Screen.ABOUT.getScreen(), true);
                    return true;
                case Common.DONATE:
                    startActivity(new Intent(getActivity(), DonateActivity.class));
                    return true;
                case Common.UNINSTALL:
                    if (!((SettingsActivity) getActivity()).isDeviceAdminActive()) {
                        Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
                        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, ((SettingsActivity) getActivity()).deviceAdmin);
                        startActivity(intent);
                    } else {
                        ((SettingsActivity) getActivity()).getDevicePolicyManager().removeActiveAdmin(((SettingsActivity) getActivity()).deviceAdmin);
                        preference.setTitle(R.string.pref_prevent_uninstall);
                        preference.setSummary(R.string.pref_prevent_uninstall_summary);
                        Intent uninstall = new Intent(Intent.ACTION_DELETE);
                        uninstall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        uninstall.setData(Uri.parse("package:de.Maxr1998.xposed.maxlock"));
                        startActivity(uninstall);
                    }
                    return true;
                case Common.SEND_FEEDBACK:
                    File tempDirectory = new File(getActivity().getCacheDir(), "feedback-cache");
                    try {
                        // Obtain data
                        FileUtils.copyDirectoryToDirectory(new File(Util.dataDir(getActivity()), "shared_prefs"), tempDirectory);
                        FileUtils.writeStringToFile(new File(tempDirectory, "device-info.txt"), "App Version: " + BuildConfig.VERSION_NAME + "\n\n" + "Device: " + Build.MANUFACTURER + " " + Build.MODEL + " (" + Build.PRODUCT + ")\n" + "API: " + SDK_INT + ", Fingerprint: " + Build.FINGERPRINT, Charset.forName("UTF-8"));
                        Process process = Runtime.getRuntime().exec("logcat -d");
                        FileUtils.copyInputStreamToFile(process.getInputStream(), new File(tempDirectory, "logcat.txt"));
                        try {
                            String xposedDir = SDK_INT >= Build.VERSION_CODES.N ? "/data/user_de/0/" + Common.XPOSED_PACKAGE_NAME : getActivity().getPackageManager().getApplicationInfo(Common.XPOSED_PACKAGE_NAME, 0).dataDir;
                            File xposedLog = new File(xposedDir + "/log", "error.log");
                            if (xposedLog.exists())
                                FileUtils.copyFileToDirectory(xposedLog, tempDirectory);
                        } catch (PackageManager.NameNotFoundException e) {
                            e.printStackTrace();
                        }
                        // Create zip
                        File zipFile = new File(getActivity().getCacheDir() + File.separator + "export", "report.zip");
                        zipFile.getParentFile().mkdir();
                        FileUtils.deleteQuietly(zipFile);
                        ZipOutputStream stream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
                        Util.writeDirectoryToZip(tempDirectory, stream);
                        stream.close();
                        FileUtils.deleteQuietly(tempDirectory);
                        Util.checkForStoragePermission(this, BUG_REPORT_STORAGE_PERMISSION_REQUEST_CODE, R.string.dialog_storage_permission_bug_report);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return true;
            }
            break;
        case TYPE:
            switch(preference.getKey()) {
                case Common.LOCKING_TYPE_PASSWORD:
                    Util.setPassword(getActivity(), null);
                    return true;
                case Common.LOCKING_TYPE_PIN:
                    LockSetupFragment lsp = new LockSetupFragment();
                    Bundle b1 = new Bundle(1);
                    b1.putString(Common.LOCKING_TYPE, Common.LOCKING_TYPE_PIN);
                    lsp.setArguments(b1);
                    launchFragment(this, lsp, false);
                    return true;
                case Common.LOCKING_TYPE_KNOCK_CODE:
                    LockSetupFragment lsk = new LockSetupFragment();
                    Bundle b2 = new Bundle(1);
                    b2.putString(Common.LOCKING_TYPE, Common.LOCKING_TYPE_KNOCK_CODE);
                    lsk.setArguments(b2);
                    launchFragment(this, lsk, false);
                    return true;
                case Common.LOCKING_TYPE_PATTERN:
                    Intent intent = new Intent(LockPatternActivity.ACTION_CREATE_PATTERN, null, getActivity(), LockPatternActivity.class);
                    startActivityForResult(intent, KUtil.getPatternCode(-1));
                    return true;
            }
            break;
        case OPTIONS:
            switch(preference.getKey()) {
                case Common.VIEW_LOGS:
                    launchFragment(this, new LogViewerFragment(), false);
                    return true;
            }
            break;
        case ABOUT:
            switch(preference.getKey()) {
                case Common.SHOW_CHANGELOG:
                    showChangelog();
                    return true;
                case Common.VISIT_WEBSITE:
                    CustomTabsIntent devWebsite = new CustomTabsIntent.Builder(((SettingsActivity) getActivity()).getSession()).setShowTitle(true).enableUrlBarHiding().setToolbarColor(Color.parseColor("#ffc107")).build();
                    devWebsite.launchUrl(getActivity(), Common.MAXR1998_URI);
                    return true;
                case Common.TECHNOSPARKS_PROFILE:
                    CustomTabsIntent technosparksSite = new CustomTabsIntent.Builder(((SettingsActivity) getActivity()).getSession()).setShowTitle(true).enableUrlBarHiding().setToolbarColor(Color.parseColor("#6d993f")).build();
                    technosparksSite.launchUrl(getActivity(), Common.TECHNO_SPARKS_URI);
                    return true;
            }
            break;
    }
    return super.onPreferenceTreeClick(preferenceScreen, preference);
}
Also used : AlertDialog(android.support.v7.app.AlertDialog) Bundle(android.os.Bundle) PackageManager(android.content.pm.PackageManager) BuildConfig(de.Maxr1998.xposed.maxlock.BuildConfig) Uri(android.net.Uri) CustomTabsIntent(android.support.customtabs.CustomTabsIntent) LockPatternActivity(com.haibison.android.lockpattern.LockPatternActivity) ColorDrawable(android.graphics.drawable.ColorDrawable) PreferenceScreen(android.preference.PreferenceScreen) SDK_INT(android.os.Build.VERSION.SDK_INT) VisibleForTesting(android.support.annotation.VisibleForTesting) Util(de.Maxr1998.xposed.maxlock.util.Util) PreferenceFragmentCompat(android.support.v4.preference.PreferenceFragmentCompat) CheckBox(android.widget.CheckBox) MLImplementation(de.Maxr1998.xposed.maxlock.MLImplementation) WebViewClient(android.webkit.WebViewClient) View(android.view.View) BUTTON_NEUTRAL(android.content.DialogInterface.BUTTON_NEUTRAL) WebView(android.webkit.WebView) PERMISSION_GRANTED(android.content.pm.PackageManager.PERMISSION_GRANTED) Fragment(android.support.v4.app.Fragment) ContextCompat(android.support.v4.content.ContextCompat) FileProvider.getUriForFile(android.support.v4.content.FileProvider.getUriForFile) PorterDuff(android.graphics.PorterDuff) ActivityCompat(android.support.v4.app.ActivityCompat) AppCompatActivity(android.support.v7.app.AppCompatActivity) IOUtils(org.apache.commons.io.IOUtils) ListPreference(android.preference.ListPreference) TextView(android.widget.TextView) ActivityNotFoundException(android.content.ActivityNotFoundException) Snackbar(android.support.design.widget.Snackbar) SettingsActivity(de.Maxr1998.xposed.maxlock.ui.SettingsActivity) ZipOutputStream(java.util.zip.ZipOutputStream) Context(android.content.Context) PreferenceCategory(android.preference.PreferenceCategory) Intent(android.content.Intent) CheckBoxPreference(android.preference.CheckBoxPreference) StringRes(android.support.annotation.StringRes) NonNull(android.support.annotation.NonNull) XmlRes(android.support.annotation.XmlRes) BufferedOutputStream(java.io.BufferedOutputStream) FingerprintManagerCompat(android.support.v4.hardware.fingerprint.FingerprintManagerCompat) SuppressLint(android.annotation.SuppressLint) KUtil(de.Maxr1998.xposed.maxlock.util.KUtil) Charset(java.nio.charset.Charset) DevicePolicyManager(android.app.admin.DevicePolicyManager) READ_EXTERNAL_STORAGE(android.Manifest.permission.READ_EXTERNAL_STORAGE) Toast(android.widget.Toast) Build(android.os.Build) AppListFragment(de.Maxr1998.xposed.maxlock.ui.settings.applist.AppListFragment) DialogInterface(android.content.DialogInterface) BUTTON_POSITIVE(android.content.DialogInterface.BUTTON_POSITIVE) ImplementationPreference(de.Maxr1998.xposed.maxlock.preference.ImplementationPreference) MLPreferences(de.Maxr1998.xposed.maxlock.util.MLPreferences) ComponentName(android.content.ComponentName) LayoutInflater(android.view.LayoutInflater) FileOutputStream(java.io.FileOutputStream) FileUtils(org.apache.commons.io.FileUtils) IOException(java.io.IOException) Common(de.Maxr1998.xposed.maxlock.Common) File(java.io.File) R(de.Maxr1998.xposed.maxlock.R) Color(android.graphics.Color) TimeUnit(java.util.concurrent.TimeUnit) FragmentManager(android.support.v4.app.FragmentManager) AlertDialog(android.support.v7.app.AlertDialog) SharedPreferences(android.content.SharedPreferences) TwoStatePreference(android.preference.TwoStatePreference) Preference(android.preference.Preference) Activity(android.app.Activity) FragmentTransaction(android.support.v4.app.FragmentTransaction) InputStream(java.io.InputStream) TwoStatePreference(android.preference.TwoStatePreference) Bundle(android.os.Bundle) CustomTabsIntent(android.support.customtabs.CustomTabsIntent) Intent(android.content.Intent) IOException(java.io.IOException) CustomTabsIntent(android.support.customtabs.CustomTabsIntent) PackageManager(android.content.pm.PackageManager) ZipOutputStream(java.util.zip.ZipOutputStream) AppListFragment(de.Maxr1998.xposed.maxlock.ui.settings.applist.AppListFragment) FileOutputStream(java.io.FileOutputStream) ComponentName(android.content.ComponentName) FileProvider.getUriForFile(android.support.v4.content.FileProvider.getUriForFile) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream)

Example 30 with Build

use of android.os.Build in project mobile-center-sdk-android by Microsoft.

the class DeviceInfoHelperTest method deviceInfo.

@Test
public void deviceInfo() throws PackageManager.NameNotFoundException, DeviceInfoHelper.DeviceInfoException {
    /* Mock system calls. */
    // noinspection WrongConstant
    when(mContext.getSystemService(eq(Context.DISPLAY_SERVICE))).thenReturn(mDisplayManager);
    when(mDisplayManager.getDisplay(anyInt())).thenReturn(mDisplay);
    // noinspection WrongConstant
    when(mContext.getResources()).thenReturn(mResources);
    // noinspection WrongConstant
    when(mResources.getDisplayMetrics()).thenReturn(mDisplayMetrics);
    mDisplayMetrics.widthPixels = SCREEN_WIDTH;
    mDisplayMetrics.heightPixels = SCREEN_HEIGHT;
    /* Mock data. */
    final Integer osApiLevel = 21;
    final String appVersion = "1.0";
    final String appBuild = "1";
    final String appNamespace = "com.contoso.app";
    final String carrierCountry = "us";
    final String carrierName = "mock-service";
    final Locale locale = Locale.KOREA;
    final String model = "mock-model";
    final String oemName = "mock-manufacture";
    final String osName = "Android";
    final String osVersion = "mock-version";
    final String osBuild = "mock-os-build";
    final String screenSizeLandscape = "100x200";
    final String screenSizePortrait = "200x100";
    final TimeZone timeZone = TimeZone.getTimeZone("KST");
    final Integer timeZoneOffset = timeZone.getOffset(System.currentTimeMillis());
    Locale.setDefault(locale);
    TimeZone.setDefault(timeZone);
    /* Delegates to mock instances. */
    when(mContext.getPackageName()).thenReturn(appNamespace);
    // noinspection WrongConstant
    when(mContext.getSystemService(eq(Context.TELEPHONY_SERVICE))).thenReturn(mTelephonyManager);
    // noinspection WrongConstant
    when(mPackageManager.getPackageInfo(anyString(), eq(0))).thenReturn(mPackageInfo);
    when(mTelephonyManager.getNetworkCountryIso()).thenReturn(carrierCountry);
    when(mTelephonyManager.getNetworkOperatorName()).thenReturn(carrierName);
    when(mDisplay.getRotation()).thenReturn(Surface.ROTATION_0, Surface.ROTATION_90, Surface.ROTATION_180, Surface.ROTATION_270);
    /* Sets values of fields for static classes. */
    Whitebox.setInternalState(mPackageInfo, "versionName", appVersion);
    Whitebox.setInternalState(mPackageInfo, "versionCode", Integer.parseInt(appBuild));
    Whitebox.setInternalState(Build.class, "MODEL", model);
    Whitebox.setInternalState(Build.class, "MANUFACTURER", oemName);
    Whitebox.setInternalState(Build.VERSION.class, "SDK_INT", osApiLevel);
    Whitebox.setInternalState(Build.class, "ID", osBuild);
    Whitebox.setInternalState(Build.VERSION.class, "RELEASE", osVersion);
    /* First call */
    Device device = DeviceInfoHelper.getDeviceInfo(mContext);
    /* Verify device information. */
    assertNull(device.getWrapperSdkName());
    assertNull(device.getWrapperSdkVersion());
    assertEquals(BuildConfig.VERSION_NAME, device.getSdkVersion());
    assertEquals(appVersion, device.getAppVersion());
    assertEquals(appBuild, device.getAppBuild());
    assertEquals(appNamespace, device.getAppNamespace());
    assertEquals(carrierCountry, device.getCarrierCountry());
    assertEquals(carrierName, device.getCarrierName());
    assertEquals(locale.toString(), device.getLocale());
    assertEquals(model, device.getModel());
    assertEquals(oemName, device.getOemName());
    assertEquals(osApiLevel, device.getOsApiLevel());
    assertEquals(osName, device.getOsName());
    assertEquals(osVersion, device.getOsVersion());
    assertEquals(osBuild, device.getOsBuild());
    assertEquals(screenSizeLandscape, device.getScreenSize());
    assertEquals(timeZoneOffset, device.getTimeZoneOffset());
    /* Verify screen size based on different orientations (Surface.ROTATION_90). */
    device = DeviceInfoHelper.getDeviceInfo(mContext);
    assertEquals(screenSizePortrait, device.getScreenSize());
    /* Verify screen size based on different orientations (Surface.ROTATION_180). */
    device = DeviceInfoHelper.getDeviceInfo(mContext);
    assertEquals(screenSizeLandscape, device.getScreenSize());
    /* Verify screen size based on different orientations (Surface.ROTATION_270). */
    device = DeviceInfoHelper.getDeviceInfo(mContext);
    assertEquals(screenSizePortrait, device.getScreenSize());
    /* Make sure screen size is verified for all orientations. */
    verify(mDisplay, times(4)).getRotation();
    /* Set wrapper sdk information. */
    WrapperSdk wrapperSdk = new WrapperSdk();
    wrapperSdk.setWrapperSdkVersion("1.2.3.4");
    wrapperSdk.setWrapperSdkName("ReactNative");
    wrapperSdk.setWrapperRuntimeVersion("4.13");
    wrapperSdk.setLiveUpdateReleaseLabel("2.0.3-beta2");
    wrapperSdk.setLiveUpdateDeploymentKey("staging");
    wrapperSdk.setLiveUpdatePackageHash("aa896f791b26a7f464c0f62b0ba69f2b");
    DeviceInfoHelper.setWrapperSdk(wrapperSdk);
    Device device2 = DeviceInfoHelper.getDeviceInfo(mContext);
    assertEquals(wrapperSdk.getWrapperSdkVersion(), device2.getWrapperSdkVersion());
    assertEquals(wrapperSdk.getWrapperSdkName(), device2.getWrapperSdkName());
    assertEquals(wrapperSdk.getWrapperRuntimeVersion(), device2.getWrapperRuntimeVersion());
    assertEquals(wrapperSdk.getLiveUpdateReleaseLabel(), device2.getLiveUpdateReleaseLabel());
    assertEquals(wrapperSdk.getLiveUpdateDeploymentKey(), device2.getLiveUpdateDeploymentKey());
    assertEquals(wrapperSdk.getLiveUpdatePackageHash(), device2.getLiveUpdatePackageHash());
    /* Check non wrapped sdk information are still generated correctly. */
    device2.setWrapperSdkVersion(null);
    device2.setWrapperSdkName(null);
    device2.setWrapperRuntimeVersion(null);
    device2.setLiveUpdateReleaseLabel(null);
    device2.setLiveUpdateDeploymentKey(null);
    device2.setLiveUpdatePackageHash(null);
    assertEquals(device, device2);
    /* Remove wrapper SDK information. */
    DeviceInfoHelper.setWrapperSdk(null);
    assertEquals(device, DeviceInfoHelper.getDeviceInfo(mContext));
    /* Verify the right API was called to get a screen size. */
    verify(mContext, atLeastOnce()).getSystemService(eq(Context.DISPLAY_SERVICE));
    verify(mContext, atLeastOnce()).getResources();
    verify(mResources, atLeastOnce()).getDisplayMetrics();
    // noinspection deprecation
    verify(mDisplay, never()).getSize(any(Point.class));
    verify(mContext, never()).getSystemService(eq(Context.WINDOW_SERVICE));
}
Also used : Locale(java.util.Locale) TimeZone(java.util.TimeZone) Build(android.os.Build) Device(com.microsoft.appcenter.ingestion.models.Device) WrapperSdk(com.microsoft.appcenter.ingestion.models.WrapperSdk) Mockito.anyString(org.mockito.Mockito.anyString) Point(android.graphics.Point) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

Build (android.os.Build)42 Context (android.content.Context)30 Intent (android.content.Intent)22 List (java.util.List)22 PackageManager (android.content.pm.PackageManager)20 ArrayList (java.util.ArrayList)19 View (android.view.View)16 Toast (android.widget.Toast)15 File (java.io.File)15 Bundle (android.os.Bundle)14 Uri (android.net.Uri)13 TextView (android.widget.TextView)13 Locale (java.util.Locale)13 Manifest (android.Manifest)11 SharedPreferences (android.content.SharedPreferences)11 NonNull (android.support.annotation.NonNull)11 Activity (android.app.Activity)10 DialogInterface (android.content.DialogInterface)10 EditText (android.widget.EditText)10 Arrays (java.util.Arrays)10