CronetEngine

public abstract class CronetEngine extends Object

An engine to process UrlRequests, which uses the best HTTP stack available on the current platform. An instance of this class can be created using CronetEngine.Builder.

Nested Class Summary

class CronetEngine.Builder A builder for CronetEngines, which allows runtime configuration of CronetEngine

Constant Summary

int ACTIVE_REQUEST_COUNT_UNKNOWN The value of the active request count is unknown
int CONNECTION_METRIC_UNKNOWN The value of a connection metric is unknown.
int EFFECTIVE_CONNECTION_TYPE_2G The estimate of the effective connection type is 2G.
int EFFECTIVE_CONNECTION_TYPE_3G The estimate of the effective connection type is 3G.
int EFFECTIVE_CONNECTION_TYPE_4G The estimate of the effective connection type is 4G.
int EFFECTIVE_CONNECTION_TYPE_OFFLINE The device is offline.
int EFFECTIVE_CONNECTION_TYPE_SLOW_2G The estimate of the effective connection type is slow 2G.
int EFFECTIVE_CONNECTION_TYPE_UNKNOWN The estimate of the effective connection type is unknown.

Public Constructor Summary

Public Method Summary

void
addRequestFinishedListener(RequestFinishedInfo.Listener listener)
Registers a listener that gets called after the end of each request with the request info.
void
addRttListener(NetworkQualityRttListener listener)
Registers a listener that gets called whenever the network quality estimator witnesses a sample round trip time.
void
addThroughputListener(NetworkQualityThroughputListener listener)
Registers a listener that gets called whenever the network quality estimator witnesses a sample throughput measurement.
void
configureNetworkQualityEstimatorForTesting(boolean useLocalHostRequests, boolean useSmallerResponses, boolean disableOfflineCheck)
Configures the network quality estimator for testing.
abstract URLStreamHandlerFactory
createURLStreamHandlerFactory()
Creates a URLStreamHandlerFactory to handle HTTP and HTTPS traffic.
int
getActiveRequestCount()
Returns the number of in-flight requests.
int
getDownstreamThroughputKbps()
Returns the downstream throughput estimate (in kilobits per second) computed by the network quality estimator.
int
getEffectiveConnectionType()
Returns an estimate of the effective connection type computed by the network quality estimator.
abstract byte[]
getGlobalMetricsDeltas()
Returns differences in metrics collected by Cronet since the last call to this method.
int
getHttpRttMs()
Returns the HTTP RTT estimate (in milliseconds) computed by the network quality estimator.
int
getTransportRttMs()
Returns the transport RTT estimate (in milliseconds) computed by the network quality estimator.
abstract String
abstract UrlRequest.Builder
newUrlRequestBuilder(String url, UrlRequest.Callback callback, Executor executor)
Creates a builder for UrlRequest.
abstract URLConnection
openConnection(URL url)
Establishes a new connection to the resource specified by the URL url.
void
removeRequestFinishedListener(RequestFinishedInfo.Listener listener)
Removes a finished request listener.
void
removeRttListener(NetworkQualityRttListener listener)
Removes a listener of round trip times if previously registered with addRttListener(NetworkQualityRttListener).
void
removeThroughputListener(NetworkQualityThroughputListener listener)
Removes a listener of throughput.
abstract void
shutdown()
Shuts down the CronetEngine if there are no active requests, otherwise throws an exception.
void
startNetLogToDisk(String dirPath, boolean logAll, int maxSize)
Starts NetLog logging to a specified directory with a bounded size.
abstract void
startNetLogToFile(String fileName, boolean logAll)
Starts NetLog logging to a file.
abstract void
stopNetLog()
Stops NetLog logging and flushes file to disk.

Inherited Method Summary

Constants

public static final int ACTIVE_REQUEST_COUNT_UNKNOWN

The value of the active request count is unknown

Constant Value: -1

public static final int CONNECTION_METRIC_UNKNOWN

The value of a connection metric is unknown.

Constant Value: -1

public static final int EFFECTIVE_CONNECTION_TYPE_2G

The estimate of the effective connection type is 2G.

Constant Value: 3

public static final int EFFECTIVE_CONNECTION_TYPE_3G

The estimate of the effective connection type is 3G.

Constant Value: 4

public static final int EFFECTIVE_CONNECTION_TYPE_4G

The estimate of the effective connection type is 4G.

Constant Value: 5

