Skip to content

Commit 548dc28

Browse files
Fix NetworkOnMainThreadException for API levels below 26 (#6940)
This change addresses a ``NetworkOnMainThreadException`` that was observed on Android API levels below 26. The crash happened during background transitions when disconnecting an ``HttpURLConnection`` because background callbacks on these older OS versions could run on the main thread. The fix restricts the disconnect logic to run only on API level 26 (Android 8.0) and higher.
1 parent 88f50d5 commit 548dc28

File tree

2 files changed

+10
-4
lines changed

2 files changed

+10
-4
lines changed

firebase-config/CHANGELOG.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
# Unreleased
2-
2+
* [fixed] Fixed `NetworkOnMainThreadException` on Android versions below 8 by disconnecting HttpURLConnection only on API levels 26 and higher.
33

44
# 22.1.1
5-
[fixed] Fixed an issue where the connection to the real-time Remote Config backend could remain
5+
* [fixed] Fixed an issue where the connection to the real-time Remote Config backend could remain
66
open in the background.
77

88

firebase-config/src/main/java/com/google/firebase/remoteconfig/internal/ConfigRealtimeHttpClient.java

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import android.annotation.SuppressLint;
2323
import android.content.Context;
2424
import android.content.pm.PackageManager;
25+
import android.os.Build;
2526
import android.util.Log;
2627
import androidx.annotation.GuardedBy;
2728
import androidx.annotation.NonNull;
@@ -409,8 +410,13 @@ public void setIsInBackground(boolean isInBackground) {
409410
}
410411
// Close the connection if the app is in the background and there is an active
411412
// HttpUrlConnection.
412-
if (isInBackground && httpURLConnection != null) {
413-
httpURLConnection.disconnect();
413+
// This is now only done on Android versions >= O (API 26) because
414+
// on older versions, background detection callbacks run on the main thread, which
415+
// could lead to a NetworkOnMainThreadException when disconnecting the connection.
416+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
417+
if (isInBackground && httpURLConnection != null) {
418+
httpURLConnection.disconnect();
419+
}
414420
}
415421
}
416422
}

0 commit comments

Comments
 (0)