Search in sources :

Example 26 with Utilities.getPrefs

use of com.android.launcher3.Utilities.getPrefs in project android_packages_apps_Launcher3 by crdroidandroid.

the class InvariantDeviceProfile method initGrid.

private void initGrid(Context context, Info displayInfo, DisplayOption displayOption, boolean isSplitDisplay) {
    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    GridOption closestProfile = displayOption.grid;
    numRows = closestProfile.numRows;
    numColumns = closestProfile.numColumns;
    dbFile = closestProfile.dbFile;
    defaultLayoutId = closestProfile.defaultLayoutId;
    demoModeLayoutId = closestProfile.demoModeLayoutId;
    numFolderRows = closestProfile.numFolderRows;
    numFolderColumns = closestProfile.numFolderColumns;
    isScalable = closestProfile.isScalable;
    devicePaddingId = closestProfile.devicePaddingId;
    mExtraAttrs = closestProfile.extraAttrs;
    float iconSizeModifier = (float) Utilities.getPrefs(context).getInt(KEY_ICON_SIZE, 100) / 100F;
    float fontSizeModifier = (float) Utilities.getPrefs(context).getInt(KEY_FONT_SIZE, 100) / 100F;
    iconSize = displayOption.iconSize * iconSizeModifier;
    landscapeIconSize = displayOption.landscapeIconSize * iconSizeModifier;
    iconBitmapSize = ResourceUtils.pxFromDp(iconSize, metrics);
    iconTextSize = displayOption.iconTextSize * fontSizeModifier;
    landscapeIconTextSize = displayOption.landscapeIconTextSize * fontSizeModifier;
    fillResIconDpi = getLauncherIconDensity(iconBitmapSize);
    minCellHeight = displayOption.minCellHeight;
    minCellWidth = displayOption.minCellWidth;
    borderSpacing = displayOption.borderSpacing;
    numShownHotseatIcons = closestProfile.numHotseatIcons;
    numDatabaseHotseatIcons = isSplitDisplay ? closestProfile.numDatabaseHotseatIcons : closestProfile.numHotseatIcons;
    numAllAppsColumns = closestProfile.numAllAppsColumns;
    numDatabaseAllAppsColumns = isSplitDisplay ? closestProfile.numDatabaseAllAppsColumns : closestProfile.numAllAppsColumns;
    if (Utilities.isGridOptionsEnabled(context)) {
        allAppsIconSize = displayOption.allAppsIconSize * iconSizeModifier;
        allAppsIconTextSize = displayOption.allAppsIconTextSize * fontSizeModifier;
    } else {
        allAppsIconSize = iconSize;
        allAppsIconTextSize = iconTextSize;
    }
    if (devicePaddingId != 0) {
        devicePaddings = new DevicePaddings(context, devicePaddingId);
    }
    // If the partner customization apk contains any grid overrides, apply them
    // Supported overrides: numRows, numColumns, iconSize
    applyPartnerDeviceProfileOverrides(context, metrics);
    final List<DeviceProfile> localSupportedProfiles = new ArrayList<>();
    defaultWallpaperSize = new Point(displayInfo.currentSize);
    for (WindowBounds bounds : displayInfo.supportedBounds) {
        localSupportedProfiles.add(new DeviceProfile.Builder(context, this, displayInfo).setUseTwoPanels(isSplitDisplay).setWindowBounds(bounds).build());
        // Wallpaper size should be the maximum of the all possible sizes Launcher expects
        int displayWidth = bounds.bounds.width();
        int displayHeight = bounds.bounds.height();
        defaultWallpaperSize.y = Math.max(defaultWallpaperSize.y, displayHeight);
        // We need to ensure that there is enough extra space in the wallpaper
        // for the intended parallax effects
        float parallaxFactor = dpiFromPx(Math.min(displayWidth, displayHeight), displayInfo.densityDpi) < 720 ? 2 : wallpaperTravelToScreenWidthRatio(displayWidth, displayHeight);
        defaultWallpaperSize.x = Math.max(defaultWallpaperSize.x, Math.round(parallaxFactor * displayWidth));
    }
    supportedProfiles = Collections.unmodifiableList(localSupportedProfiles);
    ComponentName cn = new ComponentName(context.getPackageName(), getClass().getName());
    defaultWidgetPadding = AppWidgetHostView.getDefaultPaddingForWidget(context, cn, null);
}
Also used : WindowBounds(com.android.launcher3.util.WindowBounds) ArrayList(java.util.ArrayList) ComponentName(android.content.ComponentName) Point(android.graphics.Point) DisplayMetrics(android.util.DisplayMetrics) Point(android.graphics.Point)

Example 27 with Utilities.getPrefs

