下面列出了android.os.StrictMode.ThreadPolicy#org.chromium.base.ContextUtils 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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());
}
/**
* 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 "";
}
/**
* 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);
}
}
/**
* 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();
}
}
}
/**
* 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();
}
}
/**
* 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);
}
/**
* 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();
}
}
/**
* @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;
}
/**
* 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();
}
/**
* 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();
}
@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;
}
@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);
}
@CalledByNative
private static InfoBar createInfoBar(
String filePath, boolean isOfflinePage, String pageUrl, boolean isIncognito) {
return new DuplicateDownloadInfoBar(
ContextUtils.getApplicationContext(), filePath, isOfflinePage, pageUrl,
isIncognito);
}
@CalledByNative
private void openWebApk() {
Context context = ContextUtils.getApplicationContext();
PackageManager packageManager = getPackageManager(context);
if (InstallerDelegate.isInstalled(packageManager, mWebApkPackage)) {
openApp(context, mWebApkPackage);
}
}
@CalledByNative
private void onNativeDestroyed() {
mNativeProfileAndroid = 0;
if (mIsOffTheRecord) {
Context context = ContextUtils.getApplicationContext();
CookiesFetcher.deleteCookiesIfNecessary(context);
}
}
private static boolean haveAccessNetworkState() {
// This could be racy if called on multiple threads, but races will
// end in the same result so it's not a problem.
if (sHaveAccessNetworkState == null) {
sHaveAccessNetworkState =
Boolean.valueOf(ContextUtils.getApplicationContext().checkPermission(
Manifest.permission.ACCESS_NETWORK_STATE,
Process.myPid(), Process.myUid())
== PackageManager.PERMISSION_GRANTED);
}
return sHaveAccessNetworkState;
}
/**
* Get a singleton instance of this class.
* @return an instance of this class (or subclass).
*/
public static PhysicalWebBleClient getInstance() {
if (sInstance == null) {
sInstance = ((ChromeApplication) ContextUtils.getApplicationContext())
.createPhysicalWebBleClient();
}
return sInstance;
}
private void updateLastModifiedBookmarkFolder(long id) {
if (getLastModifiedBookmarkFolderId() == id) return;
mLastModifiedBookmarkFolderId = id;
SharedPreferences sharedPreferences =
ContextUtils.getAppSharedPreferences();
sharedPreferences.edit()
.putLong(LAST_MODIFIED_BOOKMARK_FOLDER_ID_KEY, mLastModifiedBookmarkFolderId)
.apply();
}
private void setUrlInfoCollectionInSharedPreferences(
String preferenceName, Collection<UrlInfo> urls) {
Set<String> serializedUrls = new HashSet<>();
for (UrlInfo url : urls) {
try {
serializedUrls.add(url.jsonSerialize().toString());
} catch (JSONException e) {
Log.e(TAG, "Could not serialize UrlInfo", e);
}
}
SharedPreferences.Editor editor = ContextUtils.getAppSharedPreferences().edit();
editor.putStringSet(preferenceName, serializedUrls);
editor.apply();
}
@VisibleForTesting
PrivacyPreferencesManager(Context context) {
mContext = context;
mSharedPreferences = ContextUtils.getAppSharedPreferences();
// We default the command line flag to disable uploads unless altered on deferred startup
// to prevent unwanted uploads at startup. If the command line flag to enable uploading is
// turned on, the other conditions (e.g. user/network preferences) for when to upload apply.
// This currently applies to only crash reporting and is ignored for metrics reporting.
mCrashUploadingDisabledByCommandLine = true;
migrateUsageAndCrashPreferences();
}
/**
* Ensure that native library is loaded and initialized. Can be called from
* any thread, the load and initialization is performed on init thread.
*/
public static void ensureInitialized(
Context applicationContext, final CronetEngineBuilderImpl builder) {
synchronized (sLoadLock) {
if (!sInitThreadInitDone) {
if (!IntegratedModeState.INTEGRATED_MODE_ENABLED) {
// In integrated mode, application context should be initialized by the host.
ContextUtils.initApplicationContext(applicationContext);
}
if (!sInitThread.isAlive()) {
sInitThread.start();
}
postToInitThread(new Runnable() {
@Override
public void run() {
ensureInitializedOnInitThread();
}
});
}
if (!sLibraryLoaded) {
if (builder.libraryLoader() != null) {
builder.libraryLoader().loadLibrary(LIBRARY_NAME);
} else {
System.loadLibrary(LIBRARY_NAME);
}
String implVersion = ImplVersion.getCronetVersion();
if (!implVersion.equals(nativeGetCronetVersion())) {
throw new RuntimeException(String.format("Expected Cronet version number %s, "
+ "actual version number %s.",
implVersion, nativeGetCronetVersion()));
}
Log.i(TAG, "Cronet version: %s, arch: %s", implVersion,
System.getProperty("os.arch"));
sLibraryLoaded = true;
sWaitForLibLoad.open();
}
}
}
/**
* Returns whether the browser should be launched when the device next goes online.
* This is set by C++ and reset to false each time {@link BackgroundSyncLauncher}'s singleton is
* created (the native browser is started). This call is asynchronous and will run the callback
* on the UI thread when complete.
* @param context The application context.
* @param sharedPreferences The shared preferences.
*/
protected static void shouldLaunchBrowserIfStopped(
final Context context, final ShouldLaunchCallback callback) {
new AsyncTask<Void, Void, Boolean>() {
@Override
protected Boolean doInBackground(Void... params) {
SharedPreferences prefs = ContextUtils.getAppSharedPreferences();
return prefs.getBoolean(PREF_BACKGROUND_SYNC_LAUNCH_NEXT_ONLINE, false);
}
@Override
protected void onPostExecute(Boolean shouldLaunch) {
callback.run(shouldLaunch);
}
}.execute();
}
/** Hides the sign in promo and sets a preference to make sure it is not shown again. */
public void dismiss() {
mDismissed = true;
setVisible(false);
ChromePreferenceManager.getInstance(ContextUtils.getApplicationContext())
.setNewTabPageSigninPromoDismissed(true);
mObserver.unregister();
}
/**
* Logs the current session.
*/
public void logAndEndSession() {
if (mTabModelSelector != null) {
mContext.unregisterComponentCallbacks(mComponentCallbacks);
mTabModelSelectorTabObserver.destroy();
mTabModelSelector = null;
}
nativeUmaEndSession(sNativeUmaSessionStats);
ContextUtils.getAppSharedPreferences()
.edit()
.putLong(LAST_USED_TIME_PREF, System.currentTimeMillis())
.apply();
}
/**
* Returns whether the user has enabled installing apps from sources other than the Google
* Play Store.
*/
private static boolean installingFromUnknownSourcesAllowed() {
ContentResolver contentResolver = ContextUtils.getApplicationContext().getContentResolver();
try {
int setting = Settings.Secure.getInt(
contentResolver, Settings.Secure.INSTALL_NON_MARKET_APPS);
return setting == 1;
} catch (Settings.SettingNotFoundException e) {
return false;
}
}
/** @return True if the user is not in document mode. */
public static boolean isOptedOutOfDocumentMode() {
// The OPT_OUT_STATE preference was introduced sometime after document mode was rolled out.
// It may not be set for all users, even if they are in document mode. In order to correctly
// detect whether the user is in document mode, if OPT_OUT_STATE is not state we must check
// whether MIGRATION_ON_UPGRADE_ATTEMPTED is set.
int optOutState = ContextUtils.getAppSharedPreferences().getInt(OPT_OUT_STATE,
OPT_OUT_STATE_UNSET);
if (optOutState == OPT_OUT_STATE_UNSET) {
boolean hasMigratedToDocumentMode = ContextUtils.getAppSharedPreferences().getBoolean(
MIGRATION_ON_UPGRADE_ATTEMPTED, false);
if (!hasMigratedToDocumentMode) {
optOutState = OPTED_OUT_OF_DOCUMENT_MODE;
} else {
// Check if a migration has already happened by looking for tab_state0 file.
// See crbug.com/646146.
boolean newMetadataFileExists = false;
StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
try {
File newMetadataFile = new File(
TabbedModeTabPersistencePolicy.getOrCreateTabbedModeStateDirectory(),
TabbedModeTabPersistencePolicy.getStateFileName(TAB_MODEL_INDEX));
newMetadataFileExists = newMetadataFile.exists();
} finally {
StrictMode.setThreadPolicy(oldPolicy);
}
if (newMetadataFileExists) {
optOutState = OPTED_OUT_OF_DOCUMENT_MODE;
} else {
optOutState = OPT_IN_TO_DOCUMENT_MODE;
}
}
setOptedOutState(optOutState);
}
return optOutState == OPTED_OUT_OF_DOCUMENT_MODE;
}
/**
* Save that user tapped "No" button on the signin promo header.
*/
private void setSigninPromoDeclined() {
SharedPreferences.Editor sharedPreferencesEditor =
ContextUtils.getAppSharedPreferences().edit();
sharedPreferencesEditor.putBoolean(PREF_SIGNIN_PROMO_DECLINED, true);
sharedPreferencesEditor.apply();
}
private void updateShouldShow(boolean notifyUI) {
boolean oldIsShowing = mShouldShow;
mShouldShow = AndroidSyncSettings.isMasterSyncEnabled(mContext)
&& mSignInManager.isSignInAllowed()
&& !wasSigninPromoDeclined()
&& ContextUtils.getAppSharedPreferences().getInt(
PREF_SIGNIN_PROMO_SHOW_COUNT, 0) < MAX_SIGNIN_PROMO_SHOW_COUNT;
if (oldIsShowing != mShouldShow && notifyUI) {
mShowingChangeListener.onPromoHeaderShowingChanged(mShouldShow);
}
}
@VisibleForTesting
PrivacyPreferencesManager(Context context) {
mContext = context;
mSharedPreferences = ContextUtils.getAppSharedPreferences();
// Crash dump uploading preferences.
// We default the command line flag to disable uploads unless altered on deferred startup
// to prevent unwanted uploads at startup. If the command line flag to enable uploading is
// turned on, the other options for when to upload (depending on user/network preferences
// apply.
mCrashUploadingCommandLineDisabled = true;
mCrashDumpNeverUpload = context.getString(R.string.crash_dump_never_upload_value);
mCrashDumpWifiOnlyUpload = context.getString(R.string.crash_dump_only_with_wifi_value);
mCrashDumpAlwaysUpload = context.getString(R.string.crash_dump_always_upload_value);
}
/**
* Lazily fetches the last modified bookmark folder id.
*/
private long getLastModifiedBookmarkFolderId() {
if (mLastModifiedBookmarkFolderId == INVALID_BOOKMARK_ID) {
SharedPreferences sharedPreferences =
ContextUtils.getAppSharedPreferences();
mLastModifiedBookmarkFolderId = sharedPreferences.getLong(
LAST_MODIFIED_BOOKMARK_FOLDER_ID_KEY, INVALID_BOOKMARK_ID);
}
return mLastModifiedBookmarkFolderId;
}