Correctly handle callSuper for Proxy

This commit is contained in:
Mygod
2020-05-31 07:40:25 +08:00
parent 3327242c2e
commit d17cd0bab3
3 changed files with 56 additions and 38 deletions

View File

@@ -5,8 +5,10 @@ import android.net.wifi.WpsInfo
import android.net.wifi.p2p.WifiP2pGroup
import android.net.wifi.p2p.WifiP2pManager
import be.mygod.vpnhotspot.App.Companion.app
import com.android.dx.stock.ProxyBuilder
import be.mygod.vpnhotspot.util.callSuper
import timber.log.Timber
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy
object WifiP2pManagerHelper {
@@ -90,17 +92,15 @@ object WifiP2pManagerHelper {
fun WifiP2pManager.requestPersistentGroupInfo(c: WifiP2pManager.Channel,
listener: (Collection<WifiP2pGroup>) -> Unit) {
val proxy = Proxy.newProxyInstance(interfacePersistentGroupInfoListener.classLoader,
arrayOf(interfacePersistentGroupInfoListener)) { proxy, method, args ->
if (method.name == "onPersistentGroupInfoAvailable") {
if (args?.size != 1) Timber.w(IllegalArgumentException("Unexpected args: $args"))
@Suppress("UNCHECKED_CAST")
listener(getGroupList.invoke(args[0]) as Collection<WifiP2pGroup>)
null
} else {
Timber.w(IllegalArgumentException("Unexpected method, calling super: $method"))
ProxyBuilder.callSuper(proxy, method, args)
}
arrayOf(interfacePersistentGroupInfoListener), object : InvocationHandler {
override fun invoke(proxy: Any, method: Method, args: Array<out Any?>?): Any? = when (method.name) {
"onPersistentGroupInfoAvailable" -> {
if (args?.size != 1) Timber.w(IllegalArgumentException("Unexpected args: $args"))
@Suppress("UNCHECKED_CAST") listener(getGroupList.invoke(args!![0]) as Collection<WifiP2pGroup>)
}
else -> callSuper(interfacePersistentGroupInfoListener, proxy, method, args)
}
})
requestPersistentGroupInfo.invoke(this, c, proxy)
}
}