use of com.android.launcher3.Utilities.getPrefs in project android_packages_apps_Launcher3 by crdroidandroid.

the class Launcher method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    Object traceToken = TraceHelper.INSTANCE.beginSection(ON_CREATE_EVT, TraceHelper.FLAG_UI_EVENT);
    if (DEBUG_STRICT_MODE) {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
    }
    if (Utilities.IS_DEBUG_DEVICE && FeatureFlags.NOTIFY_CRASHES.get()) {
        final String notificationChannelId = "com.android.launcher3.Debug";
        final String notificationChannelName = "Debug";
        final String notificationTag = "Debug";
        final int notificationId = 0;
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(new NotificationChannel(notificationChannelId, notificationChannelName, NotificationManager.IMPORTANCE_HIGH));
        Thread.currentThread().setUncaughtExceptionHandler((thread, throwable) -> {
            String stackTrace = Log.getStackTraceString(throwable);
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("text/plain");
            shareIntent.putExtra(Intent.EXTRA_TEXT, stackTrace);
            shareIntent = Intent.createChooser(shareIntent, null);
            PendingIntent sharePendingIntent = PendingIntent.getActivity(this, 0, shareIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            Notification notification = new Notification.Builder(this, notificationChannelId).setSmallIcon(android.R.drawable.ic_menu_close_clear_cancel).setContentTitle("Launcher crash detected!").setStyle(new Notification.BigTextStyle().bigText(stackTrace)).addAction(android.R.drawable.ic_menu_share, "Share", sharePendingIntent).build();
            notificationManager.notify(notificationTag, notificationId, notification);
            Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
            if (defaultUncaughtExceptionHandler != null) {
                defaultUncaughtExceptionHandler.uncaughtException(thread, throwable);
            }
        });
    }
    super.onCreate(savedInstanceState);
    LauncherAppState app = LauncherAppState.getInstance(this);
    mOldConfig = new Configuration(getResources().getConfiguration());
    mModel = app.getModel();
    mRotationHelper = new RotationHelper(this);
    InvariantDeviceProfile idp = app.getInvariantDeviceProfile();
    initDeviceProfile(idp);
    idp.addOnChangeListener(this);
    mSharedPrefs = Utilities.getPrefs(this);
    mIconCache = app.getIconCache();
    mAccessibilityDelegate = createAccessibilityDelegate();
    mDragController = new LauncherDragController(this);
    mAllAppsController = new AllAppsTransitionController(this);
    mStateManager = new StateManager<>(this, NORMAL);
    mOnboardingPrefs = createOnboardingPrefs(mSharedPrefs);
    mAppWidgetManager = new WidgetManagerHelper(this);
    mAppWidgetHost = createAppWidgetHost();
    mAppWidgetHost.startListening();
    inflateRootView(R.layout.launcher);
    setupViews();
    crossFadeWithPreviousAppearance();
    mPopupDataProvider = new PopupDataProvider(this::updateNotificationDots);
    boolean internalStateHandled = ACTIVITY_TRACKER.handleCreate(this);
    if (internalStateHandled) {
        if (savedInstanceState != null) {
            // InternalStateHandler has already set the appropriate state.
            // We dont need to do anything.
            savedInstanceState.remove(RUNTIME_STATE);
        }
    }
    restoreState(savedInstanceState);
    mStateManager.reapplyState();
    // We only load the page synchronously if the user rotates (or triggers a
    // configuration change) while launcher is in the foreground
    int currentScreen = PagedView.INVALID_PAGE;
    if (savedInstanceState != null) {
        currentScreen = savedInstanceState.getInt(RUNTIME_STATE_CURRENT_SCREEN, currentScreen);
    }
    mPageToBindSynchronously = currentScreen;
    if (!mModel.addCallbacksAndLoad(this)) {
        if (!internalStateHandled) {
            // If we are not binding synchronously, show a fade in animation when
            // the first page bind completes.
            mDragLayer.getAlphaProperty(ALPHA_INDEX_LAUNCHER_LOAD).setValue(0);
        }
    }
    // For handling default keys
    setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
    setContentView(getRootView());
    getRootView().dispatchInsets();
    // Listen for broadcasts
    registerReceiver(mScreenOffReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));
    getSystemUiController().updateUiState(SystemUiController.UI_STATE_BASE_WINDOW, Themes.getAttrBoolean(this, R.attr.isWorkspaceDarkText));
    if (mLauncherCallbacks != null) {
        mLauncherCallbacks.onCreate(savedInstanceState);
    }
    mOverlayManager = getDefaultOverlay();
    PluginManagerWrapper.INSTANCE.get(this).addPluginListener(this, OverlayPlugin.class, false);
    mRotationHelper.initialize();
    TraceHelper.INSTANCE.endSection(traceToken);
    mUserChangedCallbackCloseable = UserCache.INSTANCE.get(this).addUserChangeListener(() -> getStateManager().goToState(NORMAL));
    if (Utilities.ATLEAST_R) {
        getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
    }
}
Also used : Configuration(android.content.res.Configuration) PropertyListBuilder(com.android.launcher3.anim.PropertyListBuilder) Notification(android.app.Notification) StrictMode(android.os.StrictMode) AllAppsTransitionController(com.android.launcher3.allapps.AllAppsTransitionController) WidgetManagerHelper(com.android.launcher3.widget.WidgetManagerHelper) IntentFilter(android.content.IntentFilter) NotificationManager(android.app.NotificationManager) RotationHelper(com.android.launcher3.states.RotationHelper) PopupDataProvider(com.android.launcher3.popup.PopupDataProvider) PendingIntent(android.app.PendingIntent) Intent(android.content.Intent) NotificationChannel(android.app.NotificationChannel) DragObject(com.android.launcher3.DropTarget.DragObject) LauncherDragController(com.android.launcher3.dragndrop.LauncherDragController) PendingIntent(android.app.PendingIntent)

