org.chromium.base.ContextUtils Java Examples
The following examples show how to use
org.chromium.base.ContextUtils.
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: ActivityDelegateImpl.java From delion with Apache License 2.0 | 6 votes |
@Override public List<Entry> getTasksFromRecents(boolean isIncognito) { Context context = ContextUtils.getApplicationContext(); ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<Entry> entries = new ArrayList<Entry>(); for (ActivityManager.AppTask task : activityManager.getAppTasks()) { Intent intent = DocumentUtils.getBaseIntentFromTask(task); if (!isValidActivity(isIncognito, intent)) continue; int tabId = getTabIdFromIntent(intent); if (tabId == Tab.INVALID_TAB_ID) continue; String initialUrl = getInitialUrlForDocument(intent); entries.add(new Entry(tabId, initialUrl)); } return entries; }
Example #2
Source File: FirstRunGlueImpl.java From AndroidChromium with Apache License 2.0 | 6 votes |
/** * Synchronizes first run native and Java preferences. * Must be called after native initialization. */ public static void cacheFirstRunPrefs() { SharedPreferences javaPrefs = ContextUtils.getAppSharedPreferences(); PrefServiceBridge prefsBridge = PrefServiceBridge.getInstance(); // Set both Java and native prefs if any of the three indicators indicate ToS has been // accepted. This needed because: // - Old versions only set native pref, so this syncs Java pref. // - Backup & restore does not restore native pref, so this needs to update it. // - checkAnyUserHasSeenToS() may be true which needs to sync its state to the prefs. boolean javaPrefValue = javaPrefs.getBoolean(CACHED_TOS_ACCEPTED_PREF, false); boolean nativePrefValue = prefsBridge.isFirstRunEulaAccepted(); boolean userHasSeenTos = ToSAckedReceiver.checkAnyUserHasSeenToS(ContextUtils.getApplicationContext()); if (javaPrefValue || nativePrefValue || userHasSeenTos) { if (!javaPrefValue) { javaPrefs.edit().putBoolean(CACHED_TOS_ACCEPTED_PREF, true).apply(); } if (!nativePrefValue) { prefsBridge.setEulaAccepted(); } } }
Example #3
Source File: PrefServiceBridge.java From delion with Apache License 2.0 | 6 votes |
/** * Migrates (synchronously) the preferences to the most recent version. */ public void migratePreferences(Context context) { SharedPreferences preferences = ContextUtils.getAppSharedPreferences(); int currentVersion = preferences.getInt(MIGRATION_PREF_KEY, 0); if (currentVersion == MIGRATION_CURRENT_VERSION) return; if (currentVersion > MIGRATION_CURRENT_VERSION) { Log.e(LOG_TAG, "Saved preferences version is newer than supported. Attempting to " + "run an older version of Chrome without clearing data is unsupported and " + "the results may be unpredictable."); } if (currentVersion < 1) { nativeMigrateJavascriptPreference(); } // Steps 2,3,4 intentionally skipped. preferences.edit().putInt(MIGRATION_PREF_KEY, MIGRATION_CURRENT_VERSION).apply(); }
Example #4
Source File: PrefServiceBridge.java From delion with Apache License 2.0 | 6 votes |
/** * 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 #5
Source File: SpellCheckerSessionBridge.java From delion with Apache License 2.0 | 6 votes |
/** * Constructs a SpellCheckerSessionBridge object as well as its SpellCheckerSession object. * @param nativeSpellCheckerSessionBridge Pointer to the native SpellCheckerSessionBridge. */ private SpellCheckerSessionBridge(long nativeSpellCheckerSessionBridge) { mNativeSpellCheckerSessionBridge = nativeSpellCheckerSessionBridge; Context context = ContextUtils.getApplicationContext(); final TextServicesManager textServicesManager = (TextServicesManager) context.getSystemService( Context.TEXT_SERVICES_MANAGER_SERVICE); // This combination of parameters will cause the spellchecker to be based off of // the language specified at "Settings > Language & input > Spell checker > Language". // If that setting is set to "Use system language" and the system language is not on the // list of supported spellcheck languages, this call will return null. This call will also // return null if the user has turned spellchecking off at "Settings > Language & input > // Spell checker". mSpellCheckerSession = textServicesManager.newSpellCheckerSession(null, null, this, true); }
Example #6
Source File: LocaleManager.java From AndroidChromium with Apache License 2.0 | 6 votes |
/** * 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 #7
Source File: ChromeWebApkHost.java From AndroidChromium with Apache License 2.0 | 6 votes |
/** * Once native is loaded we can consult the command-line (set via about:flags) and also finch * state to see if we should enable WebAPKs. */ public static void cacheEnabledStateForNextLaunch() { ChromePreferenceManager preferenceManager = ChromePreferenceManager.getInstance(ContextUtils.getApplicationContext()); boolean wasCommandLineEnabled = preferenceManager.getCachedWebApkCommandLineEnabled(); boolean isCommandLineEnabled = isCommandLineFlagSet(); if (isCommandLineEnabled != wasCommandLineEnabled) { // {@link launchWebApkRequirementsDialogIfNeeded()} is skipped the first time Chrome is // launched so do caching here instead. preferenceManager.setCachedWebApkCommandLineEnabled(isCommandLineEnabled); } boolean wasEnabled = isEnabledInPrefs(); boolean isEnabled = computeEnabled(); if (isEnabled != wasEnabled) { Log.d(TAG, "WebApk setting changed (%s => %s)", wasEnabled, isEnabled); preferenceManager.setCachedWebApkRuntimeEnabled(isEnabled); } }
Example #8
Source File: FeatureUtilities.java From AndroidChromium with Apache License 2.0 | 6 votes |
/** * @return Which flavor of Herb is being tested. * See {@link ChromeSwitches#HERB_FLAVOR_ELDERBERRY} and its related switches. */ public static String getHerbFlavor() { Context context = ContextUtils.getApplicationContext(); if (isHerbDisallowed(context)) return ChromeSwitches.HERB_FLAVOR_DISABLED; if (!sIsHerbFlavorCached) { sCachedHerbFlavor = null; // Allowing disk access for preferences while prototyping. StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads(); try { sCachedHerbFlavor = ChromePreferenceManager.getInstance(context).getCachedHerbFlavor(); } finally { StrictMode.setThreadPolicy(oldPolicy); } sIsHerbFlavorCached = true; Log.d(TAG, "Retrieved cached Herb flavor: " + sCachedHerbFlavor); } return sCachedHerbFlavor; }
Example #9
Source File: AndroidNetworkLibrary.java From cronet with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Gets the SSID of the currently associated WiFi access point if there is one, and it is * available. SSID may not be available if the app does not have permissions to access it. On * Android M+, the app accessing SSID needs to have ACCESS_COARSE_LOCATION or * ACCESS_FINE_LOCATION. If there is no WiFi access point or its SSID is unavailable, an empty * string is returned. */ @CalledByNative public static String getWifiSSID() { final Intent intent = ContextUtils.getApplicationContext().registerReceiver( null, new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION)); if (intent != null) { final WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO); if (wifiInfo != null) { final String ssid = wifiInfo.getSSID(); // On Android M+, the platform APIs may return "<unknown ssid>" as the SSID if the // app does not have sufficient permissions. In that case, return an empty string. if (ssid != null && !ssid.equals("<unknown ssid>")) { return ssid; } } } return ""; }
Example #10
Source File: ChromeApplication.java From AndroidChromium with Apache License 2.0 | 6 votes |
/** * Removes all session cookies (cookies with no expiration date) after device reboots. * This function will incorrectly clear cookies when Daylight Savings Time changes the clock. * Without a way to get a monotonically increasing system clock, the boot timestamp will be off * by one hour. However, this should only happen at most once when the clock changes since the * updated timestamp is immediately saved. */ public static void removeSessionCookies() { long lastKnownBootTimestamp = ContextUtils.getAppSharedPreferences().getLong(PREF_BOOT_TIMESTAMP, 0); long bootTimestamp = System.currentTimeMillis() - SystemClock.uptimeMillis(); long difference = bootTimestamp - lastKnownBootTimestamp; // Allow some leeway to account for fractions of milliseconds. if (Math.abs(difference) > BOOT_TIMESTAMP_MARGIN_MS) { nativeRemoveSessionCookies(); SharedPreferences prefs = ContextUtils.getAppSharedPreferences(); SharedPreferences.Editor editor = prefs.edit(); editor.putLong(PREF_BOOT_TIMESTAMP, bootTimestamp); editor.apply(); } }
Example #11
Source File: WebappDelegateFactory.java From AndroidChromium with Apache License 2.0 | 6 votes |
@Override public void activateContents() { String startUrl = mActivity.getWebappInfo().uri().toString(); // Create an Intent that will be fired toward the WebappLauncherActivity, which in turn // will fire an Intent to launch the correct WebappActivity. On L+ this could probably // be changed to call AppTask.moveToFront(), but for backwards compatibility we relaunch // it the hard way. Intent intent = new Intent(); intent.setAction(WebappLauncherActivity.ACTION_START_WEBAPP); intent.setPackage(mActivity.getPackageName()); mActivity.getWebappInfo().setWebappIntentExtras(intent); intent.putExtra( ShortcutHelper.EXTRA_MAC, ShortcutHelper.getEncodedMac(mActivity, startUrl)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); ContextUtils.getApplicationContext().startActivity(intent); }
Example #12
Source File: IncognitoNotificationManager.java From AndroidChromium with Apache License 2.0 | 6 votes |
/** * Shows the close all incognito notification. */ public static void showIncognitoNotification() { Context context = ContextUtils.getApplicationContext(); String actionMessage = context.getResources().getString(R.string.close_all_incognito_notification); String title = context.getResources().getString(R.string.app_name); NotificationCompat.Builder builder = new NotificationCompat.Builder(context) .setContentTitle(title) .setContentIntent( IncognitoNotificationService.getRemoveAllIncognitoTabsIntent(context)) .setContentText(actionMessage) .setOngoing(true) .setVisibility(Notification.VISIBILITY_SECRET) .setSmallIcon(R.drawable.incognito_statusbar) .setShowWhen(false) .setLocalOnly(true); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); nm.notify(INCOGNITO_TABS_OPEN_TAG, INCOGNITO_TABS_OPEN_ID, builder.build()); }
Example #13
Source File: FirstRunStatus.java From AndroidChromium with Apache License 2.0 | 5 votes |
/** * Sets the "main First Run Experience flow complete" preference. * @param isComplete Whether the main First Run Experience flow is complete */ public static void setFirstRunFlowComplete(boolean isComplete) { ContextUtils.getAppSharedPreferences() .edit() .putBoolean(FIRST_RUN_FLOW_COMPLETE, isComplete) .apply(); }
Example #14
Source File: ToSAckedReceiver.java From delion with Apache License 2.0 | 5 votes |
/** * Checks whether any of the current google accounts has seen the ToS in setup wizard. * @param context Context for the app. * @return Whether or not the the ToS has been seen. */ public static boolean checkAnyUserHasSeenToS(Context context) { Set<String> toSAckedAccounts = ContextUtils.getAppSharedPreferences().getStringSet( TOS_ACKED_ACCOUNTS, null); if (toSAckedAccounts == null || toSAckedAccounts.isEmpty()) return false; AccountManagerHelper accountHelper = AccountManagerHelper.get(context); List<String> accountNames = accountHelper.getGoogleAccountNames(); if (accountNames.isEmpty()) return false; for (int k = 0; k < accountNames.size(); k++) { if (toSAckedAccounts.contains(accountNames.get(k))) return true; } return false; }
Example #15
Source File: UrlManager.java From delion with Apache License 2.0 | 5 votes |
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: DocumentTabModelSelector.java From delion with Apache License 2.0 | 5 votes |
@Override public void selectModel(boolean incognito) { super.selectModel(incognito); Context context = ContextUtils.getApplicationContext(); SharedPreferences prefs = context.getSharedPreferences(PREF_PACKAGE, Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean(PREF_IS_INCOGNITO_SELECTED, incognito); editor.apply(); }
Example #17
Source File: ShortcutHelper.java From AndroidChromium with Apache License 2.0 | 5 votes |
/** * Returns whether the given icon matches the size requirements to be used on the home screen. * @param width Icon width, in pixels. * @param height Icon height, in pixels. * @return whether the given icon matches the size requirements to be used on the home screen. */ @CalledByNative public static boolean isIconLargeEnoughForLauncher(int width, int height) { Context context = ContextUtils.getApplicationContext(); ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); final int minimalSize = am.getLauncherLargeIconSize() / 2; return width >= minimalSize && height >= minimalSize; }
Example #18
Source File: IncognitoNotificationManager.java From AndroidChromium with Apache License 2.0 | 5 votes |
/** * Dismisses the incognito notification. */ public static void dismissIncognitoNotification() { Context context = ContextUtils.getApplicationContext(); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); nm.cancel(INCOGNITO_TABS_OPEN_TAG, INCOGNITO_TABS_OPEN_ID); }
Example #19
Source File: FirstRunGlueImpl.java From AndroidChromium with Apache License 2.0 | 5 votes |
@Override public void acceptTermsOfService(boolean allowCrashUpload) { UmaSessionStats.changeMetricsReportingConsent(allowCrashUpload); ContextUtils.getAppSharedPreferences() .edit() .putBoolean(CACHED_TOS_ACCEPTED_PREF, true) .apply(); PrefServiceBridge.getInstance().setEulaAccepted(); }
Example #20
Source File: DocumentTabModelSelector.java From delion with Apache License 2.0 | 5 votes |
public DocumentTabModelSelector(ActivityDelegate activityDelegate, StorageDelegate storageDelegate, TabDelegate regularTabDelegate, TabDelegate incognitoTabDelegate) { mActivityDelegate = activityDelegate; mStorageDelegate = sStorageDelegateForTests == null ? storageDelegate : sStorageDelegateForTests; mRegularTabDelegate = regularTabDelegate; mIncognitoTabDelegate = incognitoTabDelegate; final Context context = ContextUtils.getApplicationContext(); mRegularTabModel = new DocumentTabModelImpl( mActivityDelegate, mStorageDelegate, this, false, sPrioritizedTabId, context); mIncognitoTabModel = new OffTheRecordDocumentTabModel(new OffTheRecordTabModelDelegate() { @Override public TabModel createTabModel() { DocumentTabModel incognitoModel = new DocumentTabModelImpl(mActivityDelegate, mStorageDelegate, DocumentTabModelSelector.this, true, sPrioritizedTabId, context); return incognitoModel; } @Override public boolean doOffTheRecordTabsExist() { // TODO(dfalcantara): Devices in document mode do not trigger the TabWindowManager. // Revisit this when we have a Samsung L multi-instance device. return mIncognitoTabModel.getCount() > 0; } }, mActivityDelegate); initializeTabIdCounter(); // Re-select the previously selected TabModel. SharedPreferences prefs = context.getSharedPreferences(PREF_PACKAGE, Context.MODE_PRIVATE); boolean startIncognito = prefs.getBoolean(PREF_IS_INCOGNITO_SELECTED, false); initialize(startIncognito, mRegularTabModel, mIncognitoTabModel); }
Example #21
Source File: DataReductionPromoUtils.java From AndroidChromium with Apache License 2.0 | 5 votes |
/** * Saves shared prefs indicating that the data reduction proxy infobar promo has been displayed * at the current time. */ public static void saveInfoBarPromoDisplayed() { AboutVersionStrings versionStrings = PrefServiceBridge.getInstance() .getAboutVersionStrings(); ContextUtils.getAppSharedPreferences() .edit() .putBoolean(SHARED_PREF_DISPLAYED_INFOBAR_PROMO, true) .putString(SHARED_PREF_DISPLAYED_INFOBAR_PROMO_VERSION, versionStrings.getApplicationVersion()) .apply(); }
Example #22
Source File: AppBannerManager.java From delion with Apache License 2.0 | 5 votes |
/** * Checks if app banners are enabled. * @return True if banners are enabled, false otherwise. */ public static boolean isEnabled() { if (sIsEnabled == null) { Context context = ContextUtils.getApplicationContext(); sIsEnabled = ShortcutHelper.isAddToHomeIntentSupported(context); } return sIsEnabled; }
Example #23
Source File: UmaSessionStats.java From delion with Apache License 2.0 | 5 votes |
/** * Logs the current session. */ public void logAndEndSession() { if (mTabModelSelector != null) { mContext.unregisterComponentCallbacks(mComponentCallbacks); mTabModelSelectorTabObserver.destroy(); mTabModelSelector = null; } nativeUmaEndSession(sNativeUmaSessionStats); NetworkChangeNotifier.removeConnectionTypeObserver(this); ContextUtils.getAppSharedPreferences() .edit() .putLong(LAST_USED_TIME_PREF, System.currentTimeMillis()) .apply(); }
Example #24
Source File: StartupMetrics.java From delion with Apache License 2.0 | 5 votes |
/** Records the startup data in a histogram. Should only be called after native is loaded. */ public void recordHistogram(boolean onStop) { if (!mShouldRecordHistogram) return; if (!isShortlyAfterChromeStarted() || mFirstActionTaken != NO_ACTIVITY || onStop) { String histogramName = mIsMainIntent ? "MobileStartup.MainIntentAction" : "MobileStartup.NonMainIntentAction"; RecordHistogram.recordEnumeratedHistogram(histogramName, mFirstActionTaken, MAX_INDEX); mShouldRecordHistogram = false; long lastUsedTimeMilli = ContextUtils.getAppSharedPreferences().getLong( UmaSessionStats.LAST_USED_TIME_PREF, 0); if (mIsMainIntent && (lastUsedTimeMilli > 0) && (mStartTimeMilli > lastUsedTimeMilli) && (mStartTimeMilli - lastUsedTimeMilli > Integer.MAX_VALUE)) { // Measured in minutes and capped at a day with a bucket precision of 6 minutes. RecordHistogram.recordCustomCountHistogram("MobileStartup.TimeSinceLastUse", (int) (mStartTimeMilli - lastUsedTimeMilli) / MILLI_SEC_PER_MINUTE, 1, MINUTES_PER_30DAYS, NUM_BUCKETS); } } else { // Call back later to record the histogram after 10s have elapsed. mHandler.postDelayed(new Runnable() { @Override public void run() { recordHistogram(false); } }, (RECORDING_THRESHOLD_NS - (System.nanoTime() - mStartTimeNanoMonotonic)) / 1000000); } }
Example #25
Source File: SigninHelper.java From delion with Apache License 2.0 | 5 votes |
public static boolean checkAndClearAccountsChangedPref(Context context) { if (ContextUtils.getAppSharedPreferences() .getBoolean(ACCOUNTS_CHANGED_PREFS_KEY, false)) { // Clear the value in prefs. ContextUtils.getAppSharedPreferences() .edit().putBoolean(ACCOUNTS_CHANGED_PREFS_KEY, false).apply(); return true; } else { return false; } }
Example #26
Source File: ActivityDelegate.java From AndroidChromium with Apache License 2.0 | 5 votes |
/** * Finishes all DocumentActivities that appear in Android's Recents. */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) public void finishAllDocumentActivities() { Context context = ContextUtils.getApplicationContext(); ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.AppTask task : activityManager.getAppTasks()) { Intent intent = DocumentUtils.getBaseIntentFromTask(task); if (isValidActivity(false, intent) || isValidActivity(true, intent)) { task.finishAndRemoveTask(); } } }
Example #27
Source File: FirstRunGlueImpl.java From AndroidChromium with Apache License 2.0 | 5 votes |
@Override public boolean didAcceptTermsOfService(Context appContext) { // Note: Does not check PrefServiceBridge.getInstance().isFirstRunEulaAccepted() // because this may be called before native is initialized. return ContextUtils.getAppSharedPreferences().getBoolean(CACHED_TOS_ACCEPTED_PREF, false) || ToSAckedReceiver.checkAnyUserHasSeenToS(appContext); }
Example #28
Source File: WebApkInstaller.java From AndroidChromium with Apache License 2.0 | 5 votes |
private void onInstallFinishedInternal(boolean success) { ApplicationStatus.unregisterApplicationStateListener(mListener); mInstallTask = null; if (mNativePointer != 0) { nativeOnInstallFinished(mNativePointer, success); } if (success && mIsInstall) { ShortcutHelper.addWebApkShortcut(ContextUtils.getApplicationContext(), mWebApkPackageName); } }
Example #29
Source File: PhysicalWebUma.java From delion with Apache License 2.0 | 5 votes |
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 #30
Source File: IncognitoNotificationManager.java From delion with Apache License 2.0 | 5 votes |
/** * Dismisses the incognito notification. */ public static void dismissIncognitoNotification() { Context context = ContextUtils.getApplicationContext(); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); nm.cancel(INCOGNITO_TABS_OPEN_TAG, INCOGNITO_TABS_OPEN_ID); }