Fix PersistentGroupInfoListener

This commit is contained in:
Mygod
2021-07-25 22:38:17 -04:00
parent bdaa8c3f51
commit ed09f747ce
2 changed files with 12 additions and 6 deletions

View File

@@ -9,7 +9,7 @@ import androidx.annotation.RequiresApi
import be.mygod.vpnhotspot.App.Companion.app
import be.mygod.vpnhotspot.net.MacAddressCompat
import be.mygod.vpnhotspot.util.callSuper
import be.mygod.vpnhotspot.util.matches1
import be.mygod.vpnhotspot.util.matchesCompat
import kotlinx.coroutines.CompletableDeferred
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
@@ -99,9 +99,8 @@ object WifiP2pManagerHelper {
private val interfacePersistentGroupInfoListener by lazy {
Class.forName("android.net.wifi.p2p.WifiP2pManager\$PersistentGroupInfoListener")
}
private val getGroupList by lazy {
Class.forName("android.net.wifi.p2p.WifiP2pGroupList").getDeclaredMethod("getGroupList")
}
private val classWifiP2pGroupList by lazy { Class.forName("android.net.wifi.p2p.WifiP2pGroupList") }
private val getGroupList by lazy { classWifiP2pGroupList.getDeclaredMethod("getGroupList") }
private val requestPersistentGroupInfo by lazy {
WifiP2pManager::class.java.getDeclaredMethod("requestPersistentGroupInfo",
WifiP2pManager.Channel::class.java, interfacePersistentGroupInfoListener)
@@ -118,7 +117,7 @@ object WifiP2pManagerHelper {
requestPersistentGroupInfo(this, c, Proxy.newProxyInstance(interfacePersistentGroupInfoListener.classLoader,
arrayOf(interfacePersistentGroupInfoListener), object : InvocationHandler {
override fun invoke(proxy: Any, method: Method, args: Array<out Any?>?): Any? = when {
method.matches1<java.util.Collection<*>>("onPersistentGroupInfoAvailable") -> {
method.matchesCompat("onPersistentGroupInfoAvailable", args, classWifiP2pGroupList) -> {
@Suppress("UNCHECKED_CAST")
result.complete(getGroupList(args!![0]) as Collection<WifiP2pGroup>)
}

View File

@@ -55,10 +55,17 @@ fun Long.toPluralInt(): Int {
@RequiresApi(26)
fun Method.matches(name: String, vararg classes: Class<*>) = this.name == name && parameterCount == classes.size &&
(0 until parameterCount).all { i -> parameters[i].type == classes[i] }
classes.indices.all { i -> parameters[i].type == classes[i] }
@RequiresApi(26)
inline fun <reified T> Method.matches1(name: String) = matches(name, T::class.java)
fun Method.matchesCompat(name: String, args: Array<out Any?>?, vararg classes: Class<*>) =
if (Build.VERSION.SDK_INT < 26) {
this.name == name && args?.size ?: 0 == classes.size && classes.indices.all { i ->
args!![i]?.let { classes[i].isInstance(it) } != false
}
} else matches(name, *classes)
fun Context.ensureReceiverUnregistered(receiver: BroadcastReceiver) {
try {
unregisterReceiver(receiver)