JavaCronetEngine

public final class JavaCronetEngine extends CronetEngineBase


java.net.HttpURLConnection backed CronetEngine.

Does not support netlogs, transferred data measurement, bidistream, cache, or priority.

Summary

Public constructors

Public methods

void

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

void

Registers a listener that gets called whenever the network quality estimator witnesses a sample round trip time.

void

Registers a listener that gets called whenever the network quality estimator witnesses a sample throughput measurement.

void
bindToNetwork(long networkHandle)

Binds the engine to the specified network handle.

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

Configures the network quality estimator for testing.

ExperimentalUrlRequest
createRequest(
    String url,
    UrlRequest.Callback callback,
    Executor executor,
    int priority,
    Collection<Object> connectionAnnotations,
    boolean disableCache,
    boolean disableConnectionMigration,
    boolean allowDirectExecutor,
    boolean trafficStatsTagSet,
    int trafficStatsTag,
    boolean trafficStatsUidSet,
    int trafficStatsUid,
    RequestFinishedInfo.Listener requestFinishedListener,
    int idempotency,
    long networkHandle,
    String method,
    ArrayList<Map.Entry<StringString>> requestHeaders,
    UploadDataProvider uploadDataProvider,
    Executor uploadDataProviderExecutor,
    byte[] sharedDictionaryHash,
    ByteBuffer sharedDictionary,
    @NonNull String sharedDictionaryId
)
URLStreamHandlerFactory

Creates a URLStreamHandlerFactory to handle HTTP and HTTPS traffic.

int

Returns the number of active requests.

int

Returns the downstream throughput estimate (in kilobits per second) computed by the network quality estimator.

int

Returns an estimate of the effective connection type computed by the network quality estimator.

byte[]

This method is deprecated.

In modern versions of Cronet, this will always return an empty array.

int

Returns the HTTP RTT estimate (in milliseconds) computed by the network quality estimator.

int

Returns the transport RTT estimate (in milliseconds) computed by the network quality estimator.

String
URLConnection

Establishes a new connection to the resource specified by the URLurl.

URLConnection
openConnection(URL url, Proxy proxy)

Establishes a new connection to the resource specified by the URLurl using the given proxy.

void

Removes a finished request listener.

void

Removes a listener of round trip times if previously registered with addRttListener.

void

Removes a listener of throughput.

void

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.

void
startNetLogToFile(String fileName, boolean logAll)

Starts NetLog logging to a file.

void

Stops NetLog logging and flushes file to disk.

Protected methods

ExperimentalBidirectionalStream
createBidirectionalStream(
    String url,
    BidirectionalStream.Callback callback,
    Executor executor,
    String httpMethod,
    List<Map.Entry<StringString>> requestHeaders,
    @CronetEngineBase.StreamPriority int priority,
    boolean delayRequestHeadersUntilFirstFlush,
    Collection<Object> connectionAnnotations,
    boolean trafficStatsTagSet,
    int trafficStatsTag,
    boolean trafficStatsUidSet,
    int trafficStatsUid,
    long networkHandle
)

Inherited Constants

From org.chromium.net.CronetEngine
static final int

The value of the active request count is unknown

From org.chromium.net.impl.CronetEngineBase
static final long

Inherited methods

From org.chromium.net.impl.CronetEngineBase
ExperimentalUrlRequest.Builder
newUrlRequestBuilder(
    String url,
    UrlRequest.Callback callback,
    Executor executor
)

Creates a builder for UrlRequest.

Public constructors

JavaCronetEngine

public JavaCronetEngine(CronetEngineBuilderImpl builder)

Public methods

addRequestFinishedListener

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 java.util.concurrent.Executor provided by the listener.

Parameters
RequestFinishedInfo.Listener listener

the listener for finished requests.

addRttListener

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 enableNetworkQualityEstimator, 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 java.util.concurrent.Executor that is passed to enableNetworkQualityEstimator.

Parameters
NetworkQualityRttListener listener

the listener of round trip times.

addThroughputListener

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 enableNetworkQualityEstimator. 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 java.util.concurrent.Executor that is passed to enableNetworkQualityEstimator.

Parameters
NetworkQualityThroughputListener listener

the listener of throughput.

bindToNetwork

public void bindToNetwork(long networkHandle)

Binds the engine to the specified network handle. All requests created through this engine will use the network associated to this handle. If this network disconnects all requests will fail, the exact error will depend on the stage of request processing when the network disconnects. Network handles can be obtained through Network#getNetworkHandle. Only available starting from Android Marshmallow.

Parameters
long networkHandle

the network handle to bind the engine to. Specify UNBIND_NETWORK_HANDLE to unbind.

configureNetworkQualityEstimatorForTesting

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
boolean useLocalHostRequests

include requests to localhost in estimates.

boolean useSmallerResponses

include small responses in throughput estimates.

