Skip to content

Commit fe30606

Browse files
authored
Add main flag to threads and in_foreground flag for app contexts (#2516)
1 parent 03c5163 commit fe30606

18 files changed

Lines changed: 201 additions & 39 deletions

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22

33
## Unreleased
44

5+
### Features
6+
7+
- Add `main` flag to threads and `in_foreground` flag for app contexts ([#2516](https://github.com/getsentry/sentry-java/pull/2516))
8+
59
### Fixes
610

711
- Ignore Shutdown in progress when closing ShutdownHookIntegration ([#2521](https://github.com/getsentry/sentry-java/pull/2521))

‎sentry-android-core/src/main/java/io/sentry/android/core/DefaultAndroidEventProcessor.java‎

Lines changed: 51 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ public DefaultAndroidEventProcessor(
9393
this.options = Objects.requireNonNull(options, "The options object is required.");
9494

9595
ExecutorService executorService = Executors.newSingleThreadExecutor();
96-
// dont ref. to method reference, theres a bug on it
96+
// don't ref. to method reference, theres a bug on it
9797
//noinspection Convert2MethodRef
9898
contextData = executorService.submit(() -> loadContextData());
9999

@@ -128,8 +128,8 @@ public DefaultAndroidEventProcessor(
128128
// we only set memory data if it's not a hard crash, when it's a hard crash the event is
129129
// enriched on restart, so non static data might be wrong, eg lowMemory or availMem will
130130
// be different if the App. crashes because of OOM.
131-
processNonCachedEvent(event);
132-
setThreads(event);
131+
processNonCachedEvent(event, hint);
132+
setThreads(event, hint);
133133
}
134134

135135
setCommons(event, true, applyScopeData);
@@ -201,23 +201,34 @@ private void mergeOS(final @NotNull SentryBaseEvent event) {
201201
}
202202

203203
// Data to be applied to events that was created in the running process
204-
private void processNonCachedEvent(final @NotNull SentryBaseEvent event) {
204+
private void processNonCachedEvent(
205+
final @NotNull SentryBaseEvent event, final @NotNull Hint hint) {
205206
App app = event.getContexts().getApp();
206207
if (app == null) {
207208
app = new App();
208209
}
209-
setAppExtras(app);
210+
setAppExtras(app, hint);
210211

211212
setPackageInfo(event, app);
212213

213214
event.getContexts().setApp(app);
214215
}
215216

216-
private void setThreads(final @NotNull SentryEvent event) {
217+
private void setThreads(final @NotNull SentryEvent event, final @NotNull Hint hint) {
217218
if (event.getThreads() != null) {
218-
for (SentryThread thread : event.getThreads()) {
219+
final boolean isHybridSDK = HintUtils.isFromHybridSdk(hint);
220+
221+
for (final SentryThread thread : event.getThreads()) {
222+
final boolean isMainThread = AndroidMainThreadChecker.getInstance().isMainThread(thread);
223+
224+
// TODO: Fix https://github.com/getsentry/team-mobile/issues/47
219225
if (thread.isCurrent() == null) {
220-
thread.setCurrent(AndroidMainThreadChecker.getInstance().isMainThread(thread));
226+
thread.setCurrent(isMainThread);
227+
}
228+
229+
// This should not be set by Hybrid SDKs since they have their own threading model
230+
if (!isHybridSDK && thread.isMain() == null) {
231+
thread.setMain(isMainThread);
221232
}
222233
}
223234
}
@@ -241,9 +252,19 @@ private void setDist(final @NotNull SentryBaseEvent event, final @NotNull String
241252
}
242253
}
243254

244-
private void setAppExtras(final @NotNull App app) {
255+
private void setAppExtras(final @NotNull App app, final @NotNull Hint hint) {
245256
app.setAppName(getApplicationName());
246257
app.setAppStartTime(DateUtils.toUtilDate(AppStartState.getInstance().getAppStartTime()));
258+
259+
// This should not be set by Hybrid SDKs since they have their own app's lifecycle
260+
if (!HintUtils.isFromHybridSdk(hint) && app.getInForeground() == null) {
261+
// This feature depends on the AppLifecycleIntegration being installed, so only if
262+
// enableAutoSessionTracking or enableAppLifecycleBreadcrumbs are enabled.
263+
final @Nullable Boolean isBackground = AppState.getInstance().isInBackground();
264+
if (isBackground != null) {
265+
app.setInForeground(!isBackground);
266+
}
267+
}
247268
}
248269

249270
@SuppressWarnings("deprecation")
@@ -256,21 +277,21 @@ private void setAppExtras(final @NotNull App app) {
256277
return Build.CPU_ABI2;
257278
}
258279

259-
@SuppressWarnings({"ObsoleteSdkInt", "deprecation"})
280+
@SuppressWarnings({"ObsoleteSdkInt", "deprecation", "NewApi"})
260281
private void setArchitectures(final @NotNull Device device) {
261-
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
262-
String[] supportedAbis = Build.SUPPORTED_ABIS;
263-
device.setArchs(supportedAbis);
282+
final String[] supportedAbis;
283+
if (buildInfoProvider.getSdkInfoVersion() >= Build.VERSION_CODES.LOLLIPOP) {
284+
supportedAbis = Build.SUPPORTED_ABIS;
264285
} else {
265-
String[] supportedAbis = {getAbi(), getAbi2()};
266-
device.setArchs(supportedAbis);
286+
supportedAbis = new String[] {getAbi(), getAbi2()};
267287
// we were not checking CPU_ABI2, but I've added to the list now
268288
}
289+
device.setArchs(supportedAbis);
269290
}
270291

271-
@SuppressWarnings("ObsoleteSdkInt")
292+
@SuppressWarnings({"ObsoleteSdkInt", "NewApi"})
272293
private @NotNull Long getMemorySize(final @NotNull ActivityManager.MemoryInfo memInfo) {
273-
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
294+
if (buildInfoProvider.getSdkInfoVersion() >= Build.VERSION_CODES.JELLY_BEAN) {
274295
return memInfo.totalMem;
275296
}
276297
// using Runtime as a fallback
@@ -393,17 +414,18 @@ private void setDeviceIO(final @NotNull Device device, final boolean applyScopeD
393414
}
394415
}
395416

396-
@SuppressWarnings("ObsoleteSdkInt")
417+
@SuppressWarnings({"ObsoleteSdkInt", "NewApi"})
397418
private @Nullable String getDeviceName() {
398-
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
419+
if (buildInfoProvider.getSdkInfoVersion() >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
399420
return Settings.Global.getString(context.getContentResolver(), "device_name");
400421
} else {
401422
return null;
402423
}
403424
}
404425

426+
@SuppressWarnings("NewApi")
405427
private TimeZone getTimeZone() {
406-
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
428+
if (buildInfoProvider.getSdkInfoVersion() >= Build.VERSION_CODES.N) {
407429
LocaleList locales = context.getResources().getConfiguration().getLocales();
408430
if (!locales.isEmpty()) {
409431
Locale locale = locales.get(0);
@@ -557,9 +579,9 @@ private TimeZone getTimeZone() {
557579
}
558580
}
559581

560-
@SuppressWarnings("ObsoleteSdkInt")
582+
@SuppressWarnings({"ObsoleteSdkInt", "NewApi"})
561583
private long getBlockSizeLong(final @NotNull StatFs stat) {
562-
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
584+
if (buildInfoProvider.getSdkInfoVersion() >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
563585
return stat.getBlockSizeLong();
564586
}
565587
return getBlockSizeDep(stat);
@@ -570,9 +592,9 @@ private int getBlockSizeDep(final @NotNull StatFs stat) {
570592
return stat.getBlockSize();
571593
}
572594

573-
@SuppressWarnings("ObsoleteSdkInt")
595+
@SuppressWarnings({"ObsoleteSdkInt", "NewApi"})
574596
private long getBlockCountLong(final @NotNull StatFs stat) {
575-
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
597+
if (buildInfoProvider.getSdkInfoVersion() >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
576598
return stat.getBlockCountLong();
577599
}
578600
return getBlockCountDep(stat);
@@ -583,9 +605,9 @@ private int getBlockCountDep(final @NotNull StatFs stat) {
583605
return stat.getBlockCount();
584606
}
585607

586-
@SuppressWarnings("ObsoleteSdkInt")
608+
@SuppressWarnings({"ObsoleteSdkInt", "NewApi"})
587609
private long getAvailableBlocksLong(final @NotNull StatFs stat) {
588-
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
610+
if (buildInfoProvider.getSdkInfoVersion() >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
589611
return stat.getAvailableBlocksLong();
590612
}
591613
return getAvailableBlocksDep(stat);
@@ -627,9 +649,9 @@ private int getAvailableBlocksDep(final @NotNull StatFs stat) {
627649
return null;
628650
}
629651

630-
@SuppressWarnings("ObsoleteSdkInt")
652+
@SuppressWarnings({"ObsoleteSdkInt", "NewApi"})
631653
private @Nullable File[] getExternalFilesDirs() {
632-
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
654+
if (buildInfoProvider.getSdkInfoVersion() >= Build.VERSION_CODES.KITKAT) {
633655
return context.getExternalFilesDirs(null);
634656
} else {
635657
File single = context.getExternalFilesDir(null);
@@ -907,7 +929,7 @@ private void setSideLoadedInfo(final @NotNull SentryBaseEvent event) {
907929
final boolean applyScopeData = shouldApplyScopeData(transaction, hint);
908930

909931
if (applyScopeData) {
910-
processNonCachedEvent(transaction);
932+
processNonCachedEvent(transaction, hint);
911933
}
912934

913935
setCommons(transaction, false, applyScopeData);

‎sentry-android-core/src/main/java/io/sentry/android/core/LifecycleWatcher.java‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,9 @@ final class LifecycleWatcher implements DefaultLifecycleObserver {
6767
public void onStart(final @NotNull LifecycleOwner owner) {
6868
startSession();
6969
addAppBreadcrumb("foreground");
70+
71+
// Consider using owner.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED);
72+
// in the future.
7073
AppState.getInstance().setInBackground(false);
7174
}
7275

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
package io.sentry.android.core
2+
3+
import io.sentry.hints.ApplyScopeData
4+
import io.sentry.hints.Cached
5+
6+
class CustomCachedApplyScopeDataHint : Cached, ApplyScopeData

‎sentry-android-core/src/test/java/io/sentry/android/core/DefaultAndroidEventProcessorTest.kt‎

Lines changed: 57 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import io.sentry.SentryEvent
1212
import io.sentry.SentryLevel
1313
import io.sentry.SentryTracer
1414
import io.sentry.TransactionContext
15+
import io.sentry.TypeCheckHint.SENTRY_DART_SDK_NAME
1516
import io.sentry.android.core.DefaultAndroidEventProcessor.EMULATOR
1617
import io.sentry.android.core.DefaultAndroidEventProcessor.KERNEL_VERSION
1718
import io.sentry.android.core.DefaultAndroidEventProcessor.ROOTED
@@ -56,7 +57,7 @@ class DefaultAndroidEventProcessorTest {
5657
private class Fixture {
5758
val buildInfo = mock<BuildInfoProvider>()
5859
val options = SentryAndroidOptions().apply {
59-
setDebug(true)
60+
isDebug = true
6061
setLogger(mock())
6162
sdkVersion = SdkVersion("test", "1.2.3")
6263
}
@@ -77,6 +78,7 @@ class DefaultAndroidEventProcessorTest {
7778
@BeforeTest
7879
fun `set up`() {
7980
context = ApplicationProvider.getApplicationContext()
81+
AppState.getInstance().resetInstance()
8082
}
8183

8284
@Test
@@ -161,7 +163,7 @@ class DefaultAndroidEventProcessorTest {
161163
}
162164

163165
@Test
164-
fun `Current should be true if it comes from main thread`() {
166+
fun `Current and Main should be true if it comes from main thread`() {
165167
val sut = fixture.getSut(context)
166168

167169
val sentryThread = SentryThread().apply {
@@ -174,6 +176,7 @@ class DefaultAndroidEventProcessorTest {
174176
assertNotNull(sut.process(event, Hint())) {
175177
assertNotNull(it.threads) { threads ->
176178
assertTrue(threads.first().isCurrent == true)
179+
assertTrue(threads.first().isMain == true)
177180
}
178181
}
179182
}
@@ -193,6 +196,7 @@ class DefaultAndroidEventProcessorTest {
193196
assertNotNull(sut.process(event, Hint())) {
194197
assertNotNull(it.threads) { threads ->
195198
assertFalse(threads.first().isCurrent == true)
199+
assertFalse(threads.first().isMain == true)
196200
}
197201
}
198202
}
@@ -497,4 +501,55 @@ class DefaultAndroidEventProcessorTest {
497501
assertEquals("en_US", device.locale)
498502
}
499503
}
504+
505+
@Test
506+
fun `Event sets InForeground to true if not in the background`() {
507+
val sut = fixture.getSut(context)
508+
509+
AppState.getInstance().setInBackground(false)
510+
511+
assertNotNull(sut.process(SentryEvent(), Hint())) {
512+
val app = it.contexts.app!!
513+
assertTrue(app.inForeground!!)
514+
}
515+
}
516+
517+
@Test
518+
fun `Event sets InForeground to false if in the background`() {
519+
val sut = fixture.getSut(context)
520+
521+
AppState.getInstance().setInBackground(true)
522+
523+
assertNotNull(sut.process(SentryEvent(), Hint())) {
524+
val app = it.contexts.app!!
525+
assertFalse(app.inForeground!!)
526+
}
527+
}
528+
529+
@Test
530+
fun `Events from HybridSDKs don't set main thread and in foreground context`() {
531+
val sut = fixture.getSut(context)
532+
533+
val cachedHint = CustomCachedApplyScopeDataHint()
534+
val hint = HintUtils.createWithTypeCheckHint(cachedHint)
535+
536+
val sdkVersion = SdkVersion(SENTRY_DART_SDK_NAME, "1.0.0")
537+
val event = SentryEvent().apply {
538+
sdk = sdkVersion
539+
threads = mutableListOf(
540+
SentryThread().apply {
541+
id = 10L
542+
}
543+
)
544+
}
545+
// set by OutboxSender during event deserialization
546+
HintUtils.setIsFromHybridSdk(hint, sdkVersion.name)
547+
548+
assertNotNull(sut.process(event, hint)) {
549+
val app = it.contexts.app!!
550+
assertNull(app.inForeground)
551+
val thread = it.threads!!.first()
552+
assertNull(thread.isMain)
553+
}
554+
}
500555
}

‎sentry/api/sentry.api‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2510,6 +2510,7 @@ public final class io/sentry/protocol/App : io/sentry/JsonSerializable, io/sentr
25102510
public fun getAppVersion ()Ljava/lang/String;
25112511
public fun getBuildType ()Ljava/lang/String;
25122512
public fun getDeviceAppHash ()Ljava/lang/String;
2513+
public fun getInForeground ()Ljava/lang/Boolean;
25132514
public fun getPermissions ()Ljava/util/Map;
25142515
public fun getUnknown ()Ljava/util/Map;
25152516
public fun serialize (Lio/sentry/JsonObjectWriter;Lio/sentry/ILogger;)V
@@ -2520,6 +2521,7 @@ public final class io/sentry/protocol/App : io/sentry/JsonSerializable, io/sentr
25202521
public fun setAppVersion (Ljava/lang/String;)V
25212522
public fun setBuildType (Ljava/lang/String;)V
25222523
public fun setDeviceAppHash (Ljava/lang/String;)V
2524+
public fun setInForeground (Ljava/lang/Boolean;)V
25232525
public fun setPermissions (Ljava/util/Map;)V
25242526
public fun setUnknown (Ljava/util/Map;)V
25252527
}
@@ -2539,6 +2541,7 @@ public final class io/sentry/protocol/App$JsonKeys {
25392541
public static final field APP_VERSION Ljava/lang/String;
25402542
public static final field BUILD_TYPE Ljava/lang/String;
25412543
public static final field DEVICE_APP_HASH Ljava/lang/String;
2544+
public static final field IN_FOREGROUND Ljava/lang/String;
25422545
public fun <init> ()V
25432546
}
25442547

@@ -3344,11 +3347,13 @@ public final class io/sentry/protocol/SentryThread : io/sentry/JsonSerializable,
33443347
public fun isCrashed ()Ljava/lang/Boolean;
33453348
public fun isCurrent ()Ljava/lang/Boolean;
33463349
public fun isDaemon ()Ljava/lang/Boolean;
3350+
public fun isMain ()Ljava/lang/Boolean;
33473351
public fun serialize (Lio/sentry/JsonObjectWriter;Lio/sentry/ILogger;)V
33483352
public fun setCrashed (Ljava/lang/Boolean;)V
33493353
public fun setCurrent (Ljava/lang/Boolean;)V
33503354
public fun setDaemon (Ljava/lang/Boolean;)V
33513355
public fun setId (Ljava/lang/Long;)V
3356+
public fun setMain (Ljava/lang/Boolean;)V
33523357
public fun setName (Ljava/lang/String;)V
33533358
public fun setPriority (Ljava/lang/Integer;)V
33543359
public fun setStacktrace (Lio/sentry/protocol/SentryStackTrace;)V
@@ -3367,6 +3372,7 @@ public final class io/sentry/protocol/SentryThread$JsonKeys {
33673372
public static final field CURRENT Ljava/lang/String;
33683373
public static final field DAEMON Ljava/lang/String;
33693374
public static final field ID Ljava/lang/String;
3375+
public static final field MAIN Ljava/lang/String;
33703376
public static final field NAME Ljava/lang/String;
33713377
public static final field PRIORITY Ljava/lang/String;
33723378
public static final field STACKTRACE Ljava/lang/String;

0 commit comments

Comments
 (0)