pariola
pariola

Reputation: 929

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 want it to fail whenever the network fails.

Upvotes: 1

Views: 1129

Answers (1)

earthw0rmjim
earthw0rmjim

Reputation: 19427

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();
}

// ...

Upvotes: 4

Related Questions