Java Code Examples for org.chromium.base.ContextUtils#getAppSharedPreferences()

The following examples show how to use org.chromium.base.ContextUtils#getAppSharedPreferences() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PrefServiceBridge.java    From delion with Apache License 2.0 6 votes vote down vote up
/**
 * Add a permission entry for Location for the default search engine.
 * @param allowed Whether to create an Allowed permission or a Denied permission.
 * @param context The current context to use.
 */
public static void maybeCreatePermissionForDefaultSearchEngine(
        boolean allowed, Context context) {
    TemplateUrlService templateUrlService = TemplateUrlService.getInstance();
    String url = templateUrlService.getSearchEngineUrlFromTemplateUrl(
            templateUrlService.getDefaultSearchEngineIndex());
    if (allowed && !url.startsWith("https:")) return;
    GeolocationInfo locationSettings = new GeolocationInfo(url, null, false);
    ContentSetting locationPermission = locationSettings.getContentSetting();
    if (locationPermission == null || locationPermission == ContentSetting.ASK) {
        WebsitePreferenceBridge.nativeSetGeolocationSettingForOrigin(url, url,
                allowed ? ContentSetting.ALLOW.toInt() : ContentSetting.BLOCK.toInt(), false);
        SharedPreferences sharedPreferences =
                ContextUtils.getAppSharedPreferences();
        sharedPreferences.edit().putBoolean(LOCATION_AUTO_ALLOWED, true).apply();
    }
}
 
Example 2
Source File: ChromeBrowserInitializer.java    From delion with Apache License 2.0 6 votes vote down vote up
/**
 * Pre-load shared prefs to avoid being blocked on the disk access async task in the future.
 * Running in an AsyncTask as pre-loading itself may cause I/O.
 */
private void warmUpSharedPrefs() {
    if (Build.VERSION.CODENAME.equals("N") || Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                ContextUtils.getAppSharedPreferences();
                DocumentTabModelImpl.warmUpSharedPrefs(mApplication);
                ActivityAssigner.warmUpSharedPrefs(mApplication);
                return null;
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    } else {
        ContextUtils.getAppSharedPreferences();
        DocumentTabModelImpl.warmUpSharedPrefs(mApplication);
        ActivityAssigner.warmUpSharedPrefs(mApplication);
    }
}
 
Example 3
Source File: LocaleManager.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
/**
 * Switches the default search engine based on the current locale, if the user has delegated
 * Chrome to do so. This method also adds some special engines to user's search engine list, as
 * long as the user is in this locale.
 */
protected void maybeAutoSwitchSearchEngine() {
    SharedPreferences preferences = ContextUtils.getAppSharedPreferences();
    boolean wasInSpecialLocale = preferences.getBoolean(PREF_WAS_IN_SPECIAL_LOCALE, false);
    boolean isInSpecialLocale = isSpecialLocaleEnabled();
    if (wasInSpecialLocale && !isInSpecialLocale) {
        revertDefaultSearchEngineOverride();
        removeSpecialSearchEngines();
    } else if (isInSpecialLocale && !wasInSpecialLocale) {
        addSpecialSearchEngines();
        overrideDefaultSearchEngine();
    } else if (isInSpecialLocale) {
        // As long as the user is in the special locale, special engines should be in the list.
        addSpecialSearchEngines();
    }
    preferences.edit().putBoolean(PREF_WAS_IN_SPECIAL_LOCALE, isInSpecialLocale).apply();
}
 
Example 4
Source File: DownloadManagerService.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
protected DownloadManagerService(Context context,
        DownloadNotifier downloadNotifier,
        Handler handler,
        long updateDelayInMillis) {
    mContext = context;
    mSharedPrefs = ContextUtils.getAppSharedPreferences();
    mDownloadNotifier = downloadNotifier;
    mUpdateDelayInMillis = updateDelayInMillis;
    mHandler = handler;
    mOMADownloadHandler = new OMADownloadHandler(context);
    mDownloadSnackbarController = new DownloadSnackbarController(context);
    mDownloadManagerDelegate = new DownloadManagerDelegate(mContext);
    // Note that this technically leaks the native object, however, DownloadManagerService
    // is a singleton that lives forever and there's no clean shutdown of Chrome on Android.
    init();
    clearPendingOMADownloads();
}
 
Example 5
Source File: DownloadNotificationService.java    From delion with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate() {
    mContext = getApplicationContext();
    mNotificationManager = (NotificationManager) mContext.getSystemService(
            Context.NOTIFICATION_SERVICE);
    mSharedPrefs = ContextUtils.getAppSharedPreferences();
    parseDownloadSharedPrefs();
    // Because this service is a started service and returns START_STICKY in
    // onStartCommand(), it will be restarted as soon as resources are available
    // after it is killed. As a result, onCreate() may be called after Chrome
    // gets killed and before user restarts chrome. In that case,
    // DownloadManagerService.hasDownloadManagerService() will return false as
    // there are no calls to initialize DownloadManagerService. Pause all the
    // download notifications as download will not progress without chrome.
    if (!DownloadManagerService.hasDownloadManagerService()) {
        onBrowserKilled();
    }
    mNextNotificationId = mSharedPrefs.getInt(
            NEXT_DOWNLOAD_NOTIFICATION_ID, STARTING_NOTIFICATION_ID);

}
 
