File tree Expand file tree Collapse file tree 2 files changed +37
-4
lines changed
main/java/io/sentry/android/core/internal/util
test/java/io/sentry/android/core/internal/util Expand file tree Collapse file tree 2 files changed +37
-4
lines changed Original file line number Diff line number Diff line change @@ -13,9 +13,11 @@ public <T> T runWithRelaxedPolicy(final @NotNull IRuntimeManagerCallback<T> toRu
1313 final @ NotNull StrictMode .VmPolicy oldVmPolicy = StrictMode .getVmPolicy ();
1414 StrictMode .setThreadPolicy (StrictMode .ThreadPolicy .LAX );
1515 StrictMode .setVmPolicy (StrictMode .VmPolicy .LAX );
16- final @ NotNull T t = toRun .run ();
17- StrictMode .setThreadPolicy (oldPolicy );
18- StrictMode .setVmPolicy (oldVmPolicy );
19- return t ;
16+ try {
17+ return toRun .run ();
18+ } finally {
19+ StrictMode .setThreadPolicy (oldPolicy );
20+ StrictMode .setVmPolicy (oldVmPolicy );
21+ }
2022 }
2123}
Original file line number Diff line number Diff line change @@ -53,4 +53,35 @@ class AndroidRuntimeManagerTest {
5353 // Ensure the code ran
5454 assertTrue(called)
5555 }
56+
57+ @Test
58+ fun `runWithRelaxedPolicy changes policy and restores it afterwards even if the code throws` () {
59+ var called = false
60+ val threadPolicy = StrictMode .ThreadPolicy .Builder ().detectAll().penaltyDeath().build()
61+ val vmPolicy = StrictMode .VmPolicy .Builder ().detectAll().penaltyDeath().build()
62+
63+ // Set and assert the StrictMode policies
64+ StrictMode .setThreadPolicy(threadPolicy)
65+ StrictMode .setVmPolicy(vmPolicy)
66+
67+ // Run the function and assert LAX policies
68+ try {
69+ sut.runWithRelaxedPolicy {
70+ assertEquals(
71+ StrictMode .ThreadPolicy .LAX .toString(),
72+ StrictMode .getThreadPolicy().toString(),
73+ )
74+ assertEquals(StrictMode .VmPolicy .LAX .toString(), StrictMode .getVmPolicy().toString())
75+ called = true
76+ throw Exception (" Test exception" )
77+ }
78+ } catch (_: Exception ) {}
79+
80+ // Policies should be reverted back
81+ assertEquals(threadPolicy.toString(), StrictMode .getThreadPolicy().toString())
82+ assertEquals(vmPolicy.toString(), StrictMode .getVmPolicy().toString())
83+
84+ // Ensure the code ran
85+ assertTrue(called)
86+ }
5687}
You can’t perform that action at this time.
0 commit comments