Example 28 with Utilities.getPrefs

use of com.android.launcher3.Utilities.getPrefs in project android_packages_apps_Launcher3 by crdroidandroid.

the class LauncherProvider method loadDefaultFavoritesIfNecessary.

/**
 * Loads the default workspace based on the following priority scheme:
 *   1) From the app restrictions
 *   2) From a package provided by play store
 *   3) From a partner configuration APK, already in the system image
 *   4) The default configuration for the particular device
 */
private synchronized void loadDefaultFavoritesIfNecessary() {
    SharedPreferences sp = Utilities.getPrefs(getContext());
    if (sp.getBoolean(mOpenHelper.getKey(EMPTY_DATABASE_CREATED), false)) {
        Log.d(TAG, "loading default workspace");
        AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
        AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
        if (loader == null) {
            loader = AutoInstallsLayout.get(getContext(), widgetHost, mOpenHelper);
        }
        if (loader == null) {
            final Partner partner = Partner.get(getContext().getPackageManager());
            if (partner != null && partner.hasDefaultLayout()) {
                final Resources partnerRes = partner.getResources();
                int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT, "xml", partner.getPackageName());
                if (workspaceResId != 0) {
                    loader = new DefaultLayoutParser(getContext(), widgetHost, mOpenHelper, partnerRes, workspaceResId);
                }
            }
        }
        final boolean usingExternallyProvidedLayout = loader != null;
        if (loader == null) {
            loader = getDefaultLayoutParser(widgetHost);
        }
        // There might be some partially restored DB items, due to buggy restore logic in
        // previous versions of launcher.
        mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
        // Populate favorites table with initial favorites
        if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0) && usingExternallyProvidedLayout) {
            // Unable to load external layout. Cleanup and load the internal layout.
            mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
            mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), getDefaultLayoutParser(widgetHost));
        }
        clearFlagEmptyDbCreated();
    }
}
Also used : SharedPreferences(android.content.SharedPreferences) AppWidgetHost(android.appwidget.AppWidgetHost) LauncherAppWidgetHost(com.android.launcher3.widget.LauncherAppWidgetHost) Resources(android.content.res.Resources)

Example 29 with Utilities.getPrefs

use of com.android.launcher3.Utilities.getPrefs in project Neo-Launcher by NeoApplications.

the class HomeWidgetMigrationTask method migrateWorkspace.

