Commit f2c48e22 authored by Tiger Oakes's avatar Tiger Oakes Committed by Commit Bot

Remove getApplicationContext calls from customtabs

Continuation of work in bug 646094.

Preparing to activate an errorprone check to flag
context#getApplicationContext calls. The goal is to prevent storing the
resulting context as a class property, and instead use ContextUtils.

Bug: 846456
Change-Id: Icfc48871f853797a15de7c50f247dc5400eab77f
Reviewed-on: https://chromium-review.googlesource.com/1095985
Commit-Queue: Tiger Oakes <tigero@google.com>
Reviewed-by: default avatarEgor Pasko <pasko@chromium.org>
Cr-Commit-Position: refs/heads/master@{#576118}
parent 0170b0a7
......@@ -22,6 +22,7 @@ import android.support.customtabs.CustomTabsSessionToken;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import org.chromium.base.ContextUtils;
import org.chromium.base.ThreadUtils;
import org.chromium.base.VisibleForTesting;
import org.chromium.base.metrics.RecordHistogram;
......@@ -255,14 +256,12 @@ class ClientManager {
}
}
private final Context mContext;
private final Map<CustomTabsSessionToken, SessionParams> mSessionParams = new HashMap<>();
private final SparseBooleanArray mUidHasCalledWarmup = new SparseBooleanArray();
private boolean mWarmupHasBeenCalled;
public ClientManager(Context context) {
mContext = context.getApplicationContext();
RequestThrottler.loadInBackground(mContext);
public ClientManager() {
RequestThrottler.loadInBackground(ContextUtils.getApplicationContext());
}
/** Creates a new session.
......@@ -276,7 +275,8 @@ class ClientManager {
public boolean newSession(CustomTabsSessionToken session, int uid,
DisconnectCallback onDisconnect, @NonNull PostMessageHandler postMessageHandler) {
if (session == null) return false;
SessionParams params = new SessionParams(mContext, uid, onDisconnect, postMessageHandler);
SessionParams params = new SessionParams(
ContextUtils.getApplicationContext(), uid, onDisconnect, postMessageHandler);
synchronized (this) {
if (mSessionParams.containsKey(session)) return false;
mSessionParams.put(session, params);
......@@ -327,7 +327,8 @@ class ClientManager {
TextUtils.isEmpty(url) && lowConfidence && !params.lowConfidencePrediction;
params.setPredictionMetrics(url, SystemClock.elapsedRealtime(), lowConfidence);
if (firstLowConfidencePrediction) return true;
RequestThrottler throttler = RequestThrottler.getForUid(mContext, uid);
RequestThrottler throttler =
RequestThrottler.getForUid(ContextUtils.getApplicationContext(), uid);
return throttler.updateStatsAndReturnWhetherAllowed();
}
......@@ -381,8 +382,8 @@ class ClientManager {
if (outcome == PredictionStatus.GOOD) {
long elapsedTimeMs = SystemClock.elapsedRealtime()
- params.getLastMayLaunchUrlTimestamp();
RequestThrottler.getForUid(mContext, params.uid).registerSuccess(
params.mPredictedUrl);
RequestThrottler.getForUid(ContextUtils.getApplicationContext(), params.uid)
.registerSuccess(params.mPredictedUrl);
RecordHistogram.recordCustomTimesHistogram("CustomTabs.PredictionToLaunch",
elapsedTimeMs, 1, TimeUnit.MINUTES.toMillis(3), TimeUnit.MILLISECONDS, 100);
}
......@@ -462,7 +463,7 @@ class ClientManager {
if (relation == CustomTabsService.RELATION_HANDLE_ALL_URLS
&& InstalledAppProviderImpl.isAppInstalledAndAssociatedWithOrigin(
params.getPackageName(), URI.create(origin.toString()),
mContext.getPackageManager())) {
ContextUtils.getApplicationContext().getPackageManager())) {
params.mLinkedOrigins.add(origin);
}
return true;
......@@ -724,13 +725,14 @@ class ClientManager {
if (connection == null) {
String packageName = intent.getComponent().getPackageName();
PackageManager pm = mContext.getApplicationContext().getPackageManager();
PackageManager pm = ContextUtils.getApplicationContext().getPackageManager();
// Only binds to the application associated to this session.
if (!Arrays.asList(pm.getPackagesForUid(params.uid)).contains(packageName)) {
return false;
}
Intent serviceIntent = new Intent().setComponent(intent.getComponent());
connection = new KeepAliveServiceConnection(mContext, serviceIntent);
connection = new KeepAliveServiceConnection(
ContextUtils.getApplicationContext(), serviceIntent);
}
boolean ok = connection.connect();
......@@ -748,22 +750,24 @@ class ClientManager {
/** See {@link RequestThrottler#isPrerenderingAllowed()} */
public synchronized boolean isPrerenderingAllowed(int uid) {
return RequestThrottler.getForUid(mContext, uid).isPrerenderingAllowed();
return RequestThrottler.getForUid(ContextUtils.getApplicationContext(), uid)
.isPrerenderingAllowed();
}
/** See {@link RequestThrottler#registerPrerenderRequest(String)} */
public synchronized void registerPrerenderRequest(int uid, String url) {
RequestThrottler.getForUid(mContext, uid).registerPrerenderRequest(url);
RequestThrottler.getForUid(ContextUtils.getApplicationContext(), uid)
.registerPrerenderRequest(url);
}
/** See {@link RequestThrottler#reset()} */
public synchronized void resetThrottling(int uid) {
RequestThrottler.getForUid(mContext, uid).reset();
RequestThrottler.getForUid(ContextUtils.getApplicationContext(), uid).reset();
}
/** See {@link RequestThrottler#ban()} */
public synchronized void ban(int uid) {
RequestThrottler.getForUid(mContext, uid).ban();
RequestThrottler.getForUid(ContextUtils.getApplicationContext(), uid).ban();
}
/**
......@@ -782,7 +786,8 @@ class ClientManager {
SessionParams params = mSessionParams.get(session);
if (params == null) return;
mSessionParams.remove(session);
if (params.postMessageHandler != null) params.postMessageHandler.cleanup(mContext);
if (params.postMessageHandler != null)
params.postMessageHandler.cleanup(ContextUtils.getApplicationContext());
if (params.originVerifier != null) params.originVerifier.cleanUp();
if (params.disconnectCallback != null) params.disconnectCallback.run(session);
mUidHasCalledWarmup.delete(params.uid);
......
......@@ -1165,8 +1165,8 @@ public class CustomTabActivity extends ChromeActivity {
params.getIcon(this), params.getDescription(), v -> {
if (getActivityTab() == null) return;
mIntentDataProvider.sendButtonPendingIntentWithUrlAndTitle(
getApplicationContext(), params, getActivityTab().getUrl(),
getActivityTab().getTitle());
ContextUtils.getApplicationContext(), params,
getActivityTab().getUrl(), getActivityTab().getTitle());
RecordUserAction.record("CustomTabsCustomActionButtonClick");
if (mIntentDataProvider.shouldEnableEmbeddedMediaExperience()
&& TextUtils.equals(
......
......@@ -21,6 +21,7 @@ import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import org.chromium.base.ContextUtils;
import org.chromium.base.Log;
import org.chromium.base.metrics.CachedMetrics;
import org.chromium.chrome.R;
......@@ -258,7 +259,8 @@ class CustomTabBottomBarDelegate implements FullscreenListener {
private boolean showRemoteViews(RemoteViews remoteViews) {
final View inflatedView;
try {
inflatedView = remoteViews.apply(mActivity.getApplicationContext(), getBottomBarView());
inflatedView =
remoteViews.apply(ContextUtils.getApplicationContext(), getBottomBarView());
} catch (RemoteViews.ActionException | InflateException | Resources.NotFoundException e) {
Log.e(TAG, "Failed to inflate the RemoteViews", e);
return false;
......
......@@ -219,6 +219,7 @@ public class CustomTabsConnection {
@VisibleForTesting
SpeculationParams mSpeculation;
/** @deprecated Use {@link ContextUtils} instead */
protected final Context mContext;
@VisibleForTesting
final ClientManager mClientManager;
......@@ -242,7 +243,7 @@ public class CustomTabsConnection {
public CustomTabsConnection() {
super();
mContext = ContextUtils.getApplicationContext();
mClientManager = new ClientManager(mContext);
mClientManager = new ClientManager();
mLogRequests = CommandLine.getInstance().hasSwitch(LOG_SERVICE_REQUESTS);
}
......@@ -413,8 +414,9 @@ public class CustomTabsConnection {
if (!initialized) {
tasks.add(() -> {
try (TraceEvent e = TraceEvent.scoped("CustomTabsConnection.initializeBrowser()")) {
initializeBrowser(mContext);
ChromeBrowserInitializer.initNetworkChangeNotifier(mContext);
initializeBrowser(ContextUtils.getApplicationContext());
ChromeBrowserInitializer.initNetworkChangeNotifier(
ContextUtils.getApplicationContext());
mWarmupHasBeenFinished.set(true);
}
});
......@@ -439,7 +441,8 @@ public class CustomTabsConnection {
// (3)
tasks.add(() -> {
try (TraceEvent e = TraceEvent.scoped("InitializeViewHierarchy")) {
WarmupManager.getInstance().initializeViewHierarchy(mContext,
WarmupManager.getInstance().initializeViewHierarchy(
ContextUtils.getApplicationContext(),
R.layout.custom_tabs_control_container, R.layout.custom_tabs_toolbar);
}
});
......@@ -455,7 +458,7 @@ public class CustomTabsConnection {
// The throttling database uses shared preferences, that can cause a
// StrictMode violation on the first access. Make sure that this access is
// not in mayLauchUrl.
RequestThrottler.loadInBackground(mContext);
RequestThrottler.loadInBackground(ContextUtils.getApplicationContext());
}
});
}
......@@ -837,7 +840,8 @@ public class CustomTabsConnection {
private void maybePreconnectToRedirectEndpoint(
CustomTabsSessionToken session, String url, Intent intent) {
// For the preconnection to not be a no-op, we need more than just the native library.
if (!ChromeBrowserInitializer.getInstance(mContext).hasNativeInitializationCompleted()) {
if (!ChromeBrowserInitializer.getInstance(ContextUtils.getApplicationContext())
.hasNativeInitializationCompleted()) {
return;
}
if (!ChromeFeatureList.isEnabled(ChromeFeatureList.CCT_REDIRECT_PRECONNECT)) return;
......@@ -880,7 +884,8 @@ public class CustomTabsConnection {
ThreadUtils.assertOnUiThread();
if (!intent.hasExtra(PARALLEL_REQUEST_URL_KEY)) return PARALLEL_REQUEST_NO_REQUEST;
if (!ChromeBrowserInitializer.getInstance(mContext).hasNativeInitializationCompleted()) {
if (!ChromeBrowserInitializer.getInstance(ContextUtils.getApplicationContext())
.hasNativeInitializationCompleted()) {
return PARALLEL_REQUEST_FAILURE_NOT_INITIALIZED;
}
if (!mClientManager.getAllowParallelRequestForSession(session)) {
......@@ -921,7 +926,8 @@ public class CustomTabsConnection {
// - The referrer's origin is allowed.
//
// TODO(lizeb): Relax the restrictions.
return ChromeBrowserInitializer.getInstance(mContext).hasNativeInitializationCompleted()
return ChromeBrowserInitializer.getInstance(ContextUtils.getApplicationContext())
.hasNativeInitializationCompleted()
&& ChromeFeatureList.isEnabled(ChromeFeatureList.CCT_PARALLEL_REQUEST)
&& mClientManager.isFirstPartyOriginForSession(session, new Origin(referrer));
}
......@@ -1232,7 +1238,8 @@ public class CustomTabsConnection {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
do {
ActivityManager am =
(ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
(ActivityManager) ContextUtils.getApplicationContext().getSystemService(
Context.ACTIVITY_SERVICE);
// Extra paranoia here and below, some L 5.0.x devices seem to throw NPE somewhere
// in this code.
// See https://crbug.com/654705.
......@@ -1286,7 +1293,8 @@ public class CustomTabsConnection {
return SPECULATION_STATUS_ON_START_NOT_ALLOWED_DATA_REDUCTION_ENABLED;
}
ConnectivityManager cm =
(ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
(ConnectivityManager) ContextUtils.getApplicationContext().getSystemService(
Context.CONNECTIVITY_SERVICE);
if (cm.isActiveNetworkMetered() && !shouldSpeculateLoadOnCellularForSession(session)) {
return SPECULATION_STATUS_ON_START_NOT_ALLOWED_NETWORK_METERED;
}
......
......@@ -11,6 +11,7 @@ import android.os.IBinder;
import android.support.customtabs.CustomTabsService;
import android.support.customtabs.CustomTabsSessionToken;
import org.chromium.base.ContextUtils;
import org.chromium.chrome.browser.browserservices.Origin;
import org.chromium.chrome.browser.firstrun.FirstRunFlowSequencer;
import org.chromium.chrome.browser.init.ProcessInitializationHandler;
......@@ -104,7 +105,7 @@ public class CustomTabsConnectionService extends CustomTabsService {
private boolean isFirstRunDone() {
if (mBindIntent == null) return true;
boolean firstRunNecessary = FirstRunFlowSequencer.checkIfFirstRunIsNecessary(
getApplicationContext(), mBindIntent, false);
ContextUtils.getApplicationContext(), mBindIntent, false);
if (!firstRunNecessary) {
mBindIntent = null;
return true;
......
......@@ -52,7 +52,7 @@ public class ClientManagerTest {
.getApplicationContext();
mActivityTestRule.loadNativeLibraryNoBrowserProcess();
RequestThrottler.purgeAllEntriesForTesting(context);
mClientManager = new ClientManager(context);
mClientManager = new ClientManager();
ThreadUtils.runOnUiThreadBlocking(new Runnable() {
@Override
public void run() {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment