From 376347014c7b2bb2f272e7aaea672ba83d57d4ab Mon Sep 17 00:00:00 2001 From: tusharkhandelwal8 Date: Wed, 7 May 2025 01:18:21 +0530 Subject: [PATCH] Fix NetworkOnMainThreadException for API levels below 26 --- firebase-config/CHANGELOG.md | 4 ++-- .../internal/ConfigRealtimeHttpClient.java | 10 ++++++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/firebase-config/CHANGELOG.md b/firebase-config/CHANGELOG.md index 817300f7cdd..5a16896e061 100644 --- a/firebase-config/CHANGELOG.md +++ b/firebase-config/CHANGELOG.md @@ -1,8 +1,8 @@ # Unreleased - +* [fixed] Fixed `NetworkOnMainThreadException` on Android versions below 8 by disconnecting HttpURLConnection only on API levels 26 and higher. # 22.1.1 -[fixed] Fixed an issue where the connection to the real-time Remote Config backend could remain +* [fixed] Fixed an issue where the connection to the real-time Remote Config backend could remain open in the background. diff --git a/firebase-config/src/main/java/com/google/firebase/remoteconfig/internal/ConfigRealtimeHttpClient.java b/firebase-config/src/main/java/com/google/firebase/remoteconfig/internal/ConfigRealtimeHttpClient.java index ef082d21086..7be3ef97136 100644 --- a/firebase-config/src/main/java/com/google/firebase/remoteconfig/internal/ConfigRealtimeHttpClient.java +++ b/firebase-config/src/main/java/com/google/firebase/remoteconfig/internal/ConfigRealtimeHttpClient.java @@ -22,6 +22,7 @@ import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageManager; +import android.os.Build; import android.util.Log; import androidx.annotation.GuardedBy; import androidx.annotation.NonNull; @@ -409,8 +410,13 @@ public void setIsInBackground(boolean isInBackground) { } // Close the connection if the app is in the background and there is an active // HttpUrlConnection. - if (isInBackground && httpURLConnection != null) { - httpURLConnection.disconnect(); + // This is now only done on Android versions >= O (API 26) because + // on older versions, background detection callbacks run on the main thread, which + // could lead to a NetworkOnMainThreadException when disconnecting the connection. + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + if (isInBackground && httpURLConnection != null) { + httpURLConnection.disconnect(); + } } } }