Skip to content

Commit

Permalink
Add a precondition check for not main thread (#6204)
Browse files Browse the repository at this point in the history
Add a precondition check for not main thread. This is more useful when
we just want to enforce not main thread, not a specific thread.
  • Loading branch information
mrober committed Aug 22, 2024
1 parent a2261d8 commit e896ac4
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,6 @@ private static String formatId(@NonNull String id) {
@Override
@NonNull
public synchronized InstallIds getInstallIds() {
CrashlyticsWorkers.checkBackgroundThread();
if (!shouldRefresh()) {
return installIds;
}
Expand Down Expand Up @@ -183,7 +182,7 @@ private String readCachedCrashlyticsInstallId(SharedPreferences prefs) {
*/
@NonNull
public FirebaseInstallationId fetchTrueFid(boolean validate) {
CrashlyticsWorkers.checkBackgroundThread(); // This fetch blocks, never do it on main.
CrashlyticsWorkers.checkNotMainThread(); // This fetch blocks, never do it on main.
String fid = null;
String authToken = null;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

package com.google.firebase.crashlytics.internal.concurrency

import android.os.Build
import android.os.Looper
import com.google.firebase.crashlytics.internal.Logger
import java.util.concurrent.ExecutorService

Expand Down Expand Up @@ -59,6 +61,12 @@ class CrashlyticsWorkers(
/** When enabled, failed preconditions will cause assertion errors for debugging. */
@JvmStatic var enforcement: Boolean = false

@JvmStatic
fun checkNotMainThread() =
checkThread(::isNotMainThread) {
"Must not be called on a main thread, was called on $threadName."
}

@JvmStatic
fun checkBlockingThread() =
checkThread(::isBlockingThread) {
Expand All @@ -71,6 +79,13 @@ class CrashlyticsWorkers(
"Must be called on a background thread, was called on $threadName."
}

private fun isNotMainThread() =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
!Looper.getMainLooper().isCurrentThread
} else {
Looper.getMainLooper() != Looper.myLooper()
}

private fun isBlockingThread() = threadName.contains("Firebase Blocking Thread #")

private fun isBackgroundThread() = threadName.contains("Firebase Background Thread #")
Expand Down

0 comments on commit e896ac4

Please sign in to comment.