Be more careful about using unsupported APIs

This commit is contained in:
Mygod
2021-06-11 00:49:54 -04:00
parent fac1451e95
commit 907283c53a
2 changed files with 12 additions and 4 deletions

View File

@@ -200,6 +200,10 @@ object WifiApManager {
private val cancelLocalOnlyHotspotRequest by lazy { private val cancelLocalOnlyHotspotRequest by lazy {
WifiManager::class.java.getDeclaredMethod("cancelLocalOnlyHotspotRequest") 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) @RequiresApi(26)
fun cancelLocalOnlyHotspotRequest() = cancelLocalOnlyHotspotRequest(Services.wifi) fun cancelLocalOnlyHotspotRequest() = cancelLocalOnlyHotspotRequest(Services.wifi)

View File

@@ -159,8 +159,12 @@ private val newLookup by lazy @TargetApi(26) {
* See also: https://stackoverflow.com/a/49532463/2245107 * See also: https://stackoverflow.com/a/49532463/2245107
*/ */
fun InvocationHandler.callSuper(interfaceClass: Class<*>, proxy: Any, method: Method, args: Array<out Any?>?) = when { fun InvocationHandler.callSuper(interfaceClass: Class<*>, proxy: Any, method: Method, args: Array<out Any?>?) = when {
Build.VERSION.SDK_INT >= 26 && method.isDefault -> newLookup.newInstance(interfaceClass, 0xf) // ALL_MODES Build.VERSION.SDK_INT >= 26 && method.isDefault -> try {
.`in`(interfaceClass).unreflectSpecial(method, interfaceClass).bindTo(proxy).run { 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) if (args == null) invokeWithArguments() else invokeWithArguments(*args)
} }
// otherwise, we just redispatch it to InvocationHandler // otherwise, we just redispatch it to InvocationHandler