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