From 91bd4d08f1eaff9c2c547f0c5846774b60f19b65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20H=C3=B6nig?= Date: Thu, 21 Jun 2018 15:33:02 +0200 Subject: [PATCH] networking: Fix requests failing when turning network off and on (#19709). This bug is probably actually a bug in OkHttp: https://github.com/square/okhttp/issues/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. --- .../com/facebook/react/ReactActivity.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java b/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java index bbe9cad4473816..9483040b7eac5d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java +++ b/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java @@ -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. @@ -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