Coded Phoenix Coded Phoenix - 3 months ago 35
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

Request
and it is still running and i off my data or internet access the
Request
still keeps on running and doesn't stop (i.e No
Callback
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)
.build();

Request req = new Request.Builder()
.url("<url>")
.build();

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

@Override
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

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() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getBooleanExtra(
                ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) {

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

// ...

@Override
protected void onResume() {
    super.onResume();
    registerReceiver(networkChangeReceiver,
        new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}

@Override
protected void onPause() {
    unregisterReceiver(networkChangeReceiver);
    super.onPause();
}

// ...