I'm writing a Work Tracker application, which needs to scan the nearby wifi hotspots for security. I'm trying to follow the code given at Google's official site, but it keeps failing. I read somewhere that this code won't work on newer versions of android, and well enough it doesn't work neither on the Android 12 emulator, nor on my Android 10 device. How am I supposed to solve this problem?
Here's my code:
fun checkWifiChannels(
localContext: Context
) {
val wifiManager = localContext.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
val wifiScanReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val success = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false)
if(success) {
scanSuccess(wifiManager, localContext)
} else {
scanFailure(wifiManager, localContext)
}
}
}
val intentFilter = IntentFilter()
intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)
localContext.registerReceiver(wifiScanReceiver, intentFilter)
val success = wifiManager.startScan()
if(!success) {
scanFailure(wifiManager, localContext)
}
}
private fun scanSuccess(
wifiManager: WifiManager,
localContext: Context
) {
val results = wifiManager.scanResults
Toast.makeText(localContext, "Scan successful", Toast.LENGTH_SHORT).show()
println(results.toString())
}
private fun scanFailure(
wifiManager: WifiManager,
localContext: Context
) {
val results = wifiManager.scanResults
println("Scan not successful, old results:")
Toast.makeText(localContext, "Scan not successful", Toast.LENGTH_SHORT).show()
println(results.toString())
}
Here's the localContext variable declared in a @Composable function:
val localContext = LocalContext.current
This code always prints "Scan not successful", and I can't find anything online how am I supposed to solve this, I'm pretty new to android programming.
Thank you in advance!