From 907283c53a1234b4561df295be4a469f9d989226 Mon Sep 17 00:00:00 2001 From: Mygod Date: Fri, 11 Jun 2021 00:49:54 -0400 Subject: [PATCH] Be more careful about using unsupported APIs --- .../be/mygod/vpnhotspot/net/wifi/WifiApManager.kt | 4 ++++ .../src/main/java/be/mygod/vpnhotspot/util/Utils.kt | 12 ++++++++---- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/mobile/src/main/java/be/mygod/vpnhotspot/net/wifi/WifiApManager.kt b/mobile/src/main/java/be/mygod/vpnhotspot/net/wifi/WifiApManager.kt index 69715336..82234eed 100644 --- a/mobile/src/main/java/be/mygod/vpnhotspot/net/wifi/WifiApManager.kt +++ b/mobile/src/main/java/be/mygod/vpnhotspot/net/wifi/WifiApManager.kt @@ -200,6 +200,10 @@ object WifiApManager { private val cancelLocalOnlyHotspotRequest by lazy { WifiManager::class.java.getDeclaredMethod("cancelLocalOnlyHotspotRequest") } + /** + * This is the only way to unregister requests besides app exiting. + * Therefore, we are happy with crashing the app if reflection fails. + */ @RequiresApi(26) fun cancelLocalOnlyHotspotRequest() = cancelLocalOnlyHotspotRequest(Services.wifi) diff --git a/mobile/src/main/java/be/mygod/vpnhotspot/util/Utils.kt b/mobile/src/main/java/be/mygod/vpnhotspot/util/Utils.kt index 2b024db6..d530d8ba 100644 --- a/mobile/src/main/java/be/mygod/vpnhotspot/util/Utils.kt +++ b/mobile/src/main/java/be/mygod/vpnhotspot/util/Utils.kt @@ -159,10 +159,14 @@ private val newLookup by lazy @TargetApi(26) { * See also: https://stackoverflow.com/a/49532463/2245107 */ fun InvocationHandler.callSuper(interfaceClass: Class<*>, proxy: Any, method: Method, args: Array?) = when { - Build.VERSION.SDK_INT >= 26 && method.isDefault -> newLookup.newInstance(interfaceClass, 0xf) // ALL_MODES - .`in`(interfaceClass).unreflectSpecial(method, interfaceClass).bindTo(proxy).run { - if (args == null) invokeWithArguments() else invokeWithArguments(*args) - } + Build.VERSION.SDK_INT >= 26 && method.isDefault -> try { + newLookup.newInstance(interfaceClass, 0xf) // ALL_MODES + } catch (e: ReflectiveOperationException) { + Timber.w(e) + MethodHandles.lookup().`in`(interfaceClass) + }.unreflectSpecial(method, interfaceClass).bindTo(proxy).run { + if (args == null) invokeWithArguments() else invokeWithArguments(*args) + } // otherwise, we just redispatch it to InvocationHandler method.declaringClass.isAssignableFrom(javaClass) -> when { method.declaringClass == Object::class.java -> when (method.name) {