public static final int EFFECTIVE_CONNECTION_TYPE_OFFLINE

The device is offline.

Constant Value: 1

public static final int EFFECTIVE_CONNECTION_TYPE_SLOW_2G

The estimate of the effective connection type is slow 2G.

Constant Value: 2

public static final int EFFECTIVE_CONNECTION_TYPE_UNKNOWN

The estimate of the effective connection type is unknown.

Constant Value: 0

Public Constructors

public CronetEngine ()

Public Methods

public void addRequestFinishedListener (RequestFinishedInfo.Listener listener)

Registers a listener that gets called after the end of each request with the request info.

The listener is called on an Executor provided by the listener.

Parameters
listener the listener for finished requests.

public void addRttListener (NetworkQualityRttListener listener)

Registers a listener that gets called whenever the network quality estimator witnesses a sample round trip time. This must be called after CronetEngine.Builder.enableNetworkQualityEstimator(boolean), and with throw an exception otherwise. Round trip times may be recorded at various layers of the network stack, including TCP, QUIC, and at the URL request layer. The listener is called on the Executor that is passed to CronetEngine.Builder.enableNetworkQualityEstimator(boolean).

Parameters
listener the listener of round trip times.

public void addThroughputListener (NetworkQualityThroughputListener listener)

Registers a listener that gets called whenever the network quality estimator witnesses a sample throughput measurement. This must be called after CronetEngine.Builder.enableNetworkQualityEstimator(boolean). Throughput observations are computed by measuring bytes read over the active network interface at times when at least one URL response is being received. The listener is called on the Executor that is passed to CronetEngine.Builder.enableNetworkQualityEstimator(boolean).

Parameters
listener the listener of throughput.

public void configureNetworkQualityEstimatorForTesting (boolean useLocalHostRequests, boolean useSmallerResponses, boolean disableOfflineCheck)

Configures the network quality estimator for testing. This must be called before round trip time and throughput listeners are added, and after the network quality estimator has been enabled.

Parameters
useLocalHostRequests include requests to localhost in estimates.
useSmallerResponses include small responses in throughput estimates.
disableOfflineCheck when set to true, disables the device offline checks when computing the effective connection type or when writing the prefs.

public abstract URLStreamHandlerFactory createURLStreamHandlerFactory ()

Creates a URLStreamHandlerFactory to handle HTTP and HTTPS traffic. An instance of this class can be installed via URL.setURLStreamHandlerFactory(URLStreamHandlerFactory) thus using this CronetEngine by default for all requests created via URL.openConnection().

Cronet does not use certain HTTP features provided via the system:

While Cronet supports and encourages requests using the HTTPS protocol, Cronet does not provide support for the HttpsURLConnection API. This lack of support also includes not using certain HTTPS features provided via the system:

Returns

public int getActiveRequestCount ()

Returns the number of in-flight requests.

A request is in-flight if its start() method has been called but it hasn't reached a final state yet. A request reaches the final state when one of the following callbacks has been called:

  • onSucceeded
  • onCanceled
  • onFailed
Cronet requests's lifecycle for more information.

public int getDownstreamThroughputKbps ()

Returns the downstream throughput estimate (in kilobits per second) computed by the network quality estimator. Set to CONNECTION_METRIC_UNKNOWN if the value is unavailable. This must be called after CronetEngine.Builder.enableNetworkQualityEstimator(boolean), and will throw an exception otherwise.

Returns
  • Estimate of the downstream throughput in kilobits per second.

public int getEffectiveConnectionType ()

Returns an estimate of the effective connection type computed by the network quality estimator. Call CronetEngine.Builder.enableNetworkQualityEstimator(boolean) to begin computing this value.

Returns

public abstract byte[] getGlobalMetricsDeltas ()

Returns differences in metrics collected by Cronet since the last call to this method.

Cronet collects these metrics globally. This means deltas returned by getGlobalMetricsDeltas() will include measurements of requests processed by other CronetEngine instances. Since this function returns differences in metrics collected since the last call, and these metrics are collected globally, a call to any CronetEngine instance's getGlobalMetricsDeltas() method will affect the deltas returned by any other CronetEngine instance's getGlobalMetricsDeltas().

Cronet starts collecting these metrics after the first call to getGlobalMetricsDeltras(), so the first call returns no useful data as no metrics have yet been collected.

Returns
  • differences in metrics collected by Cronet, since the last call to getGlobalMetricsDeltas(), serialized as a protobuf .

