audienceproject / audienceproject/userreport-android-sdk
Calling `setAnonymousTracking` from non-main thread results in an `IllegalStateException` crash on Android 8
- Dominant language
- Java
- Stars
- 3
- Forks
- 2
- PR merge metrics
- No merged PRs in 30d
Description
I have some code that listens for data changes within a flow in a coroutine on the `IO` dispatcher.
When the flow emits something, I call `setAnonymousTracking()` based on this data, which ends up calling `userReport.setAnonymousTracking(enabled)` in the end.
It turns out that this call has to be made from the main thread, otherwise I get an `IllegalStateException` with the message:
> Fatal Exception: java.lang.IllegalStateException
> Calling View methods on another thread than the UI thread.
Stack traceback after calling the API function:
```
com.android.webview.chromium.WebViewChromium.a (chromium-Monochrome.aab-stable-720417920:12)
android.webkit.WebView. (WebView.java:548)
com.audienceproject.userreport.InAppEventsTrack.getUserAgentString (InAppEventsTrack.java:227)
com.audienceproject.userreport.InAppEventsTrack. (InAppEventsTrack.java:65)
com.audienceproject.userreport.UserReport.initTracker (UserReport.java:130)
com.audienceproject.userreport.UserReport.init (UserReport.java:94)
com.audienceproject.userreport.UserReport. (UserReport.java:56)
com.audienceproject.userreport.UserReport.configure (UserReport.java:67)
com.audienceproject.userreport.UserReport.configure (UserReport.java:85)
```
There is no mention in the documentation that this needs to be called from the main thread. I also don't currently have an explanation for why only Android 8 has the crashes.
To fix it, I wrapped the call in `withContext(Dispatchers.Main)`.
This is where the WebView is created by the SDK and ends up crashing on Android 8:
```
private String getUserAgentString(Context context) {
try {
return new WebView(context).getSettings().getUserAgentString();
} catch (Exception ex) {
return null; // exception might appear if there is no google APIs
}
}
```
Contributor guide
No contributing guide indexed for this repository
Research direction
Start with InAppEventsTrack.getUserAgentString, where the payload shows a WebView is created, and trace the call through UserReport.initTracker, UserReport.init, and UserReport.configure. Reproduce setAnonymousTracking from a non-main thread on Android 8, then verify that the SDK no longer crashes while preserving the existing tracking behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- android, java
- Domain
- mobile
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 55/100