Search code examples
androidkotlinandroid-wifi

Get WiFi Scan Results List With Kotlin


I need to scan for a list of wifi access points in my android app. I've done it in the past using java, but I'm having trouble getting my kotlin code to work.

My code:

var resultList = ArrayList<ScanResult>()
lateinit var wifiManager: WifiManager

val broadcastReceiver = object : BroadcastReceiver() {
    override fun onReceive(contxt: Context?, intent: Intent?) {
        resultList = wifiManager.scanResults as ArrayList<ScanResult>
        Log.d("TESTING", "onReceive Called")
    }
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    wifiManager = this.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager

}

override fun onGridTileClicked(x: Int, y: Int) {
    startScanning()
}

fun startScanning() {
    registerReceiver(broadcastReceiver, IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION))

    Handler().postDelayed({
        stopScanning()
    }, 10000)
}

fun stopScanning() {
    unregisterReceiver(broadcastReceiver)
    val axisList = ArrayList<Axis>()
    for (result in resultList) {
        axisList.add(Axis(result.BSSID, result.level))
    }
    Log.d("TESTING", axisList.toString())

}

The onReceive() function is never called, and I have the ACCESS_FINE_LOCATION and ACCESS_WIFI_STATE both declared in the manifest, so I'm not sure what I'm doing wrong. I'm sure I'm missing something obvious, but some help would be appreciated. Thanks!


Solution

  • You forgot to start scanning. Add wifiManager.startScan() call in your startScanning method.