public int getHttpRttMs ()

Returns the HTTP RTT estimate (in milliseconds) computed by the network quality estimator. Set to CONNECTION_METRIC_UNKNOWN if the value is unavailable. This must be called after CronetEngine.Builder.enableNetworkQualityEstimator(boolean), and will throw an exception otherwise.

Returns
  • Estimate of the HTTP RTT in milliseconds.

public int getTransportRttMs ()

Returns the transport RTT estimate (in milliseconds) computed by the network quality estimator. Set to CONNECTION_METRIC_UNKNOWN if the value is unavailable. This must be called after CronetEngine.Builder.enableNetworkQualityEstimator(boolean), and will throw an exception otherwise.

Returns
  • Estimate of the transport RTT in milliseconds.

public abstract String getVersionString ()

Returns
  • a human-readable version string of the engine.

public abstract UrlRequest.Builder newUrlRequestBuilder (String url, UrlRequest.Callback callback, Executor executor)

Creates a builder for UrlRequest. All callbacks for generated UrlRequest objects will be invoked on executor's threads. executor must not run tasks on the thread calling Executor.execute(Runnable) to prevent blocking networking operations and causing exceptions during shutdown.

Parameters
url URL for the generated requests.
callback callback object that gets invoked on different events.
executor Executor on which all callbacks will be invoked.

public abstract URLConnection openConnection (URL url)

Establishes a new connection to the resource specified by the URL url.

Note: Cronet's HttpURLConnection implementation is subject to certain limitations, see createURLStreamHandlerFactory() for details.

Parameters
url URL of resource to connect to.
Returns
Throws
IOException if an error occurs while opening the connection.

public void removeRequestFinishedListener (RequestFinishedInfo.Listener listener)

Removes a finished request listener.

Parameters
listener the listener to remove.

public void removeRttListener (NetworkQualityRttListener listener)

Removes a listener of round trip times if previously registered with addRttListener(NetworkQualityRttListener). This should be called after a NetworkQualityRttListener is added in order to stop receiving observations.

Parameters
listener the listener of round trip times.

public void removeThroughputListener (NetworkQualityThroughputListener listener)

Removes a listener of throughput. This should be called after a NetworkQualityThroughputListener is added with addThroughputListener(NetworkQualityThroughputListener) in order to stop receiving observations.

Parameters
listener the listener of throughput.

public abstract void shutdown ()

Shuts down the CronetEngine if there are no active requests, otherwise throws an exception.

Cannot be called on network thread - the thread Cronet calls into Executor on (which is different from the thread the Executor invokes callbacks on). May block until all the CronetEngine's resources have been cleaned up.

public void startNetLogToDisk (String dirPath, boolean logAll, int maxSize)

Starts NetLog logging to a specified directory with a bounded size. The NetLog will contain events emitted by all live CronetEngines. The NetLog is useful for debugging. Once logging has stopped stopNetLog(), the data will be written to netlog.json in dirPath. If logging is interrupted, you can stitch the files found in .inprogress subdirectory manually using: https://chromium.googlesource.com/chromium/src/+/main/net/tools/stitch_net_log_files.py. The log can be viewed using a Chrome browser navigated to chrome://net-internals/#import.

Parameters
dirPath the directory where the netlog.json file will be created. dirPath must already exist. NetLog files must not exist in the directory. If actively logging, this method is ignored.
logAll true to include basic events, user cookies, credentials and all transferred bytes in the log. This option presents a privacy risk, since it exposes the user's credentials, and should only be used with the user's consent and in situations where the log won't be public. false to just include basic events.
maxSize the maximum total disk space in bytes that should be used by NetLog. Actual disk space usage may exceed this limit slightly.

public abstract void startNetLogToFile (String fileName, boolean logAll)

Starts NetLog logging to a file. The NetLog will contain events emitted by all live CronetEngines. The NetLog is useful for debugging. The file can be viewed using a Chrome browser navigated to chrome://net-internals/#import

Parameters
fileName the complete file path. It must not be empty. If the file exists, it is truncated before starting. If actively logging, this method is ignored.
logAll true to include basic events, user cookies, credentials and all transferred bytes in the log. This option presents a privacy risk, since it exposes the user's credentials, and should only be used with the user's consent and in situations where the log won't be public. false to just include basic events.

public abstract void stopNetLog ()

Stops NetLog logging and flushes file to disk. If a logging session is not in progress, this call is ignored.