@@ -10,20 +10,21 @@ import kotlinx.coroutines.*
10
10
import java.lang.reflect.*
11
11
import kotlin.coroutines.*
12
12
13
- private val getter by lazy {
14
- try {
15
- Thread ::class .java.getDeclaredMethod(" getUncaughtExceptionPreHandler" ).takeIf {
16
- Modifier .isPublic(it.modifiers) && Modifier .isStatic(it.modifiers)
17
- }
18
- } catch (e: Throwable ) {
19
- null /* not found */
20
- }
21
- }
22
-
23
13
@Keep
24
14
internal class AndroidExceptionPreHandler :
25
- AbstractCoroutineContextElement (CoroutineExceptionHandler ), CoroutineExceptionHandler
26
- {
15
+ AbstractCoroutineContextElement (CoroutineExceptionHandler ), CoroutineExceptionHandler , Function0 <Method ?> {
16
+
17
+ private val preHandler by lazy(this )
18
+
19
+ // Reflectively lookup pre-handler. Implement Function0 to avoid generating second class for lambda
20
+ override fun invoke (): Method ? = try {
21
+ Thread ::class .java.getDeclaredMethod(" getUncaughtExceptionPreHandler" ).takeIf {
22
+ Modifier .isPublic(it.modifiers) && Modifier .isStatic(it.modifiers)
23
+ }
24
+ } catch (e: Throwable ) {
25
+ null /* not found */
26
+ }
27
+
27
28
override fun handleException (context : CoroutineContext , exception : Throwable ) {
28
29
/*
29
30
* If we are on old SDK, then use Android's `Thread.getUncaughtExceptionPreHandler()` that ensures that
@@ -38,8 +39,8 @@ internal class AndroidExceptionPreHandler :
38
39
if (Build .VERSION .SDK_INT >= 28 ) {
39
40
thread.uncaughtExceptionHandler.uncaughtException(thread, exception)
40
41
} else {
41
- (getter ?.invoke(null ) as ? Thread .UncaughtExceptionHandler )
42
+ (preHandler ?.invoke(null ) as ? Thread .UncaughtExceptionHandler )
42
43
?.uncaughtException(thread, exception)
43
44
}
44
45
}
45
- }
46
+ }
0 commit comments