Example 6
Source File: PrecacheUMA.java    From delion with Apache License 2.0 6 votes vote down vote up
/**
 * Record the precache event. The event is persisted in shared preferences if the native library
 * is not loaded. If library is loaded, the event will be recorded as UMA metric, and any prior
 * persisted events are recorded to UMA as well.
 * @param event the precache event.
 */
public static void record(int event) {
    SharedPreferences sharedPreferences = ContextUtils.getAppSharedPreferences();
    long persistent_metric = sharedPreferences.getLong(PREF_PERSISTENCE_METRICS, 0);
    Editor preferencesEditor = sharedPreferences.edit();

    if (LibraryLoader.isInitialized()) {
        RecordHistogram.recordEnumeratedHistogram(
                EVENTS_HISTOGRAM, Event.getBitPosition(event), Event.EVENT_END);
        for (int e : Event.getEventsFromBitMask(persistent_metric)) {
            RecordHistogram.recordEnumeratedHistogram(
                    EVENTS_HISTOGRAM, Event.getBitPosition(e), Event.EVENT_END);
        }
        preferencesEditor.remove(PREF_PERSISTENCE_METRICS);
    } else {
        // Save the metric in preferences.
        persistent_metric = Event.addEventToBitMask(persistent_metric, event);
        preferencesEditor.putLong(PREF_PERSISTENCE_METRICS, persistent_metric);
    }
    preferencesEditor.apply();
}
 
Example 7
Source File: DownloadNotificationService.java    From delion with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method to clear the remaining number of background resumption attempts left.
 */
static void clearResumptionAttemptLeft() {
    SharedPreferences SharedPrefs = ContextUtils.getAppSharedPreferences();
    SharedPreferences.Editor editor = SharedPrefs.edit();
    editor.remove(AUTO_RESUMPTION_ATTEMPT_LEFT);
    editor.apply();
}
 
Example 8
Source File: UrlManager.java    From delion with Apache License 2.0 5 votes vote down vote up
private void recordUpdate() {
    // Record a timestamp.
    // This is useful for tracking whether a notification is pressed soon after an update or
    // much later.
    SharedPreferences prefs = ContextUtils.getAppSharedPreferences();
    SharedPreferences.Editor editor = prefs.edit();
    editor.putLong(PREFS_NOTIFICATION_UPDATE_TIMESTAMP, SystemClock.elapsedRealtime());
    editor.apply();
}
 
Example 9
Source File: PhysicalWebUma.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
private static void storeAction(Context context, String key) {
    SharedPreferences prefs = ContextUtils.getAppSharedPreferences();
    int count = prefs.getInt(key, 0);
    prefs.edit()
            .putBoolean(HAS_DEFERRED_METRICS_KEY, true)
            .putInt(key, count + 1)
            .apply();
}
 
Example 10
Source File: LocaleManager.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Shows a promotion dialog saying the default search engine will be set to Sogou. No-op if
 * device is not in special locale.
 *
 * @return Whether such dialog is needed.
 */
public boolean showSearchEnginePromoIfNeeded(Context context) {
    if (!isSpecialLocaleEnabled()) return false;
    SharedPreferences preferences = ContextUtils.getAppSharedPreferences();
    if (preferences.getBoolean(PREF_PROMO_SHOWN, false)) {
        return false;
    }

    new SearchEnginePromoDialog(context, this).show();
    return true;
}
 
Example 11
Source File: PrecacheController.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
private static void recordPeriodicTaskIntervalHistogram() {
    SharedPreferences prefs = ContextUtils.getAppSharedPreferences();
    long previous_start_time_ms = prefs.getLong(PREF_PRECACHE_PERIODIC_TASK_START_TIME_MS, 0);
    long current_start_time_ms = System.currentTimeMillis();
    if (previous_start_time_ms > 0 && current_start_time_ms > previous_start_time_ms) {
        int interval_mins =
                (int) ((current_start_time_ms - previous_start_time_ms) / (1000 * 60));
        RecordHistogram.recordCustomCountHistogram(
                "Precache.PeriodicTaskInterval", interval_mins, 1, 10000, 50);
    }
    prefs.edit()
            .putLong(PREF_PRECACHE_PERIODIC_TASK_START_TIME_MS, current_start_time_ms)
            .apply();
}
 
Example 12
Source File: PhysicalWebUma.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Uploads metrics that we have deferred for uploading.
 */
public static void uploadDeferredMetrics() {
    // Read the metrics.
    SharedPreferences prefs = ContextUtils.getAppSharedPreferences();
    if (prefs.getBoolean(HAS_DEFERRED_METRICS_KEY, false)) {
        AsyncTask.THREAD_POOL_EXECUTOR.execute(new UmaUploader(prefs));
    }
}
 
Example 13
Source File: BookmarkUtils.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * @return The parent {@link BookmarkId} that the user used the last time or null if the user
 *         has never selected a parent folder to use.
 */
