Skip to content

Commit

Permalink
networking: Fix requests failing when turning network off and on (fac…
Browse files Browse the repository at this point in the history
…ebook#19709).

This bug is probably actually a bug in OkHttp: square/okhttp#4079
Both issues linked above contain extensive details about the issue, its likely origins and
how to reproduce it. A short summary of the issue and the fix in this commit:

On Android, disconnecting from the network somehow corrupts the idle connections in okhttp
clients. New requests made over these clients fail. This commit works around that bug by
clearing the idle connection pool when Android disconnects from the network.
  • Loading branch information
roberthoenig committed Jun 21, 2018
1 parent d2dd7e9 commit 91bd4d0
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,20 @@
import javax.annotation.Nullable;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;

import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.modules.core.PermissionAwareActivity;
import com.facebook.react.modules.core.PermissionListener;
import com.facebook.react.modules.network.OkHttpClientProvider;

/**
* Base Activity for React Native applications.
Expand Down Expand Up @@ -46,10 +53,33 @@ protected ReactActivityDelegate createReactActivityDelegate() {
return new ReactActivityDelegate(this, getMainComponentName());
}

private class EvictIdleConnectionsTask extends AsyncTask {
@Override
protected Object doInBackground(Object[] objects) {
OkHttpClientProvider.getOkHttpClient().connectionPool().evictAll();
return null;
}
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDelegate.onCreate(savedInstanceState);

BroadcastReceiver br = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
NetworkInfo info = extras.getParcelable("networkInfo");
NetworkInfo.State state = info.getState();
if (state == NetworkInfo.State.DISCONNECTED) {
new EvictIdleConnectionsTask().execute();
}
}
};
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
getApplicationContext().registerReceiver(br, intentFilter);
}

@Override
Expand Down

0 comments on commit 91bd4d0

Please sign in to comment.