Skip to content

Fix NetworkOnMainThreadException for API levels below 26 #6940

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions firebase-config/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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();
}
}
}
}
Expand Down
Loading