Coded Phoenix Coded Phoenix - 1 year ago 97
Android Question

OkHttp Request keeps running even when network fails

I am using OkHttp3 as my client and i noticed this behavior:
Whenever i start a

and it is still running and i off my data or internet access the
still keeps on running and doesn't stop (i.e No
is called)

I wrote my code like this:

final OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)

Request req = new Request.Builder()

client.newCall(req).enqueue(new Callback() {
public void onFailure(Call call, IOException e) {
Log.d(TAG, "Failed");

public void onResponse(Call call, okhttp3.Response response) throws IOException {
Log.d(TAG, "Response");

How can i stop this?

Because i wan't it to fail whenever the network fails.

Answer Source

You could register for the ConnectivityManager.CONNECTIVITY_ACTION broadcast, so you can get notified when there is no network connection and cancel your requests.

From its documentation:

For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY is set to true if there are no connected networks at all.

For example, in your Activity you could do something like this:

// ...

private OkHttpClient client;

private final BroadcastReceiver networkChangeReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
                ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) {

            // no network connection
            if(client != null && client.dispatcher() != null) {

// ...

protected void onResume() {
        new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

protected void onPause() {

// ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download