@Override
protected boolean migrateWorkspace() throws Exception {
    IntArray allScreens = getWorkspaceScreenIds(mDb);
    if (allScreens.isEmpty()) {
        throw new Exception("Unable to get workspace screens");
    }
    boolean allowOverlap = Utilities.getPrefs(mContext).getBoolean(ALLOW_OVERLAP_PREF, false);
    GridOccupancy occupied = new GridOccupancy(mTrgX, mTrgY);
    if (!allowOverlap) {
        ArrayList<DbEntry> firstScreenItems = new ArrayList<>();
        for (int i = 0; i < allScreens.size(); i++) {
            int screenId = allScreens.get(i);
            ArrayList<DbEntry> items = loadWorkspaceEntries(screenId);
            if (screenId == Workspace.FIRST_SCREEN_ID) {
                firstScreenItems.addAll(items);
                break;
            }
        }
        for (DbEntry item : firstScreenItems) {
            occupied.markCells(item, true);
        }
    }
    if (allowOverlap || occupied.isRegionVacant(0, 0, mTrgX, 1)) {
        List<LauncherAppWidgetProviderInfo> customWidgets = CustomWidgetParser.getCustomWidgets(mContext);
        if (!customWidgets.isEmpty()) {
            LauncherAppWidgetProviderInfo provider = customWidgets.get(0);
            int widgetId = CustomWidgetParser.getWidgetIdForCustomProvider(mContext, provider.provider);
            long itemId = Settings.call(mContext.getContentResolver(), Settings.METHOD_NEW_ITEM_ID).getLong(Settings.EXTRA_VALUE);
            ContentValues values = new ContentValues();
            values.put(Favorites._ID, itemId);
            values.put(Favorites.CONTAINER, Favorites.CONTAINER_DESKTOP);
            values.put(Favorites.SCREEN, Workspace.FIRST_SCREEN_ID);
            values.put(Favorites.CELLX, 0);
            values.put(Favorites.CELLY, 0);
            values.put(Favorites.SPANX, mTrgX);
            values.put(Favorites.SPANY, 1);
            values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_CUSTOM_APPWIDGET);
            values.put(Favorites.APPWIDGET_ID, widgetId);
            values.put(Favorites.APPWIDGET_PROVIDER, provider.provider.flattenToString());
            mDb.insert(Favorites.TABLE_NAME, null, values);
        }
    }
    return true;
}
Also used : LauncherAppWidgetProviderInfo(com.android.launcher3.LauncherAppWidgetProviderInfo) ContentValues(android.content.ContentValues) IntArray(com.android.launcher3.util.IntArray) ArrayList(java.util.ArrayList) GridOccupancy(com.android.launcher3.util.GridOccupancy) Point(android.graphics.Point) SuppressLint(android.annotation.SuppressLint)

Example 30 with Utilities.getPrefs

use of com.android.launcher3.Utilities.getPrefs in project Neo-Launcher by NeoApplications.

the class HomeWidgetMigrationTask method migrateIfNeeded.

@SuppressLint("ApplySharedPref")
public static void migrateIfNeeded(Context context) {
    SharedPreferences prefs = Utilities.getPrefs(context);
    boolean needsMigration = !prefs.getBoolean(PREF_MIGRATION_STATUS, false) && prefs.getBoolean(SMARTSPACE_PREF, false);
    if (!needsMigration)
        return;
    // Save the pref so we only run migration once
    prefs.edit().putBoolean(PREF_MIGRATION_STATUS, true).commit();
    HashSet<String> validPackages = getValidPackages(context);
    InvariantDeviceProfile idp = LauncherAppState.getIDP(context);
    Point size = new Point(idp.numColumns, idp.numRows);
    long migrationStartTime = System.currentTimeMillis();
    try (SQLiteTransaction transaction = (SQLiteTransaction) Settings.call(context.getContentResolver(), Settings.METHOD_NEW_TRANSACTION).getBinder(Settings.EXTRA_VALUE)) {
        if (!new HomeWidgetMigrationTask(context, transaction.getDb(), validPackages, size).migrateWorkspace()) {
            throw new RuntimeException("Failed to migrate Smartspace");
        }
    } catch (Exception e) {
        Log.e(TAG, "Error during grid migration", e);
    } finally {
        Log.v(TAG, "Home widget migration completed in " + (System.currentTimeMillis() - migrationStartTime));
    }
}
Also used : SharedPreferences(android.content.SharedPreferences) InvariantDeviceProfile(com.android.launcher3.InvariantDeviceProfile) SQLiteTransaction(com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction) Point(android.graphics.Point) SuppressLint(android.annotation.SuppressLint)

Aggregations

SharedPreferences (android.content.SharedPreferences)23 Point (android.graphics.Point)15 Utilities.getPointString (com.android.launcher3.Utilities.getPointString)11 SQLiteTransaction (com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction)10 Intent (android.content.Intent)8 Configuration (android.content.res.Configuration)8 TargetApi (android.annotation.TargetApi)7 IntentFilter (android.content.IntentFilter)7 StrictMode (android.os.StrictMode)7 DragObject (com.android.launcher3.DropTarget.DragObject)7 AllAppsTransitionController (com.android.launcher3.allapps.AllAppsTransitionController)7 PropertyListBuilder (com.android.launcher3.anim.PropertyListBuilder)7 PopupDataProvider (com.android.launcher3.popup.PopupDataProvider)7 RotationHelper (com.android.launcher3.states.RotationHelper)7 ArrayList (java.util.ArrayList)7 Resources (android.content.res.Resources)6 Notification (android.app.Notification)5 AppWidgetHost (android.appwidget.AppWidgetHost)5 LauncherAppWidgetHost (com.android.launcher3.widget.LauncherAppWidgetHost)5 WidgetManagerHelper (com.android.launcher3.widget.WidgetManagerHelper)5