boolean disableOfflineCheck

when set to true, disables the device offline checks when computing the effective connection type or when writing the prefs.

createRequest

public ExperimentalUrlRequest createRequest(
    String url,
    UrlRequest.Callback callback,
    Executor executor,
    int priority,
    Collection<Object> connectionAnnotations,
    boolean disableCache,
    boolean disableConnectionMigration,
    boolean allowDirectExecutor,
    boolean trafficStatsTagSet,
    int trafficStatsTag,
    boolean trafficStatsUidSet,
    int trafficStatsUid,
    RequestFinishedInfo.Listener requestFinishedListener,
    int idempotency,
    long networkHandle,
    String method,
    ArrayList<Map.Entry<StringString>> requestHeaders,
    UploadDataProvider uploadDataProvider,
    Executor uploadDataProviderExecutor,
    byte[] sharedDictionaryHash,
    ByteBuffer sharedDictionary,
    @NonNull String sharedDictionaryId
)

createURLStreamHandlerFactory

public URLStreamHandlerFactory createURLStreamHandlerFactory()

Creates a URLStreamHandlerFactory to handle HTTP and HTTPS traffic. An instance of this class can be installed via setURLStreamHandlerFactory thus using this CronetEngine by default for all requests created via 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
URLStreamHandlerFactory

an URLStreamHandlerFactory instance implemented by this CronetEngine.

getActiveRequestCount

public int getActiveRequestCount()

Returns the number of active requests.

A request becomes "active" in UrlRequest.start(), assuming that method does not throw an exception. It becomes inactive when all callbacks have returned and no additional callbacks can be triggered in the future. In practice, that means the request is inactive once onSucceeded/onCanceled/onFailed has returned and all request finished listeners have returned. Cronet requests's lifecycle for more information.

getDownstreamThroughputKbps

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 enableNetworkQualityEstimator, and will throw an exception otherwise.

Returns
int

Estimate of the downstream throughput in kilobits per second.

getEffectiveConnectionType

public int getEffectiveConnectionType()

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

Returns
int

the estimated connection type. The returned value is one of EFFECTIVE_CONNECTION_TYPE_* .

getGlobalMetricsDeltas

public byte[] getGlobalMetricsDeltas()

getHttpRttMs

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 enableNetworkQualityEstimator, and will throw an exception otherwise.

Returns
int

Estimate of the HTTP RTT in milliseconds.

getTransportRttMs

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 enableNetworkQualityEstimator, and will throw an exception otherwise.

Returns
int

Estimate of the transport RTT in milliseconds.

getVersionString

public String getVersionString()
Returns
String

a human-readable version string of the engine.

openConnection

public URLConnection openConnection(URL url)

Establishes a new connection to the resource specified by the URLurl.

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

Parameters
URL url

URL of resource to connect to.

Returns
URLConnection

an java.net.HttpURLConnection instance implemented by this CronetEngine.

Throws
java.io.IOException

if an error occurs while opening the connection.

openConnection

public URLConnection openConnection(URL url, Proxy proxy)

Establishes a new connection to the resource specified by the URLurl using the given proxy.

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

Parameters
URL url

URL of resource to connect to.

Proxy proxy

proxy to use when establishing connection.

Returns
URLConnection

an java.net.HttpURLConnection instance implemented by this CronetEngine.

Throws
java.io.IOException

if an error occurs while opening the connection.

removeRequestFinishedListener

public void removeRequestFinishedListener(RequestFinishedInfo.Listener listener)

Removes a finished request listener.

Parameters
RequestFinishedInfo.Listener listener

the listener to remove.

removeRttListener

public void removeRttListener(NetworkQualityRttListener listener)

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

Parameters
NetworkQualityRttListener listener

the listener of round trip times.

removeThroughputListener

public void removeThroughputListener(NetworkQualityThroughputListener listener)

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

Parameters
NetworkQualityThroughputListener listener

the listener of throughput.

shutdown

public 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.

startNetLogToDisk

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
String 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.

boolean 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.

int maxSize

the maximum total disk space in bytes that should be used by NetLog. Actual disk space usage may exceed this limit slightly.

startNetLogToFile

public 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
String 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.

boolean 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.

stopNetLog

public void stopNetLog()

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

Protected methods

createBidirectionalStream

protected ExperimentalBidirectionalStream createBidirectionalStream(
    String url,
    BidirectionalStream.Callback callback,
    Executor executor,
    String httpMethod,
    List<Map.Entry<StringString>> requestHeaders,
    @CronetEngineBase.StreamPriority int priority,
    boolean delayRequestHeadersUntilFirstFlush,
    Collection<Object> connectionAnnotations,
    boolean trafficStatsTagSet,
    int trafficStatsTag,
    boolean trafficStatsUidSet,
    int trafficStatsUid,
    long networkHandle
)