static BookmarkId getLastUsedParent(Context context) {
    SharedPreferences preferences = ContextUtils.getAppSharedPreferences();
    if (!preferences.contains(PREF_LAST_USED_PARENT)) return null;

    return BookmarkId.getBookmarkIdFromString(
            preferences.getString(PREF_LAST_USED_PARENT, null));
}
 
Example 14
Source File: DocumentModeAssassin.java    From delion with Apache License 2.0 5 votes vote down vote up
/** Migrates the user from document mode to tabbed mode if necessary. */
@VisibleForTesting
public final void migrateFromDocumentToTabbedMode() {
    ThreadUtils.assertOnUiThread();

    // Migration is already underway.
    if (mStage != STAGE_UNINITIALIZED) return;

    // If migration isn't necessary, don't do anything.
    if (!isMigrationNecessary()) {
        setStage(STAGE_UNINITIALIZED, STAGE_DONE);
        return;
    }

    // If we've crashed or failed too many times, send them to tabbed mode without their data.
    // - Any incorrect or invalid files in the tabbed mode directory will be wiped out by the
    //   TabPersistentStore when the ChromeTabbedActivity starts.
    //
    // - If it crashes in the step after being migrated, then the user will simply be left
    //   with a bunch of inaccessible document mode data instead of being stuck trying to
    //   migrate, which is a lesser evil.  This case will be caught by the check above to see if
    //   migration is even necessary.
    SharedPreferences prefs = ContextUtils.getAppSharedPreferences();
    int numMigrationAttempts = prefs.getInt(PREF_NUM_MIGRATION_ATTEMPTS, 0);
    if (numMigrationAttempts >= MAX_MIGRATION_ATTEMPTS_BEFORE_FAILURE) {
        Log.e(TAG, "Too many failures.  Migrating user to tabbed mode without data.");
        setStage(STAGE_UNINITIALIZED, STAGE_WRITE_TABMODEL_METADATA_DONE);
        return;
    }

    // Kick off the migration pipeline.
    // Using apply() instead of commit() seems to save the preference just fine, even if Chrome
    // crashes immediately afterward.
    SharedPreferences.Editor editor = prefs.edit();
    editor.putInt(PREF_NUM_MIGRATION_ATTEMPTS, numMigrationAttempts + 1);
    editor.apply();
    setStage(STAGE_UNINITIALIZED, STAGE_INITIALIZED);
}
 
Example 15
Source File: UrlManager.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
private void recordUpdate() {
    // Record a timestamp.
    // This is useful for tracking whether a notification is pressed soon after an update or
    // much later.
    SharedPreferences prefs = ContextUtils.getAppSharedPreferences();
    SharedPreferences.Editor editor = prefs.edit();
    editor.putLong(PREFS_NOTIFICATION_UPDATE_TIMESTAMP, SystemClock.elapsedRealtime());
    editor.apply();
}
 
Example 16
Source File: MediaCaptureNotificationService.java    From delion with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    mContext = getApplicationContext();
    mNotificationManager = (NotificationManager) mContext.getSystemService(
            Context.NOTIFICATION_SERVICE);
    mSharedPreferences = ContextUtils.getAppSharedPreferences();
    super.onCreate();
}
 
Example 17
Source File: TabSwitcherCallout.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
/**
 * Sets whether the tab switcher callout should be shown when the browser starts up.
 */
public static void setIsTabSwitcherCalloutNecessary(Context context, boolean shouldShow) {
    SharedPreferences prefs = ContextUtils.getAppSharedPreferences();
    prefs.edit().putBoolean(PREF_NEED_TO_SHOW_TAB_SWITCHER_CALLOUT, shouldShow).apply();
}
 
Example 18
Source File: DownloadUtils.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
/**
 * Caches the native flag that enables the Download Home in SharedPreferences.
 * This is necessary because the DownloadActivity can be opened before native has been loaded.
 */
public static void cacheIsDownloadHomeEnabled() {
    boolean isEnabled = ChromeFeatureList.isEnabled("DownloadsUi");
    SharedPreferences preferences = ContextUtils.getAppSharedPreferences();
    preferences.edit().putBoolean(PREF_IS_DOWNLOAD_HOME_ENABLED, isEnabled).apply();
}
 
Example 19
Source File: FontSizePrefs.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
private FontSizePrefs(Context context) {
    mFontSizePrefsAndroidPtr = nativeInit();
    mApplicationContext = context.getApplicationContext();
    mSharedPreferences = ContextUtils.getAppSharedPreferences();
    mObserverList = new ObserverList<FontSizePrefsObserver>();
}
 
Example 20
Source File: FontSizePrefs.java    From delion with Apache License 2.0 4 votes vote down vote up
private FontSizePrefs(Context context) {
    mFontSizePrefsAndroidPtr = nativeInit();
    mApplicationContext = context.getApplicationContext();
    mSharedPreferences = ContextUtils.getAppSharedPreferences();
    mObserverList = new ObserverList<FontSizePrefsObserver>();
}